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
- Inside the loop, skip positions whose
PositionGetString(POSITION_SYMBOL)is not the EA's symbol. - Check the symbol together with the magic number.
Code that fires it
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
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
- 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.
- MediumNew entries without reading the open positionsOnTick() 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.
- 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.
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.