preview
Volatility Sizing Under Controlled Stress in MQL5 (Part 2): Heavy Tails, Outliers, and Risk Recovery

Volatility Sizing Under Controlled Stress in MQL5 (Part 2): Heavy Tails, Outliers, and Risk Recovery

MetaTrader 5 — Tester |
61 0
Maxell Agustin Aguiran
Maxell Agustin Aguiran

Contents

  1. Introduction
  2. Two kinds of next-bar risk
  3. Build paired stress paths
  4. Keep the sizing decision unchanged
  5. How the stress script works
  6. Run and check the native audit
  7. What changes in the decisions
  8. The response after an isolated outlier
  9. Limits and practical use
  10. Conclusion


Introduction

Returns can alter an estimate of volatility even if the shock is not part of the generator’s persistent variance. In this case, we retain the sizing rule from Part 1. We examine standardized Student-t returns and consider those returns with transient outliers. Our approach to capped exposure captures both base and complete-return risk. This permits us to assess the effect of transient shocks in the context of the persistent variation and the possibility of further shocks. We keep the rolling window at 20 bars and EWMA lambda at 0.94 to compare return mechanisms without changing the sizing rules. The fixed control remains at 0.75. The next-bar standard-deviation target is 0.0075. The exposure cap is 1.5, twice the fixed control, to examine truncation.


Two kinds of next-bar risk

In the stress test, persistent GARCH variance is updated by the squared base return; shocks are simply added to the return. Thus a given estimator can remember a transient shock.

base_r_t = sqrt(h_t) * z_t
observed_r_t = base_r_t + outlier_t
h_(t+1) = omega + alpha * base_r_t^2 + beta * h_t

The shock is sign-symmetric, occurs with probability 0.02, and has magnitude equal to 4× the base-return standard deviation. Its expectation is zero, and its conditional variance is 0.02 × 16h, or 0.32h. Thus, complete next-bar return variance is 1.32 times the latent next-bar base-return variance. The variances coincide for the uncontaminated case.

0.02*16*h_t = 0.32*h_t
full_h_(t+1) = h_(t+1) * (1 + 0.02 * 4^2)
             = 1.32 * h_(t+1)

base_oracle_risk and full_oracle_risk multiply the exposure value by the respective next-bar variance’s square root. Both measure conditional standard deviation in log-return units. estimated_exposure_risk uses a forecast, and next_realized_exposure_return is the signed outcome.


Build paired stress paths

The protocol table saves the frozen settings. The Part 1 base variance and GARCH parameters are preserved. The rolling window and EWMA memory also stay fixed to isolate the changed return process. Student-t(5) distributional assumptions allow heavier-tailed returns with finite variance. Standardization is used to preserve the base variance level. Independent shocks with 2% probability and magnitude four standard deviations are illustrative stress settings, not market estimates or optimized choices. FinStressTS supports the rationale behind the stress test design.

Related reading: MQL5-based works.

Protocol item

Frozen value / role

Seeds

104729, 130363, 155921, 180503, 205279, 229969, 254749, 279511

Base GARCH

Initial/long-run variance 0.0001; alpha 0.08; beta 0.90; omega 0.000002; persistence 0.98

Innovations

Student-t(5), standardized to mean 0 and variance 1

Outliers

Independent p=0.02; symmetric sign; magnitude 4sqrt(current h); excluded from base recurrence

Pairing

Same completed innovation/event/sign tape in both scenarios

Estimators

Rolling 20 squared returns; EWMA lambda 0.94; initial EWMA 0.0001

Sizing

Target SD 0.0075; cap 1.5; fixed exposure 0.75

Timing

801 observations; 200 burn-in; 600 decisions after bars 201–800; outcomes 202–801

Outputs

28,800 decision rows; 48 summaries; 600 rows per scenario/seed/method

Relative to the 1% base standard deviation, the exposure is fixed at 0.75. The long-run variance of the contaminated complete-return process is 0.000132.

0.0075 / 0.01 = 0.75

The first 200 observations reduce EWMA’s direct initial weight to 0.94^200 and fill the rolling window. The only difference between the scenarios is the presence of flagged shocks.

A paired heavy-tail path with transient outliers

Figure 1: paired Student-t returns with and without transient outliers

Figure 1. Seed 104729, observed bars 250–350 from the native ledger. The paths coincide except at bars marked as outliers. The marks are data events, not trading signals or corrected bad quotes.


Keep the sizing decision unchanged

After bar t, RunPath updates the estimators and passes their forecasts to SizeForVariance to determine exposure for t+1. Only after exposure selection does WriteRow add the next-bar latent variances and the next-bar observed return. The field-group table indicates this boundary.

Field group Values Role

Decision input

observed_bar, observed_return

Available through the decision cutoff

Estimator and request

estimated_next_variance, desired_exposure, exposure, capped

Produced by the frozen sizing rule

Generator audit

next_base_variance, next_full_variance, base_oracle_risk, full_oracle_risk

Hidden from the decision path

Later outcome

next_observed_return, next_realized_exposure_return, tail_hit

Known only after the sized bar

A tail_hit means the next-bar scaled return is more than 0.015 (in absolute terms) and is either positive or negative. It is a descriptive event flag.


How the stress script works

The main component of VolatilitySizing, VolatilitySizingCore.mqh, contains the estimator state and variance-to-exposure sizing. SizingTailAudit.mq5 manages the experiment. OnStart draws one tape per random seed, MakePath generates paired paths, RunPath observes and sizes each path, and WriteRow books decisions and updates method totals. The Python code rebuilds the process and checks results.

Estimate variance and choose exposure

The window, lambda and positive initial variance are validated by Init. The EWMA is seeded. The estimator uses nondemeaned squared returns. After being initialized, RollingVariance will not be usable until 20 returns have been observed. EWMAVariance is usable after the first return.

   //--- CVolatilitySizingCore::CVolatilitySizingCore: Start with invalid, empty estimator state
                     CVolatilitySizingCore(void)
     {
      m_window=0;
      m_seen=0;
      m_lambda=0.0;
      m_ewma=0.0;
      m_rolling_sum=0.0;
      m_valid=false;
     }
   //--- CVolatilitySizingCore::Init: Validate settings, allocate the ring and reset the estimator
   bool              Init(const int rolling_window,const double lambda,const double initial_variance)
     {
      m_valid=false;
      if(rolling_window<1 || !MathIsValidNumber(lambda) || lambda<0.0 || lambda>=1.0 ||
         !MathIsValidNumber(initial_variance) || initial_variance<=0.0)
         return false;
      if(ArrayResize(m_squared,rolling_window)!=rolling_window)
         return false;
      ArrayInitialize(m_squared,0.0);
      m_window=rolling_window;
      m_seen=0;
      m_lambda=lambda;
      m_ewma=initial_variance;
      m_rolling_sum=0.0;
      m_valid=true;
      return true;
     }

The model’s mean is zero, so estimators use squared returns and do not center them by the sample mean. Each of the last twenty observed squares has been assigned a weight of 1/20, and the contribution of that squared value is removed when it moves out of the rolling window. EWMA gives the most recent square a weight of 0.06, and multiplies that by 0.94 at each subsequent step. Compared to an unshocked update from the same prior estimator state, a shock that increases the squared return increases the forecast and reduces the exposure requested. A base return can also be offset by a signed shock.

   //--- CVolatilitySizingCore::Observe: Update the rolling ring and EWMA with one finite return
   bool              Observe(const double zero_mean_log_return)
     {
      if(!m_valid || !MathIsValidNumber(zero_mean_log_return))
         return false;
      const double squared=zero_mean_log_return*zero_mean_log_return;
      if(!MathIsValidNumber(squared))
         return false;
      //--- Observe: Update the squared-return ring and EWMA state
      const int slot=m_seen%m_window;
      if(m_seen>=m_window)
         m_rolling_sum-=m_squared[slot];
      m_squared[slot]=squared;
      m_rolling_sum+=squared;
      m_ewma=m_lambda*m_ewma+(1.0-m_lambda)*squared;
      m_seen++;
      return true;
     }
   //--- CVolatilitySizingCore::Ready: Report whether the rolling observation window is complete
   bool              Ready(void) const { return m_valid && m_seen>=m_window; }

   //--- CVolatilitySizingCore::Observations: Return the number of successfully observed returns
   int               Observations(void) const { return m_seen; }

   //--- CVolatilitySizingCore::RollingVariance: Return the mean squared return or EMPTY_VALUE
   double            RollingVariance(void) const
     {
      if(!Ready())
         return EMPTY_VALUE;
      return m_rolling_sum/m_window;
     }

   //--- CVolatilitySizingCore::EWMAVariance: Return updated EWMA variance or EMPTY_VALUE
   double            EWMAVariance(void) const
     {
      if(!m_valid || m_seen<1)
         return EMPTY_VALUE;
      return m_ewma;
     }

SizeForVariance divides target standard deviation by forecast standard deviation. It then sets the desired exposure and its minimum with the cap. Equality does not set capped; only a larger request does. Estimated risk is exposure times the standard deviation of the forecast.

//+------------------------------------------------------------------+
//| SizeForVariance - turn variance into capped exposure             |
//+------------------------------------------------------------------+
SizingDecision SizeForVariance(const double forecast_variance,
                               const double target_standard_deviation,
                               const double maximum_exposure)
  {
   SizingDecision result;
   result.valid=false;
   result.capped=false;
   result.desired_exposure=0.0;
   result.exposure=0.0;
   result.estimated_risk=0.0;
   if(forecast_variance==EMPTY_VALUE ||
      !MathIsValidNumber(forecast_variance) || forecast_variance<=0.0 ||
      !MathIsValidNumber(target_standard_deviation) || target_standard_deviation<=0.0 ||
      !MathIsValidNumber(maximum_exposure) || maximum_exposure<=0.0)
      return result;
//--- SizeForVariance: Convert forecast variance to capped exposure
   const double standard_deviation=MathSqrt(forecast_variance);
   const double desired=target_standard_deviation/standard_deviation;
   if(!MathIsValidNumber(desired) || desired<0.0)
      return result;
   result.valid=true;
   result.desired_exposure=desired;
   result.exposure=MathMin(desired,maximum_exposure);
   result.capped=(desired>maximum_exposure);
   result.estimated_risk=result.exposure*standard_deviation;
   return result;
  }

CScalarVarianceGenerator is a shared-header fixture. Part 2 builds its paired paths in MakePath.

// Scalar GARCH fixture. This is not FinStressTS's multi-asset factor generator.
//+------------------------------------------------------------------+
//| CScalarVarianceGenerator                                         |
//+------------------------------------------------------------------+
class CScalarVarianceGenerator
  {
private:
   double            m_h;
   double            m_omega;
   double            m_alpha;
   double            m_beta;
   bool              m_valid;

public:
   //--- CScalarVarianceGenerator::CScalarVarianceGenerator: Start with invalid scalar-generator state
                     CScalarVarianceGenerator(void)
     {
      m_h=0.0;
      m_omega=0.0;
      m_alpha=0.0;
      m_beta=0.0;
      m_valid=false;
     }

   //--- CScalarVarianceGenerator::Init: Validate GARCH parameters and initialize latent variance
   bool              Init(const double long_run_variance,const double alpha,const double beta)
     {
      m_valid=false;
      if(!MathIsValidNumber(long_run_variance) || long_run_variance<=0.0 ||
         !MathIsValidNumber(alpha) || alpha<0.0 ||
         !MathIsValidNumber(beta) || beta<0.0 || alpha+beta>=1.0)
         return false;
      m_h=long_run_variance;
      m_alpha=alpha;
      m_beta=beta;
      m_omega=(1.0-alpha-beta)*long_run_variance;
      m_valid=true;
      return true;
     }

   //--- CScalarVarianceGenerator::Step: Emit a scalar return and advance its latent GARCH variance
   bool              Step(const double innovation,double &observed_return,
                          double &current_variance,double &next_variance)
     {
      if(!m_valid || !MathIsValidNumber(innovation))
         return false;
      current_variance=m_h;
      observed_return=MathSqrt(m_h)*innovation;
      next_variance=m_omega+m_alpha*observed_return*observed_return+m_beta*m_h;
      if(!MathIsValidNumber(next_variance) || next_variance<=0.0)
         return false;
      m_h=next_variance;
      return true;
     }
  };

Generate reproducible paired paths

CStressRandom::Init sets the seed. Uniform advances a 32-bit integer state using XOR shifts (Xorshift32). The generator maps the state to the open interval (0, 1) to simulate a uniform random variable. CStressRandom::Normal() consumes two independently sampled uniforms and uses the Box–Muller transform (cosine form).

Draw performs a Student-t(5) draw by combining a normal draw with five squared normal draws and rescaling by sqrt(3/sum) to get unit-variance. Matching the unconditional draw order allows replaying of the draw process for the same seed in Python.

//+------------------------------------------------------------------+
//| CStressRandom                                                    |
//+------------------------------------------------------------------+
class CStressRandom
  {
private:
   uint              m_state;
   //--- CStressRandom::Uniform: Advance xorshift32 and return an open-interval uniform draw
   double            Uniform(void)
     {
      m_state^=(m_state<<13);
      m_state^=(m_state>>17);
      m_state^=(m_state<<5);
      return ((double)m_state+0.5)/4294967296.0;
     }
   //--- CStressRandom::Normal: Use Box-Muller to return one deterministic normal draw
   double            Normal(void)
     {
      const double u=Uniform();
      const double v=Uniform();
      return MathSqrt(-2.0*MathLog(u))*MathCos(6.283185307179586*v);
     }
public:
   //--- CStressRandom::Init: Initialize deterministic xorshift state with a nonzero seed
   void              Init(const uint seed) { m_state=(seed==0 ? 2463534242 : seed); }
   //--- CStressRandom::Draw: Fill a unit-variance t(5) draw, outlier flag and shock sign
   void              Draw(double &standardized_t,bool &outlier,bool &positive)
     {
      //--- Draw: Standardize the Student-t innovation to unit variance
      const double numerator=Normal();
      double chi_squared=0.0;
      for(int k=0;k<5;k++)
        {
         const double n=Normal();
         chi_squared+=n*n;
        }
      //--- Z*sqrt((nu-2)/chi2_nu) has unit variance when nu=5.
      standardized_t=numerator*MathSqrt(3.0/chi_squared);
      outlier=(Uniform()<OUTLIER_PROBABILITY);
      positive=(Uniform()<0.5);
     }
  };

MakePath allocates 801 StressBar records, and sets h to 0.0001. Shocks are only added to observed_return if contamination is set and the shared event flag is set. The base return is then used to compute the next-bar variance.

//+------------------------------------------------------------------+
//| MakePath - construct a paired controlled stress path             |
//+------------------------------------------------------------------+
bool MakePath(const double &innovations[],const bool &flags[],const bool &signs[],
              const bool contaminated,StressBar &bars[])
  {
   const int total=BURN_IN+EVALUATION_BARS+1;
   if(ArrayResize(bars,total)!=total)
      return false;
   double h=LONG_RUN_VARIANCE;
   const double omega=(1.0-GARCH_ALPHA-GARCH_BETA)*LONG_RUN_VARIANCE;
   for(int i=0;i<total;i++)
     {
      bars[i].base_innovation=innovations[i];
      bars[i].current_base_variance=h;
      //--- MakePath: Keep the base recursion separate from the additive shock
      bars[i].base_return=MathSqrt(h)*innovations[i];
      bars[i].outlier=(contaminated && flags[i]);
      const double shock=bars[i].outlier ?
                         (signs[i] ? OUTLIER_SCALE : -OUTLIER_SCALE)*MathSqrt(h) : 0.0;
      bars[i].observed_return=bars[i].base_return+shock;
      bars[i].next_base_variance=omega+GARCH_ALPHA*bars[i].base_return*bars[i].base_return+GARCH_BETA*h;
      if(!MathIsValidNumber(bars[i].next_base_variance) || bars[i].next_base_variance<=0.0)
         return false;
      h=bars[i].next_base_variance;
     }
   return true;
  }

Process paths and record decisions

//+------------------------------------------------------------------+
//| ClearTotals - clear the stress-audit accumulators                |
//+------------------------------------------------------------------+
void ClearTotals(MethodTotals &a)
  {
   a.count=0;
   a.capped=0;
   a.tail_hits=0;
   a.base_absolute=0.0;
   a.full_absolute=0.0;
   a.turnover=0.0;
   a.prior_exposure=0.0;
   a.has_prior=false;
  }

For each scenario and seed, RunPath creates an estimator. It observes the current return before checking for burn-in and readiness.

Rolling and EWMA forecasts make separate adaptive decisions after burn-in, while the fixed decision uses exposure 0.75 and variance 0.0001. Each decision is sent to WriteRow with the current-bar and next-bar records.

//+------------------------------------------------------------------+
//| RunPath - size one path and write method summaries               |
//+------------------------------------------------------------------+
bool RunPath(const string scenario,const uint seed,const StressBar &bars[],
             const int ledger,const int summary)
  {
   CVolatilitySizingCore estimator;
   if(!estimator.Init(ROLLING_WINDOW,EWMA_LAMBDA,LONG_RUN_VARIANCE))
      return false;
   MethodTotals rolling_totals,ewma_totals,fixed_totals;
   ClearTotals(rolling_totals);
   ClearTotals(ewma_totals);
   ClearTotals(fixed_totals);
   int last_outlier=-1;
   for(int i=0;i<BURN_IN+EVALUATION_BARS;i++)
     {
      if(!estimator.Observe(bars[i].observed_return))
         return false;
      if(bars[i].outlier)
         last_outlier=i;
      if(i<BURN_IN || !estimator.Ready())
         continue;
      const int since=(last_outlier<0 ? -1 : i-last_outlier);
      SizingDecision rolling=SizeForVariance(estimator.RollingVariance(),TARGET_SD,MAX_EXPOSURE);
      SizingDecision ewma=SizeForVariance(estimator.EWMAVariance(),TARGET_SD,MAX_EXPOSURE);
      SizingDecision fixed;
      fixed.valid=true;
      fixed.capped=false;
      fixed.desired_exposure=FIXED_EXPOSURE;
      fixed.exposure=FIXED_EXPOSURE;
      fixed.estimated_risk=FIXED_EXPOSURE*MathSqrt(LONG_RUN_VARIANCE);
      if(!WriteRow(ledger,scenario,seed,i,bars[i],bars[i+1],since,"rolling",
                   estimator.RollingVariance(),rolling,rolling_totals) ||
         !WriteRow(ledger,scenario,seed,i,bars[i],bars[i+1],since,"ewma",
                   estimator.EWMAVariance(),ewma,ewma_totals) ||
         !WriteRow(ledger,scenario,seed,i,bars[i],bars[i+1],since,"fixed",
                   LONG_RUN_VARIANCE,fixed,fixed_totals))
         return false;
     }
   const string methods[3]= {"rolling","ewma","fixed"};
   MethodTotals values[3];
   values[0]=rolling_totals;
   values[1]=ewma_totals;
   values[2]=fixed_totals;
   for(int k=0;k<3;k++)
     {
      if(values[k].count!=EVALUATION_BARS)
         return false;
      const double n=(double)values[k].count;
      if(FileWrite(summary,scenario,seed,methods[k],values[k].count,values[k].capped,
                   values[k].tail_hits,
                   DoubleToString(values[k].base_absolute/n,16),
                   DoubleToString(values[k].full_absolute/n,16),
                   DoubleToString(values[k].turnover/n,16))==0)
         return false;
     }
   return true;
  }

After a sizing decision is made, WriteRow evaluates it using the next-bar base variance, the next-bar full variance, and the selected exposure. The next-bar observed return is scaled by the same exposure. A strict, two-sided test is performed. Absolute risk deviations, as well as changes in exposure, are accumulated. Previous exposure is saved. RunPath averages deviations and turnover over the decision count, and writes these averages along with cap and tail counts.

//+------------------------------------------------------------------+
//| WriteRow - record base/full risk and later outcomes              |
//+------------------------------------------------------------------+
bool WriteRow(const int handle,const string scenario,const uint seed,
              const int index,const StressBar &bar,const StressBar &future,
              const int bars_since_outlier,const string method,
              const double estimate,const SizingDecision &decision,
              MethodTotals &totals)
  {
   if(!decision.valid)
      return false;
   const double multiplier=(scenario=="student_t_outliers" ? FULL_VARIANCE_FACTOR : 1.0);
   const double base_sd=MathSqrt(bar.next_base_variance);
   const double full_sd=MathSqrt(bar.next_base_variance*multiplier);
   const double base_risk=decision.exposure*base_sd;
   const double full_risk=decision.exposure*full_sd;
   const double realized=decision.exposure*future.observed_return;
   const bool tail_hit=(MathAbs(realized)>2.0*TARGET_SD);
   const double change=totals.has_prior ? MathAbs(decision.exposure-totals.prior_exposure) : 0.0;
   totals.count++;
   if(decision.capped)
      totals.capped++;
   if(tail_hit)
      totals.tail_hits++;
   totals.base_absolute+=MathAbs(base_risk-TARGET_SD);
   totals.full_absolute+=MathAbs(full_risk-TARGET_SD);
   totals.turnover+=change;
   totals.prior_exposure=decision.exposure;
   totals.has_prior=true;
   return FileWrite(handle,scenario,seed,index+1,index+2,
                    DoubleToString(bar.base_innovation,16),
                    DoubleToString(bar.base_return,16),
                    DoubleToString(bar.observed_return,16),
                    bar.outlier ? 1 : 0,bars_since_outlier,
                    DoubleToString(bar.current_base_variance,16),
                    DoubleToString(bar.next_base_variance,16),
                    DoubleToString(bar.next_base_variance*multiplier,16),
                    method,DoubleToString(estimate,16),
                    DoubleToString(decision.desired_exposure,16),
                    DoubleToString(decision.exposure,16),decision.capped ? 1 : 0,
                    DoubleToString(decision.estimated_risk,16),
                    DoubleToString(base_risk,16),DoubleToString(full_risk,16),
                    DoubleToString(future.observed_return,16),
                    DoubleToString(realized,16),tail_hit ? 1 : 0,
                    DoubleToString(change,16))>0;
  }

Trace one shock through the sizing decision

Before seed 104729’s outlier at observed bar 267 is included, both rolling windows contain outlier-free bars 247-266. The shock increases the forecast and decreases the request for bar 268; neither request is capped. The next-bar base-return variance for both paths is approximately 0.00004796839, while contaminated full next-bar return variance is approximately 1.32 times that value. The contaminated rolling decision meets the 0.0075 target using its own forecast, but its full conditional risk is approximately 0.00628913 and its later signed exposure return is approximately -0.00082943. The older shocks are captured and weighted by EWMA, hence differences in paired EWMA exist.

Path (rolling) Observed return, bar 267 Forecast variance for bar 268 Requested/capped exposure
Student-t only -0.00313028 0.00004101136 1.171141
Contaminated -0.03147247 0.00009004725 0.790362

Control output and completion

OnStart verifies that RUNNING is set before opening or truncating the CSV files. OnStart’s MakePath and RunPath calls are ordered and stop at the first failure. All valid handles are closed. It attempts to publish the result as PASS or FAIL based on the accumulated outcomes. WriteManifest logs settings and timing. Numerical replay is a separate check.

//+------------------------------------------------------------------+
//| OnStart - replay paired paths and report only checked completion  |
//+------------------------------------------------------------------+
void OnStart()
  {
//--- Reset the receipt before any CSV can be truncated.
   if(!WriteText("tail_status.txt","RUNNING\r\n"))
     {
      Print("TAIL_AUDIT_FAIL initial status; any existing receipt may be stale");
      return;
     }
   const string ledger_header=
      "scenario,seed,observed_bar,sized_bar,base_innovation,base_return,observed_return,"+
      "outlier,bars_since_outlier,current_base_variance,next_base_variance,next_full_variance,"+
      "method,estimated_next_variance,desired_exposure,exposure,capped,estimated_exposure_risk,"+
      "base_oracle_risk,full_oracle_risk,next_observed_return,next_realized_exposure_return,"+
      "tail_hit,turnover\r\n";
   const string summary_header=
      "scenario,seed,method,count,capped,tail_hits,mean_base_absolute_deviation,"+
      "mean_full_absolute_deviation,mean_turnover\r\n";
   int ledger=FileOpen("tail_decisions.csv",FILE_WRITE|FILE_CSV|FILE_ANSI,',');
   int summary=FileOpen("tail_summary.csv",FILE_WRITE|FILE_CSV|FILE_ANSI,',');
   bool passed=(ledger!=INVALID_HANDLE && summary!=INVALID_HANDLE);
   if(passed)
      passed=(FileWriteString(ledger,ledger_header)==(uint)StringLen(ledger_header) &&
              FileWriteString(summary,summary_header)==(uint)StringLen(summary_header));
   const uint seeds[8]= {104729,130363,155921,180503,205279,229969,254749,279511};
   for(int s=0;passed && s<ArraySize(seeds);s++)
     {
      const int total=BURN_IN+EVALUATION_BARS+1;
      double innovations[];
      bool flags[],signs[];
      if(ArrayResize(innovations,total)!=total ||
         ArrayResize(flags,total)!=total || ArrayResize(signs,total)!=total)
        { passed=false; break; }
      CStressRandom random;
      random.Init(seeds[s]);
      for(int i=0;i<total;i++)
         random.Draw(innovations[i],flags[i],signs[i]);
      StressBar base[],contaminated[];
      if(!MakePath(innovations,flags,signs,false,base) ||
         !MakePath(innovations,flags,signs,true,contaminated) ||
         !RunPath("student_t",seeds[s],base,ledger,summary) ||
         !RunPath("student_t_outliers",seeds[s],contaminated,ledger,summary))
        { passed=false; break; }
     }
//--- Close valid handles on every path; failed partial data must be discarded.
   if(ledger!=INVALID_HANDLE)
      FileClose(ledger);
   if(summary!=INVALID_HANDLE)
      FileClose(summary);
   if(passed)
      passed=(VerifyText("tail_decisions.csv",ledger_header,false) &&
              VerifyText("tail_summary.csv",summary_header,false) && WriteManifest());
   const bool receipt=PublishStatus(passed ? "PASS" : "FAIL");
   if(!receipt)
     {
      //--- Promotion may already have succeeded; a later FAIL attempt can fail too.
      PublishStatus("FAIL");
      Print("TAIL_AUDIT_FAIL final status; receipt unavailable or unverified");
      return;
     }
   Print(passed ? "TAIL_AUDIT_PASS" : "TAIL_AUDIT_FAIL");
  }
//+------------------------------------------------------------------+
//| WriteManifest - record and verify frozen settings and timing      |
//+------------------------------------------------------------------+
bool WriteManifest(void)
  {
   const string contents=
      "Part 2: standardized Student-t(5), additive symmetric outliers\r\n"+
      "Seeds: 104729,130363,155921,180503,205279,229969,254749,279511\r\n"+
      "Observed bars: 801; burn-in: 200; evaluation decisions: 600\r\n"+
      "GARCH base only: hbar=.0001, alpha=.08, beta=.90\r\n"+
      "Outlier probability=.02; scale=4*sqrt(current base h); symmetric sign\r\n"+
      "Full next variance=next base h*(1+.02*4^2)=1.32*next base h\r\n"+
      "Estimator: rolling 20, EWMA .94; target SD=.0075; cap=1.5; fixed=.75\r\n"+
      "Decision at observed bar t sizes bar t+1. Future realized return is audit only.\r\n"+
      "Tail count: abs(exposure*next observed return)>2*target SD; descriptive only.\r\n";
   return WriteText("tail_manifest.txt",contents);
  }
//+------------------------------------------------------------------+
//| WriteText - check ASCII/CRLF byte count and closed-file readback   |
//+------------------------------------------------------------------+
bool WriteText(const string filename,const string contents)
  {
//--- All callers supply ASCII with explicit CRLF, so one character is one byte.
   const int h=FileOpen(filename,FILE_WRITE|FILE_TXT|FILE_ANSI);
   if(h==INVALID_HANDLE)
      return false;
   const uint written=FileWriteString(h,contents);
   FileClose(h);
   if(written!=(uint)StringLen(contents))
      return false;
   return VerifyText(filename,contents);
  }
//+------------------------------------------------------------------+
//| VerifyText - compare an ASCII file or prefix after closing writes |
//+------------------------------------------------------------------+
bool VerifyText(const string filename,const string expected,const bool whole=true)
  {
   const int h=FileOpen(filename,FILE_READ|FILE_BIN|FILE_ANSI);
   if(h==INVALID_HANDLE)
      return false;
   const int length=StringLen(expected);
   const ulong size=FileSize(h);
   const bool size_ok=whole ? size==(ulong)length : size>=(ulong)length;
   const string actual=size_ok ? FileReadString(h,length) : "";
   FileClose(h);
   return size_ok && actual==expected;
  }
//+------------------------------------------------------------------+
//| PublishStatus - verify a temporary receipt before replacement     |
//+------------------------------------------------------------------+
bool PublishStatus(const string token)
  {
   const string contents=token+"\r\n";
   if(!WriteText("tail_status.tmp",contents))
      return false;
   if(!FileMove("tail_status.tmp",0,"tail_status.txt",FILE_REWRITE))
      return false;
   return VerifyText("tail_status.txt",contents);
  }

Replay and validate the native ledger

The Python checker runs separately from MetaTrader. It reconstructs the random tape from the eight seeds, rebuilds both paired paths, and re-simulates rolling, EWMA and fixed decisions. It reviews all native ledger rows and summaries. It compares discrete fields exactly and applies tolerances to floating-point fields.

class Random:
    def __init__(self, seed):
        self.state = seed

    def uniform(self):
        x = self.state
        x ^= (x << 13) & 0xffffffff
        x ^= x >> 17
        x ^= (x << 5) & 0xffffffff
        self.state = x & 0xffffffff
        return (self.state + .5) / 4294967296.0

    def normal(self):
        return sqrt(-2 * log(self.uniform())) * cos(2 * pi * self.uniform())

    def draw(self):
        numerator = self.normal()
        chi2 = sum(self.normal() ** 2 for _ in range(5))
        return numerator * sqrt(3 / chi2), self.uniform() < .02, self.uniform() < .5
def make_path(tape, contaminated):
    h = .0001
    path = []
    for z, flag, positive in tape:
        base = sqrt(h) * z
        outlier = contaminated and flag
        observed = base + ((4 if positive else -4) * sqrt(h) if outlier else 0)
        next_h = .000002 + .08 * base * base + .90 * h
        path.append((z, base, observed, h, next_h, int(outlier)))
        h = next_h
    return path
def read_native_csv(path, expected_header):
    """Check the fixed native schema and row widths before mapping any fields."""
    with path.open(newline='', encoding='utf-8') as handle:
        reader = csv.reader(handle)
        header = next(reader, None)
        assert header is not None, f'{path.name}: missing header'
        assert len(set(header)) == len(header), f'{path.name}: duplicate header names'
        assert tuple(header) == expected_header, f'{path.name}: header differs from the native schema'
        rows = []
        for line, fields in enumerate(reader, 2):
            assert len(fields) == len(header), f'{path.name}:{line}: incorrect field count'
            rows.append(dict(zip(header, fields)))
    return rows


Run and check the native audit

Locally compile SizingTailAudit.mq5 from the archive using MetaTrader's MetaEditor, and run. Four files are generated from a successful run: tail_decisions.csv, tail_summary.csv, tail_status.txt, and tail_manifest.txt. tail_decisions.csv lists the decisions made. tail_summary.csv contains scenario, seed and method summaries. The completion status of the analysis is recorded in tail_status.txt. The protocol and timing of the decisions are recorded in tail_manifest.txt. The current run must display "TAIL_AUDIT_PASS", and PASS in tail_status.txt must be verified. Do not consider any partial results from failed runs. Accept the complete audit only after the Python checker reports PASS for the corresponding CSV files.

Python 3.12.14 was able to replay 28,800 decisions and 48 summaries.


What changes in the decisions

The mean absolute conditional-risk deviations in Part 1 for the eight Gaussian GARCH paths were 0.000772984 (rolling), 0.000533918 (EWMA), and 0.001697695 (fixed exposure). The averages are for eight seed paths, each with 600 decisions and against a target of 0.0075. The mean absolute deviations are in log-return units. These were results of the descriptive protocol.

Each row of the results represents 4,800 decisions, or 8 seed means of 600 decisions. The cap and threshold columns represent the total number of events. The mean change in exposure is a summary of 599 changes and a zero first change contribution per seed, divided by 600. The mean exposure changes do not include initial entry and do not define a cost.

Scenario Method Mean absolute full-risk deviation Mean exposure change Forecast cap events / 4,800 Two-sided realized events / 4,800

Student-t only

Fixed

0.001930

0.000000

0

208

Student-t only

Rolling

0.000968

0.031483

582

329

Student-t only

EWMA

0.000686

0.029112

269

300

Student-t + outliers

Fixed

0.001772

0.000000

0

296

Student-t + outliers

Rolling

0.001718

0.033746

413

348

Student-t + outliers

EWMA

0.001273

0.028792

122

306

Distance from the target under complete-return risk

Figure 2: complete-return conditional-risk deviation across stress paths

Figure 2. Under these frozen parameters and seeds, EWMA has the smallest average full-risk deviation in each scenario. The contaminated path raises that deviation for both adaptive rules. This is a conditional-risk accounting result, not a ranking of trading strategies.

During contamination, mean absolute full-risk deviation for fixed exposure decreases to 0.001772 from the uncontaminated value of 0.001930, and the number of realized threshold events increases from 208 to 296. The exposure and base path remain the same. The full conditional risk for each of the paired decisions is multiplied by √1.32. Therefore, distance from the 0.0075 target can decrease, and full conditional risk can increase. Consequently, the mean shortfall of the fixed exposure rule decreases, and its mean excess increases. The two adaptive rules evaluated herein record lesser mean absolute full-risk deviations than the fixed exposure rule, and a larger number of realized threshold events in each scenario. Of the 4,800 observed evaluation bars, 92 contain outliers.

Base and complete-return risk under contamination

Under contamination, rolling mean absolute base/full deviations are 0.001275/0.001718 and EWMA mean absolute deviations are 0.000964/0.001273. Fixed exposure’s contaminated base diagnostics and Student-t-only full diagnostics are the same because its exposure and base path do not change. Addressing only base risk would omit the conditional variance of another possible outlier. Addressing only full risk would not compare the effect of the shock with the unchanged base process of the system. Reading both risks provides this information.

Method Mean absolute base deviation Mean base excess Mean base shortfall Base above target / 4,800

Fixed

0.001930

0.000568

0.001361

1051

Rolling

0.001275

0.000579

0.000696

2482

EWMA

0.000964

0.000265

0.000699

2017

Variation across the eight seeds

The variation shown in the seed min/max table is among the seed-level mean absolute full-risk deviations, not among confidence intervals or limits for unobserved paths. A deviation of 0.001 is 0.1 percentage points of standard deviation of returns.

Scenario Method Lowest seed mean Highest seed mean

Student-t only

Fixed

0.001670

0.002404

Student-t only

Rolling

0.000753

0.001113

Student-t only

EWMA

0.000498

0.000972

Student-t + outliers

Fixed

0.001181

0.002640

Student-t + outliers

Rolling

0.001379

0.002054

Student-t + outliers

EWMA

0.000956

0.001546

Overshoots and shortfalls

Excess is defined as:

max(full_oracle_risk - 0.0075, 0)

And shortfall is defined as:

max(0.0075 - full_oracle_risk, 0)

Both are non-negative; their means include zeros across all 4,800 decisions and sum to mean absolute deviation before rounding. Above-target counts are expressed using strict inequality. Due to equal seed lengths, the mean of eight seed means is the same as the sample mean. A smaller mean absolute deviation does not guarantee that the mean excess will be smaller. In the Student-t-only case, rolling mean absolute deviation was 0.000968, while fixed exposure mean absolute deviation was 0.001930. The mean excess of fixed exposure was 0.000568, while the mean excess of rolling was 0.000811. The distance score accounts for both mean shortfall and mean excess.

Scenario Method Mean excess Mean shortfall Above target / 4,800

Student-t only

Fixed

0.000568

0.001361

1051

Student-t only

Rolling

0.000811

0.000157

3553

Student-t only

EWMA

0.000575

0.000111

3662

Student-t + outliers

Fixed

0.000989

0.000783

1885

Student-t + outliers

Rolling

0.001350

0.000368

3343

Student-t + outliers

EWMA

0.000945

0.000328

3355

Mechanical effect of the exposure cap

The uncapped diagnostic uses:

desired_exposure * sqrt(next_full_variance)

The capped diagnostic uses:

exposure * sqrt(next_full_variance)

Change is the mean absolute full-risk deviation under capped exposure minus the mean absolute full-risk deviation under uncapped exposure. It does not evaluate a separate, uncapped trading strategy.

Scenario Method Uncapped mean deviation Capped mean deviation Change

Student-t only

Rolling

0.001140

0.000968

-0.000172

Student-t only

EWMA

0.000726

0.000686

-0.000040

Student-t + outliers

Rolling

0.001868

0.001718

-0.000150

Student-t + outliers

EWMA

0.001295

0.001273

-0.000022

Cap binding and target feasibility

Forecast binding checks if the desired exposure is greater than 1.5. Oracle target infeasibility checks if exposure 1.5 results in conditional risk below the target with the generator’s next-bar variance. The rolling rule, Student-t-only, records 582 cap events, but no evaluated bar is oracle-infeasible. A forecast may request exposure greater than the cap even when the next-bar variance of the generator allows an exposure within that cap to meet the target. Zero oracle infeasibility indicates that an exposure exists that meets the target; it doesn’t mean that the exposure was chosen by the sizing rule.

1.5 * sqrt(next_variance) < 0.0075
Scenario Base infeasible / 4,800 Full infeasible / 4,800 Minimum next-bar base variance Minimum next-bar full variance

Student-t only

0

0

0.0000280696

0.0000280696

Student-t + outliers

0

0

0.0000280696

0.0000370518

No evaluated bar is infeasible in either risk view. In the full risk, contaminated case, the frozen recurrence also applies; nonnegative squared returns ensure the base lower bound of 0.00002, and therefore, complete variance is at least 0.0000264, above the infeasibility line of 0.000025. The observed zero base-risk infeasibility count has no such guarantee for all paths. Other cases require checking the bound.

h ≥ omega / (1 − beta) = 0.00002
(0.0075 / 1.5)^2 = 0.000025


The response after an isolated outlier

The event diagnostic singles out outlier bars 221 to 780, which have no other outlier bars within the preceding or succeeding 20 bars. This represents 43 events. Future flags are used retrospectively for this figure and never for sizing. The plotted value for lag k equals the average of the 43 ratios of the EWMA next-bar variance estimate to that row’s full next-bar variance. Lag zero refers to the forecast made after the outlier was observed, which is used to size the next-bar return.

Relative bar -1 0 1 5 10 20

Mean EWMA / full variance

0.758

1.544

1.514

1.291

1.143

0.985

EWMA response around isolated outliers

Figure 3: EWMA variance ratio around isolated outliers

Figure 3. The mean EWMA/full-variance ratio rises at the outlier bar and then declines at the displayed lags. The line is an event average under this one stress setting, not an estimated recovery time for live markets.

In the case of an individual decision, with an EWMA forecast above the full next-bar variance, exposure is less than that needed to meet the full-risk target; the cap can only reduce the exposure further. The mean ratio (43 events; 0.985 at lag 20) does not imply average exposure or recovery time. Ratios can offset each other, and changing base variance prevents isolating a causal shock effect.


Limits and practical use

This experiment uses eight synthetic seeds with one scalar GARCH configuration, t(5) innovations, and a single symmetric-shock setting (probability and scale). The parameters are not calibrated or fitted to any financial instrument, and latent oracle variances are not discernible in normal financial charts. The 4,800 decisions, which depend on the EWMA, GARCH and rolling methods, are not independent simulations. All differences are considered for a descriptive purpose, without considering confidence limits or conducting a hypothesis test for superiority. Zero-mean second-moment estimators match the generator’s zero conditional mean. Misspecification of the mean, parameter and initialization sensitivity and uncertainty intervals are not evaluated. General rankings are also untested.

Standard deviation is not a bound on loss and choosing a threshold does not confer a VaR. This script neither trades nor retrieves broker data. Part 3 is planned to reconcile requested, filled and held exposure in the Strategy Tester. There are many phenomena related to trading and investing, including lots, tick value, contract size, account mode, positions, margin, costs and fills, which require their own validation.


Conclusion

This experiment produced paired stress paths and a native MQL5 ledger covering 28,800 decisions and 48 summaries. The ledger records the sizing decisions, base and complete-return risk diagnostics, and subsequent outcomes. A run should be accepted only when the MQL5 audit completes with TAIL_AUDIT_PASS and a PASS receipt, and the independent Python replay also reports PASS .

Under these fixed settings and seeds, EWMA had the smallest mean absolute deviation of complete-return conditional risk from the target in both scenarios. Both adaptive methods also recorded more realized threshold events than fixed exposure. These results describe the behavior of the tested rules in this stress test; they do not establish trading superiority or predict performance in live markets.

The practical result is a reproducible way to examine how transient outliers affect estimator memory, exposure decisions and risk diagnostics while keeping the underlying sizing rule unchanged. It is an audit of sizing behavior—not a loss guarantee.

Files

File

Location

Purpose

VolatilitySizingCore.mqh

MQL5/Include/SizingAudit

Shared rolling/EWMA estimators, sizing decision and controlled variance generator.

SizingTailAudit.mq5

MQL5/Scripts/SizingAudit

Paired Student-t and outlier runner with complete-return risk diagnostics.

verify_tail_ledger.py

MQL5/Files/SizingAudit/Part2/tools

Independently replays 28,800 decisions and 48 Part 2 summaries.

MQL5.zip

MQL5

Archive with source files and verification tools in their terminal folder structure. Extract its MQL5 folder into the MT5 data folder. Compile the source locally; no EX5 files are included.

Reproducibility note

The revised source code compiled without errors or warnings in MetaEditor build 6235 on 20 October 2026 and ran in MetaTrader 5 x64 build 6235 on Windows 11 build 22000 through Wine 11.1 on Darwin 25.6.0.

Copy the current tail_decisions.csv and tail_summary.csv into MQL5/Files/SizingAudit/Part2/evidence. From the Part2 directory, execute the checker using the command shown, with Python 3.10 or above. Do not use the -O flag or set the PYTHONOPTIMIZE variable.

python3 tools/verify_tail_ledger.py
File SHA-256

VolatilitySizingCore.mqh

1abbbc1ba9e205b8cf47255d6591a95f2cad61e55da39d2cf46319457ae2a467

SizingTailAudit.mq5

e6b9f19b9b3c02b7eca0b692da3d1132238202b646137a8a61393796bd913dde

verify_tail_ledger.py

eba5063b96bf62206c366f2a2f4437b023420d93322de92e2b1c9a30512bdbae

MQL5.zip

5b42607494dfec896aadf94bf49fd2adb9a5190c306a5e0268913384f7688a02

Attached files |
SizingTailAudit.mq5 (18.24 KB)
MQL5.zip (9.39 KB)
Building a Price Ladder Aggregator for Depth-of-Market Analysis in MQL5 Building a Price Ladder Aggregator for Depth-of-Market Analysis in MQL5
The article presents a live‑only MQL5 indicator that converts MarketBook data into a price ladder with tick‑based bucketing, per‑level aggregation, outward cumulative columns, and top‑3 cluster marking per side. A canvas panel renders the ladder, spread, and diagnostics, avoiding empty or misleading displays when DOM is missing. Logic is isolated in tested classes, providing a clear, reusable structure for DOM visualization.
Gating Trades with the Wald-Wolfowitz Runs Test: An O(1) Randomness Filter for Bar Direction Gating Trades with the Wald-Wolfowitz Runs Test: An O(1) Randomness Filter for Bar Direction
A rolling Wald–Wolfowitz runs-test engine classifies recent bar direction as persistent, alternating, or indistinguishable from noise before any entry logic is applied. The package includes full MQL5 source, a chart indicator, a three-mode Expert Advisor (Gated, No gate, Placebo), validation scripts, and an audit log. An 18‑run Strategy Tester matrix with fixed window and critical value, plus a null‑rate calibration on real history, shows how a regime gate changes trade frequency and drawdown.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
Implementing Golden-File Regression Tests for Expert Advisors in MQL5 Implementing Golden-File Regression Tests for Expert Advisors in MQL5
Golden-file testing compares the trade decisions of a modified Expert Advisor with an accepted run, so an unintended logic change appears as changed decisions. CDecisionRecorder writes each recorded request with run context and a tick hash, and CGfFile refuses truncated or malformed files. CGoldenCompare pairs rows by time and returns a verdict that separates changed decisions from different settings or ticks. Random execution delay made the tested runs differ, so compare runs with the same fixed delay or none.