Backtesting is essential before risking real money. This guide covers how to test your Expert Advisors using MT5's Strategy Tester and analyze the results.
Opening Strategy Tester
Access the Tester
- In MT5: View → Strategy Tester (or Ctrl+R)
- The Strategy Tester panel opens at bottom
Tester Interface
Key sections:
- Settings: Configure test parameters
- Inputs: EA input parameters
- Results: Trade history
- Graph: Equity curve
- Report: Detailed statistics
Configuring a Backtest
Basic Settings
| Setting | Description | Recommendation |
|---|---|---|
| Expert | Select your EA | Your compiled EA |
| Symbol | Trading pair | Match your strategy |
| Period | Timeframe | Match your strategy |
| Model | Tick generation | "Every tick based on real ticks" |
| Deposit | Starting balance | Realistic amount |
| Leverage | Account leverage | Match broker |
Testing Models Explained
Every tick based on real ticks:
- Most accurate
- Uses recorded tick data
- Slowest but best for final testing
Every tick:
- Generates ticks from M1 data
- Good accuracy
- Faster than real ticks
1 minute OHLC:
- Only uses open, high, low, close
- Fast but less accurate
- Good for quick tests
Open prices only:
- Tests only on bar open
- Very fast
- Only for strategies trading on bar open
Date Range
- Use date: Enable custom range
- From: Start date
- To: End date
Recommendation: Test at least 2-3 years of data including different market conditions.
Execution Settings
- Delay: Simulated execution delay
- Random delay: Add randomness (realistic)
- Slippage: Custom slippage model
Running a Backtest
Step 1: Configure Settings
`` Expert: MyEA.ex5 Symbol: EURUSD Period: H1 Model: Every tick based on real ticks Date: 2021.01.01 to 2024.01.01 Deposit: 10000 USD Leverage: 1:100 `
Step 2: Set Inputs
Click "Inputs" tab to set EA parameters:
- FastMA: 10
- SlowMA: 20
- RiskPercent: 1
- StopLossPips: 50
Step 3: Start Test
Click "Start" button. Progress bar shows completion.
Step 4: Analyze Results
When complete, examine:
- Graph tab for equity curve
- Results tab for trade history
- Report tab for statistics
Understanding Backtest Results
Key Metrics
Profitability:
| Metric | Good Value | Meaning |
|---|---|---|
| Total Net Profit | Positive | Overall profit |
| Profit Factor | >1.5 | Gross profit / Gross loss |
| Expected Payoff | Positive | Average profit per trade |
Risk:
| Metric | Good Value | Meaning |
|---|---|---|
| Max Drawdown | <20% | Largest peak-to-trough decline |
| Relative DD | <20% | Drawdown as % of balance |
| Recovery Factor | >3 | Profit / Max Drawdown |
Trade Statistics:
| Metric | Meaning |
|---|---|
| Total Trades | Number of trades |
| Win Rate | % of winning trades |
| Avg Win | Average winning trade |
| Avg Loss | Average losing trade |
Reading the Graph
Equity Curve (blue line):
- Should trend upward
- Smooth is better than volatile
- Look for consistent growth
Balance Line (green):
- Only changes on trade close
- Steps up/down with each trade
Bad Signs:
- Long flat periods
- Steep drops
- Erratic movement
Optimization
What Is Optimization?
Testing multiple parameter combinations to find best settings.
Setting Up Optimization
- Go to "Inputs" tab
- For each parameter to optimize:
- Check the checkbox - Set Start, Step, Stop values
Example: ` FastMA: Start=5, Step=5, Stop=30 (6 values) SlowMA: Start=10, Step=10, Stop=50 (5 values) Total combinations: 30 `
Optimization Types
Slow complete algorithm:
- Tests ALL combinations
- Most thorough
- Slowest
Fast genetic based:
- Uses genetic algorithms
- Finds good solutions quickly
- May miss optimal
Choose optimization criterion:
- Maximum profit
- Maximum profit factor
- Maximum recovery factor
- Minimum drawdown
Running Optimization
- Configure parameter ranges
- Select optimization type
- Click "Start"
- View "Optimization" tab for results
Analyzing Optimization Results
- Sort by desired criterion
- Look at top 10-20 results
- Check if parameters cluster (robust)
- Avoid outliers (curve fitting)
Avoiding Over-Optimization
Signs of Curve Fitting
- Very specific parameter values (17, 23.7, etc.)
- Results too good to be true
- Performance varies wildly with small changes
- Works only on test period
Prevention Strategies
Out-of-Sample Testing: `
- Optimize on 2021-2022 (in-sample)
- Test on 2023 (out-of-sample)
- If results similar, strategy is robust
`
Walk-Forward Analysis: ` Period 1: Optimize 2021, Test 2022 Q1 Period 2: Optimize 2021-Q1 2022, Test Q2 2022 Period 3: Continue... `
Use Round Numbers:
- FastMA: 10, 20, 50 (not 17, 23, 47)
- Better generalization
Forward Testing
What Is Forward Testing?
Running EA on live data without real money:
- Demo account
- Real market conditions
- Verifies backtest results
How to Forward Test
- Attach EA to demo account chart
- Enable "Allow Algo Trading"
- Run for at least 1-2 months
- Compare to backtest expectations
What to Monitor
- Trade execution matches expectations
- No technical errors
- Drawdown within limits
- Slippage is acceptable
Generating Reports
Export Report
- Right-click on results
- Select "Save as Report"
- Choose HTML or XML format
Report Sections
Summary:
- Initial deposit
- Total net profit
- Profit factor
- Expected payoff
- Drawdown
Trade History:
- Every trade with entry/exit
- Profit/loss
- Duration
Graph:
- Visual equity curve
Code for Backtest-Aware EA
Detecting Tester Mode
`mql5 void OnTick() { // Check if running in tester bool isTesting = MQLInfoInteger(MQL_TESTER); bool isOptimization = MQLInfoInteger(MQL_OPTIMIZATION);
if(isTesting && !isOptimization) { // Log extra info during testing Print("Testing mode - extra logging enabled"); }
// Normal trading logic... } `
OnTester Function
Called after backtest completes:
`mql5 double OnTester() { double profit = TesterStatistics(STAT_PROFIT); double drawdown = TesterStatistics(STAT_EQUITY_DD_RELATIVE); double trades = TesterStatistics(STAT_TRADES);
// Custom criterion for optimization // Higher is better if(trades < 100) return 0; // Minimum trades if(drawdown > 20) return 0; // Maximum drawdown
// Return profit factor as criterion double profitFactor = TesterStatistics(STAT_PROFIT_FACTOR); return profitFactor; } ``
Key Takeaways
- Use "Every tick based on real ticks" for accurate results
- Test at least 2-3 years of data
- Key metrics: Profit Factor >1.5, Max DD <20%
- Optimization finds best parameters
- Avoid curve fitting with out-of-sample testing
- Forward test before live trading
- Use OnTester() for custom optimization criteria
What's Next?
Learn Python for forex trading to expand your automation capabilities beyond MQL5.
This article is for educational purposes only and does not constitute financial advice.