EA Doctor rule · Positions and orders
No magic number on the EA's trades
The EA opens trades without a magic number, so it cannot tell its own positions from manual trades or another EA's.
Why it matters
The magic number is how an EA recognises its own positions and orders. Without one, its trades carry 0, the same as manual trades and those of other EAs that skip it.
The EA can then count, trail or close positions that are not its own, and two copies on different charts cannot keep their trades apart.
When the rule fires
The EA opens trades (OrderSend() with a deal or pending request, or CTrade Buy(), Sell(), PositionOpen() or a pending-order method) and never sets request.magic or calls SetExpertMagicNumber().
When it stays quiet
request.magic is assigned or SetExpertMagicNumber() is called anywhere in the file.
How to fix it
- Add an input for the magic number, so two copies of the EA can run with different ones.
- With
CTrade, calltrade.SetExpertMagicNumber(InpMagic)inOnInit(); with a raw request, setreq.magic. - Filter every position and order loop by it (see the loop rules below).
Code that fires it
int OnInit()
{
return(INIT_SUCCEEDED);
}
void OpenSell()
{
if(!trade.Sell(InpLots, _Symbol))
Print("Sell failed: ", trade.ResultRetcodeDescription());
}Fixed code
int OnInit()
{
trade.SetExpertMagicNumber(InpMagic);
return(INIT_SUCCEEDED);
}
void OpenSell()
{
if(!trade.Sell(InpLots, _Symbol))
Print("Sell 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
- 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.
- 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.