Always Loop Down

When you are looping through open orders in MQL4 to close or delete them, make sure that you always loop down (decrement) instead of looping up (increment).

To put it another way, this is bad:

  int orders_total=OrdersTotal();
  int count;
  for(count=0;count<orders_total;count++)

This is good:

  int orders_total=OrdersTotal();
  int count;
  for(count=orders_total-1;count>=0;count--)

Here is why:

Save yourself some error headaches!

1 Like

Or you can also check whether the orders are already open for your particular currency and place a condition. In case it’s positive, notify your EA to not execute the technical analysis or place any new orders. The metatrader and metaquote language in particular comes with native functions to assist you. I for instance use:
OrdersTotal- it returns the pending and open orders.
OrderSelect- Selects an order and gathers the info.
OrderSymbol- Return the currency pair of your chosen order.
Symbol- Return the currency pair of the chart that’s running the indicator or script.
Put the above functionalities with few IF conditions and FOR loop, you can scan all the open and pending orders like mentioned above.

With all due respect my friend, I think you misunderstand. OrdersTotal, OrderSelect, and OrderSymbol are the constructs you’ll use to actually select an order. The reason it’s important to loop down when deleting or closing orders is completely different. Read that article in the OP, it explains it well, but I’ll summarize to the best of my ability.

The first parameter in OrderSelect is usually order position. It is possible to select by ticket, but most code I’ve seen is SELECT_BY_POS. The normal move is to tell your loop to continue looping compared to OrdersTotal, and use the loop counter as the order position index in OrderSelect. Here’s the fun part. When we close or delete an order, it changes the positions of any other open orders, but our loop has no idea! As soon as we delete the order in position 0, the order that was in position 1 now becomes in position 0, but our loop moves on to increment its counter!

If we loop down instead, the number gets smaller, so as the order index shrinks, so does our loop index.