Entropy Pooling and Scenario Budgets for Expected-Shortfall Sizing
Introduction
Every risk number an Expert Advisor computes from history rests on an unstated choice: which past bars count, and by how much. A 250-bar volatility or historical VaR gives the last 250 bars equal weight and everything older exactly zero. That is a probability vector over the history, chosen by the length of an array rather than by anyone deciding it.
The choice has measurable costs. Later in this article an Expert Advisor holds a five-pair currency basket at a daily expected-shortfall budget of 1% of equity. Sized by a 250-bar window, it entered March 2020 at 1.70 times equity in gross notional, because the window still described the calm of 2019, and on 10 March the book lost 2.85% in a day. The window also cannot take in information the history lacks, such as an expected rise in USDJPY volatility before a central bank meeting.
Entropy pooling, introduced by Attilio Meucci in Fully Flexible Views: Theory and Practice, addresses both problems. Keep every historical scenario as it happened and change only the probability attached to each, choosing the new probabilities as close as possible to a prior, in relative entropy, subject to whatever you want to be true: that today's volatility regime applies, that USDJPY volatility is 50% higher, that a Swiss franc shock has at least a 1% chance. The entropy here is the relative entropy between two probability vectors over the same scenarios, used as a distance, not the randomness of a price series.
We build the method in pure MQL5: a five-file library, a demonstration script, a set of checks against closed-form results, a walk-forward test of the forecasts, an indicator that draws the conditioned risk on a chart, and the sizing Expert Advisor.
We will cover:
- A Lookback Window Is a Probability Vector
- Entropy Pooling
- Building the Scenario Set
- The Solver
- Views and Conditioning on the State
- Reading the Posterior: EP_Demo
- Does Conditioning Forecast Risk Better?
- The Indicator: EP_ViewCost
- The Expert Advisor: EP_Sizer
- Conclusion
A Lookback Window Is a Probability Vector
Take a history of T bars. Any statistic we compute from it, a mean, a volatility, a quantile, is a weighted sum over those bars, and the weights sum to one. A plain average over the last N bars uses weight 1/N on each of them and 0 on the rest. Written out explicitly, that is all a rolling window is:
//+------------------------------------------------------------------+ //| The rolling window written out: 1/N on the last N rows. | //+------------------------------------------------------------------+ bool EpRollingWindow(const int rows,const int window,vector &p) { if(rows<1 || window<1) return false; const int n=MathMin(window,rows); p.Init(rows); p.Fill(0.0); for(int i=rows-n;i<rows;i++) p[i]=1.0/n; return true; } //+------------------------------------------------------------------+ //| Exponential decay by age: one half-life older, half the weight. | //+------------------------------------------------------------------+ bool EpExponentialDecay(const int rows,const double half_life,vector &p) { if(rows<1 || half_life<=0.0) return false; const double k=MathLog(2.0)/half_life; p.Init(rows); for(int i=0;i<rows;i++) p[i]=MathExp(-k*(rows-1-i)); return EpNormalise(p); }
Exponential decay, the usual alternative, halves the weight every half_life bars, so no bar is dropped but old bars fade. Every later step takes such a vector as input: the history is fixed, and all modelling happens in the probabilities.
Two numbers describe what a probability vector costs. The first is the effective number of scenarios (ENS), the exponential of its entropy. It equals N for N equal weights and 1 when a single bar holds all the mass, so it tells us how much of the history a vector is really using.
//+------------------------------------------------------------------+ //| Exp of the entropy: N for N equal rows, 1 if one row holds all. | //+------------------------------------------------------------------+ double EpEffectiveScenarios(const vector &p) { double h=0.0; const ulong n=p.Size(); for(ulong i=0;i<n;i++) if(p[i]>0.0) h-=p[i]*MathLog(p[i]); return MathExp(h); }
The second is the relative entropy of one vector against another, the sum of q ln(q/p) in nats. It is zero when the vectors agree and infinite if q puts mass where p has none, so a 250-bar window can never be reweighted towards 2015: that year's prior weight is exactly zero.
Our basket is five major pairs on D1 (EURUSD, GBPUSD, AUDUSD, USDJPY, USDCHF), giving 4,655 joint daily rows from October 2008 to September 2026. The book holds 0.2 of notional in each, long the first three and short the last two, so it is short the US dollar. Its eight worst days are the Swiss franc floor of 2011, the Brexit vote, and three days each of late 2008 and March 2020, and a 250-bar window gives every one of them zero weight.

Fig. 1. The same bar history under three probability vectors: a rolling window, exponential decay, and decay conditioned on today's volatility
Entropy Pooling
We have T joint scenarios x_j, one row per bar, each holding the returns of every symbol and any other variable we care about. We have a prior vector p over those rows, for example the exponential decay. We want a posterior q that satisfies K statements, each written as an expectation of some function of a scenario:
minimise sum_j q_j * ln(q_j / p_j) subject to sum_j q_j * f_k(x_j) =, <=, or >= c_k k = 1..K sum_j q_j = 1, q_j >= 0
A mean view uses f(x) = x, a tail view the indicator of the event, and a spread view the difference of two columns. These are linear in q and fit this form exactly; volatility and correlation views do not, and the library approximates them, as the views section explains.
The problem has T unknowns, and T is in the thousands. What makes it practical is its dual. Introduce one multiplier per view, collect them in a vector theta, and scale each view by its standard deviation under the prior, g_jk = (f_k(x_j) - c_k) / s_k. The solution then has a closed form in theta, and theta itself minimises a smooth convex function of only K variables:
q_j(theta) = p_j * exp(theta . g_j) / Z(theta) psi(theta) = ln Z(theta) = ln sum_j p_j * exp(theta . g_j) gradient = E_q[g] (zero when every equality view holds) Hessian = Cov_q[g] (positive semidefinite, so psi is convex)
This is an exponential tilt of the prior: every scenario keeps its outcome, and its probability is scaled by how it scores on the views. With three views the solver works on three numbers, however long the history. An inequality view constrains the sign of its multiplier, and a multiplier of zero means the view already held under the prior.
For a linear view the multiplier is also a price. By the envelope theorem, theta_k / s_k is the derivative of the relative entropy with respect to c_k, so theta_k is the price per prior standard deviation of the target, comparable across views.
Two closed-form results give us something to test against. For a Gaussian prior and a mean view that moves asset A by z standard deviations, the tilted distribution is still Gaussian, its relative entropy is z^2/2, every other mean moves by its regression beta on A times the shift, and the covariance does not change. The mean result is what Black-Litterman gives for a view held with full confidence. The unchanged covariance is what separates the tilt from conditioning, which would pin A to its target and remove its variance.

Fig. 2. A mean view as an exponential tilt: scenario weights shift until the view holds, while the one-dimensional dual reaches its minimum
Meucci's companion paper, Historical Scenarios with Fully Flexible Probabilities, applies the same machinery to the prior itself: time decay, and conditioning on a state variable such as volatility. That is the use this article leans on most.
Building the Scenario Set
The scenarios are held in CEpScenarios, a matrix with one row per bar and one column per variable. Two details decide whether a row is a genuine joint outcome.
Shared bar times. Aligning five symbols by index would silently pair returns from different days whenever one market has a holiday. LoadReturns keeps only the bar times all symbols share and takes log returns between consecutive shared closes, so a missing day folds its move into the next shared bar.
//--- shared times: intersect each symbol into the running list datetime common[]; ArrayCopy(common,ser[0].time); for(int s=1;s<n;s++) { datetime keep[]; ArrayResize(keep,ArraySize(common)); int a=0,b=0,m=0; while(a<ArraySize(common) && b<ArraySize(ser[s].time)) { if(common[a]==ser[s].time[b]) { keep[m++]=common[a]; a++; b++; } else if(common[a]<ser[s].time[b]) a++; else b++; } ArrayResize(keep,m); ArrayCopy(common,keep); ArrayResize(common,m); }
A state known before the bar. To condition on volatility we need a state variable whose value on row t was already known when bar t opened. AddTrailingVolatility builds it as the root mean square of the previous window rows, excluding row t itself, and stores the value for the next, still unopened, bar separately. The first rows cannot be filled and are dropped, so all columns stay aligned.
//+------------------------------------------------------------------+ //| Row t gets the RMS of rows t-window..t-1, known before its bar. | //+------------------------------------------------------------------+ int CEpScenarios::AddTrailingVolatility(const int col,const int window) { const int T=Rows(); if(col<0 || col>=Cols() || window<2 || window>=T-10) return -1; double z[]; ArrayResize(z,T); double s2=0.0; for(int t=0;t<T;t++) { z[t]=(t>=window ? MathSqrt(s2/window) : 0.0); s2+=m_x[t][col]*m_x[t][col]; if(t>=window) s2-=m_x[t-window][col]*m_x[t-window][col]; } const double next=MathSqrt(MathMax(s2,0.0)/window); if(!AppendColumn(m_name[col]+" vol"+IntegerToString(window),EP_COLUMN_STATE,z,next)) return -1; if(!DropHead(window)) return -1; return Cols()-1; }
The book is added as a column of its own. The symbol columns hold log returns, which add across time and suit views on a single pair, but money only adds across positions as simple returns, so EpPortfolio converts each leg with exp(r) - 1 before weighting it. The demonstration script builds the book and its 20-bar volatility state in a few lines:
//--- the book as a column, then its trailing volatility as the state vector book; EpPortfolio(scen,cols,weights,book); double values[]; ArrayResize(values,scen.Rows()); for(int t=0;t<scen.Rows();t++) values[t]=book[t]; const int book_col =scen.AddColumn("Book",EP_COLUMN_RETURN,values,EMPTY_VALUE); const int state_col=scen.AddTrailingVolatility(book_col,InpStateWindow); if(state_col<0) return; scen.Column(book_col,book);
After the state's first 20 rows are dropped, the basket has 4,655 joint rows. On the last bar, 14 September 2026, the book's trailing volatility was 0.346% per day, 5.49% annualised.
The Solver
CEpSolver implements the dual problem from the previous section. It takes the prior, a T by K matrix of view functions evaluated at every scenario, the K targets, and a relation for each view.
//+------------------------------------------------------------------+ //| CEpSolver - the probabilities closest to a prior that meet views.| //| Newton on the dual, one multiplier per view instead of per row: | //| q_j = p_j exp(theta . g_j - psi), with g = (f - c) / s. | //+------------------------------------------------------------------+ class CEpSolver { private: int m_max_iter; double m_tol; // dual gradient tolerance, prior std units double m_cap; // |theta| beyond this means the views cannot be met bool m_warm; int m_rows; int m_views; double m_logp[]; // log prior, -DBL_MAX off the support double m_g[]; // scaled views, row-major T x K double m_scale[]; // prior std of each view, sign-flipped for EP_AT_LEAST bool m_ineq[]; double m_theta[]; double m_cost[]; // d(relative entropy) / d(target), per view double Evaluate(const double &theta[],double &grad[],double &hess[], const bool need_hess) const; bool CholeskySolve(double &a[],double &b[],const int n) const; public: CEpSolver(void); void SetTolerance(const double tol) { m_tol=(tol>0.0 ? tol : 1e-11); } void SetMaxIterations(const int iter) { m_max_iter=(iter>5 ? iter : 5); } //--- start from the last solve's multipliers when the view count matches void SetWarmStart(const bool warm) { m_warm=warm; } //--- f is T x K view functions at each scenario; rel[] has K entries bool Solve(const vector &prior,const matrix &f,const vector &target, const ENUM_EP_RELATION &rel[],vector &posterior,SEpSolve &out); //--- multiplier of view k in prior std units, 0 when the view is slack double Multiplier(const int k) const { return (m_scale[k]<0.0 ? -m_theta[k] : m_theta[k]); } //--- nats of relative entropy per unit move of view k's target double MarginalCost(const int k) const { return m_cost[k]; } };
Before iterating, each view is centred on its target and divided by its prior standard deviation, so a volatility view near 10^-5 and a probability view of 0 or 1 share a well-scaled Hessian. A greater-or-equal view is stored as a less-or-equal view with its sign flipped, so the solver handles one kind of bound.
//--- scale each view by its prior std; a >= view is a <= view negated for(int k=0;k<K;k++) { double m1=0.0,m2=0.0; for(int j=0;j<T;j++) { m1+=p[j]*f[j][k]; m2+=p[j]*f[j][k]*f[j][k]; } const double sd=MathSqrt(MathMax(m2-m1*m1,0.0)); const double sign=(rel[k]==EP_AT_LEAST ? -1.0 : 1.0); m_scale[k]=sign*(sd>1e-300 ? sd : 1.0); m_ineq[k] =(rel[k]!=EP_EQUAL); if(m_ineq[k] && m_theta[k]>0.0) m_theta[k]=0.0; for(int j=0;j<T;j++) m_g[j*K+k]=(f[j][k]-target[k])/m_scale[k]; }
Each evaluation computes psi, its gradient and its Hessian in one pass, shifting the log-sum-exp by its largest term so no weight overflows.
//+------------------------------------------------------------------+ //| psi, its gradient E_q[g] and Hessian Cov_q(g), overflow-safe. | //+------------------------------------------------------------------+ double CEpSolver::Evaluate(const double &theta[],double &grad[],double &hess[], const bool need_hess) const { const int T=m_rows,K=m_views; double a[]; ArrayResize(a,T); double amax=-DBL_MAX; for(int j=0;j<T;j++) { if(m_logp[j]==-DBL_MAX) { a[j]=-DBL_MAX; continue; } double s=m_logp[j]; for(int k=0;k<K;k++) s+=theta[k]*m_g[j*K+k]; a[j]=s; if(s>amax) amax=s; } double z=0.0; for(int j=0;j<T;j++) if(a[j]!=-DBL_MAX) z+=MathExp(a[j]-amax); const double psi=amax+MathLog(z); ArrayInitialize(grad,0.0); if(need_hess) ArrayInitialize(hess,0.0); for(int j=0;j<T;j++) { if(a[j]==-DBL_MAX) continue; const double w=MathExp(a[j]-psi); if(w==0.0) continue; const int row=j*K; for(int k=0;k<K;k++) { const double wg=w*m_g[row+k]; grad[k]+=wg; if(need_hess) for(int l=0;l<=k;l++) hess[k*K+l]+=wg*m_g[row+l]; } } if(!need_hess) return psi; for(int k=0;k<K;k++) { for(int l=0;l<=k;l++) { hess[k*K+l]-=grad[k]*grad[l]; hess[l*K+k] =hess[k*K+l]; } } return psi; }
The iteration is a projected Newton method. Inequality multipliers must stay at or below zero; one at zero with its gradient pushing outward is held fixed, the step is solved on the rest by a small Cholesky factorisation, and it is shortened until psi decreases enough. Near the optimum, where psi changes by less than its rounding error, a full step that reduces the gradient is also accepted. If the multipliers pass a large cap, no reweighting can meet the views, and the solver reports that instead of returning a distorted vector.
//--- backtrack; a full step that shrinks the gradient is also taken bool accepted=false; double alpha=1.0,tpsi=psi; for(int ls=0;ls<60;ls++) { double slope=0.0; for(int k=0;k<K;k++) { trial[k]=m_theta[k]+alpha*step[k]; if(m_ineq[k] && trial[k]>0.0) trial[k]=0.0; slope+=grad[k]*(trial[k]-m_theta[k]); } tpsi=Evaluate(trial,tgrad,thess,false); if(tpsi<=psi+1e-4*slope) { accepted=true; break; } if(ls==0) { double tworst=0.0; for(int k=0;k<K;k++) if(!(m_ineq[k] && trial[k]>=0.0 && tgrad[k]<0.0)) tworst=MathMax(tworst,MathAbs(tgrad[k])); if(tworst<worst) { accepted=true; break; } } alpha*=0.5; } if(!accepted) break; ArrayCopy(m_theta,trial); psi=Evaluate(m_theta,grad,hess,true); double big=0.0; for(int k=0;k<K;k++) big=MathMax(big,MathAbs(m_theta[k])); if(big>m_cap) { out.status=EP_INFEASIBLE; break; } }
After the loop, each view's miss is measured in its own units and the marginal cost is recovered from the multiplier and the scale:
out.violation=0.0; for(int k=0;k<K;k++) { double e=0.0; for(int j=0;j<T;j++) e+=posterior[j]*f[j][k]; double miss=e-target[k]; if(rel[k]==EP_AT_MOST) miss=MathMax(miss,0.0); if(rel[k]==EP_AT_LEAST) miss=MathMax(-miss,0.0); out.violation=MathMax(out.violation,MathAbs(miss)); m_cost[k]=m_theta[k]/m_scale[k]; }
Checking the solver. EP_Checks generates 200,000 correlated Gaussian scenarios and compares the library with the closed-form results. The exponential tilt part reads:
//--- 2. a half-sigma mean view on Gaussian rows is an exponential tilt CEpViews tilt; tilt.AddMean(0,EP_EQUAL,ma+0.5*sa); tilt.Pool(scen,p,solver,q,r); const double shift=0.5*sa; const double mb_bl=EpMean(b,p)+EpCorrelation(a,b,p)*sb/sa*shift; Check("mean view met",EpMean(a,q)-(ma+shift),1e-12); Check("relative entropy against z^2/2",r.entropy-0.125,5e-3); Check("mean of B against the Black-Litterman mean, / shift",(EpMean(b,q)-mb_bl)/shift,5e-3); Check("vol of A unchanged by a mean view, relative",EpVolatility(a,q)/sa-1.0,5e-3); Check("vol of B unchanged by a mean view, relative",EpVolatility(b,q)/sb-1.0,5e-3);
Table 1 lists every check. The tolerances on the Gaussian results are loose because 200,000 draws are only approximately Gaussian.
| Check | Measured miss | Tolerance |
|---|---|---|
| A slack view leaves the prior unchanged (max |q - p| times T) | 3.4e-16 | 1e-9 |
| Mean view is met | 1.7e-16 | 1e-12 |
| Relative entropy against z^2/2 | 9.3e-5 | 5e-3 |
| Mean of B against the Black-Litterman mean, per unit of shift | 1.5e-3 | 5e-3 |
| Volatility of A and B unchanged by a mean view, relative | 3.6e-4, 1.4e-3 | 5e-3 |
| A binding >= view equals the equality posterior | 0 | 1e-9 |
| A mean above every scenario is reported as infeasible | reported | - |
| Marginal cost against a finite difference, relative | 1.0e-7 | 1e-6 |
| Volatility view met, relative / correlation view met | 4.2e-10 / 7.1e-11 | 1e-9 |
| Tail probability view met | 2.4e-13 | 1e-12 |
| Conditioning past the edge of history keeps ENS at the budget, relative | 1.7e-5 | 1e-3 |
Table 1. EP_Checks on 200,000 Gaussian scenarios
Views and Conditioning on the State
CEpViews provides five kinds of view and turns them into the matrix and targets the solver needs.
//--- the statement a view makes about the next bar enum ENUM_EP_VIEW { EP_VIEW_MEAN, // E[x] EP_VIEW_VOLATILITY, // std of x EP_VIEW_CORRELATION, // corr of x and y EP_VIEW_TAIL, // P(x <= threshold) EP_VIEW_SPREAD // E[x - y], a ranking when the target is 0 };
Means, spreads and tail probabilities are linear in q. Volatility and correlation are not, because they are measured around a mean that depends on q, so the library replaces each with a linear constraint on a second moment around reference values: E[x^2] = s^2 + m^2, and E[xy] = rho * s_x * s_y + m_x * m_y.
//+------------------------------------------------------------------+ //| One f column and target per view; vol and corr as second moments.| //+------------------------------------------------------------------+ void CEpViews::Build(const CEpScenarios &scen,const double &mean[],const double &vol[], matrix &f,vector &c,ENUM_EP_RELATION &rel[]) const { const int T=scen.Rows(),K=ArraySize(m_v); f.Init(T,K); c.Init(K); ArrayResize(rel,K); for(int k=0;k<K;k++) { const SEpView v=m_v[k]; rel[k]=v.rel; for(int t=0;t<T;t++) { const double x=scen.Value(t,v.a); const double y=(v.b>=0 ? scen.Value(t,v.b) : 0.0); switch(v.type) { case EP_VIEW_MEAN: f[t][k]=x; break; case EP_VIEW_VOLATILITY: f[t][k]=x*x; break; case EP_VIEW_CORRELATION: f[t][k]=x*y; break; case EP_VIEW_TAIL: f[t][k]=(x<=v.threshold ? 1.0 : 0.0); break; case EP_VIEW_SPREAD: f[t][k]=x-y; break; } } switch(v.type) { case EP_VIEW_VOLATILITY: c[k]=v.value*v.value+mean[v.a]*mean[v.a]; break; case EP_VIEW_CORRELATION: c[k]=v.value*vol[v.a]*vol[v.b]+mean[v.a]*mean[v.b]; break; default: c[k]=v.value; } } }
The references come from an equality view on the column when one exists, and from the current posterior otherwise. Pool solves, refreshes the references, and solves again from the previous multipliers until the second-moment views hold. The demonstration views took 8 passes, and a volatility and correlation view on 200,000 synthetic rows took 47 of the 60 allowed:
for(int pass=1;pass<=m_max_passes;pass++) { if(nonlinear) References(scen,posterior,mean,vol); Build(scen,mean,vol,f,c,rel); vector q; const bool ok=solver.Solve(prior,f,c,rel,q,res); ms+=res.ms; iterations+=res.iterations; m_passes=pass; if(!ok) break; posterior=q; solver.SetWarmStart(true); if(!nonlinear) break; //--- a vol or corr view is met once the achieved value is on target m_miss=0.0; for(int k=0;k<ArraySize(m_v);k++) { if(m_v[k].type!=EP_VIEW_VOLATILITY && m_v[k].type!=EP_VIEW_CORRELATION) continue; const double got=Achieved(k,scen,posterior); double miss=got-m_v[k].value; if(m_v[k].rel==EP_AT_MOST) miss=MathMax(miss,0.0); if(m_v[k].rel==EP_AT_LEAST) miss=MathMax(-miss,0.0); m_miss=MathMax(m_miss,MathAbs(miss)/MathMax(MathAbs(m_v[k].value),1e-12)); } if(m_miss<=m_pass_tol) break; }
This is an iterative approximation. When the loop stops, the posterior meets the stated volatility and correlation, but it is not in general the minimum-relative-entropy posterior of the exact nonlinear constraints, and the multipliers of these views price their second-moment constraints, not the volatility or correlation itself. When a mean view fixes the column's mean, the volatility constraint is linear and the result is exact.
A view says only what it says. The cheapest way to lower the EURUSD/GBPUSD correlation is to take weight from days when both moved far together, which also lowers both volatilities. To change the correlation alone, hold the volatilities explicitly, as the demonstration script does:
CEpViews views; views.AddMean(state_col,EP_EQUAL,z_now); const int v_vol =views.AddVolatility(vol_col,EP_EQUAL,vol_target); const int v_tail=views.AddTail(tail_col,InpTailMove,EP_AT_LEAST,InpTailProb); const int v_corr=views.AddCorrelation(ca,cb,EP_AT_MOST,InpCorr); if(InpCorrPinVol) { vector xa,xb; scen.Column(ca,xa); scen.Column(cb,xb); if(ca!=vol_col) views.AddVolatility(ca,EP_EQUAL,EpVolatility(xa,p_state)); if(cb!=vol_col) views.AddVolatility(cb,EP_EQUAL,EpVolatility(xb,p_state)); }
Conditioning on today's state. The most useful statement for risk is not a subjective view: it is that today's volatility regime applies, so the posterior's average trailing volatility equals today's. That is a single mean view on the state column, giving p_j * exp(theta * z_j), normalised. When today is calmer than the prior's average, theta is negative and the calmest days gain the most weight; when today is stressed, the most stressed days do. The tilt matches the average level of the state rather than picking out days near today's value. The view can be met exactly when the target lies strictly inside the range of the state, and the library solves this scalar case with its own Newton iteration, kept inside a bracket because the derivative is monotone in theta.
//+------------------------------------------------------------------+ //| One mean view: scalar Newton on theta, feasibility known upfront.| //+------------------------------------------------------------------+ bool EpTiltMean(const vector &z,const vector &prior,const double target,vector &q,SEpSolve &res) { const uint t0=GetTickCount(); ZeroMemory(res); res.status=EP_BAD_INPUT; const int T=(int)z.Size(); if(T<2 || (int)prior.Size()!=T) return false; double lo=DBL_MAX,hi=-DBL_MAX,m1=0.0,m2=0.0; for(int j=0;j<T;j++) { if(prior[j]<=0.0) continue; lo=MathMin(lo,z[j]); hi=MathMax(hi,z[j]); m1+=prior[j]*z[j]; m2+=prior[j]*z[j]*z[j]; } res.status=EP_INFEASIBLE; if(!(target>lo && target<hi)) return false; const double s=MathSqrt(MathMax(m2-m1*m1,1e-300));
When a Newton step would leave the bracket, bisection replaces it, so convergence is unconditional:
//--- psi' = E_q[(z - target) / s] rises with theta: Newton inside a bracket double theta=0.0,psi=0.0,mean_g=0.0,blo=-DBL_MAX,bhi=DBL_MAX; bool solved=false; for(int it=0;it<200 && !solved;it++) { double amax=-DBL_MAX; for(int j=0;j<T;j++) if(prior[j]>0.0) amax=MathMax(amax,logp[j]+theta*(z[j]-target)/s); double zsum=0.0,d1=0.0,d2=0.0; for(int j=0;j<T;j++) { if(prior[j]<=0.0) continue; const double g=(z[j]-target)/s; const double e=MathExp(logp[j]+theta*g-amax); zsum+=e; d1 +=e*g; d2 +=e*g*g; } psi =amax+MathLog(zsum); d1 /=zsum; d2 =d2/zsum-d1*d1; mean_g=d1; res.iterations=it+1; res.gradient =MathAbs(d1); if(res.gradient<=1e-13) { solved=true; break; } if(d1<0.0) blo=theta; else bhi=theta; double next=(d2>0.0 ? theta-d1/d2 : EMPTY_VALUE); if(!(next>blo && next<bhi)) { if(blo>-DBL_MAX && bhi<DBL_MAX) next=0.5*(blo+bhi); else next=theta+(d1<0.0 ? 1.0 : -1.0)*MathMax(1.0,2.0*MathAbs(theta)); } theta=next; }
Since ln q is known at the solution, the relative entropy and ENS come from the same final pass:
//--- ln q is already known, so entropy and ENS need no further logarithms q.Init(T); double h=0.0,mz=0.0; for(int j=0;j<T;j++) { if(prior[j]<=0.0) { q[j]=0.0; continue; } const double lq=logp[j]+theta*(z[j]-target)/s-psi; q[j]=MathExp(lq); h -=q[j]*lq; mz +=q[j]*z[j]; } res.status =EP_SOLVED; res.violation=MathAbs(mz-target); res.entropy =theta*mean_g-psi; res.ens =MathExp(h);
Why a scenario budget is needed. A target near the edge of history can only be met by piling the mass onto the few days that were as extreme. On 20 March 2020 the book's trailing volatility was 1.016% per day, and a Gaussian kernel on the state answers that date with 4 effective scenarios. An unconstrained mean view collapses the same way.
EpConditionState adds a budget. If the requested target leaves too few effective scenarios, or lies outside the history, it pulls the target towards the prior mean by bisection until the budget holds, and returns the target it used:
//+------------------------------------------------------------------+ //| Condition on a state, pulling the target towards the prior mean | //| until min_ens scenarios survive. Returns the target it used. | //+------------------------------------------------------------------+ double EpConditionState(const CEpScenarios &scen,const vector &prior,const int col, const double target,const double min_ens,vector &posterior,SEpSolve &res) { vector z; scen.Column(col,z); const double m0 =EpMean(z,prior); const double budget=MathMin(min_ens,EpEffectiveScenarios(prior)); if(EpTiltMean(z,prior,target,posterior,res) && res.ens>=budget) return target; double lo=0.0,hi=1.0; for(int i=0;i<20;i++) { const double mid=0.5*(lo+hi); vector q; SEpSolve r; if(EpTiltMean(z,prior,m0+mid*(target-m0),q,r) && r.ens>=budget) lo=mid; else hi=mid; } const double used=m0+lo*(target-m0); if(!EpTiltMean(z,prior,used,posterior,res)) { posterior=prior; return m0; } return used; }
On 20 March 2020, with a budget of 250, the target moves from 1.016% to 0.638%. That is still far above anything a calm year produces, so the forecast stays a stressed one.

Fig. 3. As the state target moves towards the edge of history the effective number of scenarios collapses; the budget stops the target where 250 scenarios remain
Kernels are close relatives. Adding a variance view on the state to the mean view gives p * exp(theta_1 * z + theta_2 * z^2), which for negative theta_2 is a Gaussian kernel in z with the bandwidth implied by the variance you ask for. The mean-only tilt is the simpler member of that family, and whether it forecasts as well as a kernel is for the walk-forward test to answer. The practical difference is that entropy pooling takes the conditioning and the views in the same solve.
Reading the Posterior: EP_Demo
Once we have a probability vector, every statistic is a weighted sum over the same rows. Only the tail needs care: with unequal weights the tail boundary usually falls inside a row, which must count only with the part of its mass inside the tail. EpTailOrdered walks the rows in ascending order and takes exactly the probability needed, from a sort order computed once and reused for every vector.
//+------------------------------------------------------------------+ //| Quantile and ES at a level; the straddling row counts partially. | //+------------------------------------------------------------------+ bool EpTailOrdered(const vector &x,const int &order[],const vector &p,const double level, double &quantile,double &shortfall) { const int n=(int)x.Size(); if(n<1 || (int)p.Size()!=n || ArraySize(order)!=n || level<=0.0 || level>=1.0) return false; double cum=0.0,sum=0.0; quantile=x[order[n-1]]; for(int i=0;i<n && cum<level;i++) { const int j=order[i]; if(p[j]<=0.0) continue; const double take=MathMin(p[j],level-cum); sum+=take*x[j]; cum+=take; quantile=x[j]; } shortfall=(cum>0.0 ? sum/cum : quantile); return true; }
EP_Demo puts the pieces together: it builds the priors, conditions on the book's state within the budget, adds three views, and prints the book's risk under each vector. The conditioning step is:
//--- condition on the state: tilt the decay prior to today's level, within budget vector p_state; SEpSolve rs; const double z_now=EpConditionState(scen,p_decay,state_col,z_today,InpMinEns,p_state,rs); PrintFormat(" %-24s %s: %d Newton steps, KL %.4f, ENS %.0f", "state conditioning",EnumToString(rs.status),rs.iterations,rs.entropy,rs.ens); if(z_now!=z_today) PrintFormat(" %-24s today's state leaves under %.0f scenarios; target pulled to %.3f%%", "",InpMinEns,100.0*z_now); AddStage("decay | state","state",p_state);
The views are USDJPY volatility at 1.5 times its conditioned level, at least a 1% chance that USDCHF loses 2% or more in a day, and a EURUSD/GBPUSD correlation of at most 0.40 with both volatilities held. They are pooled on the decay prior with the state target as the first view, so conditioning and views are solved together. With InpConfidence below 1 the script also blends the two vectors, Meucci's way of holding views with partial confidence:
vector p_post; SEpSolve rv; const bool pooled=views.Pool(scen,p_decay,solver,p_post,rv); ReportSolve("state and views",rv,views); if(!pooled) return; AddStage("decay | state + views","views",p_post); if(InpConfidence<1.0) { vector p_mix; EpBlend(p_state,p_post,InpConfidence,p_mix); AddStage(StringFormat("blend c=%.2f",InpConfidence),"blend",p_mix); }
Table 2 shows the solve on a calm day, the last bar of the history.
| View | Conditioned | After views | Multiplier |
|---|---|---|---|
| Book volatility state = 0.346% | 0.346% | 0.346% | -0.79 |
| USDJPY daily volatility = 0.855% | 0.570% | 0.855% | 0.31 |
| P(USDCHF <= -2%) >= 1% | 0.43% | 1.00% | 0.12 |
| Correlation EURUSD/GBPUSD <= 0.40 | 0.80 | 0.40 | -1.58 |
| EURUSD and GBPUSD volatility held | 0.389%, 0.417% | 0.389%, 0.417% | 0.44, 0.57 |
Table 2. EP_Demo views on the last bar: 8 passes, 22 Newton steps, worst miss 4.3e-18
For the linear views, the state and the tail, the multiplier is a price per prior standard deviation, so the tail view is cheap next to the state. Signs are reported in the direction of the view. The volatility and correlation multipliers come from the second-moment approximation, so they rank strain rather than measure it; the correlation constraint strains most. Table 3 is the book under every vector; the size column is the position multiple that keeps the 2.5% ES of the rolling window.
| Vector | ENS | KL vs decay | Vol (ann.) | VaR 2.5% | ES 2.5% | Size |
|---|---|---|---|---|---|---|
| Full history | 4655 | 3.896 | 7.32% | -0.898% | -1.206% | - |
| Rolling 250 | 250 | 0.713 | 5.85% | -0.654% | -0.834% | 1.00x |
| Decay, half-life 250 | 980 | 0 | 6.61% | -0.756% | -1.001% | 0.83x |
| Decay times kernel | 672 | 0.296 | 6.07% | -0.744% | -0.948% | 0.88x |
| Decay conditioned on state | 799 | 0.135 | 6.24% | -0.731% | -0.938% | 0.89x |
| Conditioned, with views | 703 | 0.456 | 6.62% | -0.596% | -0.799% | 1.04x |
Table 3. The book on the last bar of the history
Even on a calm day the rolling window is the most optimistic history-based vector: conditioning uses 799 effective scenarios, including calm days the window has forgotten, and asks for about 11% less size. The views lower the book's ES despite raising USDJPY volatility, because the lower correlation lets the three long legs diversify each other.
Table 4 repeats the exercise as of 20 March 2020, using the script's replay input.
| Vector | ENS | Vol (ann.) | ES 2.5% | Size |
|---|---|---|---|---|
| Rolling 250 | 250 | 6.02% | -1.644% | 1.00x |
| Decay, half-life 250 | 978 | 6.21% | -1.430% | 1.15x |
| Decay times kernel | 4 | 15.91% | -1.773% | 0.93x |
| Decay conditioned on state, budget 250 | 250 | 13.43% | -1.922% | 0.86x |
| Conditioned, with views | 188 | 14.38% | -1.919% | 0.86x |
Table 4. The book as of 20 March 2020
The rolling window's ES is already large, because the first days of the crash are inside it, but its volatility still says 6%. Conditioning puts the volatility at 13.4% and the ES at 1.92%; the kernel reaches a similar volatility on 4 scenarios, the collapse the budget exists to prevent. The views solve in 19 passes and leave 188 effective scenarios, below the budget, because the budget governs only the conditioning step.
Does Conditioning Forecast Risk Better?
A single date proves nothing, so EP_WalkForward forecasts the book's next-day VaR and ES at every row using only the rows before it. After a 1,000-row warm-up that gives 3,655 forecasts, from late 2012 to September 2026, for seven methods: two rolling windows, exponential decay, a RiskMetrics variance with a normal tail, the kernel with a bandwidth of half the state's standard deviation, and state conditioning with and without the budget.
//--- the state for row r was known before its bar opened const double sd=EpVolatility(z,p[M_DECAY]); EpKernel(z,z[r],InpKernelBand*sd,p[M_DECAY],p[M_KERNEL]); SEpSolve res; EpConditionState(scen,p[M_DECAY],state_col,z[r],0.0,p[M_STATE_FREE],res); if(EpConditionState(scen,p[M_DECAY],state_col,z[r],InpMinEns,p[M_STATE],res)!=z[r]) bound++;
Three scores are reported: the share of VaR hits with Kupiec's test; the FZ0 loss of Patton, Ziegel and Chen, which scores VaR and ES jointly, lower being better; and Diebold-Mariano statistics on the FZ0 differences, where values below about -2 indicate a significantly lower loss.
//+------------------------------------------------------------------+ //| FZ0 loss of Patton, Ziegel and Chen, joint for VaR and ES. | //+------------------------------------------------------------------+ double Fz0(const double y,const double var,const double es,const double level) { const double hit=(y<=var ? 1.0 : 0.0); return -hit*(var-y)/(level*es)+var/es+MathLog(-es)-1.0; } //+------------------------------------------------------------------+ //| Kupiec's p-value for the VaR hit rate against the level. | //+------------------------------------------------------------------+ double KupiecP(const int hits,const int n,const double level) { const double pi=(double)hits/n; double lr=-2.0*((n-hits)*MathLog(1.0-level)+hits*MathLog(level)); if(hits>0 && hits<n) lr+=2.0*((n-hits)*MathLog(1.0-pi)+hits*MathLog(pi)); int err=0; return 1.0-MathCumulativeDistributionChiSquare(lr,1.0,err); }
Table 5 shows the result for the book at the 2.5% level.
| Method | Mean ENS | Min ENS | VaR hits | Kupiec p | FZ0 | DM vs rolling | DM vs decay | DM vs kernel |
|---|---|---|---|---|---|---|---|---|
| Rolling 250 | 250 | 250 | 3.04% | 0.044 | -4.494 | 0 | 1.59 | 2.22 |
| Rolling 60 | 60 | 60 | 3.06% | 0.035 | -4.520 | -0.59 | 0.16 | 1.97 |
| Decay 250 | 953 | 764 | 2.35% | 0.565 | -4.528 | -1.59 | 0 | 1.85 |
| EWMA 0.94, normal | - | - | 3.17% | 0.012 | -4.587 | -1.83 | -1.34 | 0.31 |
| Decay times kernel | 527 | 4 | 2.57% | 0.782 | -4.593 | -2.22 | -1.85 | 0 |
| State, no budget | 706 | 1 | 2.74% | 0.368 | n/a | n/a | n/a | n/a |
| State, ENS >= 250 | 723 | 250 | 2.22% | 0.263 | -4.601 | -2.23 | -1.96 | -0.76 |
Table 5. EP_WalkForward, book at the 2.5% level, 3,655 forecasts
Both rolling windows are breached too often, and Kupiec's test rejects them at 5%, as it does the normal tail on an EWMA variance. Conditioning with a budget has the lowest joint loss and an accepted coverage, and it improves significantly on the rolling window, as the kernel does. Against its decay prior the statistic is -1.96: a modest gain at the edge of significance. The budget bound on 442 forecasts, about one in eight. Without it, conditioning collapsed to a single scenario on the most extreme days, and 6 forecasts had a non-negative ES, where FZ0 is undefined. At the 1% level the budgeted version scores -2.11 against the rolling window, -1.93 against decay and -0.04 against the kernel, with a Kupiec p-value of 0.93.
Settings and sub-periods. The defaults are conventional rather than tuned on a held-out period, and other budgets were tried during development. Table 6 varies one setting at a time and splits the forecasts into halves.
| Setting | VaR hits | Kupiec p | DM vs rolling | DM vs decay | DM vs kernel |
|---|---|---|---|---|---|
| Defaults, as in Table 5 | 2.22% | 0.263 | -2.23 | -1.96 | -0.76 |
| Budget 100 | 2.35% | 0.565 | -2.12 | -1.81 | -0.32 |
| Budget 500 | 2.11% | 0.118 | -2.21 | -1.99 | -0.69 |
| Half-life 125 | 2.33% | 0.494 | -2.19 | -1.66 | -1.77 |
| Half-life 500 | 2.05% | 0.074 | -2.05 | -2.30 | 0.28 |
| State window 10 | 2.02% | 0.054 | -1.85 | -1.54 | 0.05 |
| State window 60 | 2.27% | 0.365 | -2.65 | -2.09 | -0.48 |
| Kernel bandwidth 0.25 SD | 2.22% | 0.263 | -2.23 | -1.96 | -2.01 |
| Kernel bandwidth 1.0 SD | 2.22% | 0.263 | -2.23 | -1.96 | -0.51 |
| First half, Aug 2012 to Aug 2019 | 1.53% | 0.004 | -2.03 | -1.86 | 0.83 |
| Second half, Aug 2019 to Sep 2026 | 2.90% | 0.286 | -1.73 | -1.48 | -1.32 |
Table 6. Budgeted state conditioning at the 2.5% level under other settings and in each half of the forecasts; each benchmark is run under the same setting
No setting changes the conclusion: conditioning beats the rolling window and its decay prior in every row and stays level with the kernel. The bandwidth rows change only the kernel. The halves expose one weakness. In the calm years 2012 to 2019 the forecast is too cautious, with 1.53% of days breaking its VaR, which Kupiec rejects. The budget is the cause: it bound on 303 first-half forecasts, 267 of them calm days, where it pulls the target up from the quiet edge of the history towards average volatility.
Other baskets. Table 7 repeats the test on five other currency baskets.
| Basket, equal notional | Forecasts | VaR hits | Kupiec p | DM vs rolling | DM vs decay | DM vs kernel |
|---|---|---|---|---|---|---|
| All long: EURUSD, AUDUSD, USDJPY, USDCHF | 3,655 | 2.60% | 0.703 | -2.42 | -2.22 | -1.46 |
| Long the dollar: long USDJPY, USDCAD, short EURUSD, GBPUSD | 3,655 | 2.33% | 0.494 | -2.46 | -2.57 | -1.26 |
| Yen carry: long EURJPY, GBPJPY, AUDJPY | 3,936 | 2.21% | 0.235 | -2.27 | -1.94 | -0.13 |
| European crosses: long EURGBP, EURCHF, AUDNZD | 3,925 | 2.17% | 0.170 | -1.89 | -3.47 | -0.92 |
| Commodity currencies: long AUDUSD, NZDUSD, short USDCAD | 3,655 | 2.22% | 0.263 | -1.47 | -1.50 | -0.26 |
Table 7. Budgeted state conditioning at the 2.5% level on other baskets, forecasts ending 14 September 2026
Conditioning never does worse than the rolling window or the decay prior and stays level with the kernel, but the edge varies: clear on the first three books, small on the European crosses, and not significant on the commodity currencies. At the 1% level it shrinks further, and only the main book stays significantly ahead of the window. On these currency baskets, then, budgeted conditioning matches or beats a lookback window, modestly improves on its decay prior and matches a kernel, while being the only one of them that takes views.
The Indicator: EP_ViewCost
EP_ViewCost draws the conditioned risk of the book under the price chart. It loads the basket at the chart's timeframe and forecasts each bar from the bars before it, exactly as the walk-forward script does, so every bar on the chart shows the risk that was forecast before it opened. The book's return is drawn as a histogram, red on the bars where it broke that bar's VaR. The conditioned VaR and ES are drawn as lines, with the ES line turning orange where the budget had to pull the state target back, and the rolling window's ES is drawn dashed for comparison.
//+------------------------------------------------------------------+ //| Forecast row r from earlier rows: VaR, ES, window ES, ENS, bound.| //+------------------------------------------------------------------+ bool Forecast(const int r,double &var,double &es,double &es_window,double &ens,bool &bound, vector &p_decay,vector &p_state) { const int T=g_scen.Rows(); if(r<InpWindow || r>T) return false; const double target=(r<T ? g_state[r] : g_scen.Next(g_state_col)); DecayBefore(r,p_decay); SEpSolve res; const double used=EpConditionState(g_scen,p_decay,g_state_col,target,InpMinEns,p_state,res); bound=(used!=target); ens =EpEffectiveScenarios(p_state); if(!EpTailOrdered(g_book,g_order,p_state,InpLevel,var,es)) return false; vector p_roll; p_roll.Init(T); p_roll.Fill(0.0); for(int i=r-InpWindow;i<r;i++) p_roll[i]=1.0/InpWindow; double var_window; return EpTailOrdered(g_book,g_order,p_roll,InpLevel,var_window,es_window); }
The buffer layout lives in the library, so an Expert Advisor can rely on the indices through iCustom:
//--- indicator buffer map, fixed for EAs reading it through iCustom enum ENUM_EP_BUFFER { EP_BUF_RETURN = 0, // book return of the bar, percent EP_BUF_RETURN_COLOR = 1, // 0 inside VaR, 1 breach EP_BUF_VAR = 2, // conditioned VaR for the bar, percent EP_BUF_ES = 3, // conditioned ES for the bar, percent EP_BUF_ES_COLOR = 4, // 0 state met, 1 target pulled back by the budget EP_BUF_ES_WINDOW = 5, // rolling-window ES, percent EP_BUF_ENS = 6, // effective scenarios behind the conditioned ES EP_BUF_SIZE = 7, // rolling ES over conditioned ES: size that keeps risk EP_BUF_ES_VIEWS = 8 // forming bar only: ES once the views are pooled in };
Forecasting 750 bars takes a couple of seconds, too long for one call on the chart, so the indicator works in 100-millisecond slices. When a slice ends with work left, it posts a custom event to its own chart and resumes in OnChartEvent; a refresh request would restart from the first bar instead. In the Strategy Tester everything is computed in one call, and without a subwindow, as when an EA creates it through iCustom, each call works for 250 milliseconds and the next continues from the same bar.
//--- the tester runs it all at once; on a chart the rest follows in slices if(MQLInfoInteger(MQL_TESTER)) { Work(0); return rates_total; } const bool on_chart=(ChartWindowFind(0,g_short)>0); Work(on_chart ? 100 : 250); if(on_chart) NextSlice(); return rates_total; } //+------------------------------------------------------------------+ //| Queue the next slice as a chart event; a refresh would restart. | //+------------------------------------------------------------------+ void NextSlice(void) { if(!g_reload && (g_cursor<g_rates || g_panel_due)) EventChartCustom(0,EP_EVENT_SLICE,0,0.0,g_short); } //+------------------------------------------------------------------+ //| Resume a slice where it stopped, without restarting the pass. | //+------------------------------------------------------------------+ void OnChartEvent(const int id,const long &lparam,const double &dparam,const string &sparam) { if(id!=CHARTEVENT_CUSTOM+EP_EVENT_SLICE || sparam!=g_short) return; Work(100); NextSlice(); }
A panel on the price chart shows the forming bar: the ES and size multiple under each vector, an effective-scenario gauge with the budget marked, and the book's distribution before and after the views.

Fig. 4. EP_ViewCost on EURUSD D1: book returns with VaR breaches in red, conditioned VaR and ES, the rolling-window ES, and the forming-bar panel
The Expert Advisor: EP_Sizer
EP_Sizer separates two decisions that trading programs usually mix. The direction of the book is an input: a list of symbols and signed notional weights. Its size is the output: once per D1 bar the EA reads the forming bar's ES forecast from EP_ViewCost and sets the gross notional so that the forecast ES equals a fixed share of equity. The indicator is created with its panel switched off and only the last two bars to compute.
g_ind=iCustom(g_symbols[0],InpTimeframe,"EP\\EP_ViewCost", "",InpSymbols,InpWeights,InpBars,2, "",InpWindow,InpHalfLife,InpStateWindow,InpMinEns,InpLevel, "",(InpSizing==EP_SIZING_VIEWS),InpVolSymbol,InpVolScale,InpTailSymbol,InpTailMove, InpTailProb,InpCorrA,InpCorrB,InpCorr, "",false);
Each empty string fills the slot of an input group, which iCustom counts as a parameter. The input InpSizing chooses which buffer sets the size: the rolling window, the conditioned forecast, or the conditioned forecast with the views. Everything else, including every trade, is identical across the three modes, so running the EA three times is a controlled comparison of the forecasts alone.
//+------------------------------------------------------------------+ //| Size the book so its forecast ES equals the budget, then trade. | //+------------------------------------------------------------------+ bool Rebalance(void) { double es,ens; if(!ForecastEs(es,ens)) return false; const double equity=AccountInfoDouble(ACCOUNT_EQUITY); double gross_w=0.0; for(int i=0;i<ArraySize(g_weights);i++) gross_w+=MathAbs(g_weights[i]); double scale=InpBudget/100.0*equity/(-es); if(scale*gross_w>InpMaxLeverage*equity) scale=InpMaxLeverage*equity/gross_w; string lots=""; bool done=true; for(int i=0;i<ArraySize(g_symbols);i++) { const double unit=LotNotional(g_symbols[i]); if(unit<=0.0) { PrintFormat("EP_Sizer: cannot value a lot of %s in %s",g_symbols[i],AccountInfoString(ACCOUNT_CURRENCY)); continue; } const double target=scale*g_weights[i]/unit; if(!SetLeg(g_symbols[i],target)) done=false; lots+=StringFormat(" %s %+.2f",g_symbols[i],target); } //--- a closed market or a refused order: try again on the next tick if(!done) return false; if(g_eq_prev>0.0) { const int n=ArraySize(g_ret); ArrayResize(g_ret,n+1,4096); ArrayResize(g_when,n+1,4096); g_ret[n] =equity/g_eq_prev-1.0; g_when[n]=g_bar_prev; } const int m=ArraySize(g_lev); ArrayResize(g_lev,m+1,4096); g_lev[m]=scale*gross_w/equity; g_eq_prev =equity; g_bar_prev=g_last_bar; if(!g_described) { g_described=true; PrintFormat("EP_Sizer: equity %.2f, forecast ES %.3f%% from %.0f scenarios, gross %.2fx, lots%s", equity,100.0*es,ens,scale*gross_w/equity,lots); } return true; }
Each leg's lot size is its notional divided by the value of one lot in the account currency. A leg is left alone while it is within 10% of its target, which keeps the EA from trading on noise in the forecast. On a hedging account the opposite side is closed first, so a leg never holds both directions. If the market is closed on the first tick of a new day, the whole rebalance is repeated on the next tick.
Scoring the promise. The EA promises that on the worst 2.5% of days the book loses 1% of equity on average. OnTester computes the realised ES over the whole test and for each calendar year and prints its ratio to the budget; the optimisation criterion is minus the distance of that ratio from 1.
//+------------------------------------------------------------------+ //| Realised ES over returns [a,b] and the count beyond the budget. | //+------------------------------------------------------------------+ double RealisedEs(const int a,const int b,int &beyond) { const int n=b-a+1; double r[]; ArrayResize(r,n); beyond=0; for(int i=0;i<n;i++) { r[i]=g_ret[a+i]; if(-r[i]>InpBudget/100.0) beyond++; } ArraySort(r); const int tail=MathMax(1,(int)MathFloor(InpLevel*n)); double worst=0.0; for(int i=0;i<tail;i++) worst+=r[i]; return -worst/tail; }
//+------------------------------------------------------------------+ //| Criterion: -|realised ES / budget - 1|, best when on budget. | //+------------------------------------------------------------------+ double OnTester(void) { const int n=ArraySize(g_ret); if(n<50) return 0.0; double r[]; ArrayCopy(r,g_ret); ArraySort(r); const int tail=MathMax(1,(int)MathFloor(InpLevel*n)); double worst=0.0,m1=0.0,m2=0.0,lev=0.0; int breaches=0; for(int i=0;i<tail;i++) worst+=r[i]; for(int i=0;i<n;i++) { m1+=g_ret[i]; m2+=g_ret[i]*g_ret[i]; if(-g_ret[i]>InpBudget/100.0) breaches++; } for(int i=0;i<ArraySize(g_lev);i++) lev+=g_lev[i]; const double es_real=-worst/tail; const double vol =MathSqrt(MathMax(m2/n-(m1/n)*(m1/n),0.0))*MathSqrt(252.0); const double ratio =es_real/(InpBudget/100.0); //--- the same measure one calendar year at a time int a=0; while(a<n) { MqlDateTime d; TimeToStruct(g_when[a],d); int b=a; MqlDateTime e; while(b+1<n && TimeToStruct(g_when[b+1],e) && e.year==d.year) b++; int beyond; const double es_year=RealisedEs(a,b,beyond); double lev_year=0.0; for(int i=a;i<=b && i<ArraySize(g_lev);i++) lev_year+=g_lev[i]; PrintFormat("EP_Sizer YEAR %d bars %d realised ES %.3f%% ratio %.3f beyond budget %d gross %.2fx", d.year,b-a+1,100.0*es_year,es_year/(InpBudget/100.0),beyond,lev_year/(b-a+1)); a=b+1; } PrintFormat("EP_Sizer RESULT %s bars %d realised ES %.3f%% ratio %.3f losses beyond budget %.2f%% " "vol %.2f%% worst %.2f%% avg gross %.2fx profit %.2f dd %.2f%% trades %.0f", EnumToString(InpSizing),n,100.0*es_real,ratio,100.0*breaches/n,100.0*vol,100.0*r[0], lev/MathMax(ArraySize(g_lev),1),TesterStatistics(STAT_PROFIT), TesterStatistics(STAT_EQUITY_DDREL_PERCENT),TesterStatistics(STAT_TRADES)); return -MathAbs(ratio-1.0); }
Test setup. EURUSD H1, open prices only, June 2009 to September 2026, a deposit of 1,000,000 USD, a 1% ES budget at the 2.5% tail and a leverage cap of 5. The EA acts on the first H1 bar of each D1 bar, inside trading hours. The scenario set grows as the test runs: the first forecast arrives in September 2010, once the joint history holds 500 bars, and each later forecast uses all the history available at that moment. History, spreads, commission and swap come from the FundedNext-Server trade server, on a hedging USD account with leverage of 1:100, and the tester loads the other four symbols itself. Execution is the tester's default zero latency, so no slippage is modelled, and today's commission and swap rates apply to the whole period.
Table 8 shows the result year by year for the rolling window and the conditioned forecast.
| Year | Rolling 250 | Conditioned |
|---|---|---|
| 2011 | 1.377 | 1.179 |
| 2012 | 0.676 | 0.837 |
| 2013 | 1.138 | 0.931 |
| 2014 | 1.269 | 1.086 |
| 2015 | 1.055 | 1.052 |
| 2016 | 1.134 | 1.149 |
| 2017 | 0.737 | 0.789 |
| 2018 | 1.178 | 0.969 |
| 2019 | 0.884 | 0.746 |
| 2020 | 1.682 | 1.104 |
| 2021 | 1.073 | 1.040 |
| 2022 | 1.286 | 1.062 |
| 2023 | 0.835 | 0.941 |
| 2024 | 1.161 | 1.087 |
| 2025 | 0.957 | 0.996 |
| Mean |ratio - 1| | 0.218 | 0.103 |
Table 8. Realised ES divided by budget, by calendar year
Conditioned sizing is closer to its budget in 13 of the 15 full years, a one-sided sign-test p-value of 0.004. The rolling window overshoots by more than 20% in 2011, 2014, 2020 and 2022, each a year in which stress followed calm, and undershoots in calm years such as 2012 and 2017. Conditioned sizing never exceeds 1.18. With about six tail days a year a single row is noisy; the evidence is the pattern across fifteen.

Fig. 5. Realised ES divided by budget for each year, rolling window against conditioned sizing, with the promise of 1.0 marked
March 2020 shows the mechanism. On 9 March the rolling window still forecast an ES of 0.59%, unchanged since February, and held the book at 1.70 times equity; conditioning had seen the state rise, forecast 0.88% and held 1.13. On 10 March the book lost 2.85% under the window and 1.86% under conditioning. The window cut only as the crash entered it, to 1.25 times equity on 12 March and 0.61 by 23 March, against 0.73 and 0.52 for the conditioned book.

Fig. 6. Gross leverage set by each sizing from January to June 2020
Over the whole test the realised ES is 1.123% for the rolling window and 0.992% for conditioned sizing, days beyond the budget are 1.35% and 0.87%, the worst days -2.85% and -2.59%, and average gross leverage 0.99 and 0.96. Conditioned sizing trades more, 1,080 times against 249, because its forecast follows the state.
Costs and the band. Commission totals about 650 USD against 165, and spread, estimated as half the spread on each fill, roughly 4,000 against 900: a small fraction of a basis point a day against a 100-basis-point budget. Removing or doubling these costs leaves every ratio in Table 8 unchanged at the third decimal. With the band at 5% or 20% instead of 10%, conditioned sizing is still closer to its budget in 13 of the 15 years. The views mode is not scored, because replaying the same fixed opinions over sixteen years says nothing about them.
Conclusion
A lookback window is a probability vector nobody chose: it forgets stress in calm periods and cannot take in information outside its history. Entropy pooling makes the choice explicit: keep every scenario, and choose the probabilities closest to a prior that satisfy what you want to be true, whether that is today's volatility regime or a view on a single pair.
To apply it to your own book with the attached library:
- Build the joint history with LoadReturns, add the book as a column with EpPortfolio, and add a state known before each bar with AddTrailingVolatility.
- Choose a prior. This article uses exponential decay with a half-life of 250 bars.
- Condition on today's state with EpConditionState and a scenario budget; our results held for budgets from 100 to 500.
- Add views with CEpViews. When a view concerns a correlation, hold the volatilities you do not mean to change.
- Read the posterior with EpTailOrdered, and size so that the forecast ES equals your budget.
- Score the result by the ratio of realised ES to budget, per year, rather than by profit.
And know when to stop:
- The budget binds. If EpConditionState returns a target different from the one requested, today is at the edge of the history, which happened on one forecast in eight in our test. The forecast is the most extreme one the data can support, not an extrapolation, and on a calm day it errs on the cautious side.
- A view is infeasible. If the solver reports that the views cannot be met, no reweighting of the history can produce that world. Relax the view rather than forcing it.
- A multiplier is large. A view whose multiplier dominates the others is fighting the data hardest and deserves a second look before it moves a position. For volatility and correlation views, treat the multiplier as a guide only.
- The effective number of scenarios is small. A posterior resting on a few dozen days is precise about those days and uninformative about the rest.
On the currency baskets tested, the walk-forward test and the Expert Advisor agree. Conditioning within a budget forecasts tail risk at least as well as a lookback window and usually better, adds modestly to its decay prior, matches a kernel, and holds a book close to its risk budget where the window overshot in years when stress followed calm. The result survives the settings we varied and trading costs; it is too cautious in long calm spells, weaker at the 1% tail, and untested on other asset classes. What it adds beyond a kernel is that the same solve accepts views, so information outside the history enters the risk numbers through one measurable change of probabilities.
Getting the Source Code via MQL5 Algo Forge
All source files are attached to this article below, but the full repository is also available on MQL5 Algo Forge, the community's Git-based platform for sharing and collaborating on trading projects.
| File name | Description |
|---|---|
| MQL5\Include\EntropyPooling\Scenarios.mqh | Joint scenario matrix: shared bar times, log returns, book and state columns, history replay |
| MQL5\Include\EntropyPooling\Probabilities.mqh | Prior builders (uniform, rolling window, exponential decay, kernel), effective scenarios, relative entropy |
| MQL5\Include\EntropyPooling\MinRelEntropy.mqh | Dual Newton solver for the minimum relative entropy posterior with equality and inequality views |
| MQL5\Include\EntropyPooling\Views.mqh | View types, sequential second-moment views, scalar state tilt and budgeted state conditioning |
| MQL5\Include\EntropyPooling\Posterior.mqh | Weighted moments, exact weighted VaR and ES, book returns, confidence blending, indicator buffer map |
| MQL5\Scripts\EP\EP_Demo.mq5 | Priors, state conditioning and views on a currency basket, with a replay date input |
| MQL5\Scripts\EP\EP_Checks.mq5 | Checks of the library against closed-form results on synthetic Gaussian scenarios |
| MQL5\Scripts\EP\EP_WalkForward.mq5 | Walk-forward comparison of VaR and ES forecasts: coverage, FZ0 loss, Diebold-Mariano tests and how often the budget binds |
| MQL5\Indicators\EP\EP_ViewCost.mq5 | Conditioned VaR and ES of a basket per bar, with a forming-bar panel on the chart |
| MQL5\Experts\EP\EP_Sizer.mq5 | Holds a basket at a fixed expected-shortfall budget sized by the indicator's forecast |
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.