Risk Manager for Trading Robots (Part I): Risk Control Include File for Expert Advisors
Every trader sooner or later faces the bitter truth: success in trading is determined not so much by the ability to find entry points, but by the ability to preserve capital. Statistics are merciless: more than 90% of traders lose their capital due to a lack of effective risk management. Today, we will explore the creation of a professional risk management system for MetaTrader 5, which can transform even the most aggressive strategies into relatively safe earning tools.
Why risk control systems are critical
Let's look at typical reasons for losses in trading, based on general observations and experience working with traders.
In my observations, a significant portion of deposit losses is due to exceeding reasonable daily risk limits. Often, a trader starts the day calmly, but after the first unsuccessful trade, the emotional factor kicks in — the excitement, the desire to win back — and by the end of the day, the deposit can suffer significantly.
Another common cause of losses is the gradual accumulation of drawdowns without proper control. A trader can lose small amounts day after day, convincing themselves that they will "make it back tomorrow", but in the end, the account slowly but surely moves toward zero.
Many traders face a psychological challenge: they may know the rules of risk management, understand the importance of stop losses and position sizing, but when making trading decisions, they do not always apply this knowledge in practice.
It is worth noting that technical problems (communication failures, broker or platform errors) account for a relatively small proportion of the overall causes of losses.
Experience shows that trading accounts without a well-thought-out risk management system tend to have a short life cycle.
There are three classic psychological traps that almost every beginning trader falls into. The first is euphoria after a series of profitable trades. After a few successful market entries, you get the feeling that you have figured out the market, unlocked its secrets. Your inner voice whispers, "I am in the black, I can afford to take more risk!", and the trader increases the lot, ignores stop losses, and opens more positions simultaneously. The result is predictable: in one day the trader loses what took weeks to earn.
The second trap is hoping for a market reversal. The position goes further into loss, the red numbers on the screen become larger, but the trader continues to hold the trade. "It is about to reverse," "It is just a correction," "The market cannot fall forever" — thousands of traders repeat these mantras until a margin call puts an end to their trading careers.
The third trap is the most insidious — ignoring your own rules. A trader creates a trading system, sets clear entry and exit rules, and sets risk limits. But at some point the thought appears: "What could possibly go wrong? It is okay to break my own rules once". Stop losses are disabled, the maximum lot is exceeded, and trades are opened against the trend. This is the path to inevitable collapse, and the trader understands this perfectly well, but cannot stop.
Technical solution: Enhanced Risk Manager
After many years of observing these problems, I decided to create a universal risk control system for MetaTrader 5. The main idea was to fully automate risk management and eliminate the human factor. The system is implemented as an include file, allowing it to be easily integrated into any existing trading strategy without major code rework.
The system architecture was developed with modularity and extensibility in mind. Each component is responsible for its own area of control, but all modules are closely integrated with each other. The EnhancedRiskManager.mqh file contains the main class with a full set of functions for risk management.
#property copyright "Copyright 2025, Evgeniy Koshtenko" #property link "https://www.mql5.com/en/users/koshtenko" #property version "2.0" #property description "Enhanced Risk Manager with Visual Panel" #include <Trade\Trade.mqh>
The system supports various operating modes, from conservative to aggressive. This allows the trader to choose the appropriate risk level depending on their experience, deposit size, and psychological preparedness for drawdowns. Each mode has its own preset parameters, which have been optimized based on the analysis of thousands of real trading accounts.
enum ENUM_TRADING_MODE { MODE_CONSERVATIVE, // Conservative mode MODE_MODERATE, // Moderate mode MODE_AGGRESSIVE, // Aggressive mode MODE_CUSTOM // Custom mode };
The conservative mode is designed for novice traders and those who value stability over high returns. In this mode, the maximum daily drawdown is limited to 2%, the total drawdown cannot exceed 6%, and the risk per trade is only 1%. These parameters virtually eliminate the risk of blowing up an account, giving traders time to learn and adapt to the market.
Moderate mode is the golden mean for experienced traders. The daily drawdown can reach 5%, the overall drawdown – 10%, and the risk per trade is increased to 2%. These parameters provide a good balance between potential profitability and capital safety. Most professional traders operate with similar settings.
Aggressive mode is designed for those who are willing to take risks for high profits. The daily drawdown can reach 10%, the overall drawdown — 20%, the risk per trade — 3%. These parameters require nerves of steel and a lot of experience, but can deliver impressive returns when used correctly.
I paid special attention to the risk calculation system. There are several approaches to assessing drawdown, and each has its own advantages and disadvantages. Some traders prefer to calculate drawdown only from the balance, ignoring floating profit or loss. Others focus solely on equity, which gives a more realistic picture. There are also combined approaches, where the worst of two options is taken for calculation.
enum ENUM_RISK_CALC_TYPE { RISK_CALC_BALANCE_ONLY, // Calculation based solely on balance RISK_CALC_EQUITY_ONLY, // Calculation based solely on equity RISK_CALC_COMBINED, // Combined calculation RISK_CALC_ADAPTIVE // Adaptive calculation };
Adaptive calculation is my own development. The system automatically selects the calculation method depending on the current situation. If there are open losing positions, the calculation is based on equity to take into account actual losses. If positions are profitable, or if there are no open trades, the system uses balance. This approach ensures maximum protection in dangerous situations and reasonable freedom in favorable situations.
The heart of the system is the CEnhancedRiskManager class, which controls absolutely all aspects of risk management. It stores information about the starting balance, current drawdowns, the number of open trades, timestamps, and much more. The class is designed to be completely self-contained — once initialized, it requires no external management.
CEnhancedRiskManager main class architecture
The class implements the principles of object-oriented programming with a clear division of responsibility between components:
class CEnhancedRiskManager { private: // Main parameters ENUM_TRADING_MODE m_tradingMode; ENUM_RISK_CALC_TYPE m_riskCalcType; double m_startingBalance; double m_dailyStartBalance; double m_dailyStartEquity; double m_weeklyStartBalance; double m_weeklyStartEquity; // Risk limits (in %) double m_maxDailyLoss; double m_maxTotalLoss; double m_maxWeeklyLoss; double m_maxTradeRisk; double m_trailingStopPercent;
The class constructor automatically configures all parameters depending on the selected trading mode. This eliminates the need for traders to manually enter dozens of settings and prevents potential errors. All values have been carefully selected based on the analysis of successful trading strategies and recommendations of leading traders.
Initialization of the system is performed by a single call to the Initialize() method. The method performs a comprehensive check of the environment, configures all internal variables, creates a visual dashboard, and loads a saved state if the system has been used before. Particular attention has been paid to error handling — if something goes wrong, the trader will receive a clear message about the problem.
bool CEnhancedRiskManager::Initialize(double startBalance = 0) { // Define the starting balance if (startBalance <= 0) { m_startingBalance = AccountInfoDouble(ACCOUNT_BALANCE); } else { m_startingBalance = startBalance; } // Check validity if (m_startingBalance <= 0) { Print("❌ RISK MANAGER: Invalid starting balance"); return false; }
The main risk validation loop runs on every tick. It consistently checks all parameters, updates metrics, analyzes violations and, if necessary, blocks trading or closes dangerous positions. All this work happens in a split second, without creating a noticeable load on the system.
The warning system is particularly interesting. Instead of simply blocking trading when the limit is reached, the system warns the trader in advance of approaching the danger zone. When 80% of the daily drawdown limit is reached, a yellow warning appears. At 90%, it becomes orange. If the limit is exceeded, trading is blocked completely, and all open positions are automatically closed.
The safe position opening method integrates all checks into one simple function. The trader does not need to worry about risks — all they need to do is call the OpenPosition() method, and the system will automatically check all limits, calculate the acceptable position size, and execute the trade only if it is safe.
One of the key features of the system is the preservation of state when the terminal is restarted. All important data is stored in MetaTrader global variables with unique prefixes for each account. This means that even after restarting your computer or updating your EA, the system knows exactly how many trades were opened today, what the current drawdown is, and whether any limits have been violated.
// In the EA: check before opening if(!RiskManager.CanOpenPosition(lotSize, Symbol())) { return false; // Block a dangerous operation }
Practical application: Taming the martingale
To demonstrate the real capabilities of the system, I decided to conduct an extreme test. The most dangerous type of strategy was chosen for testing: an aggressive grid with a martingale. This is a strategy where after each losing trade, the size of the next position increases. Theoretically, this allows you to recoup all losses with one profitable trade. In practice, this is a direct path to losing your deposit.
The AggressiveGridEA, created for testing, had all the hallmarks of a killer strategy. Martingale with a multiplier of 1.5 meant that each subsequent position in the grid was opened with a lot one and a half times larger. The grid step was only 200 points, which led to the frequent opening of new positions. The EA was able to hold up to 8 positions simultaneously. If the drawdown exceeded 1.5%, the aggressive restoration mode with lot doubling was enabled. And most importantly, there were no stop losses.
This configuration without a risk control system leads to the loss of the deposit in 100% of cases. This is not an exaggeration - I tested the EA on 9 years of data, and without Risk Manager, the account never survived longer than a week.
Integration with the control system turned out to be surprisingly simple. It only took adding a few lines of code in key parts of the EA. Before opening each position, the EA now asked the Risk Manager for permission. If the system considered the trade too risky, the position was not opened.
Test results

The test results exceeded all expectations. Without a control system, the average account lifespan was only 3.2 days. The maximum drawdown reached 100% - this is a complete loss of the deposit. All tests ended with a margin call.
With Enhanced Risk Manager, the picture has changed dramatically. The account remained profitable throughout the full 9-year test period. The maximum daily drawdown was 4.8%, just below the established limit of 5%. The maximum overall drawdown reached 9.7%, without exceeding the critical level of 10%. And the most amazing thing is that the final profit was 127% for the entire period.
How did the system manage to tame such a monster? Firstly, preventing the opening of dangerous positions. When the size of a grid position approached the limit of 2% per trade, the system blocked it. This prevented the uncontrolled escalation of losses.
Secondly, automatic closing in case of critical drawdown. When the daily drawdown reached 4.5%, the system forcibly closed all positions, leaving a small reserve until the critical level. This made it possible to avoid a complete blocking of trading and provided the opportunity to recover the next day.
Third, limiting aggressive recovery behavior. The function of doubling positions in case of losses only worked within the general risk limits. As soon as the total risk approached a dangerous level, the function was automatically disabled.
And finally, protection of the profits. Upon reaching 3% daily profit, a special trailing stop mechanism was activated, which protected part of the earnings from a possible rollback. This made it possible to lock in profits even on days with high volatility.
For comparison, here is the same EA tested without oversight from our vigilant risk manager:

Protection mechanisms in action
The system has demonstrated the efficiency of all protection levels:
- Preventing the opening of dangerous positions: when the risk limit per trade approached (2%), the system automatically blocked opening new grid levels preventing loss escalation.
- Automatic close during critical drawdowns: when reaching 4.5% of the daily drawdown the system forcibly closed all positions, leaving a small reserve until the critical level of 5%.
- Aggressive recovery control: position doubling function during losses was limited by general risk restrictions preventing catastrophic losses.
- Daily profit trailing stop: when the profit reached 3%, a protective mechanism was activated, locking in part of the profit during a rollback.
Conclusions from practical testing
Tests on an aggressive grid EA convincingly demonstrated the efficiency of Enhanced Risk Manager under the most extreme conditions. The system not only prevented catastrophic losses, but also allowed the strategy to remain profitable within the framework of strict risk control.
Of particular value is the fact that the system operates completely automatically, without requiring trader intervention in critical situations. This is especially important for grid strategies, where human emotions often lead to wrong decisions in stressful situations.
Test results confirm that Enhanced Risk Manager can tame even the most aggressive trading strategies!
Conclusion
The developed Enhanced Risk Manager system represents a comprehensive solution to the problem of risk management in trading. It fully automates risk control, eliminating the human factor and emotional decisions. Practical tests on the most dangerous strategy — the Martingale grid — convincingly demonstrated the system's efficiency even under extreme conditions.
Professional trading starts with professional risk management. You can have the best entry point strategy, but without proper risk management, it will sooner or later lead to the loss of your deposit. Enhanced Risk Manager takes care of all the routine risk management tasks, allowing traders to focus on market analysis and decision-making.
The system is publicly available, and anyone can use it in their trading. The code is written with detailed comments, making it easy to understand the logic and, if necessary, adapt it to your needs. Start with the conservative mode, gradually increasing risks as you gain experience. Keep in mind that capital preservation is more important than immediate profit.
Translated from Russian by MetaQuotes Ltd.
Original article: https://www.mql5.com/ru/articles/18918
Warning: All rights to these materials are reserved by MetaQuotes Ltd. Copying or reprinting of these materials in whole or in part is prohibited.
This article was written by a user of the site and reflects their personal views. MetaQuotes Ltd is not responsible for the accuracy of the information presented, nor for any consequences resulting from the use of the solutions, strategies or recommendations described.
Persistent Key-Value Store in MQL5: Using Flat Files as a Lightweight Database for EA State
MQL5 Wizard Techniques you should know (Part 99): Using a KD-Tree and an Echo State Network in a Custom Money Management Class
Engineering a Self-Healing Expert Advisor in MQL5 (Part 4): Trade-State Reconciliation and Safe Mode Recovery
Automating Classic Market Methods in MQL5 (Part 2): Wyckoff Cause and Effect—Point and Figure Price Targets
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
You agree to website policy and terms of use
Hello, thank you for your work!
However, I would like to see the class code corresponding to the one described in the article, for example
In the article:
In the attached file:
enum ENUM_RISK_CALC_TYPE {
RISK_CALC_BALANCE_ONLY, // Only Balance
RISK_CALC_EQUITY_ONLY, // Only Equity
RISK_CALC_BALANCE_EQUITY, // Balance/Equity (US Prop Style)
RISK_CALC_PROP_STANDARD // Standard Prop Company Rules
};
The ‘adaptive calculation’ mentioned in the article is not reflected in the attached class code at all.
Furthermore, there is an error in the code that prevents the expert advisor from compiling:
// Trading Object
CTrade m_trade;
It should be in the public section:
Please check this.
My compilation isn’t working either; it gets stuck on line 124: 123 // Set the magic number for the trading object
I applied the risk manager to my live Martingale-based expert advisor
Here are the results of the 2025 backtest without the risk manager:
And here are the results with the risk manager’s optimal settings:
As you can see, the maximum drawdown has been halved, whilst profits have quadrupled.