preview
The MQL5 Standard Library Explorer (Part 19): Developing a Reusable Portfolio Risk Manager

The MQL5 Standard Library Explorer (Part 19): Developing a Reusable Portfolio Risk Manager

MetaTrader 5 — Examples |
84 0
Clemence Benjamin
Clemence Benjamin

Introduction

Per-node position sizing cannot prevent several strategy nodes from committing the same account capacity during one processing cycle. This article builds a portfolio risk authority around Trade\AccountInfo.mqh and its CAccountInfo class, combining account values, managed-position risk, and same-cycle reservations before approving, reducing, or rejecting an entry. In Part 18, we established shared indicator caching; the present step extends that architecture from shared market data to shared risk permission.

Contents
  1. Portfolio Risk Architecture
  2. Modeling Requests, Decisions, and Reservations
  3. Exploring AccountInfo.mqh Through the Risk Authority
  4. Measuring Open and Reserved Risk
  5. Evaluating a New Request
  6. Reserving Capacity Before Execution
  7. Building a Risk-Aware Strategy Node
  8. Routing the Portfolio Cycle
  9. Operating the Expert Advisor
  10. Verification Plan and Recorded Demonstration
  11. Limitations
  12. Conclusion 
  13. Attachments


Portfolio Risk Architecture

The host Expert Advisor (EA) still routes timer and trade events. CRiskPortfolioManager owns the strategy-node collection and coordinates two shared services: the Part 18 indicator cache and the new portfolio risk authority. Each node reads its cached indicators, constructs a proposal, and waits for a decision before reaching CTrade.

The two similarly named classes have different roles throughout the article. CRiskPortfolioManager is the coordinator: it owns nodes and routes portfolio events. CPortfolioRiskManager is the risk authority: it refreshes exposure, evaluates requests, and owns reservations. The shorter phrase “risk authority” always refers to CPortfolioRiskManager.

Fig. 1. Portfolio components, ownership boundaries, and risk-request path

Fig. 1. Portfolio components, ownership boundaries, and risk-request path

Component Responsibility Owned state
CRiskAwareStrategyNode Creates signals and proposed entries Symbol, indicators, bar state, position view, and execution object
CPortfolioRiskManager Measures exposure and applies shared limits Risk policy, account snapshot, counters, and reservations
CRiskReservation Protects capacity promised before execution finishes Node identity, volume, monetary risk, and margin
CIndicatorCache Reuses Standard Library indicator objects Reference-counted moving-average and ATR entries
CAccountInfo Provides current account equity, margin, and free margin Standard Library interface to the active trading account

Standard Library Files Supporting the Application

AccountInfo.mqh is the principal file in this installment. The remaining classes support ownership, indicator reuse, position inspection, and execution without moving portfolio policy back into individual nodes.

File Class Role in the application
Trade\AccountInfo.mqh CAccountInfo Supplies equity, used margin, and free margin to the shared risk policy.
Object.mqh; Arrays\ArrayObj.mqh CObject; CArrayObj Make reservations and nodes storable in owning collections with controlled cleanup.
Trade\PositionInfo.mqh CPositionInfo Keeps owned-position inspection separate from authorization.
Trade\Trade.mqh CTrade Submits approved volume and exposes the server result for checking.
Indicators\Indicator.mqh; Trend.mqh; Oscilators.mqh CIndicator; CiMA; CiATR Retain the shared indicator workflow developed in Part 18.

The architecture contains three different ownership relationships. CArrayObj owns the nodes, the indicator cache owns its entries, and the risk manager owns active reservation objects. Shutdown must release nodes first because they still hold indicator references. The cache and risk reservations can then be cleared safely.

Fig. 2. Decision path from a node proposal to confirmation or release

Fig. 2. Decision path from a node proposal to confirmation or release


Modeling Requests, Decisions, and Reservations

The request, decision, and reservation types form one directional contract: a node proposes, the authority decides, and CArrayObj owns any temporary capacity record. Symbol, magic number, and completed-bar time identify one reservation without coupling the manager to signal logic. Requested and approved quantities remain separate, so volume reduction is visible to the node and the diagnostics.

//+------------------------------------------------------------------+
//| Identifies the outcome of a portfolio risk evaluation            |
//+------------------------------------------------------------------+
enum ENUM_RISK_DECISION_STATUS
  {
   RISK_DECISION_REJECTED=0,
   RISK_DECISION_APPROVED=1,
   RISK_DECISION_REDUCED=2
  };

//+------------------------------------------------------------------+
//| Describes one proposed market entry before risk authorization    |
//+------------------------------------------------------------------+
struct SRiskRequest
  {
   string          symbol;
   ENUM_ORDER_TYPE order_type;
   ulong           magic;
   datetime        bar_time;
   double          requested_volume;
   double          entry_price;
   double          stop_loss;
   double          take_profit;
  };

//+------------------------------------------------------------------+
//| Returns the portfolio decision and approved resource amounts     |
//+------------------------------------------------------------------+
struct SRiskDecision
  {
   ENUM_RISK_DECISION_STATUS status;
   double                    approved_volume;
   double                    risk_money;
   double                    margin_required;
   string                    reason;
  };

//+------------------------------------------------------------------+
//| Holds approved risk while a node submits its trade request       |
//+------------------------------------------------------------------+
class CRiskReservation : public CObject
  {
private:
   string          m_symbol;
   ENUM_ORDER_TYPE m_order_type;
   ulong           m_magic;
   datetime        m_bar_time;
   double          m_volume;
   double          m_risk_money;
   double          m_margin;

public:
                   CRiskReservation(void);
   void            Configure(const SRiskRequest &request,
                             const SRiskDecision &decision);
   bool            Matches(const string symbol,
                           const ulong magic,
                           const datetime bar_time) const;
   string          Symbol(void) const { return(m_symbol); }
   ENUM_ORDER_TYPE OrderType(void) const { return(m_order_type); }
   ulong           Magic(void) const { return(m_magic); }
   double          Volume(void) const { return(m_volume); }
   double          RiskMoney(void) const { return(m_risk_money); }
   double          Margin(void) const { return(m_margin); }
  };

The request includes the symbol, direction, magic number, completed-bar time, proposed volume, entry, stop loss, and take profit. These fields make the proposal traceable and give a reservation a stable identity. These fields alone do not make the decision reproducible. The result also depends on account values, managed positions, existing reservations, symbol properties, and broker calculations at evaluation time. Matching the symbol, magic number, and bar time prevents the same node from reserving capacity twice for one signal event.

The three decision states remove ambiguity from the return path. REJECTED means that the node must stop before execution. APPROVED permits the original volume, whereas REDUCED permits only the smaller normalized volume recorded in the decision. The reason field supports both chart monitoring and journal diagnostics, so you can see which portfolio rule produced the outcome without reconstructing the calculation from several counters.


Exploring AccountInfo.mqh Through the Risk Authority

CPortfolioRiskManager stores CAccountInfo as a normal member and uses it for current account facts. Configure rejects inconsistent risk, count, and magic-range limits before the first Refresh. These reads support policy decisions, but they are not an atomic account snapshot or an exclusive gateway for the entire EA.

#include <Arrays\ArrayObj.mqh>
#include <Trade\AccountInfo.mqh>
#include "RiskModels.mqh"

//+------------------------------------------------------------------+
//| Measures aggregate exposure and authorizes proposed entries      |
//+------------------------------------------------------------------+
class CPortfolioRiskManager
  {
private:
   CArrayObj m_reservations;
   CAccountInfo m_account;

CAccountInfo deliberately provides information rather than trading permission. Equity() reports the current equity value, Margin() reports margin already in use, and FreeMargin() reports the remaining free margin. Our manager must still compare those values with its configured percentages, measure potential loss at each stop, and include capacity promised by reservations. This boundary helps you distinguish a Standard Library service from the application policy built around it.

Configure validates both ranges and relationships: per-symbol risk cannot exceed total risk, the direction count cannot exceed the position count, and the managed magic range must be valid. It then calls Refresh, so READY is never reported before account and position data have been inspected. The complete validation appears in PortfolioRiskManager.mqh.


Measuring Open and Reserved Risk

For every managed position, the manager reads its type, volume, opening price, and stop loss. It uses OrderCalcProfit() to estimate the result at the stop in the account currency. The absolute negative result becomes the bounded monetary risk.

Refresh() rebuilds the snapshot rather than incrementally trusting earlier totals. This matters because positions can be opened, closed, or modified outside the current timer pass. Beginning from zero ensures that the next decision reflects the terminal's current position set together with reservations that still belong to requests in progress.

R p = ((R o + R r ) / E) × 100

Here, R p is the committed portfolio risk percentage, R o is the sum of bounded risk from open managed positions, R r is the sum of active reservations, and E is current account equity. All monetary terms use the account deposit currency.

//+------------------------------------------------------------------+
//| Refreshes aggregate open-position and reservation exposure       |
//+------------------------------------------------------------------+
bool CPortfolioRiskManager::Refresh(void)
  {
//--- Reset the snapshot and read current account resources
   m_equity=m_account.Equity();
   m_current_margin=m_account.Margin();
   m_open_risk=0.0;
   m_reserved_risk=0.0;
   m_positions=0;
   m_long_positions=0;
   m_short_positions=0;
   if(m_equity<=0.0)
     {
      m_status="INVALID EQUITY";
      return(false);
     }

//--- Measure every position owned by the portfolio magic range
   for(int i=PositionsTotal()-1;i>=0;i--)
     {
      const ulong ticket=PositionGetTicket(i);
      if(ticket==0 ||
         !IsManagedMagic((ulong)PositionGetInteger(POSITION_MAGIC)))
         continue;
      m_positions++;
      const ENUM_POSITION_TYPE position_type=
         (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
      if(position_type==POSITION_TYPE_BUY)
         m_long_positions++;
      else if(position_type==POSITION_TYPE_SELL)
         m_short_positions++;
      double risk=0.0;
      if(!PositionRisk(PositionGetString(POSITION_SYMBOL),position_type,
                       PositionGetDouble(POSITION_VOLUME),
                       PositionGetDouble(POSITION_PRICE_OPEN),
                       PositionGetDouble(POSITION_SL),risk))
        {
         m_open_risk=m_equity*m_max_portfolio_risk/100.0;
         m_status="UNBOUNDED POSITION RISK";
         return(false);
        }
      m_open_risk+=risk;
     }

//--- Add capacity already promised to requests awaiting execution
   for(int i=0;i<m_reservations.Total();i++)
     {
      CRiskReservation *item=(CRiskReservation*)m_reservations.At(i);
      if(item!=NULL)
         m_reserved_risk+=item.RiskMoney();
     }
   m_status="READY";
   return(true);
  }

The magic-number filter is equally important. It prevents unrelated manual trades or other EAs from being counted as positions owned by this manager. Within the managed range, however, every position contributes to the shared position and direction counters. Refresh() therefore produces both the monetary totals and the concentration state consumed by Evaluate().


Evaluating a New Request

Evaluate() begins with rejection rather than approval. It checks request identity, prevents duplicate reservations, refreshes current exposure, and applies position-count and directional limits before calculating volume. A malformed request therefore cannot inherit stale values from an earlier decision.

//+------------------------------------------------------------------+
//| Evaluates and, when possible, sizes one proposed entry           |
//+------------------------------------------------------------------+
bool CPortfolioRiskManager::Evaluate(const SRiskRequest &request,
                                     SRiskDecision &decision)
  {
//--- Start from a safe rejected decision
   ZeroMemory(decision);
   decision.status=RISK_DECISION_REJECTED;
   decision.reason="INVALID REQUEST";
   if(request.symbol=="" || request.magic==0 || request.bar_time<=0 ||
      request.requested_volume<=0.0 || request.entry_price<=0.0 ||
      request.stop_loss<=0.0 || !IsManagedMagic(request.magic))
     {
      m_rejections++;
      return(false);
     }

//--- Accept only directional market requests supported by this manager
   if(request.order_type!=ORDER_TYPE_BUY &&
      request.order_type!=ORDER_TYPE_SELL)
     {
      decision.reason="UNSUPPORTED ORDER TYPE";
      m_rejections++;
      return(false);
     }

//--- Require the stop loss to bound risk on the losing side of entry
   if((request.order_type==ORDER_TYPE_BUY &&
       request.stop_loss>=request.entry_price) ||
      (request.order_type==ORDER_TYPE_SELL &&
       request.stop_loss<=request.entry_price))
     {
      decision.reason="INVALID STOP POSITION";
      m_rejections++;
      return(false);
     }

//--- Reject a duplicate reservation for the same node and bar
   if(FindReservation(request.symbol,request.magic,request.bar_time)>=0)
     {
      decision.reason="DUPLICATE RESERVATION";
      m_rejections++;
      return(false);
     }

//--- Refresh portfolio exposure before allocating more capacity
   if(!Refresh())
     {
      decision.reason=m_status;
      m_rejections++;
      return(false);
     }

//--- Enforce position and directional concentration limits
   const int pending=m_reservations.Total();
   if(m_positions+pending>=m_max_positions)
     {
      decision.reason="POSITION LIMIT";
      m_rejections++;
      return(false);
     }
   const int directional=request.order_type==ORDER_TYPE_BUY ?
                         m_long_positions : m_short_positions;
   if(directional+DirectionReservations(request.order_type)>=m_max_direction)
     {
      decision.reason="DIRECTION LIMIT";
      m_rejections++;
      return(false);
     }

//--- Calculate the requested monetary risk
   double requested_risk=0.0;
   if(!RequestRisk(request,request.requested_volume,requested_risk))
     {
      decision.reason="RISK CALCULATION FAILED";
      m_rejections++;
      return(false);
     }

//--- Find the remaining account-wide and symbol-specific risk budgets
   const double portfolio_limit=m_equity*m_max_portfolio_risk/100.0;
   const double symbol_limit=m_equity*m_max_symbol_risk/100.0;
   const double portfolio_room=portfolio_limit-m_open_risk-m_reserved_risk;
   const double symbol_room=symbol_limit-SymbolOpenRisk(request.symbol)-
                            SymbolReservedRisk(request.symbol);
   const double risk_room=MathMin(portfolio_room,symbol_room);
   if(risk_room<=0.0)
     {
      decision.reason="RISK LIMIT";
      m_rejections++;
      return(false);
     }

//--- Reduce the requested volume when only part of the risk fits
   double approved=request.requested_volume;
   if(requested_risk>risk_room)
      approved=request.requested_volume*risk_room/requested_risk;
   approved=NormalizeVolume(request.symbol,approved);
   if(approved<=0.0)
     {
      decision.reason="VOLUME BELOW MINIMUM";
      m_rejections++;
      return(false);
     }

//--- Recalculate risk and margin at the normalized volume
   double approved_risk=0.0;
   double required_margin=0.0;
   if(!RequestRisk(request,approved,approved_risk) ||
      !RequestMargin(request,approved,required_margin))
     {
      decision.reason="PRETRADE CALCULATION FAILED";
      m_rejections++;
      return(false);
     }

//--- Reduce volume again when projected margin exceeds either limit
   const double margin_room=MathMin(m_equity*m_max_margin_use/100.0-
                                    m_current_margin,
                                    m_account.FreeMargin()-
                                    m_equity*m_min_free_margin/100.0);
   if(required_margin>margin_room && margin_room>0.0)
     {
      approved=NormalizeVolume(request.symbol,
                               approved*margin_room/required_margin);
      if(approved<=0.0 ||
         !RequestRisk(request,approved,approved_risk) ||
         !RequestMargin(request,approved,required_margin))
        {
         decision.reason="MARGIN LIMIT";
         m_rejections++;
         return(false);
        }
     }
   if(margin_room<=0.0 || required_margin>margin_room+0.01)
     {
      decision.reason="MARGIN LIMIT";
      m_rejections++;
      return(false);
     }

//--- Return the final approval and identify any volume reduction
   decision.approved_volume=approved;
   decision.risk_money=approved_risk;
   decision.margin_required=required_margin;
   if(approved+1.0e-9<request.requested_volume)
     {
      decision.status=RISK_DECISION_REDUCED;
      decision.reason="APPROVED WITH REDUCED VOLUME";
      m_reductions++;
     }
   else
     {
      decision.status=RISK_DECISION_APPROVED;
      decision.reason="APPROVED";
      m_approvals++;
     }
   return(true);
  }

The public request is now validated independently of the node that created it. Evaluate accepts only ORDER_TYPE_BUY and ORDER_TYPE_SELL. It also requires a buy stop loss below the entry price and a sell stop loss above the entry price. Unsupported order types return UNSUPPORTED ORDER TYPE, while an incorrectly placed stop returns INVALID STOP POSITION before exposure, margin, or reservation logic is evaluated.

The remaining monetary capacity is the smaller of the portfolio-wide room and the symbol-specific room. When the requested risk exceeds that amount, the manager scales volume proportionally and rounds downward to the symbol's volume step. Rounding downward is important because ordinary rounding could increase the approved risk above the remaining budget.

The manager then calls OrderCalcMargin(). This function estimates the margin required by the proposed operation in the account currency, but it does not incorporate current positions or pending orders into that calculation. The current implementation combines that estimate with account-wide used and free margin. Although each reservation stores margin_required, Evaluate does not subtract the margin of active reservations from margin_room. The reservation mechanism therefore protects promised monetary risk and count capacity, but it does not yet prevent several same-cycle approvals from collectively overcommitting the configured margin room.

Volume may be reduced a second time when the risk budget fits but the currently observed margin room does not. The final normalized volume is rejected if it falls below the symbol minimum. A successful return means that the request passed the limits measured during that Evaluate call; it is not an execution guarantee, and it does not include reserved margin or external pending-order exposure.


Reserving Capacity Before Execution

A reservation closes the monetary-risk gap between evaluation and submission. It does not recheck capacity or bind a decision to a request, and its stored margin is not deducted from later margin room. Those boundaries remain explicit in the implementation.

Ownership transfers only after m_reservations.Add() succeeds. If insertion fails, the allocating method deletes the unowned object. Once insertion succeeds, CArrayObj releases it through Delete() or Clear(). This is the same ownership discipline introduced for strategy nodes in Part 17.

//+------------------------------------------------------------------+
//| Reserves the capacity granted to an approved request             |
//+------------------------------------------------------------------+
bool CPortfolioRiskManager::Reserve(const SRiskRequest &request,
                                    const SRiskDecision &decision)
  {
//--- Accept only a positive approved or reduced decision
   if((decision.status!=RISK_DECISION_APPROVED &&
       decision.status!=RISK_DECISION_REDUCED) ||
      decision.approved_volume<=0.0 || decision.risk_money<=0.0 ||
      FindReservation(request.symbol,request.magic,request.bar_time)>=0)
      return(false);

//--- Create the reservation and transfer ownership to CArrayObj
   CRiskReservation *item=new CRiskReservation;
   if(item==NULL)
      return(false);
   item.Configure(request,decision);
   if(!m_reservations.Add(item))
     {
      delete item;
      return(false);
     }
   m_reserved_risk+=decision.risk_money;
   m_status="CAPACITY RESERVED";
   return(true);
  }

//+------------------------------------------------------------------+
//| Releases one reservation after execution succeeds or fails       |
//+------------------------------------------------------------------+
bool CPortfolioRiskManager::Release(const string symbol,
                                    const ulong magic,
                                    const datetime bar_time)
  {
//--- Let the owning collection delete the matching reservation
   const int index=FindReservation(symbol,magic,bar_time);
   if(index<0)
      return(false);
   const bool removed=m_reservations.Delete(index);
   Refresh();
   return(removed);
  }

//+------------------------------------------------------------------+
//| Converts a completed reservation into observed position risk     |
//+------------------------------------------------------------------+
void CPortfolioRiskManager::ConfirmExecution(const string symbol,
                                             const ulong magic,
                                             const datetime bar_time)
  {
//--- Remove promised capacity and rebuild the live position snapshot
   Release(symbol,magic,bar_time);
   Refresh();
  }

Execution has two terminal paths. A failed order removes the reservation, returning its unused risk capacity to later nodes. After a successful trade-server result, ConfirmExecution also removes the reservation and calls Refresh. The code does not first verify the actual filled volume, price, final stop loss, or that the new position is already selectable. A short interval can therefore exist in which promised risk has been released but measured live risk is not yet visible.


Building a Risk-Aware Strategy Node

BuildRequest() receives the node's completed signal state and fills every field required by the central contract. It does not submit an order or reserve capacity. Keeping those side effects outside this method allows a request to be inspected, rejected, or reduced before any account resource is committed.

//+------------------------------------------------------------------+
//| Builds a complete risk request from the current signal           |
//+------------------------------------------------------------------+
bool CRiskAwareStrategyNode::BuildRequest(SRiskRequest &request)
  {
//--- Read executable prices and reject an excessive spread
   ZeroMemory(request);
   MqlTick tick;
   if(!SymbolInfoTick(m_symbol,tick) || tick.ask<=0.0 || tick.bid<=0.0)
      return(false);
   const double point=SymbolInfoDouble(m_symbol,SYMBOL_POINT);
   if(point<=0.0 || (tick.ask-tick.bid)/point>m_max_spread)
     {
      m_status="BLOCKED: SPREAD";
      return(false);
     }

//--- Build entry, stop, and target prices from ATR and symbol limits
   const int digits=(int)SymbolInfoInteger(m_symbol,SYMBOL_DIGITS);
   const int stops=(int)SymbolInfoInteger(m_symbol,SYMBOL_TRADE_STOPS_LEVEL);
   const double stop_distance=MathMax(m_last_atr*m_atr_multiplier,
                                      (stops+1)*point);
   request.symbol=m_symbol;
   request.order_type=m_signal==RISK_SIGNAL_LONG ?
                      ORDER_TYPE_BUY : ORDER_TYPE_SELL;
   request.magic=m_magic;
   request.bar_time=m_last_bar;
   request.entry_price=request.order_type==ORDER_TYPE_BUY ? tick.ask : tick.bid;
   if(request.order_type==ORDER_TYPE_BUY)
     {
      request.stop_loss=NormalizeDouble(request.entry_price-stop_distance,digits);
      request.take_profit=NormalizeDouble(request.entry_price+
                                          stop_distance*m_reward_risk,digits);
     }
   else
     {
      request.stop_loss=NormalizeDouble(request.entry_price+stop_distance,digits);
      request.take_profit=NormalizeDouble(request.entry_price-
                                          stop_distance*m_reward_risk,digits);
     }

//--- Convert the requested equity percentage into a proposed volume
   double loss_per_lot=0.0;
   if(!OrderCalcProfit(request.order_type,m_symbol,1.0,
                       request.entry_price,request.stop_loss,loss_per_lot))
      return(false);
   loss_per_lot=MathAbs(loss_per_lot);
   const double equity=AccountInfoDouble(ACCOUNT_EQUITY);
   if(loss_per_lot<=0.0 || equity<=0.0)
      return(false);
   request.requested_volume=
      NormalizeVolume(equity*m_requested_risk/100.0/loss_per_lot);
   return(request.requested_volume>0.0);
  }

The request uses the executable ask for a buy and the executable bid for a sell. Its stop distance is the greater of the ATR-based distance and the symbol's minimum stop level plus one point. OrderCalcProfit then converts that price distance into an estimated one-lot loss in account currency. Dividing the node's monetary risk allowance by that loss produces the proposed volume, which is normalized before the central authority evaluates it.

//+------------------------------------------------------------------+
//| Reserves risk and submits the approved market request            |
//+------------------------------------------------------------------+
bool CRiskAwareStrategyNode::SubmitApprovedRequest(
                                      const SRiskRequest &request,
                                      const SRiskDecision &decision)
  {
//--- Reserve approved capacity before any order reaches the server
   if(!m_risk_manager.Reserve(request,decision))
     {
      Fail("RESERVATION FAILED");
      return(false);
     }

//--- Submit only the centrally approved volume
   const bool sent=m_trade.PositionOpen(request.symbol,request.order_type,
                                        decision.approved_volume,
                                        request.entry_price,request.stop_loss,
                                        request.take_profit,"Risk-aware node");
   if(!sent || !TradeResultSucceeded())
     {
      m_risk_manager.Release(request.symbol,request.magic,request.bar_time);
      Fail("ENTRY FAILED: "+m_trade.ResultRetcodeDescription());
      return(false);
     }

//--- Replace promised capacity with the resulting live position risk
   m_risk_manager.ConfirmExecution(request.symbol,request.magic,
                                   request.bar_time);
   m_status=decision.status==RISK_DECISION_REDUCED ?
            "OPENED: REDUCED VOLUME" : "OPENED: APPROVED";
   return(true);
  }

//+------------------------------------------------------------------+
//| Applies one signal through position and portfolio safeguards     |
//+------------------------------------------------------------------+
void CRiskAwareStrategyNode::ApplySignal(void)
  {
//--- Keep neutral bars from creating or closing exposure
   if(m_signal==RISK_SIGNAL_NEUTRAL)
     {
      m_status="NO CROSSOVER";
      return;
     }
   if(HasForeignPosition())
     {
      m_status="BLOCKED: FOREIGN POSITION";
      return;
     }

//--- Manage an existing owned position before considering entry
   if(m_position.SelectByMagic(m_symbol,m_magic))
     {
      const ENUM_POSITION_TYPE type=m_position.PositionType();
      const bool aligned=(m_signal==RISK_SIGNAL_LONG &&
                          type==POSITION_TYPE_BUY) ||
                         (m_signal==RISK_SIGNAL_SHORT &&
                          type==POSITION_TYPE_SELL);
      if(aligned)
        {
         m_status="HOLDING "+SignalName();
         return;
        }
      CloseOwnedPosition("opposite crossover");
      return;
     }

//--- Build the proposal and request a central portfolio decision
   SRiskRequest request;
   SRiskDecision decision;
   if(!BuildRequest(request))
     {
      Fail("REQUEST BUILD FAILED");
      return;
     }
   if(!m_risk_manager.Evaluate(request,decision))
     {
      m_status="RISK REJECTED: "+decision.reason;
      PrintFormat("Risk rejected %s: %s",m_symbol,decision.reason);
      return;
     }

//--- In monitoring mode, display the decision without reserving risk
   if(!m_allow_trading)
     {
      m_status="MONITOR: "+decision.reason;
      return;
     }
   SubmitApprovedRequest(request,decision);
  }

SubmitApprovedRequest() is the only entry path that reaches CTrade. It first creates a reservation. It then submits the approved volume and resolves the reservation according to the trade-server result.

ApplySignal() also preserves position ownership through CPositionInfo from PositionInfo.mqh. A foreign position blocks the node. An aligned owned position remains open, while an opposite signal closes it without reversing during the same cycle. A new proposal is evaluated only when the node has a directional signal and no owned position.

When InpAllowTrading is false, the node still builds and evaluates the proposal. It records MONITOR with the decision reason but does not reserve capacity or call CTrade. This makes the safety switch useful for inspecting policy behavior before enabling execution.


Routing the Portfolio Cycle

CRiskPortfolioManager refreshes the shared risk snapshot before visiting the nodes. It then processes each node sequentially. Any reservation or position created by an earlier node changes the capacity available to the next node.

Sequential processing gives every decision a deterministic place. Node order does not change the limits, but it can decide which simultaneous signal receives scarce capacity first. Consider that policy when ordering symbols or adding priorities.

//+------------------------------------------------------------------+
//| Routes one timer cycle through the shared risk snapshot          |
//+------------------------------------------------------------------+
void CRiskPortfolioManager::ProcessAll(void)
  {
//--- Refresh once before nodes request capacity in sequence
   m_cycles++;
   if(!m_risk.Refresh())
      m_failed_cycles++;
   for(int i=0;i<m_nodes.Total();i++)
     {
      CRiskAwareStrategyNode *node=(CRiskAwareStrategyNode*)m_nodes.At(i);
      if(node==NULL || !node.Process())
         m_failed_cycles++;
     }
  }

A node failure increments the diagnostic counter without ending the loop. Other symbols continue in the same timer event. Refresh supplies the starting snapshot; reservations protect capacity until the next refresh.

The host handlers remain deliberately small: OnInit validates and builds the portfolio before starting the timer, OnTimer calls ProcessAll, OnTradeTransaction refreshes exposure, and OnDeinit stops the timer before clearing nodes, cached indicators, and reservations. Their complete definitions are in PortfolioRiskManagerEA.mq5.


Operating the Expert Advisor

Download MQL5.zip, open the terminal's Data Folder, and extract the archive there. Merge the archive's top-level MQL5 folder with the existing MQL5 folder. Compile MQL5\Experts\StandardLibraryExplorer\Part19\PortfolioRiskManagerEA.mq5 in MetaEditor, then attach it to a chart.

Input Default Purpose
InpSymbols EURUSD,GBPUSD,USDJPY,AUDUSD Symbols represented by strategy nodes
InpTimeframe PERIOD_H1 Completed-bar processing timeframe
InpFastMAPeriod/InpSlowMAPeriod 12/26 Crossover signal periods
InpATRPeriod/InpATRMultiplier 14/2.00 Volatility-based stop distance
InpRequestedRiskPerNode 0.25 Risk percentage proposed by one signal
InpMaxRiskPerSymbol 0.50 Maximum committed risk for one symbol
InpMaxPortfolioRisk 1.50 Maximum open plus reserved portfolio risk
InpMaxMarginUse 30.0 Maximum projected margin as a percentage of equity
InpMinFreeMarginPercent 50.0 Minimum projected free-margin reserve
InpMaxPositions 4 Total managed positions and pending reservations
InpMaxSameDirection 3 Long or short concentration limit
InpAllowTrading false Switches from decision monitoring to execution

The percentage limits are educational defaults, not optimized trading settings. Their hierarchy illustrates how a small node proposal can be constrained first by symbol capacity and then by portfolio capacity. The 0.25% request is below the 0.50% symbol ceiling, while the 1.50% portfolio ceiling leaves room for several independent proposals. The 30% margin-use limit and 50% free-margin reserve demonstrate that risk and margin are separate constraints. You should select production values from account size, instrument behavior, strategy correlation, drawdown tolerance, and broker conditions rather than copying these defaults.

For a focused reduction test, let several nodes request 0.25% in the same cycle and temporarily set InpMaxPortfolioRisk to 0.60%. If the first two requests consume about 0.50%, the next request can be reduced to the remaining room, subject to the symbol's volume step, and a later request can be rejected. This is a test configuration for exposing the decision sequence, not a recommended risk policy.


Verification Plan and Recorded Demonstration

The retained evidence has three boundaries. MetaEditor confirms compilation, the monitoring journal confirms initialization and continued scheduling, and the tester report confirms a completed zero-trade run. None of these artifacts verifies live reservation release or the APPROVED, REDUCED, and REJECTED execution branches. Static source review checks control paths and ownership structure, but it is not substituted for focused runtime scenarios.

Compiling the Expert Advisor

I compiled PortfolioRiskManagerEA.mq5 with its project headers in MetaEditor. The result was 0 errors and 0 warnings. Compilation confirms source acceptance in this build; it does not validate the risk decisions.

PortfolioRiskManagerEA.mq5: 0 errors, 0 warnings
Status Check Evidence or next record
Observed Compilation and monitoring mode 0 errors, 0 warnings; four nodes initialized; zero trades; full interval completed.
Planned Approval, reduction, and risk/direction/margin rejection Record decision reason, requested and approved volume, and unchanged exposure after rejection.
Planned Execution failure and unbounded position Confirm reservation release after ENTRY FAILED and blocked approval after UNBOUNDED POSITION RISK.
Planned Shutdown Confirm timer removal and cleanup of nodes, indicator entries, and reservations.

Recording the Monitoring-Mode Demonstration

The settings and result tables record the environment once: build, symbols, period, model, account size, inputs, history quality, and zero-trade outcome. Missing margin mode and transaction-cost settings remain identified rather than inferred. This lets you reproduce the monitoring boundary without mistaking unchanged balance and zero drawdown for strategy-performance evidence.

Run condition Recorded value Interpretation
Program and terminal build PortfolioRiskManagerEA.ex5; MetaTester build 6230 The EX5 loaded and initialized in the tester; the MetaEditor compile result is recorded separately above
Quote source Third-party demo account All four configured symbols synchronized before portfolio initialization
Host symbol, timeframe, and dates EURUSD, H1, 2024.01.01–2024.12.31; no forward period The run covers one calendar year on the host chart while managing EURUSD, GBPUSD, USDJPY, and AUDUSD
Deposit, leverage, and margin mode USD 10,000; 1:100 leverage; margin mode not recorded Account size and leverage are reproducible, but netting-versus-hedging behavior remains unverified
Modeling and execution assumption Every tick; zero latency, ideal execution; optimization disabled; visual mode enabled The journal reports 107,403,959 generated ticks across the four symbols
Spread, commission, and slippage Tester spread and commission not recorded; zero-latency ideal execution selected No transaction-cost or execution-quality conclusion is drawn, and trading was disabled
Complete input set Four symbols; H1; MA 12/26; ATR 14 × 2.0; reward/risk 1.5; requested risk 0.25%; symbol risk 0.50%; portfolio risk 1.50%; margin use 30%; free-margin floor 50%; maximum four positions and three in one direction; one-second timer; base magic 2026081900; maximum spread 30 points; trading disabled The journal records every EA input used by this run

Reading the Exported Tester Report

Report field Recorded value What it verifies
History quality 100% The tester completed the selected historical-data preparation without reporting a quality reduction
Bars and host-symbol ticks 6,218 bars; 20,732,299 ticks The report agrees with the EURUSD H1 completion line in the journal
Trades, deals, and orders 0 trades; 0 deals; no order rows Monitoring mode did not submit or execute market exposure
Profit and drawdown USD 0.00 net profit; 0.00% balance and equity drawdown The account balance and equity were unchanged because the run did not trade
2026.11.13 01:01:14.854  login (build 6230)
2026.11.13 01:01:14.892  initial deposit 10000.00 USD, leverage 1:100
2026.11.13 01:01:14.946  EURUSD,H1 (Deriv-Demo): every tick generating
2026.11.13 01:01:14.946  EURUSD,H1: testing of Experts\StandardLibraryExplorer\Part19\PortfolioRiskManagerEA.ex5 from 2024.01.01 00:00 to 2024.12.31 00:00 started with inputs:
2026.11.13 01:01:14.946    InpSymbols=EURUSD,GBPUSD,USDJPY,AUDUSD
2026.11.13 01:01:14.946    InpMaxPortfolioRisk=1.5
2026.11.13 01:01:14.946    InpAllowTrading=false
2026.11.13 01:01:15.069  2024.01.01 00:00:00  Risk portfolio initialized with 4 nodes. Trading=DISABLED
2026.11.13 01:01:38.558  2024.01.02 05:00:00  Risk-aware node USDJPY: REQUEST BUILD FAILED
2026.11.13 04:49:39.840  final balance 10000.00 USD
2026.11.13 04:49:39.875  EURUSD,H1: 20732299 ticks, 6218 bars generated. Test passed in 3:48:23.318
2026.11.13 04:49:39.875  107403959 total ticks for all symbols

The journal localizes REQUEST BUILD FAILED only to proposal construction; it does not identify the failing branch. The full-period completion demonstrates scheduling resilience, not correct portfolio decisions. A separate trading-enabled run must retain decision-level logs, reservation changes, account mode, costs, and a matching report.

Fig. 3. Separate illustrative Strategy Tester visualization; not evidence from the documented monitoring run

Fig. 3. Separate illustrative Strategy Tester visualization; not evidence from the documented monitoring run


Limitations

The moving-average crossover is a demonstration, not a validated trading strategy. A single backtest cannot establish profitability or robustness.

Key limitations:

  • Order validation: Unsupported order types and invalid stop-loss direction are rejected. Take-profit direction, price freshness, and freeze levels are not checked.
  • Risk coverage: Open risk excludes external pending orders, while margin remains account-wide.
  • Account compatibility: Magic-number ownership is unreliable when multiple strategies share a symbol on netting accounts.
  • Risk estimation: Gaps, costs, changing tick values, and correlation are not modeled.
  • Margin checks: OrderCalcMargin() and CAccountInfo provide estimates, not atomic data or execution guarantees.
  • Reservations: Decisions are not cryptographically bound to requests. Limits are not rechecked during Reserve.
  • Monitoring: Approval counters track decisions, not executed trades.
  • Limit breaches: Falling equity blocks new entries but does not trigger automatic position reduction.
  • Execution model: Asynchronous operation requires reservation expiry, reconciliation, and restart recovery.

The manager centralizes risk controls but cannot guarantee execution or portfolio safety.


Conclusion

We connected CAccountInfo to a reusable request–decision boundary for the Part 18 portfolio. CPortfolioRiskManager combines account facts, managed-position risk, count limits, and same-cycle monetary reservations before returning APPROVED, REDUCED, or REJECTED. The result is an educational risk authority, not a guarantee of execution or portfolio safety.

  • Account data and policy: CAccountInfo supplies equity and margin facts; the application defines how those facts constrain a request. The reads are current but not atomic.
  • Object ownership: CObject and CArrayObj let the risk manager own temporary reservations through one transfer and cleanup contract.
  • Separated responsibilities: CPositionInfo inspects positions, CTrade submits approved volume, and the indicator classes preserve the Part 18 signal layer.
  • Decision versus execution: Approval grants permission to submit. Server retcodes, actual fills, and resulting exposure still require reconciliation.
  • Reusable outcome: You can replace the crossover signal while retaining one portfolio-wide authorization path. Production use still requires reserved-margin accounting, pending-order coverage, stronger request binding, and restart recovery.

Attachments

Extract MQL5.zip into the terminal's Data Folder. The table gives each component's exact destination.

Component Type Installation path Description
PortfolioRiskManagerEA.mq5 Expert Advisor MQL5\Experts\StandardLibraryExplorer\Part19\PortfolioRiskManagerEA.mq5 Validates inputs and routes terminal events
RiskModels.mqh Include class MQL5\Include\StandardLibraryExplorer\Part19\RiskModels.mqh Defines requests, decisions, and reservations
PortfolioRiskManager.mqh Include class MQL5\Include\StandardLibraryExplorer\Part19\PortfolioRiskManager.mqh Applies aggregate limits using CAccountInfo
RiskAwareStrategyNode.mqh Include class MQL5\Include\StandardLibraryExplorer\Part19\RiskAwareStrategyNode.mqh Builds proposals and submits approved volume
RiskPortfolioManager.mqh Include class MQL5\Include\StandardLibraryExplorer\Part19\RiskPortfolioManager.mqh Coordinates nodes, cache, and risk authority
IndicatorCache.mqh Include class MQL5\Include\StandardLibraryExplorer\Part19\IndicatorCache.mqh Preserves shared MA and ATR resources from Part 18
ReportTester-41066355.xlsx Strategy Tester report MQL5\ReportTester-41066355.xlsx Exported Strategy Tester report of the monitoring-mode demonstration run
Attached files |
MQL5.zip (34.04 KB)
Building a Prop-Firm Rule Guard in MQL5 (Part 2): Eight Rules, One Directive, and the Action Layer Building a Prop-Firm Rule Guard in MQL5 (Part 2): Eight Rules, One Directive, and the Action Layer
An MQL5 prop-firm guard must evaluate account rules before it acts and verify that protective actions have completed. This article examines eight rules, two-phase directive resolution, position closing, Algo Trading state checks and restart recovery. A demo and synthetic tests show how to use the guard and verify its rule logic.
Automating Chart Patterns in MQL5 (Part 4): The Flag and Pennant Automating Chart Patterns in MQL5 (Part 4): The Flag and Pennant
This article implements a flag and pennant detector in MQL5 using swing-structure data from a higher timeframe. The pole is validated by ATR-based height and a maximum bar duration, and the subsequent consolidation is replayed bar by bar on the chart timeframe with limits on minimum length, lifetime, and retracement. A three-state machine trades a fresh breakout once and projects a measured-move target from the pole's height.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
Marginal Drawdown Contribution Analyzer in MQL5: Which Configuration Deepens Your Portfolio Drawdown Marginal Drawdown Contribution Analyzer in MQL5: Which Configuration Deepens Your Portfolio Drawdown
We show how to attribute realized portfolio drawdown to individual configurations inside MetaTrader 5. Using daily results grouped by magic (optionally magic and symbol), the tool rebuilds the portfolio curve and quantifies three contributions: leave-one-out drawdown, shares of the deepest drawdown episodes, and Euler variance share. Flags are checked for stability across sample halves and rolled up into a heuristic A+–F score for practical diagnostics.