Formula 1 Auto Calculating everything To create a custom optimization criterion using the metrics you've selected (Total Net Profit, Maximum Drawdown, Recovery Factor, Sharpe Ratio, Trade Duration, and Total Trades), you can utilize the `OnTester()` function in MT5. This function is designed to allow you to define and use a custom criterion for optimization based on the values returned at the end of each test pass of your Expert Advisor. Here's a generalized approach on how to set this up based on the concepts detailed in the MQL5 documentation: 1. **Defining the Criterion**: - You will need to calculate a custom value in the `OnTester()` function that ideally combines the metrics you are interested in. The function should return a double value that MT5 will use to rank the performance of each set of parameters tested. 2. **Example Implementation**: - Suppose you want to create a criterion that considers both the Recovery Factor and the Sharpe Ratio, adjusting for the number of trades to favor solutions with fewer trades but high recovery and risk-adjusted returns. The custom criterion might look something like this: ```mql5 double OnTester() { double recoveryFactor = TesterStatistics(STAT_RECOVERY_FACTOR); double sharpeRatio = TesterStatistics(STAT_SHARPE_RATIO); double totalTrades = TesterStatistics(STAT_TRADES); double maxDrawdown = TesterStatistics(STAT_BALANCE_DD_MAX); // Example formula: prioritize high recovery factor and Sharpe ratio while penalizing high trade counts double customValue = (recoveryFactor * sharpeRatio) / (totalTrades * sqrt(maxDrawdown)); return customValue; } ``` 3. **Using the Custom Criterion**: - In the strategy tester settings, you would select "Custom max" as the optimization criterion. This tells MT5 to use the value returned from your `OnTester()` function to determine the best performing parameter set. 4. **Optimization and Analysis**: - Run the optimization and observe the outcomes. Adjust the weights and components of your formula based on the performance and your strategic goals. For instance, you might find that adjusting the impact of Sharpe Ratio or Recovery Factor better aligns with your risk management preferences. This setup enables you to finely tune how the optimization process selects the best parameters for your EA, aligning it closely with your specific risk and reward preferences. For further details and examples, you can refer directly to the MQL5 articles on creating custom optimization criteria here: - [Creating Custom Criteria of Optimization of Expert Advisors](https://www.mql5.com/en/articles/286) - [OnTester - Event Handling - MQL5 Reference](https://www.mql5.com/en/docs/event_handling/ontester) These resources provide comprehensive guides and examples that can help you implement robust optimization criteria. The formula provided in your custom optimization criterion for MetaTrader 5's strategy tester is designed to evaluate trading strategies based on several factors related to profitability, risk, and trading frequency. Here's a breakdown of what each component in the formula means and how they work together: ### Formula Breakdown ```mql5 double customValue = (recoveryFactor * sharpeRatio) / (totalTrades * sqrt(maxDrawdown)); ``` 1. **Recovery Factor**: - This metric measures how much profit the Expert Advisor (EA) generates for each unit of risk taken, as measured by the maximum drawdown. A higher Recovery Factor indicates a more efficient use of risk capital. 2. **Sharpe Ratio**: - The Sharpe Ratio evaluates the risk-adjusted performance of the EA, essentially measuring how much excess return you are receiving for the extra volatility endured by holding a riskier asset. A higher Sharpe Ratio suggests that the returns are compensating well for the risk taken. 3. **Total Trades**: - This is the count of trades executed during the testing period. Generally, fewer trades may indicate a more selective and potentially prudent trading strategy, especially if profitability and good risk management are maintained. 4. **Maximum Drawdown**: - Maximum Drawdown is a measure of the largest single drop from peak to bottom in the portfolio's value, before a new peak is achieved. It provides an indication of the highest amount of loss that the strategy might have taken during the testing period. 5. **Square Root of Maximum Drawdown**: - Taking the square root of the Maximum Drawdown moderates the influence of this variable, reducing the scale of variability and making the formula more balanced. It reduces the penalization effect of larger drawdowns in a nonlinear way, acknowledging risk but not letting a single large drawdown overly skew the results. ### How the Formula Works The formula combines these metrics by multiplying the Recovery Factor with the Sharpe Ratio, which together emphasize high returns adjusted for the risk taken. This product is then divided by the product of the Total Trades and the square root of Maximum Drawdown. - **Multiplying Recovery Factor and Sharpe Ratio** boosts strategies that are both profitable and efficient in risk management. - **Dividing by Total Trades** adjusts for the frequency of trading, favoring strategies that achieve good results with fewer trades. - **Dividing by the Square Root of Maximum Drawdown** further adjusts the score by penalizing strategies with higher potential losses, but in a moderated way that does not overly penalize large drawdowns. ### Overall Purpose This formula aims to find a balance between high profitability, efficient risk management, and operational efficiency. It prioritizes strategies that not only perform well on a risk-adjusted basis (high Sharpe Ratio and Recovery Factor) but also manage to do so with fewer, more effective trades and controlled losses (lower Maximum Drawdown). The use of square root for drawdown helps to ensure that a single, potentially anomalous, large drawdown does not disproportionately affect the strategy's overall evaluation. This formula is particularly useful when you want to maximize efficiency and effectiveness in trading strategies without overly frequent trading or excessive risk. Formula 2 Similar to A Score To optimize your MetaTrader 5 Expert Advisor (EA) using a custom function that takes into account specific trading constraints, you can modify the `OnTester()` function. This function will help ensure that the trades do not exceed the specified boundaries for the minimum and maximum number of trades, average trade duration, and maximum individual trade duration. Here's an example of how you can structure this function to incorporate these parameters: ### Custom `OnTester()` Function Overview The goal is to optimize the strategy ensuring it adheres to set constraints on trading activity and duration, which are: - **Max Trades**: Maximum allowable trades - **Min Trades**: Minimum number of trades to be considered valid - **Average Trade Duration**: Target average duration of trades - **Max Duration Individual Trade**: Maximum duration for any single trade ### MQL5 Code Example Here's how you could write the `OnTester()` function to include these checks: ```mql5 // Define input parameters for optimization limits input int maxTrades = 500; // Maximum number of trades input int minTrades = 10; // Minimum number of trades input double maxTradeDuration = 24; // Maximum duration of a single trade in hours input double targetAvgTradeDuration = 6; // Target average trade duration in hours double OnTester() { // Retrieve statistics double totalNetProfit = TesterStatistics(STAT_PROFIT); double maxDrawdown = TesterStatistics(STAT_BALANCE_DD_MAX); int totalTrades = TesterStatistics(STAT_TRADES); double avgTradeDuration = TesterStatistics(STAT_POSITION_HOLDING_TIME_AVG); // Check if trade constraints are violated if(totalTrades < minTrades || totalTrades > maxTrades) return(0); // Disqualify this parameter set for violating trade count constraints if(avgTradeDuration > targetAvgTradeDuration) return(0); // Disqualify for exceeding average trade duration // Calculate custom optimization criterion double recoveryFactor = totalNetProfit / maxDrawdown;[AS1] double customValue = recoveryFactor; // Simple example, can be expanded with more complex formulas // Further checks can be implemented for maximum individual trade duration // This requires additional logging within the EA's trading logic to track individual trade durations return(customValue); } ``` ### Notes 1. **Trade Duration Checks**: To effectively use trade duration in your optimization, you need to ensure your EA's trading logic logs trade durations accurately. This might involve capturing the time each trade opens and closes and calculating the duration explicitly. 2. **Complex Criteria**: You might want to integrate more complex formulas or additional metrics like the Sharpe Ratio or Sortino Ratio depending on your risk management strategy. 3. **Performance Metrics**: Adjust the formula within `OnTester()` to better reflect your strategic goals, balancing risk and return effectively. 4. **Testing and Validation**: Extensively backtest the EA using historical data to ensure the optimization criteria work as expected under various market conditions. By implementing these modifications, your EA's optimization process will not only focus on improving financial metrics but also adhere to operational constraints, leading to potentially more robust and consistent performance in live trading environments. [AS1]Use built in recovery factor from the report