MT5 Expert Advisors: Build, Test & Deploy Your First EA
Expert Advisors (EAs) are automated trading programs that run inside MetaTrader 5. They can analyze markets, generate signals, and execute trades without human intervention. This guide takes you from zero to a working EA — no programming background required, though basic logic helps.
Table of Contents
What Is an Expert Advisor?
An Expert Advisor is a program written in MQL5 (MetaQuotes Language 5) that automates trading decisions on MT5. EAs can:
- Monitor price and indicator values in real time
- Open and close trades based on predefined rules
- Manage position sizing, stop losses, and take profits
- Run 24/5 without human supervision
- Execute strategies faster than any human trader
EAs range from simple moving-average crossover systems to complex machine-learning algorithms. The most reliable EAs tend to be rule-based systems with clear entry and exit logic that has been validated through rigorous backtesting.
The MQL5 Editor (MetaEditor)
MetaEditor is the built-in IDE for writing MQL5 code. To open it, press F4 inside MT5 or go to Tools > MetaQuotes Language Editor.
MetaEditor includes:
- Code editor with syntax highlighting and autocomplete
- Compiler that converts your .mq5 file into an executable .ex5 file
- Debugger for stepping through code line by line
- MQL5 Reference — a complete function library accessible with F1
Build Your First EA: Moving Average Crossover
The simplest profitable EA is a moving average crossover. It buys when a fast moving average crosses above a slow one, and sells when it crosses below. Here is the logic:
Trading Rules
- Buy signal: 9 EMA crosses above 21 EMA
- Sell signal: 9 EMA crosses below 21 EMA
- Stop loss: 50 pips from entry
- Take profit: 100 pips from entry
- Lot size: 0.01 (micro lot)
Implementation Steps
- Open MetaEditor (F4) and go to File > New > Expert Advisor
- Name your EA (e.g., "MA_Crossover") and click Next
- Add input parameters for the fast and slow EMA periods
- In the OnTick() function, calculate the current and previous values of both EMAs using the iMA() function
- Check for crossover: if the fast EMA was below the slow EMA on the previous bar and is now above it, trigger a buy
- Use OrderSend() to open positions with your defined stop loss and take profit
- Add position management to prevent multiple positions in the same direction
- Compile (F7) and fix any errors shown in the Errors tab
The MQL5 documentation at mql5.com/en/docs has detailed examples for every function. Focus on understanding iMA(), OrderSend(), PositionSelect(), and PositionClose() for your first EA.
Backtesting in the Strategy Tester
Before risking real money, test your EA against historical data. Open the Strategy Tester from View > Strategy Tester or press Ctrl+R.
Backtesting Steps
- Select your EA from the Expert dropdown
- Choose the symbol (e.g., EURUSD) and timeframe (e.g., H1)
- Set the date range — test at least 2 years of data
- Select "Every tick based on real ticks" for the most accurate results
- Set your initial deposit (e.g., $10,000)
- Click "Start"
After the test completes, review the Results tab for key metrics:
- Net profit: Total profit after all trades
- Profit factor: Gross profit / Gross loss. Above 1.5 is good.
- Max drawdown: The largest peak-to-trough decline. Keep this below 20%.
- Win rate: Percentage of profitable trades
- Sharpe ratio: Risk-adjusted return. Higher is better.
Optimization Without Overfitting
Optimization finds the best parameter values for your EA. The Strategy Tester's optimization mode tests thousands of parameter combinations. However, there is a critical risk: overfitting.
Overfitting happens when your EA is perfectly tuned to past data but fails on new data. Prevent it by:
- Out-of-sample testing: Optimize on 2022-2024 data, then test on 2025-2026 without changing parameters
- Walk-forward analysis: Divide data into segments, optimize on each, and validate on the next
- Keeping parameters simple: Fewer parameters means less room for overfitting
- Avoiding curve-fit results: If your EA only works on one specific pair and timeframe, it is likely overfit
Live Deployment
Once your EA passes backtesting and out-of-sample validation:
- Start with a demo account for 2-4 weeks to verify real-time behavior matches backtest results
- Deploy on a live account with minimal capital (0.01 lots)
- Use a VPS (Virtual Private Server) for 24/5 uptime — most brokers offer free VPS for active accounts
- Monitor performance weekly and compare to expected metrics
- Scale lot size gradually only after 3+ months of consistent results
XM offers free VPS hosting for EA traders and a $30 no-deposit bonus to test your first strategy live.
Open XM MT5 AccountCommon EA Mistakes to Avoid
- No stop loss: Every trade must have a stop loss. Martingale strategies that double down on losers eventually blow up the account.
- Too many parameters: If your EA needs 15 input parameters to be profitable, it is overfit. Aim for 3-5 parameters maximum.
- Ignoring slippage and spread: Backtest results assume ideal conditions. Set realistic spread and slippage values in the Strategy Tester.
- Not testing on multiple pairs: A robust EA should work on at least 3-4 correlated pairs, not just one.
- Running without a VPS: If your home internet drops or your PC sleeps, your EA stops running. Use a VPS.