for+OrderSelect+OrderDelete,to delete all pending orders,but only half work,why?

 

use the first code,it works.

int init()
  {
   int OrdersTotalNumber=OrdersTotal();
   Print(OrdersTotalNumber);
   for(int i=OrdersTotalNumber-1;i>=0;i--)	//first code
   //for(int i=0;i<OrdersTotalNumber;i++)	//second code
   {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      Print(OrderTicket());
      OrderDelete(OrderTicket());
   }
   return(0);
  }

int deinit()
  {

   return(0);
  }

int start()
  {

   return(0);
  }

but the second one,it just delete half of the orders.If i have 8 pending orders it will delete 4.

why?i can't understand.thx a lot ! i'm confused.

int init()
  {
   int OrdersTotalNumber=OrdersTotal();
   Print(OrdersTotalNumber);
   //for(int i=OrdersTotalNumber-1;i>=0;i--)	//first code
   for(int i=0;i<OrdersTotalNumber;i++)		//second code
   {
      OrderSelect(i,SELECT_BY_POS,MODE_TRADES);
      Print(OrderTicket());
      OrderDelete(OrderTicket());
   }
   return(0);
  }

int deinit()
  {

   return(0);
  }

int start()
  {

   return(0);
  }
 

i have figure it out.

after OrderDelete(),the index of OrderSelect changed.so the second code is not working.

 

he, he. :) that's why you MUST cycle through them downwards.

Let's assume there are six orders - 0,1,2,3,4,5. What happens if you cycle upwards:

* it deletes order 0.

* order 1 becomes order 0, order 2 becomes order 1, etc. - 0(1),1(2),2(3),3(4),4(5). (initial positions in parentheses)

* it then proceeds to delete order 1(2), order 0(1) stays intact.

* order 2(3) becomes 1(3) etc. - 0(1),1(3),2(4),3(5).

* it then proceeds to delete order 2(4), orders 0(1) and 1(3) stay intact.

* order 3(5) becomes 2(5), there are three orders left - 0(1),1(3),2(5).

* AFAIK it then attempts to delete orders 3(?), 4(?) and 5(?), which simply do not exist at that moment. If you add Print(GetLastError()), you'd probably get three OrderSelect errors.

(Note about the last statement: not 100% sure of that. Different programming languages handle this sort of situation differently.)

 

To be super safe, I do ..

- Loop all orders, storing 'tagged' orders in an array

- Loop array, deleting(or whatever) orders as it goes

 
Always count down in the presence of multiple orders (multiple charts) Always test return codes.
    for(pos = OrdersTotal()-1; pos >= 0 ; pos--) if (
        OrderSelect(pos, SELECT_BY_POS)                 // Only my orders w/
    &&  OrderMagicNumber()  == magic.number             // my magic number
    &&  OrderSymbol()       == Symbol() ){              // and my pair.
Reason: