Skip to content

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

  1. Add an input for the magic number, so two copies of the EA can run with different ones.
  2. With CTrade, call trade.SetExpertMagicNumber(InpMagic) in OnInit(); with a raw request, set req.magic.
  3. Filter every position and order loop by it (see the loop rules below).

Code that fires it

MQL5 · fires this rule
int OnInit()
  {
   return(INIT_SUCCEEDED);
  }

void OpenSell()
  {
   if(!trade.Sell(InpLots, _Symbol))
      Print("Sell failed: ", trade.ResultRetcodeDescription());
  }

Fixed code

MQL5 · fixed
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

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.