When you optimize an Expert Advisor (EA) in MetaTrader 5, the Strategy Tester runs the EA across many combinations of inputs and sorts them by one number. Whatever that number rewards, the optimizer will find, including results that come from luck, from a handful of trades or from taking more risk.
Most guides focus on which parameters to optimize and over what ranges. This one is about the score itself: what the built-in criteria reward, how each can be gamed, how to write your own criterion in OnTester(), and how to check whether the score you chose picks parameter sets that hold up on data the optimizer never saw.
One point up front: a better criterion makes the search less likely to reward fragile results. It does not make the result robust, and it cannot remove overfitting. Out-of-sample and walk-forward testing still decide whether anything the optimizer found is worth keeping.
What the optimizer actually does
An optimization pass is a backtest with one set of inputs. The tester runs many passes, scores each one with the criterion you selected, and lists them from best to worst. There are two search modes:
- The complete (slow) search runs every combination in the ranges you set. It sees the whole surface, but the number of passes multiplies with every parameter you add.
- The genetic (fast) search starts from a sample of combinations and breeds new ones from the best scorers. It covers large ranges quickly, but it only explores where the score points it, so the score shapes what it finds.
The list of built-in criteria depends on your terminal build. It typically includes maximum balance, profit factor, expected payoff, recovery factor and Sharpe ratio, minimum drawdown, and a custom option that ranks passes by the value your EA returns from its OnTester() function. Our guide to reading an MT5 Strategy Tester report explains how each of these figures is calculated.
How single-number criteria get gamed
Each built-in criterion measures something real. Used alone as the thing to maximize, each also has a way of rewarding the wrong pass.
| Criterion | What it rewards | How it can mislead when maximized |
|---|---|---|
| Balance (net profit) | Total money made | Favours passes that took the most risk or caught one large move. Drawdown is ignored. |
| Profit factor | Gross profit over gross loss | Very high values are easy with very few trades. A pass with no losing trades has no finite value at all. |
| Expected payoff | Average result per trade | Also unstable on few trades, and favours a few large wins. |
| Drawdown (minimum) | Small drawdown | A pass that barely trades has almost no drawdown. One that never trades has none. |
| Recovery factor | Net profit over maximum drawdown | One lucky path with a small drawdown makes the ratio very large. |
| Sharpe ratio | Return relative to variability | Unstable on short records, and says little about rare large losses. |
Hypothetical arithmetic, for illustration only. Imagine two passes. Pass A has 6 trades: 5 wins of 90 and 1 loss of 50, so its profit factor is 450 ÷ 50 = 9.0. Pass B has 300 trades, with gross profit of 13,000 and gross loss of 10,000, so its profit factor is 1.3. Ranked by profit factor, A comes first by a wide margin, yet six trades tell you almost nothing. Our guide to how many trades a backtest needs shows how wide the uncertainty is on samples that small.
Step 1: Separate the rules from the score
Before writing any code, write down what an acceptable pass must look like. Split it into two kinds of requirement.
- Rules (constraints): conditions a pass must meet to be considered at all. For example: at least a minimum number of trades, equity drawdown below a set level, a positive result after realistic costs. For a prop-firm strategy, the firm's daily loss and maximum drawdown limits belong here. Our guide to drawdown metrics explains why equity drawdown is usually the measure to constrain.
- Score (objective): one measure used to rank the passes that meet every rule. It should reward an edge that is both present and measured on enough trades.
Keeping the two apart stops one strong figure from buying its way past a failed rule. A pass with an outstanding profit factor and a drawdown far beyond your limit should not rank above a sound one; it should not rank at all.
Step 2: Write the score in OnTester
When you select the custom criterion, the tester calls your EA's OnTester() function at the end of each pass and ranks passes by the value it returns. Inside it, TesterStatistics() gives you the figures from the pass's report.
A guarded profit-factor score
This sketch applies the rules first, scoring any pass that fails them at zero, then ranks the rest by profit factor, pulled towards 1.0 when the trade count is low.
input int InpMinTrades = 100; // rule: minimum trades (placeholder; set your own)
input double InpMaxDDPct = 20.0; // rule: max equity drawdown, % (placeholder)
double OnTester()
{
double trades = TesterStatistics(STAT_TRADES);
double profit = TesterStatistics(STAT_PROFIT);
double ddPct = TesterStatistics(STAT_EQUITY_DDREL_PERCENT);
double gp = TesterStatistics(STAT_GROSS_PROFIT);
double gl = TesterStatistics(STAT_GROSS_LOSS); // reported as a negative number
// Rules: a pass that fails any of them scores zero
if(trades < InpMinTrades) return 0.0;
if(ddPct > InpMaxDDPct) return 0.0;
if(profit <= 0.0) return 0.0;
if(gl >= 0.0) return 0.0; // no losing trades: too odd to rank
// Score: profit factor, shrunk towards 1.0 when trades are few
double pf = gp / -gl;
double shrink = trades / (trades + InpMinTrades);
return 1.0 + (pf - 1.0) * shrink;
}
Notes on the sketch:
- The shrink factor is one simple choice, not a standard. It means a pass needs more trades to keep the same score. Any penalty that grows as the trade count falls does the same job.
- Exclude the rule inputs from the optimization. If
InpMinTradesandInpMaxDDPctare optimized too, the optimizer will loosen your rules for you. - Choose the thresholds before you look at results, and from your own tolerance or account rules, not from what the best passes happened to achieve.
A trade-level t-statistic
A second option scores the average trade relative to how variable the trades are, scaled by the square root of the trade count. It rises with a larger average edge, with steadier results and with more trades, which is close to what most people actually want a score to reward.
double TradeTStat()
{
if(!HistorySelect(0, TimeCurrent())) return 0.0;
int n = 0;
double sum = 0.0, sumSq = 0.0;
for(int i = 0; i < HistoryDealsTotal(); i++)
{
ulong ticket = HistoryDealGetTicket(i);
long entry = HistoryDealGetInteger(ticket, DEAL_ENTRY);
if(entry != DEAL_ENTRY_OUT && entry != DEAL_ENTRY_INOUT && entry != DEAL_ENTRY_OUT_BY) continue;
double r = HistoryDealGetDouble(ticket, DEAL_PROFIT)
+ HistoryDealGetDouble(ticket, DEAL_SWAP)
+ HistoryDealGetDouble(ticket, DEAL_COMMISSION);
sum += r; sumSq += r * r; n++;
}
if(n < 2) return 0.0;
double mean = sum / n;
double var = (sumSq - n * mean * mean) / (n - 1);
if(var <= 0.0) return 0.0;
return mean / MathSqrt(var / n);
}
You would call TradeTStat() from OnTester() after the same rule checks. Three cautions apply:
- Each closing deal counts as one trade. Partial closes count separately. If your broker also charges commission on the opening deal, add it.
- Results in money mix edge with position size. If the EA's lot size changes a lot over the test, results measured in multiples of the risk taken on each trade, often written R, are a fairer input.
- Use it as a ranking score, not as a significance test. After the optimizer has searched thousands of passes, the best t-statistic is inflated by the search itself. Our guide to spotting an overfit backtest covers why a huge search behind a single winner is a warning sign, and our guide to data-mining bias shows how to measure how much a search flatters its best result.
Step 3: Match the search to the score
The genetic search follows the score, so the score's shape matters.
- Hard zeros create flat ground. If most passes fail a rule and all score zero, a genetic search has little to climb in those regions and can settle early. If that happens, try a softer penalty, such as reducing the score in proportion to how far a pass exceeds the drawdown limit, rather than zeroing it, so failing passes still point towards better ones.
- Spiky scores attract spikes. A score that jumps around between neighbouring inputs leads a genetic search to isolated peaks. Run the genetic search more than once. If repeated runs settle on very different "best" passes, the surface is spiky and the top result is fragile.
- Use a complete search where you can afford it, at least on a coarse grid of the main parameters. It shows the whole surface, including how much of it passes your rules.
Step 4: Don't take the top row
A good score improves the ranking. It does not make the first row the answer. Treat the top of the list as a short list:
- Look at where the top passes sit. If they cluster in one region of the inputs, that region is the candidate. If they are scattered, the score is mostly ranking noise.
- Check the neighbourhood of any candidate. A pass whose neighbours score almost as well is more trustworthy than one surrounded by much weaker results. Our guide to parameter sensitivity shows how to map and score neighbourhoods rather than single cells.
- MT5 can export optimization results. In your terminal build, look for an export option in the results list, so you can analyse every pass rather than the visible top rows.
Step 5: Check the score on data it never saw
The real test of a criterion is whether passes it ranks highly on the optimization period also do better on a later period. The Strategy Tester's Forward setting holds back the end of the date range and reports each pass's forward result separately. Export both, then measure how well the in-sample ranking carries forward.
import pandas as pd
# One row per pass: the score on the optimization period and the same score on the forward period
df = pd.read_csv("optimization_results.csv") # columns: is_score, fwd_score
rho_all = df["is_score"].corr(df["fwd_score"], method="spearman")
top = df.nlargest(50, "is_score")
print(f"Rank correlation, all passes: {rho_all:.2f}")
print(f"Median forward score, top 50: {top['fwd_score'].median():.3f}")
print(f"Median forward score, all: {df['fwd_score'].median():.3f}")
How to read it:
- A rank correlation near zero, or negative, means the in-sample ranking says little about forward behaviour. The score is mostly rewarding noise in the optimization period.
- Top passes that do no better forward than the typical pass point the same way. The selection added nothing.
- Restricting to the top passes narrows the range, which weakens any correlation calculated on them alone. That is why the sketch reports the correlation on all passes and compares the top group's median with everyone's.
Do this check once per criterion you seriously consider, and decide the criterion before you run the final test. Swapping criteria until the forward results look good turns the forward period into part of the optimization. Our guides to out-of-sample testing and walk-forward testing explain how to keep a final period untouched.
Common optimization-criterion mistakes
- Maximizing net profit with lot sizes that grow with the balance. Compounding rewards the passes that took the most risk early.
- No minimum trade count. The top of the list fills with passes that barely traded.
- Optimizing the thresholds in your own criterion. The optimizer relaxes them, and the rules stop being rules.
- Ranking without realistic costs. A score computed without spread, commission and slippage favours high-frequency passes that costs would erase.
- Changing the criterion after seeing forward results. Each swap is another look at the data you were keeping back.
- Trusting the top row. The best pass of thousands is the one most likely to owe its score to luck.
Optimization criterion checklist
- Rules (minimum trades, drawdown limit, positive result after costs) written down before optimizing
- One score chosen to rank the passes that meet every rule
- Rule thresholds excluded from the optimization
- Realistic costs and modelling mode set for every pass
- Complete search on a coarse grid, or several genetic runs compared
- Top passes checked for clustering and stable neighbourhoods, not just the first row
- In-sample ranking compared with forward results on held-back data
- Criterion fixed before the final out-of-sample or walk-forward test
Frequently asked questions
What is a custom optimization criterion in MT5?
It is a score your EA calculates itself. When you choose the custom option, the Strategy Tester calls the EA's OnTester() function at the end of each pass and ranks passes by the value it returns. That lets you combine rules, such as a minimum trade count, with the measure you want to rank by.
Which built-in optimization criterion should I use?
Each one can mislead when used alone: net profit ignores risk, profit factor and expected payoff are unstable on few trades, and minimum drawdown rewards not trading. If you use a built-in criterion, check the trade count and drawdown of every pass you shortlist. A custom criterion lets you build those checks in.
How many trades should my minimum be?
There is no universal number. It depends on how variable the trades are and how small the edge is. Set it before optimizing, high enough that a single trade cannot swing the result, and check the trade count of anything you shortlist.
Does a custom criterion prevent overfitting?
No. It can stop the optimizer from rewarding the most obvious kinds of fragile result, such as passes with very few trades. The search still fits the history it sees, so out-of-sample and walk-forward testing are still needed.
Should I use genetic or complete optimization?
Use the complete search where the number of passes is manageable, because it shows the whole surface. The genetic search suits large ranges, but it follows the score, so run it more than once and treat very different results between runs as a sign the surface is fragile.
Want a second pair of eyes?
Start with our free Sample Stress-Test Report. It walks one anonymized, illustrative strategy through a full stress test, start to finish, so you can see what rigorous validation looks like before you test your own.
Read the Sample Stress-Test ReportWant your own backtest checked? The Strategy Audit + 60-minute call is a paid service at a launch price of £100, credited in full against our build and portfolio offers. You send an MT4/MT5 Strategy Tester report or trade-list CSV; what we can check depends on the files you supply, and walk-forward and parameter sweeps are not included because they need the strategy itself. It is analysis of strategy testing, not investment advice, and does not promise any trading or evaluation outcome. See the Strategy Audit
Disclaimers
CollosoTrading provides educational content and analytical services for retail and professional algorithmic traders. We do not provide regulated investment advice, financial advice, or personal recommendations. Trading derivatives, leveraged products, and CFDs carries a high level of risk and may result in losses exceeding deposits. Past performance, including any verified or unverified historical results referenced on this site, is not indicative of future results. Consult an independent regulated financial adviser before making investment decisions.
All figures are backtests or simulations unless marked LIVE. Hypothetical or backtested performance results have inherent limitations and may not reflect actual trading. No representation is made that any account will or is likely to achieve profits or losses similar to those shown. Individual results vary. Any figures in this article are hypothetical arithmetic for teaching purposes, not results from any strategy or account. We do not guarantee the outcome of any prop firm challenge.