2 EMA Crossover

 

Hi

I have 2 questions regarding a practice EA I am coding.

1. A SELL position is not opened immediately after closing a BUY position. This results in the EA only having long or only short trades. What is the problem?

2. When the CurrentFastEMA = CurrentSlowEMA (unlikely, but it happens), the code executes multiple times (keeps buying/selling in the same candle). How can I overcome this bug?

 

if(CurrentFastEMA < CurrentSlowEMA && PastFastEMA > PastSlowEMA && Position > 0)
     {
      
     while(Position > 0)
       {
        
       for(int i = 0; i < OrdersTotal(); i++) {
           OrderSelect(i, SELECT_BY_POS, MODE_TRADES);
           if(Symbol() == OrderSymbol()) {
              while(IsTradeAllowed() == false) Sleep(100);
              RefreshRates();
              if(OrderType() == OP_BUY) {
                 int Closed = OrderClose(OrderTicket(), OrderLots(), Bid, Slippage, White);
                 Print("Attempting to CloseSingleSell orders # ", IntegerToString(i), " ", DoubleToString(Bid));
                 if (Closed == -1) {
                     Print("Failed to close");
                 }  
                  
                 else {
                    Print("Close Successful");
                    Position--;
                     
                 }
              }
           }                
       }      
     }
        
     int res = OrderSend(Symbol(), OP_SELL, Lots, Bid, Slippage, 0, 0, NULL, Magic, 0, White);
    
    return;
   }  

 

Thanks in advance for the responses. Cheers!


 

Reason: