AXIFLARE
AXIFLARE // GUIDESBACKTESTING

How to Optimize an EA in MT5 Without Overfitting

BY AXIFLARE RESEARCHPUBLISHED UPDATED

MetaTrader 5 can test an Expert Advisor repeatedly using different input combinations. This can help identify how strategy behaviour changes as parameters change. But optimization creates a major risk: if enough combinations are tested against the same historical data, some settings may look exceptional partly because they fit that specific historical sample unusually well. This is commonly discussed as overfitting, parameter fitting or over-optimization.

The distinction that matters is this: optimization searches parameter combinations, while validation asks whether the apparent advantage persists outside the data used to select those parameters. Optimization itself does not prove robustness. The highest Net Profit, Profit Factor, Sharpe Ratio, Recovery Factor or final balance is not automatically the best parameter set, and selecting the best historical result does not guarantee future performance. The goal should not be to discover the prettiest historical equity curve. The goal should be to understand whether a strategy behaves reasonably across a range of plausible settings and conditions.

What EA optimization actually does

In MT5 Strategy Tester, optimization performs multiple historical test runs using different combinations of selected EA input parameters. Generically, these may include indicator periods, filters, stop parameters, exit parameters, volatility thresholds and timing settings.

Each run is still a historical simulation under defined testing conditions. For the official functionality, see the MetaTrader 5 Strategy Optimization documentation.

Optimization is not strategy discovery

Optimization cannot turn fundamentally weak strategy logic into robust logic simply by searching enough parameter combinations. A large search space can always produce historically attractive runs.

Optimization should therefore refine a coherent strategy hypothesis, not replace one. The practical sequence is: define the logic first, then use optimization to study how that logic responds to parameter changes.

What is overfitting?

Overfitting occurs when a strategy or parameter set becomes too closely adapted to characteristics of the historical data used to develop or optimize it.

A fitted parameter set may perform impressively on the optimization sample but deteriorate substantially when tested on a different historical period, different broker data, different execution conditions or genuinely new market data.

Performance deterioration does not automatically prove overfitting. It can be evidence that deserves investigation.

Why optimization creates overfitting risk

The more parameter combinations that are evaluated against one historical sample, the greater the opportunity to discover combinations that happen to match quirks of that sample.

  • Too many adjustable parameters.
  • Extremely narrow parameter ranges.
  • Highly specific values.
  • Repeated optimization against the same period.
  • Selecting only the single highest-profit run.
  • Changing logic after repeatedly reviewing failed out-of-sample tests.

There is no universal maximum number of parameters. The risk comes from the relationship between the search, the data and the selection process.

Start with fewer meaningful parameters

Only optimize parameters that have a defensible role in the strategy. Do not optimize every available input merely because MT5 allows it. A parameter should ideally have a reasonable relationship to strategy behaviour.

Restricting the search to meaningful parameters can reduce unnecessary search complexity. It does not automatically guarantee robustness.

Use sensible parameter ranges

For each optimized input, MT5 allows a Start, Step and Stop value. Parameter ranges should be chosen for a reason, not solely to search for extreme historical performance.

An excessively narrow search can hide sensitivity by never testing how behaviour changes outside a small region. An excessively broad search can create a huge search space in which some combinations fit the sample by chance. There are no universal parameter ranges; the defensible range depends on the strategy and the role of the parameter.

Understand the search space

When multiple parameters are optimized together, the number of possible combinations can grow rapidly. A simple mathematical example: if Parameter A has 10 possible values, Parameter B has 10 and Parameter C has 10, together they define 1,000 possible combinations.

This is not an MT5 limit; it is arithmetic. The core lesson is that adding one more optimization variable can dramatically expand the search space, and with it the opportunity to find combinations that fit the historical sample unusually well.

Slow Complete Algorithm

The Slow Complete Algorithm evaluates all possible combinations of the selected optimization parameter values. It is exhaustive for the defined grid: every combination in that grid is evaluated.

The trade-off is computation. As the number of combinations increases, a complete search can require much more time and processing. It is not automatically the better choice for every task; it depends on the size of the search problem. See the MetaTrader 5 Optimization Types documentation.

Fast Genetic Algorithm

MT5 also provides a Fast Genetic Algorithm. Rather than exhaustively evaluating every possible combination, genetic optimization searches the parameter space by repeatedly selecting combinations that perform better according to the chosen optimization criterion.

This can dramatically reduce the number of required optimization passes. But it does not mean every possible parameter combination was tested, and it does not guarantee that the global optimum was found. Genetic optimization is a different search method, not an inaccurate or inferior one.

Complete vs genetic optimization

SLOW COMPLETE VS FAST GENETIC
AREASLOW COMPLETEFAST GENETICIMPORTANT CONTEXT
Search methodAll defined combinationsSelective genetic searchDepends on search-space size
Optimization criterion required for searchNoYesGenetic selection depends on the criterion
SpeedCan be slow on large gridsUsually much fasterDepends on EA and parameter space
Tests every combinationYes, within defined gridNoGenetic algorithm searches selectively
Guarantees robust parametersNoNoValidation is separate

What is an optimization criterion?

An optimization criterion defines how MT5 evaluates parameter sets during genetic optimization. Official built-in criteria include Balance max, Profit Factor max, Expected Payoff max, Drawdown min, Recovery Factor max, Sharpe Ratio max, Custom max and Complex Criterion max.

Choosing any one criterion does not prove strategy quality; it defines what the search is asked to prefer. See the MetaTrader 5 Optimization Types documentation for the official list.

Why maximum profit can be misleading

Selecting the parameter set with the highest historical profit can ignore drawdown, trade sample, equity behaviour, parameter sensitivity, concentration of profit and out-of-sample behaviour.

Highest profit is one observation, not a verdict. It is not “bad”; it is simply insufficient on its own.

Complex Criterion

MetaTrader's Complex Criterion considers multiple components, including the number of deals, drawdown, Recovery Factor, Expected Payoff and Sharpe Ratio. The purpose is to assess a test pass using multiple dimensions rather than a single performance metric.

The Complex Criterion does not eliminate overfitting, and this guide does not attempt to reverse-engineer its internal formula; the official documentation does not require disclosing one. It is an evaluation criterion, not a robustness guarantee.

Custom optimization criteria

MQL5 developers can return a custom optimization criterion through the OnTester() event handler and use Custom max during optimization. This allows a developer to define a project-specific evaluation measure.

A custom criterion is not automatically superior to a built-in one; it simply changes what the search optimizes for. See the MQL5 OnTester documentation.

Do not select only one “winning” pass

A single isolated parameter combination with exceptional results can be less reassuring than a broader region of nearby settings producing reasonably similar behaviour. This idea is discussed as parameter stability, neighbourhood stability or a performance plateau.

There is no mathematical plateau threshold, and plateaus do not guarantee robustness. They are one form of evidence about how sensitive the strategy is to the exact values chosen.

Look for parameter stability

Suppose one parameter produces strong historical results at 19, but results collapse at 18 and 20. That isolated optimum deserves more scrutiny than a broader region where 17, 18, 19, 20 and 21 all behave reasonably.

This is a hypothetical educational example only; it is not associated with any AXIFLARE parameter. The principle is that sensitivity to small parameter changes is information about fragility.

Use 2D and 3D optimization visualization

MT5 can display optimization results graphically in 2D and 3D. These views can help inspect relationships between parameter values and optimization results.

The purpose should be to look for broad behaviour patterns rather than simply the single highest point. Visual smoothness does not prove future robustness. See the MetaTrader 5 Strategy Optimization documentation.

Separate optimization from validation

The historical data used to choose parameters should not be treated as independent evidence that those parameters generalize. A separate validation period provides additional evidence.

In-sample is the historical data used for optimization and parameter selection. Out-of-sample is historical data withheld from parameter selection and used afterward for validation. Out-of-sample testing still uses historical data; it does not use future real-time data.

MT5 Forward optimization

The Forward option in Strategy Tester divides the selected historical date range into two parts. Available splits include 1/2, 1/3, 1/4 and Custom. Optimization is performed on the first part, and selected best runs are then tested on the later historical Forward period.

Importantly, this is still historical data. MT5 Forward is not Live or future market data. For the distinction between historical forward segments and real-time testing, see backtesting vs forward testing an Expert Advisor and the MetaTrader 5 Strategy Optimization documentation.

Which passes go to the Forward period?

According to the current official documentation, with a Slow / full search 10% of the best runs are selected for the Forward period, and with Fast genetic optimization 25% of the best runs are selected.

MT5 documentation also describes a lower-limit mechanism for Forward passes, so the exact number may depend on the total number of runs. It should not be oversimplified as “only exactly 10% or 25% are always tested.”

What a good Forward result means

If a parameter set behaves reasonably in both the optimization period and the withheld historical Forward period, that provides stronger historical evidence than optimization-period results alone.

It does not prove that overfitting is impossible, and it does not guarantee future Live results. It is one additional piece of historical evidence.

What a weak Forward result can tell you

If optimization results are excellent but the withheld Forward segment deteriorates substantially, possible explanations may include parameter fitting, market-regime differences, insufficient sample, strategy instability or sensitivity to the selected dates.

A weak Forward result does not automatically mean the EA is broken. It deserves investigation.

Do not re-optimize until the Forward test looks good

Repeatedly changing parameters, parameter ranges or strategy rules after reviewing the same out-of-sample period can gradually turn that supposedly independent validation period into part of the development process.

Once that happens, it is no longer truly independent evidence. Preserving genuinely unseen data is what gives out-of-sample testing its meaning.

Test multiple historical periods

A parameter set that works only in one narrow historical window may be regime-dependent. Additional historical evaluation can include different years, trending conditions, ranging conditions, and higher- or lower-volatility periods.

These classifications are not always objective, and multi-period success does not guarantee future results. For setting up the underlying tests, see how to backtest an EA in MT5.

Avoid optimizing to one broker dataset only

Historical results may change with the price feed, tick history, spread history, commission assumptions, symbol specifications and execution assumptions. Cross-checking under another plausible data environment can provide information about sensitivity.

This does not mean every EA must produce identical results across brokers. See Every Tick vs Real Ticks and how spread, commission and slippage affect MT5 backtests.

Model execution conditions appropriately

Optimization using unrealistically favorable spread, commission, execution delay or data assumptions can select parameter sets that depend on those assumptions. Testing conditions should reasonably represent the intended environment.

This does not mean intentionally extreme pessimistic assumptions should be used without reason. The goal is plausible, representative conditions.

Keep position sizing consistent

Changing position-sizing logic during optimization can make it difficult to distinguish strategy improvement from risk scaling.

When comparing parameter sets, understand whether differences come from entry/exit behaviour, trade frequency or risk sizing. Otherwise, a “better” result may simply be a larger exposure.

Watch for small trade samples

An optimization pass with an unusually small number of trades may produce impressive statistics based on limited observations. Metrics such as Profit Factor, Sharpe Ratio, Expected Payoff and win rate can be unstable with small samples.

There is no universal minimum number of trades; sample size should be interpreted together with strategy frequency and the length and variety of the tested period. Metric definitions are covered in MT5 backtest metrics.

Profit concentration

A parameter set may look attractive because a large part of its historical result came from one short period, a few unusual trades or one market regime.

Inspect the underlying test rather than only the optimization ranking. How to read an MT5 Strategy Tester report explains what to examine in the detailed report.

Do not optimize every metric at once

Trying to simultaneously maximize profit, win rate, Profit Factor, Sharpe and Recovery Factor while minimizing drawdown, trade duration and loss streaks can create a highly selective optimization problem.

The objective should reflect the strategy's intended behaviour. There is no one universal optimization objective.

Use economic / strategic logic

Parameters should ideally make sense in the context of the strategy. If a value is selected solely because “17 historically worked better than 16 or 18”, with no understanding of why the parameter exists, it deserves additional scrutiny.

This does not mean every mathematical parameter must have a fundamental-market explanation. The point is that unexplained precision is a reason to ask more questions, not an automatic disqualification.

Stress test selected parameter sets

After optimization, consider testing selected candidates under somewhat different plausible assumptions: another historical period, altered trading costs, execution delay, different broker data or slightly different nearby parameter values.

The purpose is to identify sensitivity. There are no universal stress levels; the useful stress test depends on the strategy and its intended environment.

Real-time forward test after historical validation

After historical optimization and out-of-sample validation, a Demo forward test can provide operational evidence as new data arrives. It can help reveal execution behaviour, broker interaction, platform stability and EA configuration problems.

Demo does not equal Live. See backtesting vs forward testing an Expert Advisor for the full distinction.

Walk-forward analysis

Walk-forward analysis repeats a sequence: optimize on one historical window, validate on a later historical window, move both windows forward, and repeat. This provides multiple out-of-sample observations across time.

MT5's normal Forward option is not automatically a complete walk-forward analysis framework, and there is no universal window length.

Common overfitting warning signs

OVERFITTING WARNING SIGNS
SIGNWHY IT DESERVES ATTENTIONWHAT TO CHECK
One isolated parameter peakMay depend strongly on one valueInspect nearby parameter combinations
Excellent optimization / weak forwardMay indicate sample-specific fittingInspect independent period behaviour
Very small trade sampleStatistics may be unstableInspect sample and trade distribution
Large performance change from small parameter changePossible parameter sensitivityTest surrounding values
Only one strong historical periodPossible regime dependencyExamine other periods
Results collapse with plausible cost changesPossible execution/cost sensitivityStress-test trading assumptions
Constant re-optimization of the same validation periodValidation loses independencePreserve genuinely unseen data

No single warning sign proves overfitting. Each is a reason to investigate further.

A practical EA optimization sequence

A PRACTICAL EA OPTIMIZATION SEQUENCE

  1. Define the strategy logic before optimizing.
  2. Choose only meaningful parameters.
  3. Set defensible Start / Step / Stop ranges.
  4. Choose Complete or Genetic optimization based on the search problem.
  5. Choose an optimization criterion that reflects the research objective.
  6. Run optimization on the in-sample period.
  7. Inspect more than the single highest-ranked pass.
  8. Look for parameter stability and reasonable trade samples.
  9. Validate selected candidates on a withheld historical Forward period.
  10. Test additional historical periods where appropriate.
  11. Check sensitivity to costs, data and execution assumptions.
  12. Run a detailed single backtest on selected candidates.
  13. Review the full Strategy Tester report.
  14. Forward test operational behaviour on Demo where appropriate.
  15. Treat all results as evidence, not a guarantee.

Common optimization mistakes

COMMON OPTIMIZATION MISTAKES
MISTAKEWHY IT IS MISLEADINGBETTER APPROACH
Pick highest Net ProfitIgnores risk and stabilityInspect multiple metrics and nearby settings
Optimize every inputUnnecessarily expands search spaceOptimize meaningful variables
Use same data for optimization and validationNo independent historical checkPreserve out-of-sample data
Keep changing settings after seeing forward resultsValidation becomes part of fittingPreserve fresh validation data
Assume genetic tests every combinationGenetic search is selectiveUnderstand search method
Assume Complete optimization prevents overfittingExhaustive search can still fit historySeparate optimization from validation
Assume Complex Criterion prevents overfittingIt is an evaluation criterion, not a robustness guaranteeUse independent validation
Assume Forward means Live dataMT5 Forward uses later historical dataDistinguish historical Forward from real-time testing

Optimization vs validation

OPTIMIZATION VS VALIDATION
STAGEPURPOSEDATAMAIN QUESTION
OptimizationSearch parameter combinationsIn-sample historical dataWhich settings performed best under the selected criterion?
Historical ForwardOut-of-sample historical checkLater withheld historical dataDid selected settings behave reasonably outside optimization data?
Stress TestingSensitivity analysisAlternative plausible conditionsHow dependent are results on assumptions?
Real-Time ForwardOperational observationNew market data as it arrivesHow does the EA behave in the actual platform environment?

No stage guarantees future profitability. Each answers a different question with different evidence.

Optimization and AXIFLARE research

AXIFLARE evaluates historical strategy behaviour using multiple metrics and market periods rather than treating a single optimized result as sufficient evidence.

Published historical results remain simulations and do not guarantee future performance. See the A—Series systems, how to evaluate an XAUUSD Expert Advisor and the Risk Disclosure.

Final perspective

Optimization is a search process, not proof. A parameter set becomes more interesting when it shows reasonable behaviour across nearby settings, outside the optimization sample, across different historical conditions and under plausible trading assumptions.

The goal is not to maximize historical perfection. The goal is to reduce dependence on one specific historical sample while understanding how the strategy responds to changing parameters and conditions. Historical evidence can improve decision-making, but it cannot guarantee future performance. For the metrics referenced throughout this guide, see the MQL5 Testing Statistics reference and balance vs equity drawdown in MT5.

Educational content only. Nothing in this guide constitutes investment advice. Trading involves substantial risk.