Skip to content

EA Doctor rule · Positions and orders

Positions closed in a loop that counts up

A loop from 0 to PositionsTotal() closes positions, so every close shifts the list and the loop skips the next position.

Why it matters

Closing a position removes it from the list, and every later position moves down one index. A loop that counts up from 0 therefore steps over the position that just moved into the current index: with four positions it closes two.

The same happens with pending orders and OrdersTotal(). When the loop compares with a total read before it started, it also asks for indexes that no longer exist (4753, position not found).

When the rule fires

A for loop counts up from 0 while i < PositionsTotal() or OrdersTotal() (or a total read from them), and its body closes positions or deletes orders (PositionClose(), OrderDelete(), a close request with .position or a removal request), directly or through a function it calls.

When it stays quiet

Loops that count down from the last index (for(int i = PositionsTotal() - 1; i >= 0; i--)), and loops that only read.

How to fix it

  1. Count down: for(int i = PositionsTotal() - 1; i >= 0; i--).
  2. Select by ticket inside the loop and filter by symbol and magic number before closing.

Code that fires it

MQL5 · fires this rule
void CloseAll()
  {
   for(int i = 0; i < PositionsTotal(); i++)
     {
      const ulong ticket = PositionGetTicket(i);
      if(ticket > 0 && PositionGetInteger(POSITION_MAGIC) == InpMagic)
         trade.PositionClose(ticket);
     }
  }

Fixed code

MQL5 · fixed
void CloseAll()
  {
   for(int i = PositionsTotal() - 1; i >= 0; i--)
     {
      const ulong ticket = PositionGetTicket(i);
      if(ticket == 0 || PositionGetInteger(POSITION_MAGIC) != InpMagic || PositionGetString(POSITION_SYMBOL) != _Symbol)
         continue;
      if(!trade.PositionClose(ticket))
         PrintFormat("Close %I64u failed: %s", ticket, trade.ResultRetcodeDescription());
     }
  }

The fixed code shows this rule’s fix and compiles in MetaEditor for MetaTrader 5 (with CTrade trade, InpLots and InpMagic declared, as in a typical EA). Other rules may still apply to it as a fragment: check your whole EA.

More rules on positions and orders

Sources

Get your EA fixed

Check a whole EA for this and 29 other mistakes with EA Doctor, free and in your browser. Or send it to us: we confirm the price in writing, then fix it.