i want to optimize an ea in mt5, what is the best option,
Assistant
User
profit factor max, balance max , drowdomn min
Assistant
User
what is the best from profit factor max, balance max , drowdomn min?
Assistant
User
i want to use this for prop fim
Assistant
User
yes
Assistant
When optimizing an Expert Advisor (EA) in MetaTrader 5 (MT5), the goal is to find the best set of input parameters that maximize performance according to your chosen criteria (e.g., profit, drawdown, Sharpe ratio). Here are some best practices and options for optimizing an EA in MT5:
1. Use the Built-in Strategy Tester Optimization
MT5 has a powerful built-in Strategy Tester with optimization capabilities:
Genetic Algorithm Optimization (Recommended):
This is the fastest and most efficient optimization method for EAs.
Instead of testing every possible combination of inputs (which can be huge), it intelligently searches promising areas of the parameter space.
Significantly reduces optimization time without compromising result quality.
To enable it:
In the Strategy Tester window, check the "Optimization" box.
Select "Genetic algorithm" as the optimization method.
Exhaustive (Brute Force) Optimization:
Tests all combinations of input parameters.
Very time-consuming, usually not feasible for many input variables or fine granularity.
2. Set Reasonable Parameter Ranges and Step Sizes
Define sensible minimum and maximum values for each input parameter.
Use appropriate step sizes to balance optimization time and granularity.
Avoid overly wide ranges that waste time testing unrealistic parameter sets.
3. Use Meaningful Optimization Criteria
By default, MT5 optimizes by maximum profit.
You can change the optimization criterion in the Strategy Tester (like Profit Factor, Sharpe ratio, or Custom Objective Function).
This helps optimize for more robust performance instead of just raw profit.
4. Use Forward Testing and Walk-Forward Analysis
Split your historical data into in-sample (for optimization) and out-of-sample (for validation).
Optimize on in-sample data, then validate on out-of-sample period.
This prevents curve-fitting and helps confirm robustness.
5. Use Multi-Currency or Multi-Timeframe Testing if Relevant
MT5 supports multi-currency/multi-symbol EAs.
Define symbols and timeframes in your inputs if your EA supports it, and test relevant combinations.
6. Leverage Multi-Core CPU and Cloud Network
MT5 Strategy Tester uses your CPU cores.
Ensure your PC has multiple cores enabled.
You can also use the MQL5 Cloud Network to run optimizations faster by distributing load across many computers (requires payment for cloud computing units).
Summary: Best Practice for MT5 EA Optimization
Step
Recommendation
Optimization method
Use Genetic Algorithm optimization
Parameter setup
Define tight, realistic ranges with reasonable steps
Criterion to optimize
Use profit factor, Sharpe ratio, or custom metrics
Validation
Use forward testing / out-of-sample validation
Speed-up techniques
Use multi-core + MQL5 Cloud Network if needed
If you want, I can guide you step-by-step on how to set this up in the MT5 Strategy Tester. Would you like that?
When optimizing an EA in MT5, you usually have to select a single optimization criterion (what the tester tries to maximize or minimize), but you want to optimize multiple objectives like:
Profit Factor (maximize)
Balance (maximize)
Drawdown (minimize)
Unfortunately, MT5 Strategy Tester does not directly support multi-objective optimization natively (i.e., optimizing multiple conflicting objectives simultaneously). However, there are ways to approach this effectively:
How to Optimize Multiple Criteria: Practical Approaches
1. Use a Custom Fitness Function in Your EA
You can create a custom fitness function inside your EA or as part of the Strategy Tester inputs.
This function combines the different metrics you want to optimize into a single scalar value.
Example custom score:
mql5
double CustomScore(double profit_factor, double balance, double drawdown)
{
// Example: Weight each factor as you prefer (higher is better except drawdown)
double score = profit_factor * 1000 + balance - drawdown * 1000;
return(score);
}
In the EA's OnTester() function (this is called by MT5 during optimization), you return the custom score. MT5 will maximize this value.
Now, if you optimize using that score, MT5 will maximize the combined metric.
2. Sequential Optimization
Run multiple optimizations focusing separately on each metric (e.g., first optimize max profit factor; next optimize low drawdown).
Then manually compare or filter the best sets of results after each run to pick the best trade-off.
3. Filter Optimization Results Manually
After optimizing for one metric (like balance max or profit factor max), export or review result sets.
Manually filter by additional metrics (e.g., keeping only those with drawdown under a certain percentage).
4. Use Third-Party Tools or Scripts
There are third-party tools/scripts to help perform multi-criteria optimizations or Pareto front analysis on optimization results.
Summary Recommendations
Optimization Priority
How to Implement
Profit Factor max + Balance max + Drawdown min
Implement a custom fitness function in your EA’s OnTester() that combines these with weights
Alternatively
Optimize for Profit Factor max, then filter results by Balance and Drawdown externally
Keep in mind
You can only optimize a single scalar objective at a time in MT5
Example Code Snippet to Implement in Your EA
Add this to your EA:
mql5
double OnTester()
{
double pf = TesterStatistics(STAT_PROFIT_FACTOR);
double balance = TesterStatistics(STAT_BALANCE);
double drawdown = TesterStatistics(STAT_MAX_DRAWDOWN); // Usually in money or pips
// Normalize drawdown by balance or use relative drawdown if needed
double relative_drawdown = TesterStatistics(STAT_MAX_RELATIVE_DRAWDOWN); // percent
// Create custom metric
double score = pf * 1000.0 + balance - relative_drawdown * 1000.0;
return(score);
}
You can adjust weights (1000 here) to emphasize what matters most for your strategy.
If you want, I can also help you create the custom OnTester function or guide you through setting up the MT5 optimization with this. Would that help?
Choosing the "best" metric among Profit Factor max, Balance max, and Drawdown min depends on your trading goals, risk tolerance, and strategy specifics. Here's a detailed comparison to help you decide:
1. Profit Factor (Maximize)
Definition: Ratio of gross profits to gross losses (Profit / Loss).
What it tells you: How much profit you make for each unit of loss.
High Profit Factor means: The system is overall profitable and winning trades outweigh the losing trades by a good margin.
Pros:
Good indicator of strategy quality and efficiency.
Helps filter out unprofitable strategies.
Cons:
Doesn't measure the absolute profit amount.
Can be artificially high if strategy trades very little or has few losing trades.
Does not capture risk or drawdown.
Use if: You want to ensure that your system has a good ratio of wins to losses, focusing on efficiency.
2. Balance (Maximize)
Definition: The net profit generated over the testing period.
What it tells you: How much money your strategy makes on absolute terms.
High Balance means: Your equity has grown substantially.
Pros:
Straightforward measure of profitability.
Cons:
Doesn’t consider risk or drawdowns.
A strategy might generate high profits but with unacceptable risk.
Use if: Your primary goal is maximizing net returns and you accept some drawdown.
3. Drawdown (Minimize)
Definition: The largest drop from peak equity during the test (absolute or relative).
What it tells you: The risk or maximum loss you might experience.
Low Drawdown means: Your strategy preserves capital and is less risky.
Pros:
Measures risk exposure directly.
Important for capital preservation and psychological comfort.
Cons:
A very low drawdown strategy might also have very low profit.
Doesn’t show if the system is profitable overall.
Use if: You want conservative strategies focused on risk management.
Which Is Best?
For balanced traders: None alone is sufficient. Profit factor combined with drawdown is usually the best way to assess quality. You want a high profit factor and a reasonable (low) drawdown.
If you prioritize growth: Choose Balance max but watch drawdown carefully.
If you prioritize risk control: Choose Drawdown min but ensure balance/profitability is acceptable.
Most robust systems: Maintain a Profit Factor > 1.5 with Drawdown below 20-30% (depending on your risk tolerance).
Practical Recommendation
Don’t optimize for one metric blindly. For example:
Maximizing profit factor alone may give very low trades or overfit.
Maximizing balance alone may lead to huge drawdowns.
Minimizing drawdown alone may give very slow or losing strategies.
Where you assign weights according to your preferences.
Summary Table
Metric
Main Focus
Pros
Cons
Use when...
Profit Factor
Efficiency
Shows profitability ratio
Ignores absolute profit/risk
Seeking efficient, risk-adjusted profit
Balance
Growth
Net profit amount
Ignores risk/volatility
Prioritizing maximum net gains
Drawdown
Risk management
Capital preservation
Might limit profits
Prioritizing low risk and drawdown
If you want a good starting point for robust strategy optimization, start with Profit Factor > 1.5-2 and Drawdown < 20%-30%, then check Balance to ensure profits are meaningful.
If you tell me your risk tolerance level or style (aggressive, conservative, balanced), I can help you choose the best metric or custom optimization approach!
If you plan to optimize your EA for a proprietary trading firm (prop firm) evaluation or live trading account, your optimization approach and metric priorities should align with the firm’s risk and performance requirements.
Key Considerations for Prop Firm Optimization
Prop firms usually have strict rules and target metrics, commonly including:
Consistent profitability
Low maximum drawdown (often strict limits, e.g., 5-10%)
Good risk/reward ratios
Stable performance with low volatility
High Sharpe or Sortino ratios (risk-adjusted returns)
What to Optimize for a Prop Firm
Metric
Why Important for Prop Firms
How to Use
Drawdown (minimize)
Prop firms usually require strict drawdown limits. Exceeding drawdowns can lead to immediate disqualification. So low drawdown is mandatory.
Use max drawdown as a hard constraint (filter out any runs over the limit). Or optimize to minimize it.
Profit Factor (maximize)
Ensures your system is profitable on a risk-adjusted basis, not just making random big wins.
Use to prioritize quality and efficiency of trades.
Balance / Net Profit (maximize)
You must be profitable to pass the challenge and scale.
Use to maximize final gains after controlling risk.
Firms want consistent equity growth without big swings.
If possible, add custom metrics for these or at least avoid runs with big equity spikes and drops.
Recommended Approach for Prop Firm EA Optimization
Choose Drawdown Limits According to Prop Firm Rules
For example, if the prop firm rules say maximum drawdown allowed is 10%, filter out any optimization results exceeding 10%.
You can set this as a custom condition or check manually post optimization.
Use a Custom Fitness Function
Since MT5 does not support multi-objective optimization directly, you can build a custom criterion that reflects prop firm needs:
mql5
double OnTester()
{
double pf = TesterStatistics(STAT_PROFIT_FACTOR);
double balance = TesterStatistics(STAT_BALANCE);
double rel_dd = TesterStatistics(STAT_MAX_RELATIVE_DRAWDOWN);
// Penalize results exceeding max allowed drawdown
if(rel_dd > 10.0) // 10% drawdown limit example
return(-1); // Discard bad runs
// Custom score emphasizing profit factor and balance, penalizing drawdown
// Weight factors to tune according to your preference or firm rules
double score = pf * 1000 + balance - rel_dd * 1000;
return(score);
}
Return -1 or a very low value if drawdown breaches firm limits to exclude those runs.
Adjust weights (1000 here) to emphasize what's key for your prop firm.
Focus on Realistic Parameter Ranges
Optimize parameters in reasonable ranges to avoid curve-fitting.
Evaluate results on out-of-sample data to ensure robustness.
Use Forward Testing / Walk-Forward Validation
Always validate optimized parameters on unseen data.
Prop firms usually expect consistent performance, so your strategy must perform well beyond the backtest period.
Supplement with Manual Filtering
After optimization, review results.
Select parameter sets with acceptable drawdown AND good profit factor AND good balance.
Discard overly risky or erratic strategies.
Additional Tips
Talk to your prop firm to verify their exact rules and metrics they value most.
Some firms also monitor maximum daily loss, profit target consistency, or max consecutive losses—you may want to incorporate these in your EA or as filtering criteria.
Avoid high leverage or aggressive parameters that produce outlier profits but risk large equity crashes.
Use genetic algorithm optimization in MT5 for faster optimization when you have many parameters.
Summary: Best Optimization for Prop Firm
Priority
Approach
Max Drawdown ≤ Firm Limit
Hard constraint inside custom fitness function or manual filtering
Profit Factor High (≥1.5-2)
Ensure effective trading with good risk/reward
Balance / Net Profit Positive and Significant
Pass profitability hurdle
Consistency / Risk-Adjusted Returns
Use custom metrics if possible or manual inspection
If you want, I can help you customize your EA’s OnTester() to implement prop firm-specific optimization. Just let me know!
Great! Below is a simple example of how you can implement a custom fitness function in your EA's OnTester() that:
Enforces a maximum relative drawdown limit (e.g., 10%),
Rewards higher Profit Factor,
Rewards higher balance,
Penalizes solutions exceeding drawdown limit by returning a very low fitness value (so that MT5 excludes them),
Uses adjustable weights so you can tune emphasis as needed.
Step-by-Step: Implement Custom Fitness Function in Your EA
1. Open your EA’s source code (.mq5 file)
2. Add or modify the OnTester() function like this:
mql5
double OnTester()
{
// Get tester statistics
double profit_factor = TesterStatistics(STAT_PROFIT_FACTOR); // Profit factor
double balance = TesterStatistics(STAT_BALANCE); // Final balance
double relative_drawdown = TesterStatistics(STAT_MAX_RELATIVE_DRAWDOWN); // Max drawdown in %
// Set maximum relative drawdown allowed by your prop firm (e.g., 10%)
double max_allowed_drawdown = 10.0;
// If drawdown exceeds max allowed limit, discard this run by returning a very low fitness value
if(relative_drawdown > max_allowed_drawdown)
return(-1.0);
// Define weights to emphasize each metric -- adjust these as you like
double weight_pf = 1000.0; // weight for profit factor
double weight_balance = 1.0; // weight for absolute balance
double weight_dd = 1000.0; // penalty weight for drawdown (already filtered, but can add additional penalty if desired)
// Calculate custom fitness score
double score = profit_factor * weight_pf + balance * weight_balance - relative_drawdown * weight_dd;
// Return score (MT5 will try to maximize this during optimization)
return(score);
}
3. Explanation:
TesterStatistics(STAT_PROFIT_FACTOR): Retrieves profit factor from the report.
TesterStatistics(STAT_BALANCE): Retrieves net balance (final equity — initial deposit).
TesterStatistics(STAT_MAX_RELATIVE_DRAWDOWN): Drawdown in percentage relative to balance.
If drawdown exceeds your prop firm’s limit, the function returns -1, forcing MT5 to exclude this parameter set.
The returned "score" combines all three metrics, prioritizing (by weight) what matters most.
MT5 optimization will try to find parameters maximizing this score.
4. How To Use This In MT5 Strategy Tester:
Compile your EA with this OnTester() function.
Open Strategy Tester, load your EA.
Check Optimization box.
Choose Genetic algorithm for speed.
Set your input ranges and steps.
Start optimization.
MT5 will use your custom scoring function to find the best parameters balancing profit factor, balance, and staying within drawdown limits.
Optional Improvements:
You can add other statistics such as STAT_SHARPE_RATIO or custom ones if you want.
You can fine-tune weights based on what you learn from your strategy and prop firm requirements.
You can implement additional hard constraints by returning -1 or 0 if any conditions are violated (e.g., max consecutive loss, max daily loss).
If you want, I can help you extend this code later with other constraints or metrics.
Would you like me to help with:
Setting up input parameters so you can easily experiment with weights and limits?
Adding other metrics?
Creating a filtering script to analyze optimization results?