#property copyright "Fabio."

extern int system_size = 50;
extern double mylot = 0.1;
extern double factor = 2.0;
extern int trades_limit = 3;

#define UP			   4
#define DOWN		   5
#define BUY                7
#define SELL               8

int system_idx ;
double mult;
int action;
bool range = false;
double last_price;
int prev_status;


int init()
  {
   system_idx = 0;
   mult = 1;
   action = BUY;
   return(0);
  }

int deinit()
  {
   return(0);
  }

int start() {
  
   manage_trades();

   return(0);
  }
  
  void store_stuff(int act, int lact, double lpric ) {
  	action = act;
  	last_price = lpric;
  	system_idx++;
  	
  }
  
  void switch_action () {
  	if (action == SELL) {
  		store_stuff (BUY, SELL, Ask);
  	}
  	else if (action == BUY) {
  		store_stuff (SELL, BUY, Bid);
  	}
  }
   

  void manage_trades() {

	bool won ;
	int status;
	
      if (OrdersTotal() == 0) { 
      
 /* manage the mult */
 		if (system_idx == 0) 
 			mult = 1;
 		else {
      		if (action == BUY && Ask < last_price) {
      			won = False;
      			status = DOWN;
      		}
      		else if (action == SELL && Bid > last_price) {
      			won = False;
      			status = UP;
      		}
			else if (action == BUY && Ask > last_price) {
				won = True;
				status = UP;
			}
      		else if (action == SELL && Bid < last_price){
      			won = True;
      			status = DOWN;
      		}
 
 			if (won == True) mult = 1; else mult*=factor;
 		}
 		
 /* ranging */     		
            if (range == True) {
                Print ("----------Prev: " + prev_status + "  status: " + status);
		    if (prev_status == status) {
		    	 range = False;
		    	 switch_action();
		    }
		    process_trade();
            }
/* mart limit reached */

            else if (mult == MathPow(2,trades_limit) && range == false) {
                range = True;
                mult = 1;
                process_trade();
                store_stuff (action, action, Ask);	// ask or Bid who cares really ?
            } 
             
/* first passed */
             else  {
                  if (system_idx != 0) {
                  	switch_action();
                  }
                  else {
                  	store_stuff (BUY, action, Ask);
                  }
/* common */
                  process_trade();
             }
             prev_status = status;
      }
  }
  
void process_trade () {
	if (action == BUY) 
		process_buy();
	else 
		process_sell();
}
 
void process_buy () {
     	OrderSend(Symbol(),OP_BUY,mylot * mult,Ask,3,
     	   Ask - system_size*Point,
     	   Ask + system_size*Point,
     	   NULL,16384,0,Red);
}

void process_sell () {
      OrderSend(Symbol(),OP_SELL, mylot * mult,Bid,3,
      Bid + system_size*Point,
      Bid - system_size*Point,
      NULL,16385,0,Blue);

}
   
 

