著者: 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 創設者兼リード開発者
米国シカゴ · 2021年より
- 12年以上のライブトレーディング
- 10年以上の MQL5 / MQL4 経験
- 3つのライブ検証済み Expert Advisor
- 2021年設立
“私は中学生の頃からコードでものづくりをしてきました。大学時代からトレードを始めました。この2つの世界の交差点 —— アルゴリズム、市場、そしてそれらを結ぶテクノロジー —— が、私が過去15年間を過ごしてきた場所です。FxRobotEasy は、思い描いたものが実際のブローカー口座で動作するまで諦めないと決めたときに生まれるものです。”