for loops

To add comments, please log in or register
BigAl
482
BigAl  
I seem to remember being advised that when using a for loop it is better to use it to count down rather than up. please can you remind me why?
Carl Schreiber
Moderator
7132
Carl Schreiber  
It matters if you loop through e.g. all open orders and you want to close one or another. If you e.g. close the on at index [0] the one at i[1] slips at [0] but you index is increased to [1] so you miss [0] now.
BigAl
482
BigAl  
Carl Schreiber:
It matters if you loop through e.g. all open orders and you want to close one or another. If you e.g. close the on at index [0] the one at i[1] slips at [0] but you index is increased to [1] so you miss [0] now.

ok thanks for that

whroeder1
17942
whroeder1  
In the presence of multiple orders (one EA multiple charts, multiple EAs, manual trading,) while you are waiting for the current operation (closing, deleting, modifying) to complete, any number of other operations on other orders could have concurrently happened and changed the position indexing:
  1. For non-FIFO (US brokers,) (or the EA only opens one order per symbol,) you can simply count down in a position loop, and you won't miss orders. Get in the habit of always counting down.
              Loops and Closing or Deleting Orders - MQL4 and MetaTrader 4 - MQL4 programming forum
  2. For FIFO (US brokers,) and you (potentially) process multiple orders per symbol, you must count up and on a successful operation, reprocess all positions (set index to -1 before continuing.)
  3. and check OrderSelect in case earlier positions were deleted.
              What are Function return values ? How do I use them ? - MQL4 and MetaTrader 4 - MQL4 programming forum
              Common Errors in MQL4 Programs and How to Avoid Them - MQL4 Articles
  4. and if you (potentially) process multiple orders, must call RefreshRates() after server calls if you want to use the Predefined Variables (Bid/Ask) or OrderClosePrice() instead, on the next order/server call.
To add comments, please log in or register