Blog / Code & convert EAs · MQL5 · MQL4 · Expert Advisors

Magic Numbers in MT5: How to Stop Your EA from Touching Other Trades

Learn how to assign and check MT5 magic numbers in MQL5 and MQL4 to prevent Expert Advisors from interfering with other trades.

· 6 min read

Running multiple Expert Advisors on one trading account creates a trade-management risk. If an EA scans open positions and modifies or closes trades without checking which system opened them, it may interfere with another EA or a manually opened position.

MT5 magic numbers help prevent this by identifying the Expert Advisor associated with a trade.

However, assigning a magic number is only part of the solution. Your EA must also check the identifier before modifying or closing a position. Otherwise, the number provides no practical protection.

1. What Is a Magic Number in MetaTrader?

A magic number is a numerical identifier assigned to trading activity initiated by an Expert Advisor.

For example, a trader running three separate EAs could use:

Expert Advisor Magic Number
EURUSD Scalper 10001
GBPUSD Trend EA 10002
Gold Trading EA 10003

When each EA submits trades using its assigned identifier, it can check that identifier when scanning trading activity.

This helps distinguish one EA's trades from those opened by other systems or manually.

Important: Magic numbers are identifiers, not security controls. They do not prevent another EA or a trader from modifying or closing a position. Your code must enforce the ownership checks.

2. How to Assign a Magic Number in MQL5

In MQL5, the standard CTrade class provides the SetExpertMagicNumber() method.

First, include the trading library, create a trade object and define the EA's magic number:

MQL5
#include <Trade/Trade.mqh>

CTrade trade;

input ulong MagicNumber = 10001;

int OnInit()
{
   trade.SetExpertMagicNumber(MagicNumber);

   return INIT_SUCCEEDED;
}

The SetExpertMagicNumber() call configures the CTrade object to use that identifier when submitting trades.

For example:

MQL5
void OpenBuy()
{
   double lot_size = 0.01;

   if(!trade.Buy(lot_size, _Symbol))
   {
      Print("Buy request failed: ",
            trade.ResultRetcodeDescription());
   }
}

The magic number must be assigned before the trade request is submitted.

If your EA uses multiple CTrade objects, configure each object with the appropriate identifier. Also remember that the setting applies to operations performed through that object; it does not automatically identify or filter every position the EA encounters.

3. How to Identify and Manage Your EA's Positions in MQL5

Assigning a magic number does not automatically restrict an EA to its own positions. Before modifying or closing a position, the EA must check its magic number.

In MQL5, POSITION_MAGIC retrieves the magic number associated with a selected position.

The following function scans open positions and identifies those matching the EA's magic number and chart symbol:

MQL5
void CheckMyPositions()
{
   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      ulong ticket = PositionGetTicket(i);

      if(ticket == 0)
         continue;

      ulong position_magic =
         (ulong)PositionGetInteger(POSITION_MAGIC);

      string position_symbol =
         PositionGetString(POSITION_SYMBOL);

      if(position_magic != MagicNumber)
         continue;

      if(position_symbol != _Symbol)
         continue;

      Print("EA-owned position found. Ticket: ", ticket);
   }
}

Here's what the function does:

  1. Loops through all currently open positions.
  2. Retrieves each position's ticket.
  3. Reads its magic number and symbol.
  4. Ignores positions that do not match the EA's identifier and chart symbol.
  5. Reports positions that pass both checks.

The symbol filter is useful when an EA is designed to manage only the instrument attached to its chart. A multi-symbol EA may need a different filtering rule.

Close a matching position by its ticket

Finding the correct position is not enough. The EA must also target that specific position when performing a trade-management operation.

For example, you can close a matching position using its ticket:

MQL5
void CloseMyPositions()
{
   for(int i = PositionsTotal() - 1; i >= 0; i--)
   {
      ulong ticket = PositionGetTicket(i);

      if(ticket == 0)
         continue;

      ulong position_magic =
         (ulong)PositionGetInteger(POSITION_MAGIC);

      string position_symbol =
         PositionGetString(POSITION_SYMBOL);

      if(position_magic != MagicNumber ||
         position_symbol != _Symbol)
         continue;

      if(!trade.PositionClose(ticket))
      {
         Print("Close failed for ticket ", ticket,
               ": ", trade.ResultRetcodeDescription());
      }
      else
      {
         Print("Close request processed for ticket ", ticket,
               ". Server response: ",
               trade.ResultRetcodeDescription());
      }
   }
}

Using the ticket is particularly important on hedging accounts. Multiple positions can exist on the same symbol, and PositionClose(symbol) closes the position with the lowest ticket in that situation. PositionClose(ticket) targets the specific position you selected.

Also, a successful return from PositionClose() does not by itself guarantee that the server executed the operation. Check the trade server's return code.

4. How to Implement Magic Numbers in MQL4

MQL4 handles magic numbers differently.

When submitting an order with OrderSend(), you supply the magic number as one of the function's parameters.

MQL4
int MagicNumber = 10001;

int ticket = OrderSend(
   Symbol(),
   OP_BUY,
   0.01,
   Ask,
   3,
   0,
   0,
   "My EA",
   MagicNumber,
   0,
   clrBlue
);

if(ticket < 0)
{
   Print("OrderSend failed. Error: ", GetLastError());
}

The magic number is the ninth parameter, following the order comment.

To identify orders belonging to the EA, select each order and retrieve its identifier using OrderMagicNumber():

MQL4
void CheckMyOrders()
{
   for(int i = OrdersTotal() - 1; i >= 0; i--)
   {
      if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
         continue;

      if(OrderMagicNumber() != MagicNumber)
         continue;

      if(OrderSymbol() != Symbol())
         continue;

      Print("EA-owned order found. Ticket: ",
            OrderTicket());
   }
}

The function checks both the magic number and symbol before identifying an order as belonging to the EA.

One important difference from the MQL5 position example is that the MQL4 MODE_TRADES pool includes both open market orders and pending orders. If your EA should manage only market orders, add a check for the order type before performing the relevant operation.

5. Why Every EA Should Have a Unique Magic Number

Using the same magic number across unrelated EAs can cause trade-identification errors.

Imagine two EAs trading EURUSD with the same magic number, 10001.

If both systems filter positions using only that identifier and the symbol, either EA may identify the other's trades as its own.

To avoid this:

  • Assign a distinct magic number to each independent strategy.
  • Give separate EA instances different identifiers when they require independent trade management.
  • Keep each identifier consistent while the EA is responsible for managing its existing trades.
  • Check both the magic number and symbol when the EA is intended to manage a specific instrument.

Changing an EA's magic number without accounting for its existing positions can also create problems. The EA may stop recognising trades opened under its previous identifier.

A magic number should therefore be treated as part of the EA's trade-management configuration, not as an arbitrary value to change whenever convenient.

6. Hedging vs. Netting: An Important Limitation

Magic numbers do not provide the same level of trade separation on every MT5 account. The account's position accounting system matters; hedging vs netting accounts covers it in depth.

Hedging accounts

A hedging account allows multiple separate positions on the same symbol.

For example, two EAs can open separate EURUSD Buy positions, each with its own magic number.

Because the positions remain separate, an EA can check POSITION_MAGIC and use the position ticket to identify and manage the intended position.

This makes ownership-based management relatively straightforward, provided the EA checks the identifier before acting.

Netting accounts

A netting account allows only one open position per symbol.

If multiple EAs and manual trades operate on EURUSD, their transactions can contribute to the same combined position.

This creates a limitation: the resulting position cannot be treated as several independently manageable EA positions simply because the original orders had different magic numbers.

POSITION_MAGIC identifies the magic number recorded for the position. It does not provide a reliable breakdown of every strategy's contribution to a combined net position.

Consequently, an EA should not assume that checking POSITION_MAGIC gives it exclusive ownership of a symbol's position on a netting account.

If multiple strategies need independent trade management, consider using separate trading accounts or a central trade-management system that coordinates all activity on the shared symbol.

This distinction is especially important when adapting an EA originally designed for hedging accounts to operate on a netting account.

7. Common Magic Number Mistakes

These mistakes can undermine an otherwise functional magic-number system:

  • Reusing identifiers across unrelated EAs: One EA may mistake another system's trades for its own.
  • Checking only the symbol: Several EAs can trade the same instrument, so the symbol alone does not establish ownership.
  • Assigning identifiers without checking them: The EA may still modify or close positions belonging to other systems.
  • Changing identifiers unexpectedly: Existing positions may no longer match the EA's configured magic number.
  • Closing by symbol instead of ticket on hedging accounts: The EA may close a different position from the one it selected.
  • Assuming magic numbers guarantee isolation: They identify trading activity but do not prevent manual intervention or interference from other programs.
  • Ignoring netting limitations: A combined position cannot always be managed independently by multiple strategies.

The practical rule is simple: assign a consistent identifier, verify it before every relevant trade-management action, and use the specific position ticket when targeting a position.

Conclusion

MT5 magic numbers help Expert Advisors identify their trading activity and avoid accidentally managing positions belonging to other systems.

In MQL5, assign an identifier using CTrade::SetExpertMagicNumber() and retrieve it through POSITION_MAGIC. In MQL4, pass the identifier to OrderSend() and retrieve it with OrderMagicNumber().

However, assigning a magic number alone is not enough. Your EA must check the identifier before modifying or closing a position, and on hedging accounts, it should target the specific position by ticket.

Finally, understand the difference between hedging and netting accounts. Magic numbers can identify positions, but they cannot turn a combined netting position into independently manageable trades.

Build a bot from your idea

Describe your trading idea and the AI writes MT4 or MT5 code for you to review and test, with a plain-English explanation and setup steps. Your first bot is free.

More from the blog