Pillar Guide 01 · MetaTrader 4 & 5

What Is an Expert Advisor (EA) in Forex Trading?

Understand the true meaning of a Forex Expert Advisor, how MQL4 and MQL5 programs process market ticks, why MT4 and MT5 architectures differ, and how to test automated systems safely without falling for curve-fitted marketing claims.

12 min read
Editorial Policy

Direct Answer — Expert Advisor Definition

An Expert Advisor (EA) is an automated software program written in MQL4 or MQL5 that runs inside MetaTrader 4 or MetaTrader 5. It monitors live price ticks, evaluates predefined technical or risk rules, and can open, modify, or close orders without manual intervention while executing through an OnInit, OnTick, and OnDeinit lifecycle.

1. Expert Advisor Meaning & How EAs Differ from Indicators & Scripts

When retail traders first ask what an Expert Advisor means, it helps to start with MetaQuotes' original terminology. Rather than labeling every module a “trading robot,” MetaTrader named chart-attached automation files Expert Advisors because a program does not have to trade fully autonomously to qualify as an EA. Some EAs execute complete entry-to-exit rules 24 hours a day, whereas others act strictly as trade-management assistants that alert you, compute risk-adjusted position sizes, or automatically attach stop-loss and break-even rules to manual trades.

Inside MetaTrader 4 (MT4) and MetaTrader 5 (MT5), automated MQL modules fall into three distinct architectural categories: Expert Advisors, Custom Indicators, and Scripts. Confusing these three file types is one of the most frequent reasons new traders see errors in the terminal or find that a downloaded file will not attach properly. Even though all three share the same underlying MQL4 or MQL5 syntax, the MetaTrader client enforces strict sandbox permissions for each category.

You will also encounter two pairs of file extensions when organizing an Expert Advisor library. Files ending in .mq4 or .mq5 contain human-readable source code that can be inspected, audited, and recompiled inside MetaEditor. Files ending in .ex4 or .ex5 are compiled executable binaries that MetaTrader actually runs on a chart. Many vendors distribute only compiled binaries alongside .set preset files containing input parameter configurations.

DimensionExpert Advisor (EA)Custom IndicatorScript
Primary PurposeAutomates trade entries, exits, risk sizing, and account monitoringCalculates and plots mathematical overlays or oscillators on price chartsExecutes a single one-off utility action immediately when dropped onto a chart
Trade Order ExecutionFull order send, modify, partial close, and delete permissions (when enabled)Prohibited from placing or modifying live trading ordersAllowed once per run (e.g., close all orders or place bracket orders)
Core Event HandlersOnInit(), OnTick(), OnTimer(), OnTrade() / OnTradeTransaction(), OnDeinit()OnInit(), OnCalculate(), OnDeinit()OnStart() (runs once from top to bottom and terminates)
Terminal Folder PathMQL4/Experts or MQL5/ExpertsMQL4/Indicators or MQL5/IndicatorsMQL4/Scripts or MQL5/Scripts
Lifecycle PersistenceRemains attached and listening across ticks until removed or terminal closesRecalculates on each incoming tick and chart redrawExits memory immediately after OnStart() finishes execution
Typical ExamplesTrend breakout bots, break-even trade managers, session range EAsMoving averages, ATR bands, RSI divergences, session high-low boxesClose-all-positions panic button, symbol export utility, mass pending order deleter

Notice the critical permission boundary: a Custom Indicator cannot open or close orders on your brokerage account, even if someone labels it a “signal bot.” Conversely, an Expert Advisor can read values from built-in or custom indicators, calculate position risk, query account free margin, and dispatch orders directly to your broker's trade server whenever automated trading is explicitly authorized.

2. Inside an MQL4 / MQL5 Expert Advisor: Event Lifecycle & MagicNumber

Unlike standalone desktop applications that loop continuously in a while(true) thread, MetaTrader Expert Advisors use an event-driven execution model. MetaTrader invokes specific callback functions only when chart, clock, or trade events occur. Understanding these core entry points helps traders troubleshoot configuration errors and evaluate how a bot actually processes price changes.

OnInit()

Runs once immediately when you drag the EA onto a chart, change chart timeframes, edit input parameters, or restart MetaTrader. Well-engineered EAs validate symbol suffixes, initialize MQL5 indicator handles, inspect minimum lot steps (SYMBOL_VOLUME_STEP), and return INIT_FAILED if unsafe inputs are supplied.

OnTick()

Executes every time the broker server delivers a new bid/ask quote for the attached symbol. Crucially, if two ticks arrive rapidly while OnTick() is still busy calculating, MetaTrader skips intermediate ticks rather than queuing them infinitely. Most disciplined swing or trend EAs include a new-bar filter so entry checks run cleanly on closed candles rather than intra-candle noise.

OnTimer()

Fires at deterministic second or millisecond intervals registered via EventSetTimer(). Because OnTick() stalls whenever a quiet market pauses incoming quotes, multi-symbol dashboard EAs and Friday session flatteners rely on OnTimer() to stay responsive regardless of single-pair tick frequency.

OnDeinit(const int reason)

Executes right before the EA unloads—whether removed by the trader, interrupted by a timeframe switch, or closed during terminal shutdown. It releases indicator handles via IndicatorRelease(), kills active timers, removes temporary chart objects, and writes a numeric deinitialization reason code to the Experts log.

Why MagicNumber Is Mandatory for Multi-EA Accounts

One of the most important parameters inside almost every Expert Advisor is its MagicNumber (accessible via OrderMagicNumber() in MQL4 or POSITION_MAGIC and CTrade::SetExpertMagicNumber() in MQL5). Whenever an EA opens an order, it stamps that order with an integer tag such as 202611. When the EA loops through open positions to trail stops or calculate basket exposure, it filters exclusively for orders matching both the current symbol and its own MagicNumber.

Manual orders placed from the MetaTrader terminal automatically receive a MagicNumber of 0. If you attach two instances of the same EA—for example, a EURUSD M15 setup and a EURUSD H1 setup—without assigning distinct MagicNumbers, the two instances will modify or prematurely close each other's positions.

Conceptual MQL5 EA Lifecycle StructureMQL5
//+------------------------------------------------------------------+
//| Educational MQL5 Lifecycle Skeleton (No live trade signals)      |
//+------------------------------------------------------------------+
#include <Trade\Trade.mqh>

input long   InpMagicNumber = 202611; // Unique ID isolating this EA's trades
input int    InpMaPeriod    = 50;     // Indicator lookback period

CTrade   trade;
int      maHandle = INVALID_HANDLE;
datetime lastBarTime = 0;

int OnInit()
{
   trade.SetExpertMagicNumber(InpMagicNumber);
   maHandle = iMA(_Symbol, PERIOD_CURRENT, InpMaPeriod, 0, MODE_EMA, PRICE_CLOSE);

   if(maHandle == INVALID_HANDLE)
      return(INIT_FAILED);

   EventSetTimer(60); // Run housekeeping checks every 60 seconds
   return(INIT_SUCCEEDED);
}

void OnTick()
{
   datetime currentBar = iTime(_Symbol, PERIOD_CURRENT, 0);
   if(currentBar == lastBarTime)
      return; // Example guard: evaluate rules once per completed bar

   lastBarTime = currentBar;
   // Read CopyBuffer(maHandle, ...) and manage positions matching InpMagicNumber
}

void OnTimer()
{
   // Periodic terminal connectivity, spread, or session window diagnostics
}

void OnDeinit(const int reason)
{
   EventKillTimer();
   if(maHandle != INVALID_HANDLE)
      IndicatorRelease(maHandle);
}

3. MT4 (.ex4 / MQL4) vs MT5 (.ex5 / MQL5) Comparison

Even though MetaTrader 4 and MetaTrader 5 share a familiar visual workspace, their internal engines are fundamentally incompatible. You cannot rename an .ex4 binary to .ex5 and expect it to compile or execute. Understanding the architectural gaps between MT4 and MT5 explains why serious quantitative testing has steadily shifted toward MT5.

Technical AreaMetaTrader 4 (.ex4 / MQL4)MetaTrader 5 (.ex5 / MQL5)
File & Language FormatSource .mq4 compiled to .ex4 (MQL4 procedural + partial OOP extensions)Source .mq5 compiled to .ex5 (MQL5 modern C++-style OOP & standard library)
Terminal & Tester Threading32-bit legacy terminal; single-threaded Strategy Tester runs one core at a time64-bit architecture; multi-threaded Strategy Tester supports local cores and network agents
Multi-Currency BacktestingNot supported natively; tester evaluates only the single selected chart symbolSupported natively; an EA can read indicators and trade multiple symbols synchronously
Historical Tick PrecisionSynthesizes ticks from M1 OHLC bars using fixed spreads (unless third-party tools used)Native 'Every tick based on real ticks' mode replays recorded bid/ask spreads and tick sequences
Order & Position ModelTicket-based order system where every open trade has an independent ticketSeparates Orders (requests), Deals (executions), and Positions (net or hedged exposure)
Account Accounting ModesHedging only (multiple opposite positions on the same pair allowed simultaneously)Supports both Hedging accounts and Netting accounts (one aggregated position per symbol)
Indicator Access PatternDirect inline function calls per bar shift (e.g., iMA(..., shift))Creates integer handle once in OnInit() and copies arrays via CopyBuffer()
Built-In Calendar & Market DepthNo native economic calendar API; relies on external feeds or custom filesIncludes native Economic Calendar database functions and MarketBookGet() Level II access

Pay special attention to Hedging vs. Netting when deploying an MT5 Expert Advisor. On an MT5 Hedging account, opening a 0.20 lot Buy EURUSD followed by a 0.10 lot Sell EURUSD maintains two separate positions, closely resembling MT4 behavior. On an MT5 Netting account (common on exchange instruments and certain regulated brokers), that 0.10 lot Sell automatically closes half of the Buy position, leaving a single net 0.10 lot Buy. Running a hedging or multi-ticket grid EA on a netting account without verifying code compatibility can scramble stop levels and position sizing immediately.

4. Common EA Strategy Types & Mechanical Risk Profiles

Every Expert Advisor expresses a specific statistical hypothesis about market microstructure or multi-session price behavior. No single algorithmic category works profitably across every macroeconomic regime. Before downloading or coding an EA, identify which behavioral archetype it uses and verify that its drawdown profile matches your risk tolerance.

Trend-Following EAs

Mechanics: Identify directional momentum using moving average crossovers, Donchian channels, Supertrend bands, or ADX strength filters, holding winning positions across multi-session extensions while cutting false signals with predefined stop-losses.

CORE STRENGTH: Asymmetric payoff potential during strong macro trends (e.g., central bank divergence cycles) with capped per-trade downside when paired with fixed fractional position sizing.
KEY VULNERABILITY: Prolonged sideways consolidation ('chop') produces sequences of small whipsaw losses that test trader discipline.

Mean-Reversion & Range EAs

Mechanics: Fade short-term price extensions away from an average or volatility band (Bollinger Bands, Keltner Channels, RSI extremes), frequently targeting calmer off-peak liquidity windows such as the late New York or Asian sessions.

CORE STRENGTH: Typically achieves higher trade frequency and smoother short-term equity progression during stable range-bound conditions.
KEY VULNERABILITY: Extreme sensitivity to widened rollover spreads, unexpected geopolitical headlines, and sharp breakout days where price fails to revert.

Breakout & Volatility-Expansion EAs

Mechanics: Define consolidation boundaries—such as pre-London session ranges or narrow inside-bar structures—and stage pending Buy Stop / Sell Stop orders (or market entries on candle close) when ATR volatility expands.

CORE STRENGTH: Avoids sitting in dead sideways markets and can participate early in high-momentum London or New York session moves.
KEY VULNERABILITY: Fakeouts ('stop runs'), widened news spreads, and positive/negative execution slippage on stop orders during rapid price gaps.

Grid & Martingale Systems

Mechanics: Space orders at fixed or volatility-scaled pip intervals against an initial entry without a tight stop-loss, often multiplying subsequent lot sizes (1x, 2x, 4x, 8x) so a minor pullback closes the entire basket at net break-even or small profit.

CORE STRENGTH: Produces deceptive, upward-sloping closed-balance curves during normal oscillating weeks because losing baskets are held open until recovery.
KEY VULNERABILITY: Carries severe left-tail blowup risk: a sustained one-way trend exhausts free margin rapidly and frequently violates daily drawdown limits enforced by retail risk budgets and prop firms.

Semi-Automated Trade & Risk Managers

Mechanics: Wait for the human trader to open a discretionary setup, then automatically enforce lot sizing from stop distance, move stops to break-even, scale partial profits, or trigger an equity kill-switch.

CORE STRENGTH: Eliminates emotional hesitation around exits and enforces repeatable risk limits without surrendering strategic trade selection to a black box.
KEY VULNERABILITY: Requires the trader to manage chart attachment and terminal uptime cleanly so active protection rules never drop offline mid-trade.

Understanding Grid & Martingale Asymmetric Risk

Suppose a martingale EA opens 0.01 lots and doubles position volume every 25 pips against a runaway move: by the eighth grid level, a single sequence accumulates 0.01 + 0.02 + 0.04 + 0.08 + 0.16 + 0.32 + 0.64 + 1.28 = 2.55 cumulative lots. Even a small additional extension can wipe out months of incremental closed gains. If you evaluate any EA under prop firm rules or strict daily loss limits, review our Prop Firm EA Risk Management Guide and verify sizing ahead of time using the Lot Size Calculator.

5. Step-by-Step Safe Installation & Demo Testing Workflow

Never attach an unfamiliar Expert Advisor directly to a funded live account. Even bug-free systems frequently behave unexpectedly when broker symbol names include prefixes or suffixes (such as EURUSD.m or EURUSDpro), minimum stop distances (SYMBOL_TRADE_STOPS_LEVEL) reject tight trailing stops, or GMT server offsets misalign session filters. Follow this verification sequence on a clean demo environment first:

  1. 01

    Open the MetaTrader Data Folder Safely

    Launch MT4 or MT5, open File → Open Data Folder, and navigate to MQL4\Experts (on MT4) or MQL5\Experts (on MT5). Paste your .ex4 / .ex5 binary there. If the EA includes preset configurations, place .set files inside Presets.

  2. 02

    Refresh the Navigator & Open the Target Chart

    In MetaTrader's Navigator panel (Ctrl+N), right-click Expert Advisors and click Refresh (or restart the terminal). Open the exact currency pair and timeframe specified in the strategy documentation, then drag the EA onto the chart.

  3. 03

    Enable Algo Trading Permissions Carefully

    Automated execution requires two permissions: first, check Allow Algo Trading (MT5) or Allow live trading (MT4) inside the EA's Common tab; second, ensure the global Algo Trading / AutoTrading toolbar button is green. Keep Allow DLL imports unchecked unless you can audit and verify why an external DLL is strictly required.

  4. 04

    Inspect the Experts & Journal Tabs Immediately

    Open the Toolbox/Terminal pane (Ctrl+T) and inspect two distinct logs: the Experts tab prints messages emitted by the EA itself (initialization status, parameter warnings, invalid stop errors like ERR_INVALID_STOPS), while the Journal tab records terminal-level authentication, trade server latency, and automated trading status changes. Confirm the chart corner displays an active status icon (blue graduation cap / smiling icon in MT4; green play indicator in MT5).

  5. 05

    Reconcile Backtests with Demo Forward Observation

    Run an independent historical validation first using our Forex Backtesting Guide, then observe the EA on a demo account (ideally hosted on a stable VPS) across different market sessions before considering live risk sizing with our Pip Calculator.

6. Red Flags & Unethical EA Marketing Claims to Avoid

Because MetaTrader makes it easy to compile locked binaries and cherry-pick visual screenshots, the retail Expert Advisor ecosystem attracts aggressive promotional tactics. Treating the following patterns as automatic disqualifiers saves new traders substantial time and capital:

1. Curve-Fitted Backtests Presented as Guarantees

Cropped equity charts showing a smooth diagonal line without test dates, modeling quality, spread assumptions, or out-of-sample verification almost always rely on over-optimized parameters tuned exclusively to past price noise.

2. Hidden Martingale Disguised as “AI” or “Neural”

Many sellers slap machine-learning buzzwords onto simple cost-averaging grids with no hard per-trade stop-loss. Look closely at trade history lot sequences and floating equity curves rather than closed-balance claims.

3. Unrealistic Fixed Return or Win-Rate Promises

Any vendor advertising guaranteed monthly percentages or near-100% win rates is typically hiding open floating losses (“never close a red trade”) or selective live account resets. Genuine systematic trading always experiences losing weeks and drawdown cycles.

4. Opaque Network Calls or Mandatory DLL Imports

Compiled binaries asking you to enable Allow DLL imports or whitelist unfamiliar third-party URLs without clear technical justification create unnecessary security and account-integrity risks.

7. Frequently Asked Questions About Expert Advisors

What does Expert Advisor (EA) mean in Forex trading?
In MetaTrader 4 and MetaTrader 5, an Expert Advisor (EA) is a compiled program written in MQL4 or MQL5 that monitors chart quotes and automates trade execution, order management, or risk controls based on explicit programmed rules.
Do MetaTrader 4 EAs work on MetaTrader 5?
No. MetaTrader 4 compiles source code into .ex4 binaries using the MQL4 order model, whereas MetaTrader 5 requires .ex5 binaries built with MQL5's handle-based indicators and position/deal accounting. An EA must be rewritten or recompiled specifically for MT5.
How much does an Expert Advisor cost, and can free EAs be safe to test?
Commercial EAs range from modest utility tools to expensive subscription licenses, while open-source and community EAs are often free. Price alone does not measure quality: any EA—free or paid—should be evaluated by inspecting its risk logic, testing it on a demo account, and verifying transparent drawdown behavior.
Does an Expert Advisor keep running when I turn off my computer?
No. An Expert Advisor runs locally inside your open MetaTrader terminal, not on the broker's server. If your PC sleeps, loses internet, or shuts down, the EA stops monitoring ticks and cannot open, trail, or close trades—which is why active algorithmic traders commonly use a reliable Forex VPS.
Why do Expert Advisors behave differently on live accounts compared to backtests?
Historical Strategy Testers often underestimate real-world spread widening during rollover or news, execution latency, partial fills, and broker-specific slippage. In addition, curve-fitted parameters tuned tightly to past price noise degrade rapidly when market volatility shifts.
What is a Magic Number in an Expert Advisor, and why does it matter?
A Magic Number is an integer identifier assigned by an EA to every order or position it creates. Assigning a unique Magic Number per chart or strategy prevents one EA from accidentally modifying, trailing, or closing trades belonging to another EA or manual entries (which carry a Magic Number of 0).

Trading Risk Notice: Trading leveraged Forex and CFDs carries a high level of risk and may not be suitable for all investors. All guides, calculators, Expert Advisors, and market tools are provided strictly for educational purposes and do not constitute financial advice.

Independence Notice: FXAlgoLab (hosted at forexfactory.cc) is an independent algorithmic trading education resource and is not affiliated with, endorsed by, or connected to Forex Factory or Fair Economy, Inc. (forexfactory.com).

Continue Your Research