рджреНрд╡рд╛рд░рд╛ William Harris ┬╖ рдЕрдВрддрд┐рдо рд╕рдореАрдХреНрд╖рд╛
How to Optimize an Expert Advisor in MT5 (without overfitting)
рдЖрдкрдХреЛ рдХреНрдпрд╛ рдЪрд╛рд╣рд┐рдП
- тАв MT5 with the EA installed and a baseline backtest done
- тАв MQL5 Community account (for Cloud Network, optional)
- тАв Spreadsheet for ranking optimization results
рдЪрд░рдг-рджрд░-рдЪрд░рдг рдирд┐рд░реНрджреЗрд╢
рдЪрд░рдг 1: Understand what optimization does
Optimization in MT5 means: run the same EA on the same data N times, each time with a different combination of input parameters, and rank the resulting backtest by a chosen metric (Profit Factor, Net Profit, Sharpe Ratio, etc).
The goal is to find the parameter combination that produced the best historical result. But this is also the source of the danger: pick the absolute best in-sample combination and you have almost always overfit тАФ the EA is now tuned to historical noise rather than market structure, and the live result will be much worse than the optimization predicted.
The correct mental model: optimization tells you which inputs are stable across the search space, not which exact values are best. If a parameter range shows roughly equal results from 50 to 100, anything in that range works live. If only the value 73 works and 72 and 74 both lose money, that parameter is overfit to noise.
рдЪрд░рдг 2: Pick 3тАУ5 parameters to optimize (not 20)
Before launching Optimization, decide which parameters to sweep and which to fix. The rule of thumb is to optimize at most 3тАУ5 parameters per run; with 10+ free parameters the search space explodes combinatorially and overfit becomes nearly certain.
Good candidates to optimize: StopLoss distance, TakeProfit distance, indicator periods (ATR length, MA length), entry threshold values. Bad candidates: Magic Number (no effect on signals), trading session times (use fixed broker hours), notification settings.
On the Inputs tab inside Strategy Tester, tick the 'Optimization' column for each parameter you want to sweep, and set Start / Step / Stop columns. For example: StopLoss 50 / 10 / 200 means the optimizer tries 50, 60, 70, ..., 200 тАФ that's 16 values. Combined with TakeProfit 100 / 10 / 300 = 21 values, the optimizer runs 16 ├Ч 21 = 336 backtests.
рдЪрд░рдг 3: Pick the optimization algorithm
Settings tab has the Optimization dropdown with three options:
'Disabled' тАФ single backtest, no optimization. Default mode.
'Slow complete algorithm' тАФ runs every combination in the search space. Use when combinations тЙд 500. Guarantees finding the absolute best result but scales linearly with combinations. 500 combinations ├Ч 15min per run = 125 hours. Use the Cloud Network for anything beyond a few hundred local-CPU minutes.
'Fast genetic-based algorithm' тАФ uses a genetic algorithm that samples the space evolutionarily. Finishes in 50тАУ200 generations regardless of search space size, but only converges to local optima. Use when combinations > 500. Results are usually within 5% of the global optimum.
For first-time use, default to Slow complete with a small search space (3 parameters ├Ч 5 values each = 125 combinations). Genetic is for serious tuning where you can afford some search-noise.
рдЪрд░рдг 4: Pick the optimization metric
The 'Optimization' parameter at the bottom of Settings is the metric the optimizer maximizes. Options:
'Balance max' тАФ simplest, maximizes ending balance. The classic optimization mistake: an EA that makes $50,000 with $40,000 max drawdown beats an EA that makes $30,000 with $5,000 drawdown, despite being objectively worse risk-adjusted.
'Profit Factor' тАФ gross_profit / gross_loss. Better than Balance Max but ignores trade frequency. An EA with 5 huge winners and 1 small loser shows PF 10 but is statistically meaningless.
'Expected Payoff' тАФ average P&L per trade. Useful but ignores variance.
'Drawdown maximal' (minimize) тАФ minimizes worst-case loss. Conservative.
'Recovery Factor' тАФ net_profit / max_drawdown. Generally the best single metric: balances profitability against risk.
'Custom max' тАФ uses the value returned by the EA's OnTester() function. If the EA exposes a meaningful custom score, use it. Otherwise default to Recovery Factor.
рдЪрд░рдг 5: Set up walk-forward validation
Strategy Tester Settings has a 'Forward' field with three options: No, Custom, Half / Third / Quarter. Pick Half. This splits the date range: first 50% is the optimization window, last 50% is the forward-test window.
The optimizer runs all combinations on the first 50% only. After optimization completes, each .set is re-tested on the second 50% тАФ the forward period the EA never saw during tuning. The 'Forward Result' column in the Optimization Results tab shows the out-of-sample metric.
The critical comparison: rank combinations by In-Sample metric, then look at the Out-of-Sample metric. A robust .set produces similar values in both columns. A overfit .set produces excellent In-Sample and bad (or negative) Out-of-Sample. Discard the latter; keep the former.
рдЪрд░рдг 6: Run the optimization
Click Start. The Strategy Tester now runs every combination. Progress shows as 'Pass X of Y' at the bottom. The Results tab populates as each combination completes.
For genetic optimization, the algorithm runs 50тАУ200 generations of ~100 individuals each. The Generation column shows progress. The Best column shows the current best score.
Do not interrupt a slow-complete optimization mid-run; the search space is mapped out before runtime starts and pausing/resuming sometimes corrupts the result set. For genetic optimization, pausing is safe тАФ the algorithm preserves the population in memory.
While waiting, do not run other heavy applications on the same machine. Each optimization pass uses 1 CPU core; MT5 by default uses 'Cores - 1' to leave headroom for the UI. If you have a dedicated optimization machine, you can configure it to use all cores via Tools тЖТ Options тЖТ Tester.
рдЪрд░рдг 7: Review and filter the optimization results
Results tab shows one row per combination, sortable by every column. Sort by your chosen metric (Recovery Factor descending).
The top 10 results are usually clustered in a narrow region of the search space. Right-click any row тЖТ 'Open Graph' to see the equity curve for that specific .set. Compare the top 3тАУ5 curves visually тАФ pick the one with the smoothest equity progression, not necessarily the highest absolute score.
Filter aggressively: drop any combination where Total Trades < 100 (statistically meaningless), Profit Factor > 3.5 (probably overfit), or Forward Result negative. The .set you want is the one that ranks well in-sample AND well out-of-sample AND has a believable trade count.
Right-click the chosen row тЖТ Save as set. Save it with a descriptive filename. Then run a fresh backtest with the full date range using this .set to confirm the combined in-sample + out-of-sample performance is what you expect.
рдЪрд░рдг 8: Use the MQL5 Cloud Network for large sweeps
For optimization runs that would take more than a few hours locally, use the MQL5 Cloud Network. Settings тЖТ Optimization dropdown тЖТ 'Optimization on MQL5 cloud'.
The Cloud distributes each combination to a different agent (~1000 agents available at peak). Cost is $0.01тАУ0.05 per agent-second; a 10,000-combination sweep typically costs $5тАУ50 and finishes in 5тАУ30 minutes. Billing requires an MQL5 Community account with credit card or PayPal on file.
Cloud agents are sandboxed: the EA must not use Windows DLLs, must not write to disk, must not access the network beyond the Cloud-provided tick stream. Most EAs from reputable vendors are Cloud-compatible. Test once with a 2-combination cloud run before launching a 10,000-combination sweep тАФ failed cloud passes are still billed.
рдмрдЪрдиреЗ рдХреЗ рд▓рд┐рдП рд╕рд╛рдорд╛рдиреНрдп рдЧрд▓рддрд┐рдпрд╛рдБ
- тЬЧ Optimizing 10+ parameters at onceрдареАрдХ рдХрд░реЗрдВ: Cap at 5. More parameters = larger search space = lower confidence in any single optimum. If you need to tune 10 params, do it sequentially in 5-at-a-time rounds.
- тЬЧ Picking the single best result without walk-forward validationрдареАрдХ рдХрд░реЗрдВ: Always split the data 70/30 or 50/50. Discard any .set whose out-of-sample performance is < 70% of the in-sample performance.
- тЬЧ Using Balance Max as the optimization metricрдареАрдХ рдХрд░реЗрдВ: Switch to Recovery Factor or a custom metric. Balance Max biases toward high-leverage / high-drawdown combinations.
- тЬЧ Ignoring Trade Count when filtering top resultsрдареАрдХ рдХрд░реЗрдВ: Drop any .set with < 100 trades. Below that threshold, the metrics are statistically noisy and unreliable.
- тЬЧ Running optimization on a single year then deploying liveрдареАрдХ рдХрд░реЗрдВ: Use minimum 3 years of data for optimization. Single-year results don't see regime changes.
- тЬЧ Trusting genetic optimization on a tiny search spaceрдареАрдХ рдХрд░реЗрдВ: Genetic is for large spaces (>500 combinations). For small spaces use Slow Complete тАФ it gives you the actual best, not an approximation.
рдЕрдХреНрд╕рд░ рдкреВрдЫреЗ рдЬрд╛рдиреЗ рд╡рд╛рд▓реЗ рдкреНрд░рд╢реНрди
How many optimization passes is too many?
Statistical theory: the False Discovery Rate scales with the number of comparisons. At 50,000 passes, even if every parameter were noise, you'd expect ~1000 passes with random PF > 2.0 just from variance. Walk-forward catches the most egregious overfit but doesn't fully prevent it. The robust workflow is: 5,000 passes тЖТ pick top 20 тЖТ walk-forward тЖТ pick top 3 тЖТ live forward-test on demo for 30 days тЖТ deploy the survivor.
Is MT5 optimization the same as machine learning?
Pure-MT5 optimization is hyperparameter search, not learning. For actual ML, most quantitative traders use Python (XGBoost, neural nets) to train on tick data exported from MT5, save the model, then load model predictions from disk inside the MQL5 EA via OnTick тЖТ FileRead. The optimization step in MT5 then tunes the EA's signal threshold and risk parameters around the pre-trained model output.
Why did my genetic optimization stop after 50 generations when I set 200?
Early stopping is configured at the algorithm level and not exposed in MT5's UI. You cannot disable it. If you suspect the genetic ended prematurely, narrow the search space (so the optimum is within easier reach) and re-run. Alternatively, you can run multiple genetic optimizations back-to-back with different random seeds and pool the top results from each.
What is a rolling walk-forward optimization?
Rolling walk-forward is the gold standard for serious EA development because it directly measures how often you need to re-tune the EA to maintain performance. If your EA needs re-optimization every 3 months to stay profitable, that is a meaningful operational cost. If it survives 18-month windows, it is robust. Python orchestration via the MetaTrader5 Python package is the standard implementation.
Roughly how much does an MQL5 Cloud optimization cost?
MetaQuotes prices Cloud agents at $0.01тАУ0.05 per agent-second depending on workload type. A complex M1 backtest takes 3тАУ10 seconds per pass on a cloud agent, so 10,000 M1 passes = 30,000тАУ100,000 agent-seconds = $300тАУ500 max. Settings тЖТ Optimization тЖТ 'Estimate cost' button gives a quote before launching. Always run a 10-pass cloud test first to confirm your EA is Cloud-compatible before launching the full sweep.
Optimization done тАФ how do you validate the winner?
Read the result statistics correctly. Profit Factor, Sharpe, Recovery Factor, and Drawdown each tell a different story тАФ and the headline 'Net Profit' is almost never the right metric.
Continue to: How to read trading statistics тЖТрд╕рдВрдмрдВрдзрд┐рдд рдЧрд╛рдЗрдб

William Harris
FxRobotEasy рдХреЗ рд╕рдВрд╕реНрдерд╛рдкрдХ рдФрд░ рд▓реАрдб рдбреЗрд╡рд▓рдкрд░
рд╢рд┐рдХрд╛рдЧреЛ, USA ┬╖ 2021 рд╕реЗ
- 12+ рд╕рд╛рд▓ рд▓рд╛рдЗрд╡ рдЯреНрд░реЗрдбрд┐рдВрдЧ
- 10+ рд╕рд╛рд▓ MQL5 / MQL4
- 3 рд▓рд╛рдЗрд╡-рд╕рддреНрдпрд╛рдкрд┐рдд Expert Advisors
- 2021 рдореЗрдВ рд╕реНрдерд╛рдкрд┐рдд
тАЬрдореИрдВ рдордзреНрдп рд╡рд┐рджреНрдпрд╛рд▓рдп рд╕реЗ рдХреЛрдб рдХреЗ рд╕рд╛рде рдЪреАрдЬреЗрдВ рдмрдирд╛ рд░рд╣рд╛ рд╣реВрдБред рдореИрдВ рд╡рд┐рд╢реНрд╡рд╡рд┐рджреНрдпрд╛рд▓рдп рд╕реЗ рдЯреНрд░реЗрдб рдХрд░ рд░рд╣рд╛ рд╣реВрдБред рдЙрди рджреЛ рджреБрдирд┐рдпрд╛рдУрдВ рдХрд╛ рдЪреМрд░рд╛рд╣рд╛ тАФ рдПрд▓реНрдЧреЛрд░рд┐рдердо, рдмрд╛рдЬрд╝рд╛рд░, рдФрд░ рдЙрдиреНрд╣реЗрдВ рдЬреЛрдбрд╝рдиреЗ рд╡рд╛рд▓реА рдкреНрд░реМрджреНрдпреЛрдЧрд┐рдХреА тАФ рд╡рд╣ рдЬрдЧрд╣ рд╣реИ рдЬрд╣рд╛рдБ рдореИрдВрдиреЗ рдкрд┐рдЫрд▓реЗ рдкрдВрджреНрд░рд╣ рд╡рд░реНрд╖ рдмрд┐рддрд╛рдП рд╣реИрдВред FxRobotEasy рддрдм рд╣реЛрддрд╛ рд╣реИ рдЬрдм рдЖрдк рддрдм рддрдХ рд░реБрдХрдиреЗ рд╕реЗ рдЗрдирдХрд╛рд░ рдХрд░рддреЗ рд╣реИрдВ рдЬрдм рддрдХ рдЖрдкрдиреЗ рдЬреЛ рдХрд▓реНрдкрдирд╛ рдХреА рд╡рд╣ рд╡рд╛рд╕реНрддрд╡ рдореЗрдВ рд▓рд╛рдЗрд╡ рдмреНрд░реЛрдХрд░ рдЦрд╛рддреЗ рдкрд░ рдХрд╛рдо рди рдХрд░реЗредтАЭ