Skip to content

EA Doctor rule · Positions and orders

New entries without reading the open positions

OnTick() opens trades but nothing in the EA reads its open positions or orders, so it keeps entering again on every signal and after every restart.

Why it matters

An EA that opens trades from OnTick() without asking the terminal what it already holds enters again on the next signal, the next tick or after a restart, when its own variables start empty.

Positions pile up until the account's margin runs out or the broker's position limit (10040) stops it.

When the rule fires

OnTick() (or a function it calls) opens trades and nothing in the file reads positions or orders: no PositionsTotal(), PositionSelect…(), PositionGetTicket(), PositionGetSymbol(), OrdersTotal(), OrderGetTicket(), CPositionInfo or COrderInfo.

When it stays quiet

Any of those is used anywhere in the file.

How to fix it

  1. Count the EA's own positions (its symbol and magic number) before an entry, and enter only below the number the strategy allows.
  2. Do the same for pending orders with OrdersTotal() and OrderGetTicket().

Code that fires it

MQL5 · fires this rule
void OnTick()
  {
   if(SymbolInfoDouble(_Symbol, SYMBOL_ASK) > iClose(_Symbol, PERIOD_D1, 1))
      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--)
     {
      const ulong ticket = PositionGetTicket(i);
      if(ticket == 0)
         continue;
      if(PositionGetString(POSITION_SYMBOL) == _Symbol && PositionGetInteger(POSITION_MAGIC) == InpMagic)
         n++;
     }
   return(n);
  }

void OnTick()
  {
   if(CountMine() > 0)
      return;
   if(SymbolInfoDouble(_Symbol, SYMBOL_ASK) > iClose(_Symbol, PERIOD_D1, 1))
      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.