Skip to content

EA Doctor rule · Positions and orders

Position loop without a magic number filter

The EA stamps its trades with a magic number, but a loop over the open positions never compares it, so it also handles other trades.

Why it matters

PositionsTotal() counts every position on the account: manual trades, other EAs, a second copy of this one. The EA gives its trades a magic number, but a loop that does not compare POSITION_MAGIC counts, trails or closes all of them.

A typical result: the EA thinks it already has a position and never enters, or it closes the trader's manual trade together with its own.

When the rule fires

The EA sets a magic number, and a loop over PositionsTotal() that selects positions (PositionGetTicket(), PositionGetSymbol(), PositionSelectByTicket(), SelectByIndex()) never reads POSITION_MAGIC or CPositionInfo::Magic(), directly or in a function it calls.

When it stays quiet

Utilities that set no magic number (they manage every position on purpose) are not flagged.

How to fix it

  1. Inside the loop, skip positions whose PositionGetInteger(POSITION_MAGIC) is not the EA's magic number.
  2. Keep one helper (IsMine(ticket)) and use it in every loop.

Code that fires it

MQL5 · fires this rule
int OnInit()
  {
   trade.SetExpertMagicNumber(InpMagic);
   return(INIT_SUCCEEDED);
  }

double OpenProfit()
  {
   double sum = 0.0;
   for(int i = PositionsTotal() - 1; i >= 0; i--)
      if(PositionGetTicket(i) > 0 && PositionGetString(POSITION_SYMBOL) == _Symbol)
         sum += PositionGetDouble(POSITION_PROFIT);
   return(sum);
  }

Fixed code

MQL5 · fixed
int OnInit()
  {
   trade.SetExpertMagicNumber(InpMagic);
   return(INIT_SUCCEEDED);
  }

double OpenProfit()
  {
   double sum = 0.0;
   for(int i = PositionsTotal() - 1; i >= 0; i--)
      if(PositionGetTicket(i) > 0 && PositionGetString(POSITION_SYMBOL) == _Symbol
         && PositionGetInteger(POSITION_MAGIC) == InpMagic)
         sum += PositionGetDouble(POSITION_PROFIT);
   return(sum);
  }

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.