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.
| Dimension | Expert Advisor (EA) | Custom Indicator | Script |
|---|---|---|---|
| Primary Purpose | Automates trade entries, exits, risk sizing, and account monitoring | Calculates and plots mathematical overlays or oscillators on price charts | Executes a single one-off utility action immediately when dropped onto a chart |
| Trade Order Execution | Full order send, modify, partial close, and delete permissions (when enabled) | Prohibited from placing or modifying live trading orders | Allowed once per run (e.g., close all orders or place bracket orders) |
| Core Event Handlers | OnInit(), OnTick(), OnTimer(), OnTrade() / OnTradeTransaction(), OnDeinit() | OnInit(), OnCalculate(), OnDeinit() | OnStart() (runs once from top to bottom and terminates) |
| Terminal Folder Path | MQL4/Experts or MQL5/Experts | MQL4/Indicators or MQL5/Indicators | MQL4/Scripts or MQL5/Scripts |
| Lifecycle Persistence | Remains attached and listening across ticks until removed or terminal closes | Recalculates on each incoming tick and chart redraw | Exits memory immediately after OnStart() finishes execution |
| Typical Examples | Trend breakout bots, break-even trade managers, session range EAs | Moving averages, ATR bands, RSI divergences, session high-low boxes | Close-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.
//+------------------------------------------------------------------+
//| 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 Area | MetaTrader 4 (.ex4 / MQL4) | MetaTrader 5 (.ex5 / MQL5) |
|---|---|---|
| File & Language Format | Source .mq4 compiled to .ex4 (MQL4 procedural + partial OOP extensions) | Source .mq5 compiled to .ex5 (MQL5 modern C++-style OOP & standard library) |
| Terminal & Tester Threading | 32-bit legacy terminal; single-threaded Strategy Tester runs one core at a time | 64-bit architecture; multi-threaded Strategy Tester supports local cores and network agents |
| Multi-Currency Backtesting | Not supported natively; tester evaluates only the single selected chart symbol | Supported natively; an EA can read indicators and trade multiple symbols synchronously |
| Historical Tick Precision | Synthesizes 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 Model | Ticket-based order system where every open trade has an independent ticket | Separates Orders (requests), Deals (executions), and Positions (net or hedged exposure) |
| Account Accounting Modes | Hedging only (multiple opposite positions on the same pair allowed simultaneously) | Supports both Hedging accounts and Netting accounts (one aggregated position per symbol) |
| Indicator Access Pattern | Direct 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 Depth | No native economic calendar API; relies on external feeds or custom files | Includes 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.
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.
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.
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.
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.
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:
- 01
Open the MetaTrader Data Folder Safely
Launch MT4 or MT5, open File → Open Data Folder, and navigate to
MQL4\Experts(on MT4) orMQL5\Experts(on MT5). Paste your.ex4/.ex5binary there. If the EA includes preset configurations, place.setfiles insidePresets. - 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.
- 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.
- 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). - 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?
Do MetaTrader 4 EAs work on MetaTrader 5?
How much does an Expert Advisor cost, and can free EAs be safe to test?
Does an Expert Advisor keep running when I turn off my computer?
Why do Expert Advisors behave differently on live accounts compared to backtests?
What is a Magic Number in an Expert Advisor, and why does it matter?
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
Next Pillar Guide
Forex Backtesting Guide
Test EAs with MT5 real ticks, realistic spreads, and walk-forward splits.
Risk Controls
Prop Firm EA Risk Management
Configure daily drawdown caps, equity stops, and safe exposure limits.
Free Tool
Position & Lot Size Calculator
Verify exact lot exposure against stop-loss distance and account equity.
Free Tool
Pip Value Calculator
Check exact pip values across crosses and account deposit currencies.
EA Library
Browse Expert Advisors
Explore community MT4 & MT5 files to inspect and demo-test.
Articles
Read Technical Blog Posts
Dive into strategy teardowns, terminal maintenance, and market notes.