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
- Count the EA's own positions (its symbol and magic number) before an entry, and enter only below the number the strategy allows.
- Do the same for pending orders with
OrdersTotal()andOrderGetTicket().
Code that fires it
void OnTick()
{
if(SymbolInfoDouble(_Symbol, SYMBOL_ASK) > iClose(_Symbol, PERIOD_D1, 1))
if(!trade.Buy(InpLots, _Symbol))
Print("Buy failed: ", trade.ResultRetcodeDescription());
}Fixed code
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.
Related MQL5 errors
More rules on positions and orders
- MediumNo magic number on the EA's tradesThe EA opens trades without a magic number, so it cannot tell its own positions from manual trades or another EA's.
- HighPositions closed in a loop that counts upA loop from 0 to PositionsTotal() closes positions, so every close shifts the list and the loop skips the next position.
- MediumPosition loop without a magic number filterThe EA stamps its trades with a magic number, but a loop over the open positions never compares it, so it also handles other trades.
- MediumPosition loop without a symbol filterThe 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.
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.