OrderDelete() Error 4108 for Closing Pending Orders

 

I have an EA running that has the potential to open a new pending order with each new candle that gets created. I'm now trying to delete the oldest pending order that was created so that each currency only has one pending order at a time. However, I'm getting error 4108 when calling OrderDelete() and not sure why. Can you look at this and see if there's any insight you can share?

   //-- Check for open trades
   int OpenTrades = 0;
   for(int i = OrdersTotal()-1; i >= 0; i--) {  
      if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
      if(OrderSymbol() != Symbol() || OrderMagicNumber() != Magic) continue;
      OpenTrades++;
      
      if (i == 0) Trade1 = OrderTicket();
      if (i == 1) Trade2 = OrderTicket();
   }   

   //-- Close older pending order if more than 1
   if (OpenTrades > 1) {
      if (OrderSelect(Trade1, SELECT_BY_POS) == true)
         Trade1Date = OrderOpenTime();
      if (OrderSelect(Trade2, SELECT_BY_POS) == true)
         Trade2Date = OrderOpenTime();
      
      if (Trade1Date < Trade2Date) {
         OrderSelect(Trade1, SELECT_BY_TICKET);
         bool del = OrderDelete(OrderTicket(), clrAqua);
      } 
   }
 
  1. You don't close pending orders you delete them.
  2. Your initial loop counts pending and open orders as the same.
  3. It also assumes that the earliest two are for the current symbol/MN. Don't use the variable i, use OpenTrades.
 

Thanks for the feedback @William Roeder!

  1. In my description and in the code, I'm calling OrderDelete for the pending order.
  2. Understood. I can make that adjustment.
  3. Is there a way to loop through the orders and order by oldest orders to newest?
 
  1. Obviously not because of #1 № 2
  2. Until you do, and we can't see what you've done, no further help is possible.
  3. Loop the other direction.