Optimisation
How to Optimize an Expert Advisor in MT5 Without Overfitting It to the Past
By Benjamin Lee · Updated · 8 min read
Optimising an Expert Advisor is easy. Optimising it so the result survives contact with live trading is the hard part. The MT5 Strategy Tester will happily try ten thousand combinations of your inputs and show you the best one, and with enough combinations the best one will look wonderful on any history, even random noise. This guide explains what the tester's optimisation options do, how to pick settings that are likely to be real rather than lucky, and a repeatable process you can follow before you put an optimised EA on a funded account.
Key takeaways
- Optimisation finds the best fit to the past. Whether that fit is an edge or luck is a separate question you must answer.
- Optimise few inputs, with sensible ranges and coarse steps. Every extra input multiplies the room for luck.
- Choose from a plateau, where neighbouring values also work, never from a lone spike.
- Use a criterion that rewards smooth results, not just net profit, and demand a minimum trade count.
- Always confirm on data the optimiser never saw: forward test, walk-forward and a demo.
What optimisation actually does
The Strategy Tester runs your EA many times over the same history, each time with a different combination of the inputs you have ticked for optimisation, and ranks the runs by a result you choose. That ranking is a search, and a search will always return a winner. The winner tells you which combination fitted this particular stretch of history best. It does not tell you whether the combination reflects something the market will keep doing. The gap between those two statements is the whole subject of this guide, and it has a name: overfitting.
To see the problem, imagine optimising a rule that has no meaning on prices that are pure noise. Try enough combinations and one of them will draw a smooth, rising curve. The more settings you try, the better the best one looks, and the less it means. Move the sliders in the calculator below to see how large the best-looking result from pure noise gets as the search widens.
Interactive: the Sharpe ratio luck can buy
Best annualised Sharpe ratio you should expect from pure noise
1.13
A strategy with no edge at all would still show this result as its best variant, so any reported Sharpe ratio below it proves nothing. Approximation: independent trials, normally distributed returns.
The MT5 tester's optimisation options
In the tester you choose an optimisation mode, a criterion and an optional forward period. MetaQuotes documents all of them in the help pages on strategy optimisation. The table summarises the choices that matter most.
| Setting | Options | What to know |
|---|---|---|
| Optimisation mode | Slow complete algorithm; fast genetic based algorithm; all symbols selected in Market Watch | Complete tries every combination and is exhaustive but slow. Genetic samples intelligently and is much faster for large spaces, and its result depends on the search, so run it more than once. |
| Optimisation criterion | Balance max; Profit factor max; Expected payoff max; Drawdown min; Recovery factor max; Sharpe ratio max; Custom max; Complex criterion max | Net balance alone rewards a lucky large trade. Prefer a ratio that includes risk, such as recovery factor or Sharpe, or a custom criterion that penalises drawdown. |
| Forward | Off; 1/2; 1/3; 1/4; custom date | Holds back the last part of the range. Each pass is also run on it, so you can compare backtest and forward results. |
| Execution model | Every tick based on real ticks, every tick, 1 minute OHLC, open prices only | Optimising on a coarse model can pick settings that only work on that model. Use real ticks for the final check. |
| Agents | Local cores, remote farms, MQL5 Cloud Network | More agents mean faster runs, not better results. |
Optimise fewer inputs, on purpose
The number of combinations grows by multiplication. Five inputs with ten values each is 100,000 combinations; ten inputs is ten billion. The genetic mode hides that cost by only sampling, but the risk of luck grows the same way. The practical rule is to optimise the two or three inputs that define the strategy's logic, such as a lookback period or a threshold, and to leave the rest at sensible fixed values.
- Fix what is not strategy. Lot size, magic number, comments and slippage tolerance are not edges. Do not optimise them.
- Use coarse steps. Testing a 20-bar lookback against 21 and 22 teaches nothing. Step in ranges that matter, such as 10, 20, 30, 40, 50.
- Set ranges from logic, not from the data. A moving-average period of 3 or 300 is outside what the idea was meant to use. Keep the range sensible before you look at results.
- Respect the data you have. An EA that makes 30 trades in five years does not have enough trades for an optimisation to mean anything.
Pick a plateau, never a spike
After an optimisation, look at the results as a landscape, not a leaderboard. In the optimisation tab you can switch to a graph of two inputs against the result. What you want to see is a broad region where the result is good, so that nudging an input a little in any direction still works. That is a plateau. What you do not want is a single bright point surrounded by weak results. That is a spike, and it usually means the optimiser found a coincidence.
A plateau does not prove an edge, but a spike nearly proves the lack of one. The plateau also gives you something practical: because the neighbours work, small changes in market behaviour, spreads or execution will not break the strategy. For the one-dimensional version of the same idea, see how a robust setting looks in a walk-forward test.
Choose the criterion that rewards the right thing
Optimising for 'Balance max' means finding the combination that ended with the most money. That is the criterion most likely to reward one lucky, huge trade and the deepest drawdown, because large risk can produce large results on a short history. Better choices reward profit relative to risk. Recovery factor divides net profit by maximum drawdown, so a setting that makes money with a modest dip beats one that makes a little more and nearly blew up. A custom criterion lets you do more, for example penalising results with fewer than a minimum number of trades, or with a drawdown above a limit.
| Filter | Reason |
|---|---|
| At least 150 to 300 trades | Too few trades makes any statistic unreliable; the exact floor depends on the strategy, but small samples flatter |
| Maximum drawdown you could live with | A result you would abandon in month three is not a result |
| Profit factor above about 1.3 after costs | Thin edges disappear when spread and slippage are realistic |
| Profit not concentrated in a few trades | If removing the best five trades erases the profit, it was luck |
| Similar behaviour long and short | A big asymmetry often means the fit rode one trend |
Interactive: win rate is not edge
- Expected result per trade
- +0.35
- Profit factor
- 1.64
- Break-even win rate
- 33%
At these numbers the system has a positive edge before costs. Add spread, commission and slippage per trade and re-check.
A repeatable process
Step 1: 1. Write the hypothesis first
State in a sentence why the strategy should work: 'breakouts from the Asian range carry on during London'. If you cannot, you are searching, not testing.
Step 2: 2. Split the history before you look
Reserve the most recent quarter to a third of the data as out-of-sample, and do not touch it while optimising. The Forward setting does this for you.
Step 3: 3. Optimise two or three inputs with coarse steps
Use the genetic mode first to find the area, then the complete mode on a narrow range if you want detail.
Step 4: 4. Read the landscape
Look at the two-input graph. Reject spikes. Note the extent of any plateau.
Step 5: 5. Pick the centre of a plateau
Choose a value inside the broad region, not its edge or its single best cell.
Step 6: 6. Test it out of sample
Run the chosen settings on the held-back data. Expect it to be worse than in-sample; the question is how much worse.
Step 7: 7. Stress it
Add spread and slippage, shift each input by 10 to 20 percent and run on a different symbol or period. A robust system degrades gently.
Step 8: 8. Forward test on a demo
Weeks of live data on your own broker, same version. See forward testing on a demo.
The mistakes that fool people most
- Peeking at the held-back data. Every time you adjust after seeing the out-of-sample result, it stops being out of sample.
- Optimising on one regime. A test over one long uptrend makes every trend system look good. Include a trend, a range and a shock.
- Trusting the best of many runs. The more variants you test, the more the winner is selection, not skill.
- Ignoring costs. Optimised scalping settings can look excellent at zero spread and fail at the broker's real one.
- Re-optimising constantly. Changing settings every few weeks to match recent results is chasing the noise. If you re-optimise, do it on a schedule and test the change out of sample.
- Believing a vendor's optimised set blindly. A set file is someone else's best fit. Check it on your broker's data and your own date range before you trust it. Our set file guide explains what is inside one.
The same discipline applies to buying. When we review an EA in our EA verdicts, a missing out-of-sample test or a result that rests on one window lowers the evidence score, because it is the first thing that fails when the market changes. For the theory behind how a backtest can mislead, the paper cited below is a readable account.
Sources and further reading
- MetaTrader 5 Help: Strategy OptimizationHow optimisation and forward testing work in the Strategy Tester.
- MetaTrader 5 Help: Strategy TestingThe Strategy Tester: testing modes, settings and forward testing.
- Bailey, Borwein, López de Prado and Zhu: Pseudo-Mathematics and Financial Charlatanism (Notices of the AMS, May 2014)A plain-language account of how backtest overfitting produces strategies that fail out of sample.
Frequently asked questions
What is overfitting in an Expert Advisor?
It is when settings are tuned so closely to a particular stretch of history that they capture its noise, not a repeatable edge. The backtest looks excellent and the live results disappoint.
Which optimisation mode should I use in MT5?
Use the fast genetic algorithm to explore a large space and the slow complete algorithm for a narrow range you care about. Run the genetic search twice; if the best results differ, the result is not stable.
Which optimisation criterion is best?
Net balance alone is the weakest because it rewards lucky large trades. A criterion that includes risk, such as recovery factor or Sharpe ratio, or a custom criterion with a drawdown limit and a minimum trade count, is usually better.
How many inputs should I optimise?
As few as possible, typically the two or three that define the strategy's logic. Every extra input multiplies the combinations and the chance that the winner is luck.
How do I know whether my optimised settings are robust?
They sit on a plateau, not a spike; shifting each input by 10 to 20 percent keeps most of the result; they hold up on data the optimiser never saw; and they survive realistic spread and slippage.
Expert Advisors in these styles
Apply the checks above to any of these before you buy: read the manual, run your own backtest, and start on demo.
Keep reading
- BacktestingWalk-Forward Analysis in MT5: A Practical GuideWalk-forward analysis for MT5 Expert Advisors: in-sample and out-of-sample periods, the tester's Forward setting, a manual rolling process and how to read results.
- BacktestingHow to Backtest an EA in MT5 ProperlyLearn how to backtest an Expert Advisor in MT5 the right way: tester modes, spreads, delays, optimisation, walk-forward checks and the red flags to avoid.
- BacktestingMT5 Strategy Tester Settings Explained, Field by FieldEvery MT5 Strategy Tester setting explained: modelling mode, date range, forward, delay, deposit, leverage and optimisation, with the safest choice for each.
- BacktestingWhy EA Live Results Differ From Backtests (and What to Do)Why EA live results differ from backtests: spread, slippage, delay, data, overfitting and more. Eleven causes, how to check each and how to close the gap.


