Skip to content

EA Doctor rule · Positions and orders

Position loop without a symbol filter

The EA trades its chart's symbol, but a loop over the open positions never checks the symbol, so it also handles positions on other symbols.

Why it matters

PositionsTotal() covers every symbol of the account. An EA that trades its chart's symbol but loops without checking POSITION_SYMBOL also counts, trails or closes positions on other symbols.

This bites when the same EA runs on two charts: the default magic number input is the same on both, so only the symbol keeps them apart.

When the rule fires

The EA opens trades, and a loop over PositionsTotal() that selects positions never compares their symbol (POSITION_SYMBOL, PositionGetSymbol(), CPositionInfo::Symbol(), _Symbol or Symbol()), directly or in a function it calls.

When it stays quiet

Loops that compare the symbol anywhere in their body.

How to fix it

  1. Inside the loop, skip positions whose PositionGetString(POSITION_SYMBOL) is not the EA's symbol.
  2. Check the symbol together with the magic number.

Code that fires it

MQL5 · fires this rule
int CountMine()
  {
   int n = 0;
   for(int i = PositionsTotal() - 1; i >= 0; i--)
      if(PositionGetTicket(i) > 0 && PositionGetInteger(POSITION_MAGIC) == InpMagic)
         n++;
   return(n);
  }

void OnTick()
  {
   trade.SetExpertMagicNumber(InpMagic);
   if(CountMine() == 0)
      if(!trade.Buy(InpLots, _Symbol))
         Print("Buy failed: ", trade.ResultRetcodeDescription());
  }

Fixed code

MQL5 · fixed
int CountMine()
  {
   int n = 0;
   for(int i = PositionsTotal() - 1; i >= 0; i--)
      if(PositionGetTicket(i) > 0 && PositionGetInteger(POSITION_MAGIC) == InpMagic
         && PositionGetString(POSITION_SYMBOL) == _Symbol)
         n++;
   return(n);
  }

void OnTick()
  {
   trade.SetExpertMagicNumber(InpMagic);
   if(CountMine() == 0)
      if(!trade.Buy(InpLots, _Symbol))
         Print("Buy failed: ", 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.