Risk Warning: CFDs are complex instruments and come with a high risk of losing money rapidly due to leverage. Between 74–89% of retail investor accounts lose money when trading CFDs. Automated trading does not eliminate risk — EAs can suffer losses equal to or greater than manual trading. You should consider whether you understand how CFDs work and whether you can afford to take the high risk of losing your money.
An Expert Advisor (EA) is an automated trading program written in the MQL4 or MQL5 programming language that runs directly within the MetaTrader 4 (MT4) or MetaTrader 5 (MT5) trading platform. An EA can automatically monitor markets, analyse price action using technical indicators, and execute buy and sell orders on a trader’s behalf — without any manual input. EAs operate 24 hours a day, 5 days a week, following pre-programmed rules exactly — eliminating emotional decision-making and enabling strategy execution at speeds and frequencies impossible for human traders.
What Is an Expert Advisor?
The term “Expert Advisor” was coined by MetaQuotes Software, the developer of MetaTrader 4 and MetaTrader 5, as the name for the automated trading program module built into their platforms. The name reflects the original concept: a piece of software that acts as an “expert” assistant, advising on and executing trades based on programmed rules — handling the mechanical execution of a trader’s strategy so the trader doesn’t have to.
In practice, EAs range from extremely simple programs (e.g., “enter long when the 9-period EMA crosses above the 21-period EMA; exit when it crosses back below”) to highly sophisticated systems encoding complex multi-indicator logic, dynamic position sizing, correlation-based portfolio management, and adaptive parameter adjustment based on market regime.
The key defining characteristics of an EA:
- Runs inside MetaTrader (MT4 or MT5) — not a separate application
- Written in MQL4/MQL5 — MetaQuotes’ proprietary programming languages
- Executes automatically — no manual intervention required once running
- Runs on a specific chart — attached to a chart of a specific instrument and timeframe
- Has full broker API access — can open, modify, and close orders with all the functions available to a manual trader
EAs are distinct from simple indicators (which only display information on charts) and scripts (which run once and then stop). An EA runs continuously — processing every incoming price tick and making decisions according to its code.
For brokers that specifically support EA trading with optimal infrastructure, see Best Scalping Brokers 2026 — which includes VPS hosting and EA-specific execution data — and Best Day Trading Brokers 2026 on CompareBroker.io.
How an EA Works Inside MT4/MT5 The Event-Driven Architecture
An EA doesn’t continuously loop through code like a traditional program. Instead, it uses an event-driven architecture — it “wakes up” and executes code only when specific events occur in the market.
The primary events that trigger EA code execution are:
OnTick(): Called every time the broker sends a new price quote (a “tick”). This is the most frequent event — on a liquid pair like EUR/USD during the London session, hundreds of ticks arrive per minute. The OnTick() function is where most trading logic lives.
OnInit(): Called once when the EA is first loaded onto a chart. Used for initialisation — setting up variables, checking parameters, creating indicator handles.
OnDeinit(): Called once when the EA is removed from the chart. Used for cleanup — closing any open resources or logging final statistics.
OnBar(): (MT5) Called when a new price bar completes — useful for strategies that act once per bar rather than on every tick.
OnTimer(): Called at specified time intervals regardless of tick activity — useful for strategies that need to act on a schedule.
The Decision Loop
On every OnTick() event, a typical EA goes through a decision loop:
- Get current price data — bid, ask, current bar OHLC
- Calculate indicators — moving averages, RSI, ATR, etc.
- Check conditions — does the current state meet the entry criteria?
- Check position status — are there existing open positions?
- Execute action — open a new order, modify existing order, close order, or do nothing
- Apply risk management — set stop-loss, take-profit, position size
This entire loop executes in microseconds — far faster than any human can process market information and act.
The MQL Language: How EAs Are Built
MQL4 vs MQL5
MQL4 (MetaQuotes Language 4) is the programming language for MT4. It is a C-like language specifically designed for financial application development. MQL4 has been in use since MT4’s release in 2005 and has a massive library of pre-existing code, examples, and community knowledge.
MQL5 (MetaQuotes Language 5) is the newer language for MT5. It is more powerful and more similar to C++ — supporting object-oriented programming, multi-threaded backtesting, and more sophisticated market data access. MQL5 is not backward compatible with MQL4 — an EA written for MT4 cannot run on MT5 without modification.
For a complete comparison of MT4 and MT5 platforms including their EA ecosystems, see the MT4 vs MT5 guide on CompareBroker.io.
Types of Expert Advisors
Trend-Following EAs
The most common EA category. These programs identify the direction of the prevailing trend and trade in its direction. Common underlying logic:
- Moving average crossovers (fast EMA crosses above slow EMA → buy)
- Breakout systems (price breaks above/below a range or channel → enter in breakout direction)
- ADX-based trend strength filters (only trade when trend strength exceeds threshold)
Mean Reversion EAs
These EAs trade against short-term price extremes, expecting price to return to a central value (mean). Common approaches:
- RSI overbought/oversold strategies (buy when RSI < 30, sell when RSI > 70)
- Bollinger Band mean reversion (buy at lower band, sell at upper band)
- Statistical arbitrage between correlated pairs
Scalping EAs
High-frequency EAs that target 2–10 pip moves with high trade frequency. These require:
- Very tight spreads (ECN brokers with 0.0–0.3 pip spreads)
- Fast execution (sub-30ms fill times)
- No requotes (STP/ECN routing)
- VPS hosting near the broker’s servers
For scalping EAs specifically, the broker selection is as critical as the EA logic. See Best Scalping Brokers 2026 for brokers with EA-optimised scalping infrastructure.
Grid EAs
Grid EAs place multiple orders at fixed price intervals above and below the current price — creating a “grid” of positions. As price moves through the grid, positions open and close at various intervals. Grid EAs can generate consistent returns during ranging markets but carry significant risk during sustained trends.
Martingale EAs
EAs that increase position size after each losing trade, expecting that an eventual winner will recover all losses. Extremely dangerous — a sequence of consecutive losses can lead to account-destroying position sizes. These should be approached with extreme caution.
News Trading EAs
EAs specifically designed to execute orders immediately after economic data releases — attempting to capture the initial directional spike. Requires a broker with extremely fast execution and no news trading restrictions. Check broker EA policies before deploying.
Arbitrage EAs
EAs that exploit price discrepancies between different brokers or between a broker’s price and an external reference price. Latency arbitrage (exploiting the microsecond delay between price updates at different brokers) is increasingly difficult due to broker countermeasures.
The Three Functions of an EA: OnTick, OnInit, OnDeinit
OnTick() — The Trading Logic Engine
This is the heart of every EA. It runs on every incoming price tick — potentially thousands of times per day. Its job is to:
- Receive and process the latest price data
- Calculate indicator values
- Evaluate entry and exit conditions
- Execute orders when conditions are met
- Manage open positions (trailing stops, breakeven moves)
OnInit() — Startup Initialisation
Called once when the EA is loaded. Used for:
- Validating input parameters (e.g., checking that stop-loss > 0)
- Creating indicator handles (in MT5)
- Printing startup messages to the log
- Initialising global variables
OnDeinit() — Cleanup on Exit
Called when the EA is removed. Used for:
- Logging final performance statistics
- Releasing indicator handles (in MT5)
- Cleaning up timers
How to Install an EA on MT4/MT5
Step 1: Obtain the EA File
EAs come as .ex4 files (compiled MT4) or .ex5 files (compiled MT5). Source code files are .mq4 or .mq5. If you have source code, MT4/MT5 can compile it to the executable format.
Step 2: Copy to the Correct Folder
In MT4/MT5: Click File → Open Data Folder → Navigate to MQL4/Experts/ (MT4) or MQL5/Experts/ (MT5). Copy the .ex4 or .ex5 file into this folder.
Step 3: Refresh in the Navigator
In MT4/MT5: Right-click on “Expert Advisors” in the Navigator panel (usually on the left side) → click “Refresh.” The EA will appear in the list.
Step 4: Enable Automated Trading
Click the “Automated Trading” button in the MT4/MT5 toolbar — it must be green (enabled) for any EA to execute trades. If this button is grey/disabled, no EA can open orders regardless of its conditions being met.
Step 5: Attach the EA to a Chart
Drag the EA from the Navigator onto a chart of the desired instrument and timeframe. A settings window appears — configure the input parameters. Click OK. The EA is now running on that chart.
Step 6: Verify EA is Active
A smiley face icon in the top-right corner of the chart indicates the EA is running. A sad face indicates the EA is loaded but not allowed to trade (check the “Allow Live Trading” setting in EA properties or enable Automated Trading in the toolbar).
How to Run an EA: Backtesting First {#backtesting}
Never deploy an EA on a live account without thorough backtesting. The MetaTrader Strategy Tester allows comprehensive backtesting against historical price data.
Running a Backtest in MT4
- Press Ctrl+R or go to View → Strategy Tester
- Select your EA from the “Expert Advisor” dropdown
- Choose the instrument (symbol) and timeframe
- Set the date range for the historical test
- Select a modelling quality: “Every tick” (most accurate, slowest), “Control points,” or “Open prices only” (fastest, least accurate for intraday strategies)
- Set initial deposit and currency
- Click “Start”
Interpreting Backtest Results
The Strategy Tester Results tab shows:
- Total net profit: Total P&L across all trades in the test period
- Profit factor: Gross profit / Gross loss — values above 1.3 are generally considered acceptable minimums
- Expected payoff: Average profit/loss per trade
- Maximum drawdown: Largest peak-to-trough equity decline — critically important risk metric
- Total trades: Number of trades taken — more trades = more statistical significance
- Win rate: Percentage of profitable trades
Key Warning About Backtests
Backtests can be misleading. Overfitting — tuning an EA’s parameters to perform well on historical data — is one of the most common causes of backtested strategies failing on live markets. An EA with 95% win rate in backtesting may perform very differently in live conditions due to spreads, slippage, changing market dynamics, and data snooping bias. Always forward-test on a demo account before going live.
Forward Testing and Live Deployment
After satisfactory backtesting, the recommended deployment sequence is:
Stage 1: Demo Account Forward Testing (Minimum 3 Months)
Run the EA on a forex demo account for at least 3 months of real-time market conditions. A demo account provides real market prices but uses virtual funds — allowing you to observe EA behaviour under live conditions without financial risk.
Monitor closely for:
- Actual vs backtested performance consistency
- Drawdown levels in live conditions
- Execution quality (slippage vs backtested assumptions)
- Any unexpected behaviour during news events or high-volatility periods
Stage 2: Micro-Lot Live Testing (1–2 Months)
Move to a live account with minimum lot sizes (0.01 micro lots). The psychological difference between demo and live — even at tiny sizes — is valuable learning. Observe for broker-specific execution differences not visible in backtesting.
Stage 3: Full Live Deployment
Only after consistent performance across both stages deploy the EA at your intended position size. Start conservatively (half intended size) and scale up only after additional live performance confirmation.
EA Parameters and Optimisation
Input parameters are the configurable variables in an EA that control its behaviour — lot size, indicator periods, stop-loss distance, risk percentage, etc.
The Optimisation Trap
MT4/MT5’s built-in Optimiser can test thousands of parameter combinations and find the settings that produced the best historical performance. This sounds valuable — but it produces curve-fitted results that are highly likely to fail on future data.
A robust approach to parameter optimisation:
- Divide your data: Optimise on 60% of data, test the result on the remaining 40% (out-of-sample data). If performance degrades significantly on the out-of-sample period, the parameters are overfit.
- Use stable parameters: Choose parameter values from a region where performance is robust across a range of values — not a single “peak” value that performs slightly better but is surrounded by poor-performing settings.
- Avoid excessive optimisation: An EA with fewer, more meaningful parameters is more robust than one with dozens of optimisable settings.
VPS Hosting for EAs: Why It Matters
An EA can only run when MetaTrader is open and connected to the internet. If your computer shuts down, loses connection, or enters sleep mode — the EA stops. For strategies that trade at any time of day or night, a VPS (Virtual Private Server) is essential.
What Is a VPS?
A VPS is a remote server that runs continuously 24/7, independent of your personal computer. By installing MetaTrader on a VPS and deploying your EA there, the EA operates continuously regardless of what happens to your local machine.
Why VPS Location Matters
EA execution latency is affected by the physical distance between the VPS server and your broker’s trading server. The closer the VPS is to the broker’s server (typically in New York — Equinix NY4/NY5 data centres — or London), the lower the execution latency. For scalping EAs where execution speed is critical, using a VPS within the same data centre as the broker’s server can reduce round-trip latency to under 1 millisecond.
VPS Providers for EA Trading
Many brokers offer free VPS hosting to qualifying clients — making it one of the key criteria when selecting a broker for EA trading. Pepperstone, Eightcap, XM Group, and ThinkMarkets all offer free VPS hosting to active EA traders meeting minimum monthly trading volume thresholds.
Where to Find Expert Advisors
MQL5 Marketplace
The official MetaTrader marketplace (mql5.com/market) contains thousands of EAs — both free and paid. Listings include performance statistics, user reviews, and often the ability to rent before purchasing. This is the most regulated EA marketplace and the best starting point.
Free EA Libraries
MQL5.com’s Code Base section contains thousands of free, open-source EAs published by the community. These range from educational examples to fully functional trading systems.
Third-Party Developers
Independent EA developers sell directly through their own websites, forums like Forex Factory, and community platforms. Due diligence is essential — verify any performance claims with independent live account verification (e.g., through myfxbook.com).
Building Your Own
The most reliable EA is one built on your own validated trading logic. MQL4/MQL5 programming can be learned from MetaQuotes’ official documentation, online courses, and the extensive community knowledge base on mql5.com.
Evaluating an EA: What to Check Before Using It
Before deploying any third-party EA, perform rigorous due diligence:
Performance Verification Checklist
✅ Live account performance: Backtested results are insufficient. Look for independently verified live account performance through myfxbook.com or similar — a minimum of 6–12 months of live trading history.
✅ Drawdown level: What is the maximum drawdown percentage on the live account? Any EA with historical drawdown above 30–40% should be considered extremely high risk.
✅ Trade frequency: How many trades per month? Statistical significance requires at minimum 30–50 trades to draw meaningful conclusions from performance data.
✅ Risk/reward profile: What is the typical stop-loss vs take-profit size? A win rate of 85% with a 1:0.1 risk/reward ratio is actually less profitable than a 40% win rate with a 1:3 ratio.
✅ Broker and instrument specifics: Some EAs are optimised for specific brokers (due to spread, execution, or broker-side conditions). Verify that the EA’s reported performance was achieved on a comparable broker to your own.
✅ Martingale check: Does the EA use Martingale position sizing? If lot sizes increase after losses, the risk profile is dramatically different from what average performance statistics suggest.
EA Risk Management Settings
Regardless of the EA’s strategy logic, robust risk management parameters are essential:
Fixed lot size: Simple and transparent — the EA always trades the same position size. Suitable for beginners.
Risk % per trade: The EA calculates position size as a fixed percentage of account equity (e.g., 1% risk per trade). Position size adjusts automatically as the account grows or shrinks. The recommended approach for most EA traders.
Maximum open trades: Limit the number of simultaneous positions the EA can hold — preventing runaway drawdowns from multiple correlated losses.
Maximum daily loss limit: A hard stop that disables the EA for the remainder of the trading day if cumulative losses exceed a defined percentage — protecting against catastrophic single-session drawdowns.
News filter: Pause trading during the 30 minutes before and after major economic data releases to avoid high-spread, high-slippage execution around economic calendar events.
Common EA Strategies
Moving Average Crossover: Long when fast EMA crosses above slow EMA; short when it crosses below. Simple, well-understood, and widely used as a starting template.
RSI Mean Reversion: Enter long when RSI drops below 30 (oversold); close when RSI returns to 50. Enter short when RSI above 70 (overbought); close when RSI returns to 50.
Breakout Trading: Enter in the direction of a breakout from a defined range (e.g., the Asian session high/low). A popular approach with many variations for London open breakout strategies.
Trend + Pullback: Use a trend filter (e.g., price above 200 SMA = uptrend) and only enter long when the Stochastic Oscillator crosses up from oversold — combining trend direction with pullback timing.
Dual-Timeframe Confirmation: Use a higher timeframe (e.g., H4) to determine trend direction via the Heikin Ashi chart colour, then use a lower timeframe (e.g., M15) to time entries.
Advantages of Expert Advisors
Emotion-free execution: EAs execute exactly as programmed — no hesitation, no fear, no greed. Emotional discipline is the most cited reason manual traders underperform their own strategies.
24/5 operation: EAs run continuously throughout the trading week — capturing opportunities at any hour, including Asia session and overnight sessions, without requiring the trader’s presence.
Backtesting capability: EAs allow strategies to be tested against years of historical data before risking real capital — providing an evidence-based foundation unavailable to purely discretionary traders.
Consistent rule application: An EA applies its rules identically on every trade, every day. No deviation due to fatigue, distraction, or changing market sentiment.
Speed: EAs respond to market conditions in microseconds — essential for scalping strategies where manual execution would be too slow to be viable.
Multiple instruments simultaneously: A single computer running multiple MT4/MT5 instances can run different EAs across dozens of instruments simultaneously — impossible for a single manual trader.
Limitations and Risks of Expert Advisors
Not adaptive to changing market regimes: Most EAs are optimised for specific market conditions (trending, ranging, volatile, quiet). When market conditions change significantly, EA performance often deteriorates — sometimes catastrophically.
Backtesting limitations: Backtests assume perfect execution at tested prices, often underestimate spreads and slippage, and may use over-sampled historical data that leads to overfitting.
Technology dependencies: EAs require continuous internet connectivity, broker server stability, and hardware reliability. Any failure in these dependencies can result in missed trades or stuck positions.
No judgement for extraordinary events: EAs cannot interpret geopolitical events, central bank emergency decisions, or systemic market dislocations. During these events, programmed strategies can suffer severe losses while a human trader would have reduced exposure.
Ongoing maintenance required: Markets evolve. An EA that performed excellently for two years may deteriorate as market microstructure changes, broker execution policies shift, or the instruments it trades change character.
EA vs Copy Trading vs Forex Robot
Feature | Expert Advisor (EA) | Copy Trading | Forex Robot (External) |
Runs in | MT4/MT5 platform | Broker’s copy platform | External software or EA |
Requires MT4/MT5 | Yes | No | Depends on type |
Requires VPS | For 24/5 operation | No (cloud-based) | Usually |
Custom programming | MQL4/MQL5 | No | Depends |
Follows another trader | No | Yes | No (follows own logic) |
Transparent logic | Yes (if own code) | Partial | Often no (black box) |
Regulatory status | Unregulated tool | Often regulated platform | Varies |
“Forex robot” is the common marketing term for an EA or automated trading system — they are functionally the same thing. Copy trading platforms (eToro CopyTrader, AvaTrade’s AvaSocial) replicate the trades of human signal providers — a fundamentally different model from EA automation.
Frequently Asked Questions
What is an Expert Advisor in MetaTrader? An Expert Advisor (EA) is an automated trading program written in MQL4 (for MT4) or MQL5 (for MT5) that runs inside the MetaTrader platform. It can automatically monitor market conditions, analyse technical indicators, and execute buy and sell orders on behalf of the trader — operating 24/5 without manual input.
Does MT4 or MT5 support EAs better? Both platforms natively support EAs. MT5 with MQL5 offers more advanced features — multi-threaded backtesting, more event types, and object-oriented programming. MT4/MQL4 has a larger existing library of EAs due to its longer history. For new EA development, MT5 is recommended. For accessing the widest range of existing EAs, MT4 has more options. See MT4 vs MT5 for full comparison.
Can Expert Advisors trade profitably? Some EAs do trade profitably over extended periods — particularly systematic trend-following and quantitative strategies backed by robust research and live performance verification. However, the majority of commercially marketed EAs fail to deliver their advertised performance in live trading. Rigorous verification, demo testing, and realistic expectations are essential.
Do I need to leave my computer on for an EA to run? Yes — unless you use a VPS (Virtual Private Server). A VPS runs MetaTrader 24/7 remotely, independent of your personal computer. For any strategy that needs to operate outside your normal waking hours, a VPS is essential. Many ECN brokers offer free VPS to active traders.
What is the difference between an EA and a script in MT4/MT5? A script runs once and terminates — it performs a single operation (e.g., closes all open positions) and stops. An EA runs continuously, processing every tick until it is removed from the chart. Both are written in MQL4/MQL5 but serve different purposes.
Where can I get Expert Advisors? The MQL5 Marketplace (mql5.com/market) is the official and most regulated source for both free and paid EAs, with verified performance statistics. The MQL5 Code Base contains thousands of free open-source EAs. You can also hire MQL programmers through the MQL5 Freelance section to build custom EAs to your specifications.
Related Resources on CompareBroker.io
- 📊 Best Scalping Brokers 2026 — Best EA execution and free VPS
- 📊 Best Day Trading Brokers 2026 — EA-compatible broker infrastructure
- 📊 Best ECN Brokers 2026 — ECN execution for scalping EAs
- 📊 Compare Forex Demo Accounts — Test EAs on demo first
- 📊 Compare Zero Spread Brokers — Critical for scalping EAs
- 📖 MT4 vs MT5 — EA platform comparison
- 📖 TradingView Review 2026 — TradingView vs MT4/MT5 for analysis
- 📖 What Is a Forex Robot? — The common term for EAs
- 📅 Economic Calendar — News filter reference for EAs
- 🔍 Pepperstone Review 2026 — Best EA broker overall
- 🔍 Eightcap Review 2026 — Strong EA + MT5 support
- 🔍 XM Group Review 2026 — Free VPS for EA traders
- 📖 Stochastic Oscillator Guide — Common EA indicator
- 📖 Williams %R Guide — Mean reversion EA logic
- 📖 Heikin Ashi Chart Guide — Trend filter for EAs
Risk Warning: Automated trading via Expert Advisors carries significant risk. Past backtesting results do not guarantee future performance. Always test EAs on a demo account before live deployment and only use capital you can afford to lose.