Blog
How to Filter Positions by Magic Number in MQL5 (Code Guide)
Quick Answer
An MQL5 magic number is an identifier an EA assigns to its trade requests so it can distinguish its own trades from other strategies. Set it on the CTrade object before submitting orders, then inspect POSITION_MAGIC while iterating open positions. Filter by both symbol and magic number when appropriate. On netting accounts, multiple deals can combine into one symbol position, so a magic number cannot fully isolate separate strategies trading the same instrument.
Key Facts
| Concept | Practical meaning |
|---|---|
| Magic number | EA-assigned identifier associated with a trade/position |
| Set for CTrade | Use SetExpertMagicNumber() before placing orders |
| Position filter | Compare POSITION_MAGIC and, as needed, POSITION_SYMBOL |
| Hedging account | Multiple independent positions may exist for the same symbol |
| Netting account | One aggregate position per symbol; same-symbol strategies share exposure |
Magic numbers help prevent an EA from managing unrelated trades, but they do not replace a complete ownership and risk model. A manual position often has a different magic value, and a second EA should use its own identifier. Choose stable values, document them, and avoid changing an EA's identifier unexpectedly while positions remain open.
Set a Magic Number on New Trades
#include <Trade/Trade.mqh>
CTrade trade;
input ulong ExpertMagic = 420105;
int OnInit()
{
trade.SetExpertMagicNumber(ExpertMagic);
return INIT_SUCCEEDED;
}
bool HasPositionForThisEA()
{
for (int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if (ticket == 0)
continue;
string symbol = PositionGetString(POSITION_SYMBOL);
long magic = PositionGetInteger(POSITION_MAGIC);
if (symbol == _Symbol && (ulong)magic == ExpertMagic)
return true;
}
return false;
}
PositionGetTicket(i) selects the position at the requested index, allowing the selected position's properties to be read. Re-check selection and properties when your code's control flow changes or when operating on tickets directly. Position lists can change as trades open and close, so a production manager should handle the possibility that a position disappears before it is modified.
Filter Carefully on Hedging and Netting Accounts
In a hedging account, each position is separate. Filtering by symbol and magic number is useful when iterating positions, and modifications or closes should target the intended ticket. Do not assume the first matching symbol position belongs to the EA.
In a netting account, there is one position per symbol. Deals from different sources can increase, reduce, or reverse that aggregate position. The final position's properties do not provide a robust way to partition its volume and risk back into independent strategies. If multiple EAs trade the same symbol on a netting account, coordinate them through a single execution/risk manager or assign each strategy exclusive symbol ownership.
Also distinguish positions from orders and deals. A pending order has order properties; a completed trade produces deals; the resulting exposure is represented by a position. Checking only open positions will not find pending orders that may later create exposure.
When an EA restarts, it should re-scan current positions using its configured ownership rule rather than relying on a variable stored only in memory. If the EA supports multiple symbols, use the position's actual symbol when querying symbol properties or calculating a modification. If an order is still pending, inspect the order list separately so a repeated signal does not submit a duplicate entry.
Magic numbers should be stable and unique within the system's ownership design. They are visible identifiers, not secrets; another program can use the same value. Add symbol, direction, and strategy context to logs, but do not encode assumptions into a magic number that the actual code never validates.
Common Mistakes
- Using the same magic number everywhere: Two EAs can mistake each other's positions for their own.
- Filtering only by symbol: This can include a manual trade or another strategy's position.
- Assuming magic numbers isolate netting positions: Netting combines same-symbol exposure.
- Ignoring pending orders: An EA may open a second trade even though an entry order is already pending.
- Closing by symbol in a hedging account: A symbol-level operation may not select the intended ticket.
- Using magic number as security: It is an identifier, not authentication or access control.
When position size is also strategy-specific, use the same ownership rules with your MQL5 lot-size calculation. Test multiple chart instances and terminals with realistic account mode settings.
Test with one EA, two EA instances with different identifiers, a manual trade, and both account modes if available. Confirm that each EA modifies only what it owns and that the netting configuration is documented. A magic number alone cannot make an otherwise shared position independent.
Frequently Asked Questions
Does a magic number identify every order, deal, and position?
It is commonly used to identify EA-originated trading activity, but orders, deals, and positions are different entities and expose different properties. Inspect the correct entity for the operation you are implementing.
Can two EAs use the same magic number?
They can, but then filtering cannot distinguish them reliably. Use distinct, documented identifiers if each EA should manage only its own activity.
Can magic numbers separate strategies on a netting account?
Not reliably for multiple strategies trading the same symbol. Netting aggregates exposure into one position, so use coordinated execution or avoid sharing that symbol across independent strategies.
Make Position Ownership Explicit
Decide whether an EA owns trades by magic number, symbol, ticket, or a shared manager before writing entry and exit logic. CodeFlowOS can produce an MQL5 draft with an optional platform check; read the verification notes. Position ownership and netting behavior still need review and testing in the target account mode.
Ticket-safe close pattern
On hedging accounts, close the specific matching ticket rather than assuming that selecting a symbol identifies the position your EA owns. With CTrade, a ticket-based close makes that choice explicit:
#include <Trade/Trade.mqh>
CTrade trade;
input ulong ExpertMagic = 420105;
bool CloseOwnedPosition(const ulong ticket)
{
if (!PositionSelectByTicket(ticket))
return false;
if (PositionGetString(POSITION_SYMBOL) != _Symbol ||
(ulong)PositionGetInteger(POSITION_MAGIC) != ExpertMagic)
return false;
if (!trade.PositionClose(ticket))
{
Print("PositionClose request failed: ",
trade.ResultRetcode(), " ",
trade.ResultRetcodeDescription());
return false;
}
return trade.ResultRetcode() == TRADE_RETCODE_DONE;
}
This helper demonstrates ownership checks, not a complete portfolio manager. A production routine should distinguish a request accepted by CTrade from a confirmed close and reconcile the resulting position state. Handle partial or pending outcomes according to the operation and account mode; do not leave the EA believing exposure was removed when it remains open.
Restart and duplicate-order review
At initialization, rebuild the EA's view from current positions and pending orders instead of relying on a memory-only flag. Before placing a new entry, check both owned positions and owned pending orders. After a restart, an unfilled order may still be working even though the EA's last in-memory “entry sent” flag is gone. A persisted event ID or strategy state can help, but it must be reconciled with terminal state rather than trusted on its own.
Use a separate, documented magic number for each strategy instance that needs independent ownership. This does not make same-symbol exposure independent on a netting account; coordinate such strategies through one manager. See trade-result classification, the daily loss guard, risk-based volume sizing, and CopyBuffer signal handling.
If your entry conditions begin in Pine Script, try the converter, compare the MQL5 conversion workflow with the focused strategy.entry-to-CTrade mapping guide, and see plans. Review ownership and account-mode behavior in MetaTrader before live use.