MQL5 Expert Advisor Code Review: Common Bugs to Check
An MQL5 Expert Advisor can pass every backtest and still fail live, because many bugs only appear under conditions the Strategy Tester does not produce: a rejected request, another broker’s symbol settings, a restart with open positions, a netting instead of a hedging account, or a different clock. When I review an EA, I check eight areas first: trade results, filling modes, magic numbers, netting versus hedging, state after a restart, symbol properties, time and sessions, and the gap between tester and live trading. This article explains what goes wrong in each area and what correct code does instead, based only on the official MQL5 reference as of November 2026.
What does a code review of an MQL5 Expert Advisor check?
A review reads the code against its specification and asks what happens outside the happy path. It does not judge whether the strategy will make money; no code review can answer that. The table maps the eight areas to a typical bug and to what correct code does instead.
| Area | Typical bug | What correct code does |
|---|---|---|
| Trade results | Treats OrderSend() returning true as a fill | Checks retcode and handles each rejection |
| Filling mode | Hard-coded FOK or IOC | Reads SYMBOL_FILLING_MODE per symbol |
| Magic numbers | None, or one shared by several instances | One per instance; filters by magic number and symbol |
| Netting vs hedging | Assumes one position per symbol, or several | Reads ACCOUNT_MARGIN_MODE, works with position tickets |
| State after restart | Keeps state only in variables | Rebuilds state from positions, orders and history |
| Symbol properties | Fixed pip factor, prices rounded to the point | Reads digits, tick size, volume step and stop levels |
| Time and sessions | Mixes server, local and GMT time | Uses one documented clock, reads sessions per symbol |
| Tester vs live | Relies on behavior only the tester shows | Tests alerts, state and execution on a demo account |
The list is the same whether a person or an AI coding assistant wrote the EA. A full trading system code review adds order and risk logic, logging and the Strategy Tester reports to these eight areas.
Trade results: OrderSend() returning true is not a filled order
A pattern that reviews flag quickly: the EA checks OrderSend() only for true or false and then assumes it holds a position. According to the MQL5 reference, a true return value is not a sign that the trade operation succeeded; for a market order it only means that the order was placed in the trading system for further execution. The outcome is in the MqlTradeResult structure: the retcode of the trade server and retcode_external, the response code of an external trading system.
Correct code logs both values together with the request, handles each rejection explicitly and does not retry blindly; a retry after an unclear answer can double the position. The reference also notes that OnTradeTransaction() is called several times while one trade request is executed, so any state updated in that handler has to tolerate repeated and partial events. The return codes and what each one points to are covered in the diagnostic checklist for an EA that places no trades.
A second check belongs to the same area: after sending, does the EA verify that the position or order it expects actually exists, and what does it do if not? An EA that keeps a variable such as “in trade” instead of querying the account drifts from reality the first time a request is rejected or only partly filled.
Filling modes and symbol properties: what the broker decides
Many values that look like constants are broker settings per symbol. MQL5 exposes them as symbol properties, and code that hard-codes them works on the developer’s account and fails on the next one. A review searches the code for these assumptions:
- Filling mode: a fixed fill-or-kill or immediate-or-cancel request instead of the flags in
SYMBOL_FILLING_MODE; which filling types are usable also depends on the execution mode (SYMBOL_TRADE_EXEMODE). - Price format: a fixed “pips to points” factor instead of
SYMBOL_DIGITSandSYMBOL_POINT, and prices rounded to the point, which assumes that the point equalsSYMBOL_TRADE_TICK_SIZE, the minimal price change. - Volume: lot sizes that are not rounded to
SYMBOL_VOLUME_STEPor ignoreSYMBOL_VOLUME_MINandSYMBOL_VOLUME_MAX. - Distances: stops closer than
SYMBOL_TRADE_STOPS_LEVEL, or modifications insideSYMBOL_TRADE_FREEZE_LEVEL, the distance within which trade operations are frozen.
The diagnostic checklist linked above explains the filling rules per execution mode and the return codes these assumptions produce. The review question is the same for each property: is it read at runtime from the symbol the EA trades, and is it logged at start? Logging these values at every initialization turns a rejected order on a new account into a one-line diagnosis.
Magic numbers on netting and hedging accounts
The magic number is the EA’s identifier in every trade request. According to the reference for MqlTradeRequest, each Expert Advisor can set its own unique ID when it sends a request, so that its orders can be told apart. Three variants of the same bug are worth checking: no magic number at all, one magic number shared by several instances on the same symbol, for example on different timeframes, and loops over positions that filter by magic number but not by symbol, or not at all. The result is an EA that counts manual trades or another EA’s positions as its own, closes them, or refuses to trade because it believes it is already in the market.
The account’s position model adds a second dimension. On netting accounts (ACCOUNT_MARGIN_MODE_RETAIL_NETTING and ACCOUNT_MARGIN_MODE_EXCHANGE) only one position per symbol can exist at any time, the result of one or more deals, so an opposite order changes that position instead of opening a second one. On hedging accounts (ACCOUNT_MARGIN_MODE_RETAIL_HEDGING) several positions per symbol can be open, and PositionSelect() by symbol selects the one with the lowest ticket, which need not be the EA’s. The reference asks for the position ticket in MqlTradeRequest.position whenever a position is modified or closed on a hedging account. Typical example: hedge logic developed on a hedging demo account sends its opposite order on a netting live account and reduces or closes the very position it was meant to protect.
Correct code reads the margin mode at start, iterates over positions by ticket, filters by symbol and magic number, and its documentation states which account types it supports. The snippet counts the EA’s own positions and pending orders and logs the account model at every initialization:
//--- Illustrative, not compiled: check every call against the MQL5 reference.
input long InpMagic = 20261119; // unique per EA instance (example value)
int OwnPositions(const string symbol, const long magic)
{
int n = 0;
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
if(PositionGetTicket(i) == 0) // selects the position, 0 = error
continue;
if(PositionGetString(POSITION_SYMBOL) == symbol &&
PositionGetInteger(POSITION_MAGIC) == magic)
n++;
}
return n;
}
int OwnOrders(const string symbol, const long magic)
{
int n = 0;
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(OrderGetTicket(i) == 0) // selects the pending order
continue;
if(OrderGetString(ORDER_SYMBOL) == symbol &&
OrderGetInteger(ORDER_MAGIC) == magic)
n++;
}
return n;
}
int OnInit()
{
ENUM_ACCOUNT_MARGIN_MODE mode =
(ENUM_ACCOUNT_MARGIN_MODE)AccountInfoInteger(ACCOUNT_MARGIN_MODE);
// State comes from the account, not from variables that may have survived.
PrintFormat("INIT symbol=%s magic=%I64d margin_mode=%s positions=%d orders=%d "
"server_minus_gmt=%I64d tester=%d",
_Symbol, InpMagic, EnumToString(mode),
OwnPositions(_Symbol, InpMagic), OwnOrders(_Symbol, InpMagic),
(long)(TimeTradeServer() - TimeGMT()), (int)MQLInfoInteger(MQL_TESTER));
return(INIT_SUCCEEDED);
}
State after a restart: what OnInit() has to rebuild
Many EAs keep their state in global variables: a flag that a trade was taken today, a counter of consecutive losses, the time of the last processed bar, the ticket of the current position. That state is lost or wrong in situations a backtest never exercises. According to the MQL5 reference, an EA is loaded on terminal start, when a template or profile is loaded, and on connection to an account if it was attached before the terminal was authorized on the server. Each of these is a fresh load, so anything held only in memory is gone.
The opposite case is just as dangerous. When the symbol or timeframe of the chart changes, the EA is not reloaded: the terminal calls OnDeinit() for the old and OnInit() for the new symbol or timeframe, and global and static variables keep their values. A static variable holding the last bar time of the old timeframe, or a cached ticket, survives into a context where it no longer fits.
Correct code treats the account as the source of truth. In OnInit(), and again once the terminal is connected, it rebuilds its state from open positions, pending orders and, if needed, the trade history, filtered by symbol and magic number. It resets cached values explicitly instead of relying on initializers. State that cannot be derived from the account, such as a daily counter, is persisted explicitly, for example in a file or a terminal global variable, and checked against the account on start. A review tests this on a demo account: restart the terminal with an open position, then change the timeframe while the EA runs, and compare the logged state with the account each time.
Time zones and sessions: which clock does the EA read?
MQL5 offers four clocks, and mixing them produces filters that open at the wrong hour. According to the reference, TimeCurrent() returns the last known server time, the time of the last quote received; TimeTradeServer() returns the current time of the trade server as calculated in the client terminal; TimeLocal() returns the time of the local computer; and TimeGMT() returns GMT, taking into account the daylight saving switch of the local computer.
Two findings follow from these definitions. A session filter written against TimeLocal() depends on the time zone of whatever computer or VPS the terminal runs on. And an offset derived as TimeTradeServer() - TimeGMT() is zero in the Strategy Tester, where local time, server time and GMT are deliberately identical, so a filter that looks right in the backtest can be shifted by hours live.
Trading sessions belong in the symbol, not in the code. SymbolInfoSessionTrade() returns the start and end of each trading session for a symbol and weekday, in seconds from midnight. The reference page does not say which clock these times refer to, so log them next to TimeTradeServer() on a demo account and compare them with the symbol specification before a filter relies on them. In general, treat the broker’s offset as data that the EA reads and logs, not as a constant in the code.
Strategy Tester versus live trading: code the tester never runs
A backtest runs the EA inside a simulation with documented simplifications, and code that depends on them stays untested. Besides the identical clocks described above, a review looks for three kinds:
- Ticks: in “Open prices only” mode,
OnTick()runs only at the open of each bar. Stop loss, take profit and pending orders are still checked on hidden ticks, but exit and trailing logic in the EA’s own code runs once per bar. - Side effects:
Alert(),SendMail(),SendNotification()andWebRequest()are not executed in the tester, so alerting and external calls stay untested. - Persistence: terminal global variables are emulated separately from the terminal’s real ones, and file operations stay in the testing agent’s own sandbox.
Rejected requests, restarts, account models and alerts therefore need deliberate tests on a demo account with the broker’s real symbol settings. How to trace a gap between live results and the backtest back to its cause is covered in backtest vs live results: how to diagnose the gap.
Limits of a review and what to do next
A code review makes weaknesses visible; it cannot prove that an EA is free of bugs, and it says nothing about future profitability. Some failures depend on the broker’s server, the network or market conditions that no reading of the code reveals, and trading with leverage carries a risk of loss up to total loss. Use the findings to decide what to fix, then test the fixes where they matter: on a demo account with the broker you will trade with.
- List the brokers and account types the EA must support, including netting or hedging.
- Search the code for hard-coded filling modes, pip factors, symbol names and session hours.
- Check every
OrderSend()call forretcodehandling and logging. - Verify that every loop over positions and orders filters by symbol and magic number.
- Restart the terminal with an open position and change the timeframe while the EA runs; compare its state with the account.
- Log symbol properties, account model and clocks at every initialization.
- Test alerts and external calls on a demo account, since the tester does not execute them.
Frequently asked questions
What are common bugs in MQL5 Expert Advisors?
Typical findings are unchecked trade results after OrderSend(), hard-coded filling modes and pip factors, missing or shared magic numbers, code that assumes either a netting or a hedging account, state kept only in global variables, mixed clocks in session filters, and logic that only works in the Strategy Tester. Each of them depends on the account, the broker or the runtime rather than on the strategy itself.
What is a magic number in an MQL5 Expert Advisor?
It is the Expert Advisor’s identifier in each trade request, the magic field of MqlTradeRequest. It lets the EA tell its own orders and positions apart from manual trades and other EAs. Give every EA instance its own value, including the same EA on different timeframes, and filter every loop over positions and orders by magic number and symbol. A missing or shared magic number lets one EA count or close another’s trades.
What is the difference between netting and hedging in MetaTrader 5?
On a netting account only one position per symbol can exist, and further deals change that position. On a hedging account several positions per symbol can be open at the same time. An EA must know which model it runs on: on hedging accounts it needs the position ticket to modify or close the right position, and PositionSelect() by symbol picks the one with the lowest ticket.
Why does my Expert Advisor lose track of its trades after a restart?
Because state kept only in global variables does not survive a fresh load of the EA, which happens on terminal start, when a template or profile is loaded and on connection to the account. Rebuild the state in OnInit() from open positions, pending orders and history, filtered by symbol and magic number, and persist only what cannot be derived from the account.
How do you find hard-coded broker settings in an Expert Advisor?
Search the code for fixed filling types such as ORDER_FILLING_FOK, pip factors, symbol names with suffixes, stop distances and session hours. Each should be read at runtime instead: the filling flags in SYMBOL_FILLING_MODE, SYMBOL_DIGITS, SYMBOL_POINT and SYMBOL_TRADE_TICK_SIZE, the volume limits and step, SYMBOL_TRADE_STOPS_LEVEL and the sessions from SymbolInfoSessionTrade(). Logging these values at every start makes differences between broker accounts visible.
Sources and status
- OrderSend (return value, MqlTradeResult, OnTradeTransaction) — MQL5 Reference (MetaQuotes) (retrieved November 19, 2026)
- The Structure of a Trade Request (MqlTradeRequest: magic, position) — MQL5 Reference (MetaQuotes) (retrieved November 19, 2026)
- PositionSelect (netting and hedging accounts) — MQL5 Reference (MetaQuotes) (retrieved November 19, 2026)
- Program Running (loading and unloading of Expert Advisors) — MQL5 Reference (MetaQuotes) (retrieved November 19, 2026)
- Symbol Properties (filling modes, digits, tick size, volume, stops and freeze level) — MQL5 Reference (MetaQuotes) (retrieved November 19, 2026)
- Date and Time (TimeCurrent, TimeTradeServer, TimeLocal, TimeGMT) — MQL5 Reference (MetaQuotes) (retrieved November 19, 2026)
- SymbolInfoSessionTrade — MQL5 Reference (MetaQuotes) (retrieved November 19, 2026)
- Testing Trading Strategies (time simulation, tick generation, functions not executed, global variables and files) — MQL5 Reference (MetaQuotes) (retrieved November 19, 2026)
As of November 2026. Third-party rules, prices and APIs may have changed since; the providers' current documentation and the official texts are authoritative.
This article is also available in German: MQL5-Expert-Advisor prüfen lassen: die häufigsten Fehler.
Want your MQL5 Expert Advisor reviewed before it trades live? Get in touch — a free intro call clarifies which parts of the code the review covers and what the report contains. More: Trading system code review and audit.