Moving average EA

 

I wanted to code an EA that would enter a trade once the moving averages cross and close when they cross again while entering the opposite trade. However, it runs fine only until it opens the second trade which will not close. Do you have an idea what is wrong with my code?

   double CurrentFast = iMA(NULL, 0, FastMA, 0, 0, 1,0);
   double CurrentSlow = iMA(NULL, 0, SlowMA, 0, 0, 1,0);
   double PreviousFast = iMA(NULL, 0, FastMA, 0, 0, 1, 1);
   double PreviousSlow = iMA(NULL, 0, SlowMA, 0, 0, 1, 1);
  
  if(PreviousFast < PreviousSlow && CurrentFast > CurrentSlow){ 
   if(OrdersTotal()==1){                                             //if there is one open trade
      OrderClose(1,LotSize,Ask,3,Red);                               //close the SELL trade
      if(OrdersTotal()==0){                                          //if the trade was closed, and there is no trade open
      OrderSend(Symbol(), OP_BUY,LotSize,Ask,3,0,0,NULL,0,0,Blue);   //put BUY trade
      }
   }
   if(OrdersTotal() ==0){                                            //if there are no open trades
      OrderSend(Symbol(), OP_BUY,LotSize,Ask,3,0,0,NULL,0,0,Blue);   //Put BUY trade
   }
  }
  if(PreviousFast > PreviousSlow && CurrentFast < CurrentSlow){
   if(OrdersTotal()==1){                                             //if there is one open trade
      OrderClose(1,LotSize,Bid,3,Green);                             //close the BUY trade
      if(OrdersTotal()==0){                                          //if the trade was closed, and there is no trade open
      OrderSend(Symbol(), OP_SELL,LotSize,Bid,3,0,0,NULL,0,0,Purple);//put SELL trade
      }
   }
   if(OrdersTotal() ==0){                                             //if there are no open trades
      OrderSend(Symbol(), OP_SELL,LotSize,Bid,3,0,0,NULL,0,0,Purple); //Put SELL trade
   }
  }
 
OrderClose(1,LotSize,Ask,3,Red);

You have to find the order ticket number to be able to close it. #1 may exist in the Strategy Tester, but nowhere else.

 

hello friend,

maybe try

do 
   operator; 
while(expression);