Iterating through positions and closing one. What happens on the next iteration?

 

Hi,

On every tick I am iterating through all my open positions, and depending on certain criteria I will close it or not.

What puzzles me, if I start iterating through and say have 100 open positions and I close the 50th, what will happen on the next  - 51st - iteration? 

Because I imagine the positions are sorted in a list, and if you take one out of the middle, the list becomes sorter, so after closing the 50th, the 51st becomes the 50th, and incrementing the iterator will actually point to the 52nd. Please correct me if I am wrong.

Programmatically it should look something like this:

      #include <Trade\Trade.mqh>

      CTrade trade;

      //...

      void OnTick(){

      ulong ticket;

      int total;

      total=PositionsTotal();

      for(int pos=0;pos<total;pos++){

         ticket = PositionGetTicket(pos);

         if(ticket == 0) continue;

//... condition check

trade.PositionClose(ticket);

        }}

 

In MQL 4 it is common to iterate from back to front, I think this holds for 5, too.

for(int pos=total-1;pos>=0;pos--)
 
lippmaje:

In MQL 4 it is common to iterate from back to front, I think this holds for 5, too.

wonderful

 
pcdeni I close the 50th, what will happen on the next  - 51st - iteration?
  1. Please edit your (original) post and use the CODE button (Alt-S)! (For large amounts of code, attach it.)
              General rules and best pratices of the Forum. - General - MQL5 programming forum
              Messages Editor

  2. 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 (non-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 programming forum
      For In First Out (FIFO-US brokers,) and you (potentially) process multiple orders per symbol, you must find the earliest order, close it, and on a successful operation, reprocess all remaining positions.
                CloseOrders by FIFO Rules - Strategy Tester - MQL4 programming forum - Page 2 #16

    2. and check OrderSelect in case earlier positions were deleted.
                What are Function return values ? How do I use them ? - MQL4 programming forum
                Common Errors in MQL4 Programs and How to Avoid Them - MQL4 Articles
    3. and if you (potentially) process multiple orders, must call RefreshRates() after server calls if you want to use, on the next order / server call, the Predefined Variables (Bid/Ask) or (be direction independent and use) OrderClosePrice().

Reason: