Account-Wide Position Sizing in MQL5: Capping Each New Trade by the Risk Already Open
Contents
- Introduction
- What is already published
- The five caps
- RiskBudget.mqh
- The test script
- A quote for each symbol in Market Watch
- Seven symbols in the Strategy Tester
- A consistency check in Python
- Using it in an EA
- Limitations
- What the checks do not cover
- Conclusion
- Attached files
Introduction
The lot size code in many MQL5 examples answers one question. How many lots lose X money if this stop loss is hit? That question is enough for an EA that holds one position on one symbol. My EAs usually trade several symbols at once, and then the one question is not enough. Before a new entry I also want to know how much money is already at risk in the open positions. I also want to know whether the free margin can carry the new trade and whether the symbol's own volume limits allow it. When the volume comes out smaller than expected, I want to know which of these checks made it smaller.
Until now the sizing in my EAs was a few lines copied into each one, and the copies drifted apart. Some of those copies multiplied the stop distance by SYMBOL_TRADE_TICK_VALUE. On the MetaQuotes-Demo server, that formula asks for 10 times the volume that OrderCalcProfit() gives on XAUUSD and XAGUSD (see the Python consistency check below). I moved the sizing into one include file so that each EA uses the same code.
CRiskBudget takes a symbol, a direction, an entry price, and a stop loss. The class returns a volume and the name of the cap that set it. There are five caps: the risk per trade, what is left of an open risk budget for the whole account, a share of the free margin, SYMBOL_VOLUME_MAX, and SYMBOL_VOLUME_LIMIT. The loss per lot comes from OrderCalcProfit(), with an optional slippage buffer. The commission added to it gives the risk per lot. When the volume is 0, the class reports the reason.
The article walks through the class. It then covers a test script with 30 checks, a script that prints a quote for each Market Watch symbol, and a Strategy Tester EA that trades seven symbols with the class. A short Python script then recomputes the tester results from the CSV files the EA writes, as a consistency check. In the Strategy Tester run on MetaQuotes-Demo, the planned open risk after each of the 195 entries stayed within the 3% budget. The planned open risk is the loss at the stops, measured from the open prices. The realized loss of a stop can be larger, and the budget does not limit it. In the two Strategy Tester runs described below, the budget did not reduce the maximum drawdown.
What is already publishedLot sizing and risk limits are not a new subject on this site. The two closest articles are Part 5 (basket risk) and Part 6 (portfolio risk) of the series by Solomon Anietie Sunday. In Part 5 the demo EA adds up what the stops of the basket legs would cost. However, that basket is one symbol traded by one EA. Part 6 covers the whole account, but it limits the current floating loss and does not use the stop levels. CRiskBudget sizes each new trade by the combined stop loss risk of all positions and pending orders on the account. With its default magic filter, this total includes every symbol, every EA, and manual trades.
The five caps
Each cap turns a limit into a volume. The smallest of the five wins, and it is rounded down to SYMBOL_VOLUME_STEP. If the result is below SYMBOL_VOLUME_MIN, the trade is refused with that cap's name.
| Cap | Volume it allows | Read from |
|---|---|---|
| RISK | risk per trade/risk per lot | AccountInfoDouble(ACCOUNT_BALANCE), OrderCalcProfit() |
| OPEN_RISK | (open risk budget minus open risk)/risk per lot | open positions and pending orders with their stops |
| MARGIN | allowed share of free margin/margin per lot | ACCOUNT_MARGIN_FREE, OrderCalcMargin() |
| VOLUME_MAX | SYMBOL_VOLUME_MAX | the symbol |
| VOLUME_LIMIT | SYMBOL_VOLUME_LIMIT minus the volume already used in that direction | the symbol, open positions, and pending orders |
The loss per lot is the money that OrderCalcProfit() returns for 1 lot from the entry to the stop, moved by the slippage buffer. The risk per lot is that loss plus the commission of both sides. The RISK and OPEN_RISK caps divide money by the risk per lot, and the SRiskQuote structure described below keeps both numbers.
The open risk is the loss the account would take if every open position closed at its stop loss. A pending order with a stop loss counts as if it had been filled first. I measure it from the open price of each position, not from the current price. The risk percentage is a share of the balance, and the balance changes by the loss from the open price. A stop that has been moved past the open price locks in a profit. It counts as 0 when that profit covers the commission still to be paid. A position without a stop has no defined risk. By default the class then refuses each new quote until that position has a stop. The total can't be computed while one of its parts is unknown. The same holds for a position or order whose loss OrderCalcProfit() can't calculate. The class then refuses the quote with the status NO_CALC, and a failed calculation is not counted as 0.
The documentation describes SYMBOL_VOLUME_LIMIT as the maximum aggregate volume of an open position and pending orders in one direction. On the MetaQuotes-Demo server, EURUSD and USDJPY have it at 0. A value of 0 means no limit. AUS200 has 15.
How Quote() decides the volume
The smallest of the five caps wins

Fig. 1. The order of the checks in Quote(): the stop and protection checks first, then the loss per lot, the five caps, the smallest cap, and the minimum volume
RiskBudget.mqh
Two enums describe the result. ENUM_RB_CAP names the cap that set the volume, and ENUM_RB_STATUS says whether the volume can be sent.
//+------------------------------------------------------------------+ //| Caps on the volume of one trade. The smallest one sets it | //+------------------------------------------------------------------+ enum ENUM_RB_CAP { RB_CAP_RISK=0, // risk per trade RB_CAP_OPEN_RISK, // what is left of the open risk budget RB_CAP_MARGIN, // allowed share of the free margin RB_CAP_VOLUME_MAX, // SYMBOL_VOLUME_MAX RB_CAP_VOLUME_LIMIT // SYMBOL_VOLUME_LIMIT minus the volume in use };
//+------------------------------------------------------------------+ //| Result of a quote | //+------------------------------------------------------------------+ enum ENUM_RB_STATUS { RB_OK=0, // the volume can be sent RB_BELOW_MIN, // the smallest cap is below SYMBOL_VOLUME_MIN RB_BAD_STOP, // no stop loss, or a stop on the wrong side RB_NO_CALC, // OrderCalcProfit() or OrderCalcMargin() failed, also for an open position RB_UNPROTECTED // an open position or order has no stop loss };
StatusText() and CapText() return the enumerator name without its RB_ or RB_CAP_ prefix. The logs and the CSV files use that form, for example NO_CALC for RB_NO_CALC.
A quote keeps everything it found. The raw volume of each cap is kept too, before rounding, so an EA or a test can see how close the other caps were.
//+------------------------------------------------------------------+ //| SRiskQuote: everything one quote found | //+------------------------------------------------------------------+ struct SRiskQuote { ENUM_RB_STATUS status; // RB_OK when the volume can be sent ENUM_RB_CAP cap; // the cap that set the volume double volume; // volume to send, 0 when rejected double loss_per_lot; // OrderCalcProfit() loss, entry to the stop plus slippage, 1 lot double cost_per_lot; // commission for both sides, 1 lot double risk_per_lot; // loss_per_lot+cost_per_lot, what 1 lot loses at the stop double risk_money; // allowed loss of one trade double trade_risk; // volume*risk_per_lot double open_risk; // open risk before this trade double budget; // open risk budget in money double margin; // OrderCalcMargin() for the volume double margin_allowed; // free margin this trade may use double caps[RB_CAPS]; // raw volume of each cap, before rounding double tv_ratio; // tick value loss / OrderCalcProfit() loss, 1.0 when they agree int unprotected; // open positions and orders without a stop loss int unpriced; // open positions and orders whose risk could not be calculated };
The class has seven settings. Five setter methods configure them. The risk per trade and the open risk budget are percentages of the balance, and the margin share is a percentage of the free margin. The commission is entered per lot and per side. Brokers quote it both ways, and per side is the smaller unit. The slippage buffer moves the stop further away by that many ticks for the loss calculation only.
The magic filter decides whether the open risk counts all positions on the account or only the EA's own. I leave it at -1, all positions, because the money at risk belongs to the account and not to one EA. The seventh setting decides what happens when a position has no stop. The class has one more field, m_tv_tolerance. The field is not a setting, because it holds the 1% tolerance of the tick value check and has no setter.
//+------------------------------------------------------------------+ //| CRiskBudget: volume of a new trade from the risk per trade, the | //| account's open risk budget, the free margin and the symbol's | //| volume limits, with the loss taken from OrderCalcProfit() | //+------------------------------------------------------------------+ class CRiskBudget { private: double m_risk_pct; // risk per trade, % of balance double m_budget_pct; // open risk budget, % of balance double m_margin_pct; // share of free margin one trade may use, % double m_commission; // commission per lot and side, account currency int m_slip_ticks; // slippage allowed at the stop, in ticks long m_magic; // -1 counts every position, else only this magic bool m_block_unprotected; // reject while a position has no stop loss double m_tv_tolerance; // tolerance of the tick value check, 0.01 is 1% public: CRiskBudget(void); void SetRisk(const double risk_pct,const double budget_pct); void SetMarginShare(const double margin_pct); void SetCosts(const double commission_per_lot_side,const int slippage_ticks); void SetMagic(const long magic); void BlockUnprotected(const bool block); bool Quote(const string symbol,const ENUM_ORDER_TYPE type,const double entry, const double sl,SRiskQuote &q) const; double OpenRisk(int &unprotected,int &unpriced) const; bool TickValueAgrees(const SRiskQuote &q) const; string Describe(const string symbol,const SRiskQuote &q) const; //--- public so that a script can feed it a symbol the server cannot price bool ExposureRisk(const string symbol,const bool buy,const double volume, const double open,const double sl,const bool entry_paid, double &risk) const; //--- the parts below make no terminal calls, so a script can test them static double RoundDown(const double volume,const double step); static double VolumeFor(const double money,const double per_lot); static ENUM_RB_STATUS Resolve(const double &caps[],const double vol_min,const double vol_step, double &volume,ENUM_RB_CAP &cap); static double TickValueRatio(const double tick_value,const double ticks,const double calc_loss); static string CapText(const ENUM_RB_CAP cap); static string StatusText(const ENUM_RB_STATUS status); private: bool IsCounted(const long magic) const; double UsedVolume(const string symbol,const bool buy) const; static bool IsBuy(const ENUM_ORDER_TYPE type); static int StepDigits(const double step); static void ResetQuote(SRiskQuote &q); };
The decision itself
Resolve() is static and reads nothing from the terminal. The function takes the five raw caps and the volume settings. The function returns the status, the volume, and the cap that won. On a tie the cap listed first wins, so RISK is reported rather than OPEN_RISK when both allow the same volume.
//+------------------------------------------------------------------+ //| Resolve: the smallest cap, rounded down to the step. On a tie | //| the cap listed first in ENUM_RB_CAP is reported | //+------------------------------------------------------------------+ ENUM_RB_STATUS CRiskBudget::Resolve(const double &caps[],const double vol_min,const double vol_step, double &volume,ENUM_RB_CAP &cap) { cap=RB_CAP_RISK; double smallest=caps[0]; for(int i=1; i<RB_CAPS; i++) { if(caps[i]<smallest) { smallest=caps[i]; cap=(ENUM_RB_CAP)i; } } volume=RoundDown(smallest,vol_step); if(volume<vol_min-1e-8) { volume=0.0; return(RB_BELOW_MIN); } return(RB_OK); }
RoundDown() rounds down to the volume step. The 1e-7 covers a floating-point case. With a step of 0.1, 0.3 divides to 2.9999999999999996, and a plain MathFloor() would turn a valid 0.3 lots into 0.2.
//+------------------------------------------------------------------+ //| RoundDown: largest volume on the step grid not above volume | //+------------------------------------------------------------------+ double CRiskBudget::RoundDown(const double volume,const double step) { if(volume<=0.0 || step<=0.0) return(0.0); //--- the small epsilon keeps 0.3/0.1 at 3 steps instead of 2 double lots=MathFloor(volume/step+1e-7)*step; return(NormalizeDouble(lots,StepDigits(step))); }
The open risk
OpenRisk() walks through the positions and the pending orders. A stop limit order opens at its limit price, not at its trigger price, so OpenRisk() uses the limit price. Orders of the ORDER_TYPE_CLOSE_BY type are skipped. Besides the total, the function returns two counts: the positions and orders without a stop, and those whose loss could not be calculated.
//+------------------------------------------------------------------+ //| OpenRisk: money lost if every counted position and pending order | //| hits its stop, measured from its open price. A stop that locks | //| in a profit counts as 0. unprotected gets the number without a | //| stop and unpriced the number whose loss could not be calculated | //+------------------------------------------------------------------+ double CRiskBudget::OpenRisk(int &unprotected,int &unpriced) const { unprotected=0; unpriced =0; double total=0.0; for(int i=PositionsTotal()-1; i>=0; i--) { if(PositionGetTicket(i)==0 || !IsCounted(PositionGetInteger(POSITION_MAGIC))) continue; double sl=PositionGetDouble(POSITION_SL); if(sl<=0.0) { unprotected++; continue; } bool buy=(PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY); double risk=0.0; if(ExposureRisk(PositionGetString(POSITION_SYMBOL),buy,PositionGetDouble(POSITION_VOLUME), PositionGetDouble(POSITION_PRICE_OPEN),sl,true,risk)) total+=risk; else unpriced++; } for(int i=OrdersTotal()-1; i>=0; i--) { ulong ticket=OrderGetTicket(i); if(ticket==0 || !IsCounted(OrderGetInteger(ORDER_MAGIC))) continue; ENUM_ORDER_TYPE type=(ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE); if(type==ORDER_TYPE_CLOSE_BY) continue; double sl=OrderGetDouble(ORDER_SL); if(sl<=0.0) { unprotected++; continue; } //--- a stop limit order opens at its limit price double open=OrderGetDouble(ORDER_PRICE_OPEN); if(type==ORDER_TYPE_BUY_STOP_LIMIT || type==ORDER_TYPE_SELL_STOP_LIMIT) open=OrderGetDouble(ORDER_PRICE_STOPLIMIT); double risk=0.0; if(ExposureRisk(OrderGetString(ORDER_SYMBOL),IsBuy(type),OrderGetDouble(ORDER_VOLUME_CURRENT), open,sl,false,risk)) total+=risk; else unpriced++; } return(total); }
ExposureRisk() makes one OrderCalcProfit() call for the full volume, from the open price to the stop. The same slippage buffer is applied. A position has paid its entry commission, so the function adds the commission of the exit side only. A pending order has not paid it, so both sides are added. The commission is added before the result is clamped at 0. A stop at breakeven, or slightly in profit, therefore still carries the commission that is left to pay. When OrderCalcProfit() fails, the function returns false and does not report a loss of 0. OpenRisk() then counts the position in unpriced, and Quote() refuses the quote.
//+------------------------------------------------------------------+ //| ExposureRisk: loss of one position or order from its open price | //| to its stop, plus the slippage buffer and the commission still | //| to be paid. A position has paid its entry side (entry_paid), a | //| pending order has not. Returns false when the loss can't be | //| calculated, so that a failure is never counted as 0 | //+------------------------------------------------------------------+ bool CRiskBudget::ExposureRisk(const string symbol,const bool buy,const double volume, const double open,const double sl,const bool entry_paid, double &risk) const { risk=0.0; double tick=SymbolInfoDouble(symbol,SYMBOL_TRADE_TICK_SIZE); double stop=buy ? sl-m_slip_ticks*tick : sl+m_slip_ticks*tick; double money=0.0; if(!OrderCalcProfit(buy ? ORDER_TYPE_BUY : ORDER_TYPE_SELL,symbol,volume,open,stop,money)) return(false); //--- the commission still to be paid is added before the clamp, so a //--- stop at breakeven or slightly in profit can still carry a risk double sides=entry_paid ? 1.0 : 2.0; risk=MathMax(0.0,-money+sides*volume*m_commission); return(true); }
UsedVolume() adds the volume of the positions and the pending orders on the symbol in the direction of the new trade. The sum is the amount that SYMBOL_VOLUME_LIMIT applies to.
//+------------------------------------------------------------------+ //| UsedVolume: position and pending order volume in one direction | //| on the symbol, the amount SYMBOL_VOLUME_LIMIT applies to | //+------------------------------------------------------------------+ double CRiskBudget::UsedVolume(const string symbol,const bool buy) const { double used=0.0; for(int i=PositionsTotal()-1; i>=0; i--) { if(PositionGetTicket(i)==0 || PositionGetString(POSITION_SYMBOL)!=symbol) continue; if((PositionGetInteger(POSITION_TYPE)==POSITION_TYPE_BUY)==buy) used+=PositionGetDouble(POSITION_VOLUME); } for(int i=OrdersTotal()-1; i>=0; i--) { ulong ticket=OrderGetTicket(i); if(ticket==0 || OrderGetString(ORDER_SYMBOL)!=symbol) continue; ENUM_ORDER_TYPE type=(ENUM_ORDER_TYPE)OrderGetInteger(ORDER_TYPE); if(type!=ORDER_TYPE_CLOSE_BY && IsBuy(type)==buy) used+=OrderGetDouble(ORDER_VOLUME_CURRENT); } return(used); }
The quote
Quote() runs the checks in the order of Figure 1. The margin cap needs an additional check at the end. The margin for 1 lot times the volume is only an estimate, because I don't assume that the margin grows exactly in line with the volume on each symbol. After the final volume is chosen, Quote() calls OrderCalcMargin() again for that exact volume. If the result is still over the allowed margin, the volume is scaled down once and checked again. The trade is refused when that second check fails too.
//+------------------------------------------------------------------+ //| Quote: volume for a new trade with this entry and stop loss | //+------------------------------------------------------------------+ bool CRiskBudget::Quote(const string symbol,const ENUM_ORDER_TYPE type,const double entry, const double sl,SRiskQuote &q) const { ResetQuote(q); bool buy=IsBuy(type); if(sl<=0.0 || (buy && sl>=entry) || (!buy && sl<=entry)) { q.status=RB_BAD_STOP; return(false); } double balance=AccountInfoDouble(ACCOUNT_BALANCE); q.risk_money=balance*m_risk_pct/100.0; q.budget =balance*m_budget_pct/100.0; q.open_risk =OpenRisk(q.unprotected,q.unpriced); if(q.unprotected>0 && m_block_unprotected) { q.status=RB_UNPROTECTED; return(false); } //--- a position whose loss is unknown makes the total unknown if(q.unpriced>0) { q.status=RB_NO_CALC; return(false); } //--- loss of 1 lot from the entry to the stop, moved by the slippage buffer ENUM_ORDER_TYPE side=buy ? ORDER_TYPE_BUY : ORDER_TYPE_SELL; double tick=SymbolInfoDouble(symbol,SYMBOL_TRADE_TICK_SIZE); double stop=buy ? sl-m_slip_ticks*tick : sl+m_slip_ticks*tick; double money=0.0; double margin_lot=0.0; if(tick<=0.0 || !OrderCalcProfit(side,symbol,1.0,entry,stop,money) || money>=0.0 || !OrderCalcMargin(side,symbol,1.0,entry,margin_lot)) { q.status=RB_NO_CALC; return(false); } q.loss_per_lot =-money; q.cost_per_lot =2.0*m_commission; q.risk_per_lot =q.loss_per_lot+q.cost_per_lot; q.margin_allowed=AccountInfoDouble(ACCOUNT_MARGIN_FREE)*m_margin_pct/100.0; double limit =SymbolInfoDouble(symbol,SYMBOL_VOLUME_LIMIT); q.caps[RB_CAP_RISK] =VolumeFor(q.risk_money,q.risk_per_lot); q.caps[RB_CAP_OPEN_RISK] =VolumeFor(q.budget-q.open_risk,q.risk_per_lot); q.caps[RB_CAP_MARGIN] =(margin_lot>0.0) ? q.margin_allowed/margin_lot : DBL_MAX; q.caps[RB_CAP_VOLUME_MAX] =SymbolInfoDouble(symbol,SYMBOL_VOLUME_MAX); q.caps[RB_CAP_VOLUME_LIMIT]=(limit>0.0) ? MathMax(0.0,limit-UsedVolume(symbol,buy)) : DBL_MAX; q.tv_ratio=TickValueRatio(SymbolInfoDouble(symbol,SYMBOL_TRADE_TICK_VALUE_LOSS), MathAbs(entry-stop)/tick,q.loss_per_lot); double vol_min =SymbolInfoDouble(symbol,SYMBOL_VOLUME_MIN); double vol_step=SymbolInfoDouble(symbol,SYMBOL_VOLUME_STEP); q.status=Resolve(q.caps,vol_min,vol_step,q.volume,q.cap); if(q.status!=RB_OK) return(false); //--- don't assume the margin grows in line with the volume: check the final volume if(!OrderCalcMargin(side,symbol,q.volume,entry,q.margin)) { q.status=RB_NO_CALC; q.volume=0.0; return(false); } if(q.margin>q.margin_allowed) { q.cap =RB_CAP_MARGIN; q.volume=RoundDown(q.volume*q.margin_allowed/q.margin,vol_step); if(q.volume<vol_min-1e-8 || !OrderCalcMargin(side,symbol,q.volume,entry,q.margin) || q.margin>q.margin_allowed) { q.status=RB_BELOW_MIN; q.volume=0.0; return(false); } } q.trade_risk=q.volume*q.risk_per_lot; return(true); }
The tick value check at the end doesn't change the volume. It only stores the ratio between the loss the tick value predicts and the loss OrderCalcProfit() gives. TickValueAgrees() is true when the ratio is within 1% of 1.0. I kept the check because it costs one SymbolInfoDouble() call. The class reads SYMBOL_TRADE_TICK_VALUE_LOSS for it. The ratio shows when code that uses the tick value formula would size that symbol differently from the class on this server.
The test script
TestRiskBudget.mq5 checks RoundDown(), VolumeFor(), Resolve(), and TickValueRatio(), which make no terminal calls. The script also checks ExposureRisk(), which calls OrderCalcProfit() on EURUSD and needs a connected account. The fixed cases use numbers from my own symbols. The gold case is a risk of 100 USD against a loss of 1,329 USD per lot.
//+------------------------------------------------------------------+ //| TestResolve: the smallest cap wins and is reported | //+------------------------------------------------------------------+ void TestResolve(void) { double caps[RB_CAPS]; double vol=0.0; ENUM_RB_CAP cap=RB_CAP_RISK; //--- the gold case: 100 of risk, 1,329 per lot, nothing else binds SetCaps(caps,100.0/1329.0,300.0/1329.0,12.0,100.0,DBL_MAX); ENUM_RB_STATUS st=CRiskBudget::Resolve(caps,0.01,0.01,vol,cap); Check(st==RB_OK && cap==RB_CAP_RISK && Same(vol,0.07),"gold: risk cap, 0.07 lots"); //--- two full trades already open, 50 left of a 300 budget SetCaps(caps,100.0/1329.0,50.0/1329.0,12.0,100.0,DBL_MAX); st=CRiskBudget::Resolve(caps,0.01,0.01,vol,cap); Check(st==RB_OK && cap==RB_CAP_OPEN_RISK && Same(vol,0.03),"open risk cap cuts it to 0.03"); //--- budget used up SetCaps(caps,100.0/1329.0,0.0,12.0,100.0,DBL_MAX); st=CRiskBudget::Resolve(caps,0.01,0.01,vol,cap); Check(st==RB_BELOW_MIN && cap==RB_CAP_OPEN_RISK && Same(vol,0.0),"no budget left: rejected"); //--- a stock where the margin binds first SetCaps(caps,222.2,666.6,80.4,10000.0,DBL_MAX); st=CRiskBudget::Resolve(caps,1.0,1.0,vol,cap); Check(st==RB_OK && cap==RB_CAP_MARGIN && Same(vol,80.0),"stock: margin cap, 80 shares"); //--- an index with a maximum deal volume of 5 SetCaps(caps,18.3,54.9,40.0,5.0,DBL_MAX); st=CRiskBudget::Resolve(caps,0.5,0.5,vol,cap); Check(st==RB_OK && cap==RB_CAP_VOLUME_MAX && Same(vol,5.0),"index: volume max 5"); //--- volume limit with 1.2 lots already in use out of 1.5 SetCaps(caps,2.0,6.0,9.0,50.0,0.3); st=CRiskBudget::Resolve(caps,0.01,0.01,vol,cap); Check(st==RB_OK && cap==RB_CAP_VOLUME_LIMIT && Same(vol,0.3),"volume limit leaves 0.3"); //--- the minimum volume already loses more than the risk SetCaps(caps,0.4,1.2,3.0,100.0,DBL_MAX); st=CRiskBudget::Resolve(caps,1.0,1.0,vol,cap); Check(st==RB_BELOW_MIN && cap==RB_CAP_RISK && Same(vol,0.0),"min volume above risk: rejected"); //--- a tie reports the cap listed first SetCaps(caps,0.5,0.5,0.9,10.0,DBL_MAX); st=CRiskBudget::Resolve(caps,0.01,0.01,vol,cap); Check(st==RB_OK && cap==RB_CAP_RISK && Same(vol,0.5),"tie between risk and open risk: RISK"); }
ExposureRisk() has seven checks of its own. A position with a stop has a risk above 0. A pending order carries one more commission side than a position. A stop beyond the open price risks 0. A symbol that the server can't price is reported as unknown, with false returned and the risk left at 0. The last three checks use a commission of 3.50 USD per lot and side on 1 lot. A position with its stop at breakeven risks 3.50 USD, the exit side. A pending order with the same stop risks 7.00 USD, both sides. A stop 0.2 pips in profit locks in 2.00 USD, so the position still risks 1.50 USD.
//+------------------------------------------------------------------+ //| Connected: the terminal is connected and an account is logged in | //+------------------------------------------------------------------+ bool Connected(void) { return(TerminalInfoInteger(TERMINAL_CONNECTED)!=0 && AccountInfoInteger(ACCOUNT_LOGIN)!=0); } //+------------------------------------------------------------------+ //| TestExposure: the risk of one position or order. The checks call | //| OrderCalcProfit() on EURUSD, so they need a connected account | //+------------------------------------------------------------------+ void TestExposure(void) { string symbol="EURUSD"; //--- a terminal started from a command line needs a few seconds to log in for(int wait=0; wait<600 && !Connected() && !IsStopped(); wait++) Sleep(100); if(!Connected() || !SymbolSelect(symbol,true)) { Print("SKIPPED TestExposure: no account connected, or EURUSD is not available"); return; } CRiskBudget rb; rb.SetCosts(3.5,0); double held=0.0,pending=0.0,locked=-1.0,unknown=-1.0; bool ok_held =rb.ExposureRisk(symbol,true,1.0,1.1000,1.0945,true,held); bool ok_pending=rb.ExposureRisk(symbol,true,1.0,1.1000,1.0945,false,pending); Check(ok_held && ok_pending && held>0.0,"a position with a stop has a risk above 0"); Check(Same(pending-held,3.5),"a pending order carries one more commission side than a position"); Check(rb.ExposureRisk(symbol,true,1.0,1.1000,1.1055,true,locked) && Same(locked,0.0), "a stop beyond the open price risks 0"); Check(!rb.ExposureRisk("NO_SUCH_SYMBOL",true,1.0,1.1000,1.0945,true,unknown) && Same(unknown,0.0), "a risk that can't be calculated is reported as unknown"); //--- a stop at breakeven, or 0.2 pips in profit, still loses the commission double even=-1.0,even_pending=-1.0,small=-1.0; Check(rb.ExposureRisk(symbol,true,1.0,1.1000,1.1000,true,even) && MathAbs(even-3.5)<1e-6, "a position with its stop at breakeven risks the exit commission"); Check(rb.ExposureRisk(symbol,true,1.0,1.1000,1.1000,false,even_pending) && MathAbs(even_pending-7.0)<1e-6, "a pending order with its stop at breakeven risks both commission sides"); Check(rb.ExposureRisk(symbol,true,1.0,1.1000,1.10002,true,small) && MathAbs(small-1.5)<1e-6, "a stop 2.00 in profit with 3.50 commission still risks 1.50"); }
The last test runs 5,000 random sets of caps and volume settings and checks four properties. The volume is on the step grid, and it is never above the smallest cap. One more step would break that cap. A trade is refused only when the smallest cap rounds below the minimum volume.
To see whether the tests catch a defect, I introduced three defects, one at a time, into a copy of RiskBudget.mqh. In the first copy RoundDown() rounded to the nearest step instead of down. The test script reported FAIL on five checks. Four were fixed cases: "0.379 rounds down to 0.37", "0.0999 on a 0.1 step is 0", "gold: risk cap, 0.07 lots", and "open risk cap cuts it to 0.03". The fifth was the random property "volume never above the smallest cap". In the second copy ExposureRisk() returned true with a risk of 0 when OrderCalcProfit() failed. That was the behavior of my first version. The check "a risk that can't be calculated is reported as unknown" reported FAIL, and the other 29 checks passed. The third copy restored the previous version of the clamp. That version returned a risk of 0 before it added the commission. The three breakeven checks reported FAIL, and the other 27 checks passed. With the corrected file the script reports 30 passed:
---- TestRiskBudget ---- PASS 0.3 on a 0.1 step stays 0.3 PASS 0.379 rounds down to 0.37 PASS 1.74 on a 0.5 step is 1.5 PASS 0.0999 on a 0.1 step is 0 PASS 7 whole lots stay 7 PASS 100 of risk at 300 per lot PASS budget already used gives 0 PASS no loss per lot gives 0 PASS gold: risk cap, 0.07 lots PASS open risk cap cuts it to 0.03 PASS no budget left: rejected PASS stock: margin cap, 80 shares PASS index: volume max 5 PASS volume limit leaves 0.3 PASS min volume above risk: rejected PASS tie between risk and open risk: RISK PASS gold ratio 0.1 PASS matching tick value gives 1.0 PASS missing tick value gives 0 PASS a position with a stop has a risk above 0 PASS a pending order carries one more commission side than a position PASS a stop beyond the open price risks 0 PASS a risk that can't be calculated is reported as unknown PASS a position with its stop at breakeven risks the exit commission PASS a pending order with its stop at breakeven risks both commission sides PASS a stop 2.00 in profit with 3.50 commission still risks 1.50 PASS 5000 random cases: volume on the step grid PASS 5000 random cases: volume never above the smallest cap PASS 5000 random cases: one more step would break a cap PASS 5000 random cases: rejected only below the minimum volume 30 passed, 0 failed
The 23 checks without terminal calls test my own logic only. The seven ExposureRisk() checks call OrderCalcProfit(). Four of them compare its results with each other. The three breakeven checks compare them with values I computed by hand. Those values assume a USD account and a contract size of 100,000 on EURUSD. Whether OrderCalcProfit() and OrderCalcMargin() return the right money on a given server is a separate question. The Strategy Tester run below gives some evidence on that for seven symbols.
A quote for each symbol in Market Watch
RiskBudgetScript.mq5 builds a buy quote for each symbol in Market Watch, with the stop 0.5% below the Ask, and prints one line per symbol. I run it on a new account or a new server first, because it shows in a few seconds which cap binds on which symbol. The output below comes from my MetaQuotes-Demo account with the default settings: 1% risk, a 3% budget, and 30% of the free margin.
RiskBudget quotes: balance 94624.23, free margin 94624.23, open risk 0.00, without stop 0, not priced 0 symbol status cap volume risk/lot risk margin tick value EURUSD OK RISK 1.68 560.00 940.80 1881.52 ok 1.000 GBPUSD OK RISK 1.43 661.00 945.23 1890.43 ok 1.000 USDCHF OK RISK 1.88 502.00 943.76 1880.00 ok 0.995 USDJPY OK RISK 1.88 502.71 945.09 1880.00 ok 0.995 USDCNH OK RISK 1.88 502.53 944.76 1880.00 ok 0.995 AUDUSD OK RISK 2.71 348.00 943.08 1888.03 ok 1.000 NZDUSD OK RISK 3.37 280.00 943.60 1888.75 ok 1.000 USDCAD OK RISK 1.88 502.70 945.08 1880.00 ok 0.995 USDSEK OK RISK 1.88 502.46 944.62 1880.00 ok 0.995 AMD OK MARGIN 43.00 3.23 138.89 27750.48 ok 1.000 MSFT OK MARGIN 53.00 2.65 140.45 28122.86 ok 1.000 INTC OK MARGIN 252.00 0.56 141.12 28385.28 ok 1.000 NVDA OK MARGIN 119.00 1.18 140.42 28191.10 ok 1.000 XAUUSD OK RISK 0.46 2056.00 945.76 1891.41 DIFFERS 0.100 NVT OK MARGIN 170.00 0.83 141.10 28347.50 DIFFERS 0.010 XAGUSD OK RISK 0.63 1495.00 941.85 1886.09 DIFFERS 0.100 AUS200 OK RISK 3.10 301.67 935.18 1871.78 DIFFERS 0.144 ESP35 OK RISK 8.00 107.29 858.32 1716.81 DIFFERS 0.893
The forex pairs are all capped by RISK. The US stocks are capped by MARGIN. One share of AMD needs about 645 USD of margin. The 946 USD of risk would ask for about 293 shares, while 30% of the free margin pays for 43. Five of the symbols were added to Market Watch by the Strategy Tester runs described in the next section. Three more symbols follow in the output, and I added them for other work. Their rows are left out here. All five are sized from OrderCalcProfit(). However, the tick value check reports DIFFERS for each of those five symbols. On XAUUSD the ratio is 0.100, so code that used SYMBOL_TRADE_TICK_VALUE there would ask for about 4.6 lots instead of 0.46.
The same script with a commission of 3.5 USD per lot and side and a slippage buffer of 10 ticks shows how the costs enter the risk per lot:
RiskBudget quotes: balance 94624.23, free margin 94624.23, open risk 0.00, without stop 0, not priced 0 symbol status cap volume risk/lot risk margin tick value EURUSD OK RISK 1.63 577.00 940.51 1825.55 ok 1.000 GBPUSD OK RISK 1.39 678.00 942.42 1837.58 ok 1.000 USDCHF OK RISK 1.81 521.13 943.25 1810.00 ok 0.995 USDJPY OK RISK 1.83 516.12 944.50 1830.00 ok 0.995 USDCNH OK RISK 1.85 511.04 945.42 1850.00 ok 0.995 AUDUSD OK RISK 2.59 365.00 945.35 1804.45 ok 1.000 NZDUSD OK RISK 3.18 297.00 944.46 1782.33 ok 1.000 USDCAD OK RISK 1.83 516.78 945.71 1830.00 ok 0.995 USDSEK OK RISK 1.85 510.48 944.39 1850.00 ok 0.995 AMD OK MARGIN 43.00 10.33 444.19 27751.77 ok 1.000 MSFT OK MARGIN 53.00 9.75 516.75 28123.39 ok 1.000 INTC OK RISK 123.00 7.66 942.18 13855.95 ok 1.000 NVDA OK RISK 114.00 8.28 943.92 27005.46 ok 1.000 XAUUSD OK RISK 0.45 2073.00 932.85 1850.34 DIFFERS 0.100 NVT OK RISK 119.00 7.93 943.67 19843.25 DIFFERS 0.010 XAGUSD OK RISK 0.60 1552.00 931.20 1796.40 DIFFERS 0.100 AUS200 OK RISK 2.90 315.64 915.36 1751.05 DIFFERS 0.144 ESP35 OK RISK 8.00 115.41 923.28 1716.84 DIFFERS 0.893
On EURUSD the risk per lot goes from 560 to 577 USD. The difference is 7 USD of commission for both sides plus 10 ticks of 1 USD. The stocks show a problem with my own input. A commission per lot is a commission per share on a stock, so 3.5 USD per share adds 7 USD to the risk of each share. INTC, NVDA, and NVT then move from the MARGIN cap to the RISK cap. The 3.5 USD was chosen for forex and is far too high for a share. The input does not know which kind of symbol it is used on. If an EA trades stocks and forex together, it needs a commission per symbol.
Seven symbols in the Strategy Tester
RiskBudgetEA.mq5 is a test driver and has no trading edge. Once a day per symbol, from 10:00 server time on, it opens a position in the direction of the last H1 close against a 50-period moving average. The stop is 0.5% of the price away and the take profit twice that. Stocks wait for their session. When the spread is wider than a fifth of the stop, the EA waits for a later tick.
I added the wait after a run without it (InpMaxSpread=100). In that run the EA sent 56 orders on NVT, and the tester refused 40 of those orders with Invalid stops. In each of the 40 refused orders the spread at the moment of the order was wider than the stop distance. In each of the 16 accepted orders it was narrower. The median spread of the 40 refused orders was 4.31 USD, against a stop distance of about 0.80 USD. The order of the symbols moves by one every day, because the budget goes to whichever symbol asks first.
//+------------------------------------------------------------------+ //| TryEntry: quote and send one trade on symbol k. Returns false | //| when it should try again on a later tick | //+------------------------------------------------------------------+ bool TryEntry(const int k) { string sym=g_sym[k]; int dir=Direction(k); if(dir==0) return(true); MqlTick tick; if(!SymbolInfoTick(sym,tick)) return(false); double size =SymbolInfoDouble(sym,SYMBOL_TRADE_TICK_SIZE); double entry =(dir>0) ? tick.ask : tick.bid; double dist =MathMax(size,MathRound(entry*InpStopPct/100.0/size)*size); //--- a stock opens with a spread wider than the stop, which puts the stop //--- on the wrong side of the closing price, so wait for a normal spread if(tick.ask-tick.bid>InpMaxSpread*dist) return(false); int digits=(int)SymbolInfoInteger(sym,SYMBOL_DIGITS); double sl =NormalizeDouble(entry-dir*dist,digits); double tp =NormalizeDouble(entry+dir*InpRewardR*dist,digits); ENUM_ORDER_TYPE type=(dir>0) ? ORDER_TYPE_BUY : ORDER_TYPE_SELL; //--- the quote decides the volume, or why there is none SRiskQuote q; g_budget.Quote(sym,type,entry,sl,q); g_status_n[q.status]++; uint retcode=0; long pos_id =0; if(q.status==RB_OK) { g_cap_n[q.cap]++; g_worst_use=MathMax(g_worst_use,(q.open_risk+q.trade_risk)/q.budget); bool sent=(dir>0) ? g_trade.Buy(q.volume,sym,entry,sl,tp,"RB") : g_trade.Sell(q.volume,sym,entry,sl,tp,"RB"); retcode=g_trade.ResultRetcode(); if(sent && retcode==TRADE_RETCODE_DONE && HistoryDealSelect(g_trade.ResultDeal())) { pos_id=HistoryDealGetInteger(g_trade.ResultDeal(),DEAL_POSITION_ID); int n=ArraySize(g_pos_id); ArrayResize(g_pos_id,n+1); ArrayResize(g_planned,n+1); ArrayResize(g_pos_sym,n+1); g_pos_id[n] =pos_id; g_planned[n]=q.trade_risk; g_pos_sym[n]=sym; } } Print(g_budget.Describe(sym,q)); if(q.status==RB_OK && retcode!=TRADE_RETCODE_DONE) g_send_fail++; if(g_csv!=INVALID_HANDLE) FileWrite(g_csv,TimeToString(TimeCurrent(),TIME_DATE|TIME_SECONDS),sym,dir>0 ? "buy" : "sell", DoubleToString(entry,digits),DoubleToString(sl,digits), CRiskBudget::StatusText(q.status),CRiskBudget::CapText(q.cap), DoubleToString(q.volume,2), DoubleToString(SymbolInfoDouble(sym,SYMBOL_VOLUME_MIN),2), DoubleToString(SymbolInfoDouble(sym,SYMBOL_VOLUME_STEP),2), DoubleToString(q.loss_per_lot,4),DoubleToString(q.cost_per_lot,4), DoubleToString(q.risk_money,2),DoubleToString(q.trade_risk,2), DoubleToString(q.open_risk,2),DoubleToString(q.budget,2), DoubleToString(q.margin,2),DoubleToString(q.margin_allowed,2), DoubleToString(q.caps[0],8),DoubleToString(q.caps[1],8),DoubleToString(q.caps[2],8), DoubleToString(MathMin(q.caps[3],1e9),2),DoubleToString(MathMin(q.caps[4],1e9),2), DoubleToString(q.tv_ratio,4), DoubleToString(NaiveVolume(sym,entry,sl,q.risk_money),4), (string)retcode,(string)pos_id, DoubleToString(tick.ask-tick.bid,digits)); return(true); }
Each quote goes into a CSV file in Common\Files, accepted or not, together with the volume the usual tick value formula would have asked for. At the end the EA reads the closing deals and writes a second file with each closed position.
| Setting | Value |
|---|---|
| Symbols | XAUUSD, XAGUSD, EURUSD, USDJPY, AUS200, ESP35, NVT |
| Chart | EURUSD H1 |
| Period | 2026.07.01 to 2026.09.19, the end date is not included. The last ticks of the run are from 2026.09.18 |
| Model | Every tick based on real ticks, no execution delay |
| Deposit and leverage | 10,000 USD, 1:100, hedging account |
| Risk per trade | 1% of balance |
| Open risk budget | 3% of balance (main run), 7% (comparison run) |
| Free margin share | 30% |
Without execution delay the run is deterministic. A repeat of the main run with the final files ended with the same balance of 8,203.55 and the same summary lines:
2026.09.18 23:59:56 RiskBudget main: quotes OK 195, BELOW_MIN 112, BAD_STOP 0, NO_CALC 0, UNPROTECTED 0 2026.09.18 23:59:56 RiskBudget main: accepted by cap RISK 110, OPEN_RISK 33, MARGIN 52, VOLUME_MAX 0, VOLUME_LIMIT 0 2026.09.18 23:59:56 RiskBudget main: highest open risk after an entry 99.9% of the budget, 0 sends refused 2026.09.18 23:59:56 RiskBudget main: 128 stop losses, planned 7416.58, lost 7791.46, worst 5.76x of plan
Of 307 quotes, 195 were accepted and 112 refused. No send was refused by the tester. The highest planned open risk after an entry was 99.9% of the budget. The planned budget was used to the edge and was not crossed in this run.
Planned open risk after each entry, as a share of the balance
RiskBudgetEA, seven symbols, 2026.07.01 to 2026.09.18, real ticks, no delay

Fig. 2. Open risk after each of the 195 entries in the 3% run stays at or below the line, while the 7% run reaches 4.86%
Figure 3 shows what decided each quote. On XAUUSD, XAGUSD, and EURUSD most volumes came from RISK. USDJPY was cut by OPEN_RISK in 11 of 19 quotes. Its quote often came later in the day than gold and silver, so it got what was left of the budget. NVT was capped by MARGIN in 52 of 54 quotes. AUS200 was refused 54 times because the budget was full, and ESP35 was refused every day. On ESP35 the minimum volume is 1 lot, and 1 lot with a 0.5% stop loses 109 to 118 USD. That loss is more than 1% of the balance from the first day on. The refusal follows from the settings, and the log line names the cap that refused the trade.
What decided the volume of each quote, 3% run
307 quotes, one per symbol and day

Fig. 3. Stacked bars per symbol: accepted by the risk cap, cut by the open risk cap or the margin, or refused because the budget was used or the minimum volume was above the risk
Did the stops cost what the quotes planned?
For each position closed by its stop loss I compared the realized loss with the trade risk of its quote:
| Symbol | Stop losses | Median realized/planned | Highest | Over 1.10 |
|---|---|---|---|---|
| EURUSD | 9 | 1.000 | 1.04 | 0 |
| USDJPY | 11 | 1.000 | 1.00 | 0 |
| XAUUSD | 33 | 1.004 | 1.48 | 1 |
| XAGUSD | 40 | 1.009 | 2.55 | 2 |
| AUS200 | 4 | 1.018 | 1.02 | 0 |
| NVT | 31 | 1.115 | 5.76 | 18 |
On the CFDs and forex pairs the median realized loss was within 2% of the plan. Three stops went further, during fast moves. NVT is different. Its median stop cost 11.5% more than planned, and 18 of 31 stops were more than 10% over. In the tester, NVT stops filled at the next trade price. On NVT that price was often a few cents past the stop. The 5.76 was a sell of 16 shares at 151.03, opened at 2026.09.17 22:43 with the stop at 151.79. The stop filled at the next session open, at 155.41. The stop didn't limit that loss. The budget couldn't limit it either, because the budget is calculated from the stop distances.
Realized loss of each stop loss against the planned loss, 3% run
128 positions closed by their stop loss, log scale

Fig. 4. Each stop loss as a multiple of its planned loss, per symbol. Most sit at 1.0x, NVT is spread up to 1.8x with one gap at 5.76x
The worst tester day of the main run shows the budget at work. On 2026.07.14 at 10:00 the EA sold XAUUSD and XAGUSD. The EA also bought USDJPY, and the budget cut that trade to the 0.03 lots that were left. EURUSD was already short from the day before. At 15:30 the gold, silver, and EURUSD stops were all hit within 8 seconds:
2026.07.14 10:00:00 XAUUSD OK 0.04 lots, cap RISK, risk/lot 2012.00, trade risk 80.48, open 85.50 of 270.16, tick value DIFFERS (0.100) 2026.07.14 10:00:00 XAGUSD OK 0.06 lots, cap RISK, risk/lot 1455.00, trade risk 87.30, open 165.98 of 270.16, tick value DIFFERS (0.100) 2026.07.14 10:00:00 USDJPY OK 0.03 lots, cap OPEN_RISK, risk/lot 502.67, trade risk 15.08, open 253.28 of 270.16, tick value ok (0.995) 2026.07.14 15:30:01 stop loss triggered #69 sell 0.04 XAUUSD 4023.93 sl: 4044.05 tp: 3983.69 [#72 buy 0.04 XAUUSD at 4044.05] 2026.07.14 15:30:01 deal #72 buy 0.04 XAUUSD at 4053.69 done (based on order #72) 2026.07.14 15:30:01 stop loss triggered #70 sell 0.06 XAGUSD 58.145 sl: 58.436 tp: 57.563 [#73 buy 0.06 XAGUSD at 58.436] 2026.07.14 15:30:01 deal #73 buy 0.06 XAGUSD at 58.888 done (based on order #73) 2026.07.14 15:30:09 stop loss triggered #61 sell 0.15 EURUSD 1.14009 sl: 1.14579 tp: 1.12869 [#74 buy 0.15 EURUSD at 1.14579] 2026.07.14 15:30:09 deal #74 buy 0.15 EURUSD at 1.14579 done (based on order #74)
The three positions had planned losses of 80.48, 87.30, and 85.50 USD, 253.28 USD in total. They lost 427.44 USD, because gold filled 9.64 past its stop and silver 0.452. Several stops hit together is the case that a budget on the planned loss addresses, and the realized loss still exceeded the plan. The budget cut no quote in the 7% run. In that run the same tester day lost 562.44 USD, against 503.69 USD in the main run.
What the two budget runs show
The EA has no edge, so its equity curve is not a test of the sizing module. The checks of the class are the unit tests, the quote log, and the stop comparison above.
I ran the same EA with a 7% budget. Seven symbols at 1% each add up to about 7%, and in this run the budget cut no quote at all (OPEN_RISK 0 times). Both runs see the same ticks, and the budget is the only input that differs. However, the 3% budget changed which entries were taken, so the runs hold different trades. The drawdown and the worst days therefore compare two different portfolios. They do not isolate the effect of the budget rule.
| Run | Entries | Highest planned open risk | Equity drawdown | Worst day |
|---|---|---|---|---|
| 3% budget | 195 | 2.997% of balance | 2,250.21 (22.29%) | -503.69 |
| 7% budget | 243 | 4.857% of balance | 2,091.61 (20.64%) | -562.44 |
In the 3% run the highest planned open risk was 2.997% of the balance, against 4.857% in the 7% run. Figure 5 compares the same calendar days. The figure takes the 10 worst days of the 7% run and shows the 3% run on the same dates. The 3% run lost less on 9 of these 10 dates. On 2026.07.30 it lost 316.08 USD against 301.73 USD. The days still hold different trades. Among the 10 worst days of the 3% run, the 7% run lost less on five dates and more on five. The Python consistency check below shows the printout.
The 10 worst days of the 7% run, with the 3% run on the same dates
Closed result per day in USD, days picked from the 7% run

Fig. 5. Bars for the 10 worst days of the 7% run, each with the 3% run on the same date. The 3% run is less negative on 9 of the 10 dates
In these two runs the 3% budget did not reduce the equity drawdown. The drawdown was 22.29%, against 20.64% in the 7% run. Both runs ended with a loss, which is expected from entries without an edge. The drawdown depends on which trades the budget happened to skip. The difference between the two drawdowns is therefore not a property of the budget. The longest losing streak in the main run report was 22 trades in a row, for -1,425.89 USD. A budget limits what the open stops can lose at the same moment. A long losing streak is many small losses one after another. An EA that needs a drawdown limit needs a separate rule for it, for example a stop after a daily or weekly loss. I did not test such a rule.
A consistency check in Python
The script riskbudget_consistency_check.py checks the CSV files and the arithmetic in them, with the Python 3 standard library only. Its inputs are the values that the EA logged. The script does not call OrderCalcProfit() or OrderCalcMargin(), so it cannot confirm the money that those functions return. I wrote both the rules and the script, so it cannot validate that the rules are correct either.
From the logged caps, the script recomputes the volume, status, and cap of each quote. It checks each trade risk against the volume times the risk per lot. It rebuilds the open risk at each quote from the positions that were open at that moment. It also checks each entry against the budget and compares each stop loss with its plan. Last, it compares the tick value formula with the class on the same quotes. The closed file of a second run, given as a third argument, adds the comparison by calendar day.
quotes: 307, volume/status/cap recomputed differently: 0 accepted: 195, trade risk not volume x loss per lot: 0 open risk, EA vs rebuilt from the files: median diff 0.00, largest 0.04 entries over the budget: 0, highest use 99.9% stop losses, realized / planned: AUS200 4 median 1.018 max 1.02 over 1.10: 0 EURUSD 9 median 1.000 max 1.04 over 1.10: 0 NVT 31 median 1.115 max 5.76 over 1.10: 18 USDJPY 11 median 1.000 max 1.00 over 1.10: 0 XAGUSD 40 median 1.009 max 2.55 over 1.10: 2 XAUUSD 33 median 1.004 max 1.48 over 1.10: 1 tick value volume / OrderCalcProfit volume, median per symbol: AUS200 7.052 ESP35 1.154 EURUSD 1.000 NVT 100.000 USDJPY 1.006 XAGUSD 10.000 XAUUSD 10.000
All 307 quotes came out the same, and so did each trade risk. The open risk the EA saw and the open risk rebuilt from the files differ by 0.04 USD at most. The difference comes from AUS200 and USDJPY, whose profit currency is not USD. The EA converts at the rate of the moment. The script adds up the planned values. In my first version of the EA the caps went into the file with only four decimals. One EURUSD quote then came out as 0.15 lots in Python against 0.14 in the EA. The cap was 0.14999 and printed as 0.1500. The EA value was correct, and the file had too few decimals. The caps are now written with eight decimals.
The next block is the tick value comparison. The ratio of the two volumes is 10 on gold and silver, about 7.05 on AUS200, and 100 on NVT. On ESP35 the ratio is 1.154. ESP35 has EUR as its profit currency, so the tick value of that symbol appears to be in euros and not converted. On EURUSD and USDJPY the two volumes agree. These ratios come from the symbol specifications of MetaQuotes-Demo. I did not check other servers, so the ratios say nothing about the tick value formula on other brokers.
The last block of the printout is the comparison of the two runs by calendar day that the Strategy Tester section describes:
10 worst days of the other run, and this run on the same date: 2026.07.14 other -562.44 this -503.69 2026.08.20 other -422.88 this -291.08 2026.07.10 other -381.93 this -218.07 2026.07.13 other -362.37 this -293.45 2026.09.04 other -310.32 this -112.10 2026.07.30 other -301.73 this -316.08 2026.07.07 other -285.19 this -175.33 2026.09.02 other -269.16 this -174.76 2026.07.27 other -235.88 this -98.20 2026.07.02 other -230.08 this -58.61 this run lost less on 9 of these 10 dates 10 worst days of this run: the other run lost less on 5 dates, more on 5
Volume from the tick value formula against the volume from OrderCalcProfit()
Same quotes of the 3% run, median per symbol, log scale

Fig. 6. Median ratio of the tick value volume to the class volume per symbol: 10 for gold and silver, about 7.05 for AUS200, 100 for NVT, and 1.0 for the forex pairs
Using it in an EA
The class needs three settings in OnInit() and one call before each order. TryEntry() in the Strategy Tester section shows the whole pattern. Build the entry and the stop, call Quote(), send q.volume only when Quote() returns true, and log Describe() in both cases.
Quote() returns false for each refusal. Describe() turns the quote into one log line with the cap, the risk per lot, the trade risk, and the open risk against the budget. I print it for each entry, accepted or not. The cap name in the log answers most of the questions I used to ask about odd lot sizes.
The class doesn't check stop levels, freeze levels, or trading sessions. Those checks belong to a trade request check and not to sizing. A volume that Quote() accepts can therefore still be rejected by the server. The tester run without the spread wait showed this with Invalid stops on NVT. An EA must check the result of its order. The class also does not place the stop. If an EA opens a position and sets the stop afterwards, the open risk is unknown for that moment. The next quote is then refused as UNPROTECTED until the stop is set.
Limitations
All tests and runs used MetaQuotes-Demo on a hedging account. The Strategy Tester runs and the Market Watch quotes used MetaTrader 5 build 6230. The final unit test run used build 6276. The tests cover one server, two builds, one account type, seven tester symbols, and about 2.5 months. They say nothing about other servers or symbols. I have not tested the class on a netting account, although the code handles one position per symbol.
The tester runs have no execution delay. The entries come from a mechanical driver, and the drawdown figures describe this driver, not the class. The realized loss of the stops depends on the tester's fills. On NVT those fills were often past the stop. The commission and the slippage buffer were 0 in the tester runs. They were used only in the Market Watch quotes described above.
The open risk adds up the stops as independent amounts. Two positions that hedge each other still add both stops to the open risk. Two positions that move together count as two separate amounts, as the gold and silver positions did on 2026.07.14. The budget doesn't know about correlation. The open risk also ignores swaps and gaps. The NVT stop at 5.76 times the plan was a gap.
The open risk is measured from the open prices, and the budget is a share of the balance, not of the equity. During a floating loss the equity is below the balance, so the budget allows more new risk than the same share of the equity would. During a floating profit it allows less.
The margin cap uses OrderCalcMargin() for the new trade alone. According to the documentation that function does not take open positions and pending orders into account. The real margin can therefore differ from the estimate, for example with an opposite position on a hedging account or an existing position on a netting account. The MARGIN cap is an estimate, not an exact limit of the free margin. The second OrderCalcMargin() call on the final volume has the same restriction.
The commission is one value for every symbol, in the open risk as well as in the new quote. The Market Watch quotes showed that 3.5 USD per lot is wrong for stocks. An account that holds forex and stocks together therefore gets a wrong risk for one of the two groups. I did not implement a commission per symbol.
The script riskbudget_consistency_check.py uses the caps, the loss per lot, and the trade risk as the EA logged them. The script recomputes the decisions from those values but doesn't call OrderCalcProfit() itself. It rebuilds the open risk from the planned trade risks. On symbols whose profit currency is not USD, its open risk therefore differs from the EA value by a few cents.
What the checks do not cover
- The UNPROTECTED path, the NO_CALC path for an open position, and the pending order part of OpenRisk(). No test or run exercised them. Only ExposureRisk() was tested on its own, on one symbol.
- UsedVolume() and the VOLUME_LIMIT cap. AUS200 has a limit of 15, but that cap never set a volume in these runs.
- Stop levels, freeze levels, and trading sessions. The class does not check them.
- Netting accounts. All runs used a hedging account.
- Execution delay and live fills. The tester runs used no delay, and no live account was used.
- Commission and the slippage buffer in a tester run. Both were 0 there.
- The money that OrderCalcProfit() and OrderCalcMargin() return on other servers and builds. The results above come from MetaQuotes-Demo, build 6230.
- Symbols outside the seven tester symbols and the Market Watch list shown above.
- Drawdown control and trading results. The class sizes trades, and the entry decision stays with the EA.
Conclusion
CRiskBudget answers in one call the questions I used to answer in several places: how much one trade may lose, how much is already at risk, what the margin allows, and what the symbol allows. The class names the cap that decided. In the Strategy Tester run on seven symbols on MetaQuotes-Demo, the planned open risk stayed at or below the 3% budget after each of the 195 entries. On the CFDs and forex pairs the median stop cost was within 2% of the plan. NVT stops cost 11.5% more at the median, and one gap reached 5.76 times the plan. The Python consistency check recomputed the same volume, status, and cap from the logged caps for all 307 quotes of that run.
In the two Strategy Tester runs, the budget did not lower the drawdown. The class limits the planned loss of the stops that are open at the same moment, and I did not build it as a drawdown control. On 2026.07.14 three stops were hit within 8 seconds. Their planned loss was within the budget, but gold and silver filled past their stops, so the realized loss was higher.
To try the class, unpack MQL5.zip into the terminal's data folder. Run TestRiskBudget.mq5 on a chart of a connected account, because its ExposureRisk() checks use EURUSD. Then run RiskBudgetScript.mq5 to see the caps on your own Market Watch. RiskBudgetEA.mq5 runs in the Strategy Tester and writes its CSV files to Common\Files. To recompute a run outside the terminal, run riskbudget_consistency_check.py on those two files with Python 3.
Attached files
| # | Name | Folder | Description |
|---|---|---|---|
| 1 | RiskBudget.mqh | MQL5/Include/RiskBudget/ | CRiskBudget, SRiskQuote, and the two enums |
| 2 | TestRiskBudget.mq5 | MQL5/Scripts/RiskBudget/ | Test script, 30 checks with PASS or FAIL |
| 3 | RiskBudgetScript.mq5 | MQL5/Scripts/RiskBudget/ | A buy quote for each Market Watch symbol |
| 4 | RiskBudgetEA.mq5 | MQL5/Experts/RiskBudget/ | Strategy Tester driver that trades several symbols with the class and writes two CSV files |
| 5 | riskbudget_consistency_check.py | MQL5/Files/RiskBudget/ | Python 3 consistency check that recomputes a run from the two CSV files, and compares two runs by calendar day |
| 6 | MQL5.zip | Unpack into the terminal's data folder | All five files, with MQL5 as the root folder and a RiskBudget subfolder in Include, Scripts, Experts, and Files |
Each MQL5 file compiles with 0 errors and 0 warnings in MetaEditor build 6230. The script riskbudget_consistency_check.py was run with Python 3.
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.