ForexCopilotEA

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.

0.51.01.52.01101001,00010,000Parameter combinations tried (log scale)Best Sharpe from noise3 yrs5 yrs10 yrs
Illustrative: the best result you can expect from pure noise rises with the number of combinations tried. A high Sharpe ratio from a large search is weaker evidence than the same figure from a small one.

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.

Optimisation settings in the MT5 Strategy Tester
SettingOptionsWhat to know
Optimisation modeSlow complete algorithm; fast genetic based algorithm; all symbols selected in Market WatchComplete 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 criterionBalance max; Profit factor max; Expected payoff max; Drawdown min; Recovery factor max; Sharpe ratio max; Custom max; Complex criterion maxNet 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.
ForwardOff; 1/2; 1/3; 1/4; custom dateHolds back the last part of the range. Each pass is also run on it, so you can compare backtest and forward results.
Execution modelEvery tick based on real ticks, every tick, 1 minute OHLC, open prices onlyOptimising on a coarse model can pick settings that only work on that model. Use real ticks for the final check.
AgentsLocal cores, remote farms, MQL5 Cloud NetworkMore 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.

Spike: probably fittedPlateau: pick from hereInput A (left to right)Input BDarker green = more profit. Invented data.
Illustrative only; the data are invented. The isolated bright cell is a spike: change either input slightly and the result vanishes. The broad warm area is a plateau, where neighbouring values also work. Choose a value from the middle of a plateau, not its best single cell.

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.

Parameter AParameter BDashed oval: plateauNeighbouring settings also profit.Small data or cost changes will not break it.Solid circle: spikeOne cell is great, its neighbours lose.Usually noise the optimiser found by chance.Green: profit. Red: loss. Darker = larger.
One input against result. A robust setting sits on a broad hill; a fitted one sits on a needle.

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.

Filters worth applying to every optimisation result
FilterReason
At least 150 to 300 tradesToo few trades makes any statistic unreliable; the exact floor depends on the strategy, but small samples flatter
Maximum drawdown you could live withA result you would abandon in month three is not a result
Profit factor above about 1.3 after costsThin edges disappear when spread and slippage are realistic
Profit not concentrated in a few tradesIf removing the best five trades erases the profit, it was luck
Similar behaviour long and shortA 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

  1. 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.

  2. 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.

  3. 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.

  4. Step 4: 4. Read the landscape

    Look at the two-input graph. Reject spikes. Note the extent of any plateau.

  5. Step 5: 5. Pick the centre of a plateau

    Choose a value inside the broad region, not its edge or its single best cell.

  6. 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.

  7. 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.

  8. Step 8: 8. Forward test on a demo

    Weeks of live data on your own broker, same version. See forward testing on a demo.

Window 1OptimiseTestWindow 2OptimiseTestWindow 3OptimiseTestWindow 4OptimiseTestJoinedThe record to judge: only the green test periods, end to end
Illustrative only. The strongest version of step 6 is a walk-forward: optimise on a window, test on the next, roll forward, and judge only the joined test periods.

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

  1. MetaTrader 5 Help: Strategy OptimizationHow optimisation and forward testing work in the Strategy Tester.
  2. MetaTrader 5 Help: Strategy TestingThe Strategy Tester: testing modes, settings and forward testing.
  3. 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.