preview
Counting Breaches Is Not Backtesting: Six Tests for a Loss Limit

Counting Breaches Is Not Backtesting: Six Tests for a Loss Limit

MetaTrader 5 — Machine learning |
77 0
Adeolu Kayode Gbadebo
Adeolu Kayode Gbadebo

Contents

  1. Introduction
  2. The two promises a limit makes
  3. A battery, not a number
  4. Four ways to quote a limit
  5. Does the battery actually work?
  6. Grading four limits on EURUSD
  7. Watching the verdict on a chart
  8. From verdict to position size
  9. Conclusion


Introduction

Almost every risk-sized Expert Advisor begins the same way: it picks a volatility measure (an ATR, a rolling standard deviation or a Value at Risk figure), turns it into a stop distance and a lot size, and trades. And then nothing in the program ever asks whether that number was right. The volatility model can be breached three times as often as it claims, for a year, and the sizing code will keep dividing by it, with no error and no warning.

Yet a risk limit is easy to test. A limit at 99% confidence is falsifiable: losses should exceed it on about one day in a hundred, and the machinery for turning that count into a verdict was worked out in the 1990s.

In this article we build a dependency-free library that grades any loss limit with six tests, check it on synthetic data, grade four standard risk models on EURUSD, put the verdict on the chart, and feed it back into an Expert Advisor's sizing.

The central claim, which the rest of the article supports, is that counting breaches is the least informative thing you can do with a risk limit, and that the model a breach count declares healthiest may be the one to trust least.


The two promises a limit makes

Write down a loss limit at confidence 1 - p and you have made two promises, not one. The first is frequency: losses should exceed the limit on a fraction p of periods. The second is arrival: those breaches should be independent, scattered rather than bunched. Nothing in the first implies the second, and the second is the one that empties accounts.

Both sequences below contain exactly twelve breaches, which is what a 95% limit over 250 days should produce.

Twelve breaches scattered through the sample versus twelve arriving in two bursts

Fig. 1. The same breach count, twice. Above, twelve breaches scattered through the year. Below, the same twelve in two bursts of six.

The upper sequence is a working limit: twelve uncomfortable days spread over a year. The lower one is a model that failed completely twice, for over a week each time. Outside those bursts it was so wide that it never registered a breach. Whether either costs an account depends on its leverage and stops, which no hit sequence records; what the lower one does record is six losses back to back, twice, with no chance to shrink the position in between. Yet count either and you get twelve.

One convention, fixed once: a loss is positive when money is lost, a limit is the positive loss the model says will rarely be exceeded, and a breach is loss > limit. Returns are converted at the boundary, never inside.

The engine consumes one bit per period, breach or not, and knows nothing about trading, so the same class grades a portfolio Value at Risk figure, a prop-firm daily loss cap, an EA's drawdown guard, or a claim like "this stop only gets taken out 30% of the time". Every one of those is a hit sequence, and almost none of them is ever tested.


A battery, not a number

One test cannot grade two promises, so the library reports a battery, and each member answers a different question.

Kupiec: is the breach rate right?

Christoffersen: are breaches independent?

Conditional coverage: both at once.

Duration: is the gap between breaches memoryless?

Dynamic quantile: is there any predictability left at all?

Acerbi-Szekely: when the limit broke, was the loss the right size?

Every one of them reports in the same shape, the record below, so they can be read side by side.

//+------------------------------------------------------------------+
//| One test's verdict, in the shape every test here reports.        |
//| `applicable` is separate from `rejected` on purpose: a test      |
//| that could not run for want of data has NOT cleared the model,   |
//| and collapsing the two states into one boolean is how an         |
//| untested model comes to look like a tested one.                  |
//+------------------------------------------------------------------+
struct SCoverageTest
  {
   string            name;        // human-readable test name
   double            stat;        // the test statistic
   int               dof;         // degrees of freedom of the reference law
   double            pvalue;      // upper-tail probability of `stat`
   bool              applicable;  // false when there was too little data
   bool              rejected;    // applicable && pvalue < alpha
   string            note;        // why it could not run, when applicable=false

//--- a cleared result reads as "not run", never as "passed"
   void              Clear()
     {
      name       = "";
      stat       = 0.0;
      dof        = 0;
      pvalue     = 1.0;
      applicable = false;
      rejected   = false;
      note       = "not run";
     }
  };

Alpha is the size of the test: the probability of rejecting a model that is in fact correct. Every test here runs at alpha = 0.05. It is not p, the breach rate the limit promises.

The field worth arguing about is applicable. At a 99% limit over 250 days, the expected breach count is two and a half, so several tests will often have nothing to work with. A test that cannot run says so and records why, rather than reporting a pass it never earned.

The zero-times-log-zero problem

Every likelihood ratio below has a cell that empties on a quiet sample, and without a guard each returns a NaN that propagates into a p-value, which is worse than an error because it prints.

//+------------------------------------------------------------------+
//| c * log(q) with the 0 * log(0) = 0 convention the likelihood     |
//| ratios need. Every one of these tests has a cell that empties    |
//| on a quiet sample, and without this each of them would return    |
//| a NaN that propagates silently into a p-value.                   |
//+------------------------------------------------------------------+
double CvXLog(const int c, const double q)
  {
   if(c == 0)
      return(0.0);
   if(q <= CV_EPS)
      return(-1.0e300);
   return((double)c * MathLog(q));
  }

Kupiec: the proportion of failures

Kupiec's test compares the likelihood of the sample under the promised breach rate against its likelihood under the observed one. With n periods, x breaches and pi = x/n:

LR_uc = -2 * [ (n-x)*ln(1-p) + x*ln(p) - (n-x)*ln(1-pi) - x*ln(pi) ]

read against a chi-square distribution with one degree of freedom.

//+------------------------------------------------------------------+
//| Kupiec's proportion-of-failures test. The likelihood ratio       |
//| between the promised breach rate and the one actually            |
//| observed, read against chi-square with one degree of freedom.    |
//| It asks a single question -- were there the right NUMBER of      |
//| breaches -- and is blind to when they arrived.                   |
//+------------------------------------------------------------------+
bool CoverageKupiec(const bool &hit[], const int n, const double p,
                    const double alpha, SCoverageTest &out)
  {
   out.Clear();
   out.name = "Kupiec POF";
   out.dof  = 1;
   if(n < 1 || p <= 0.0 || p >= 1.0)
     {
      out.note = "no observations";
      return(false);
     }

   int x = 0;
   for(int i = 0; i < n; i++)
      if(hit[i])
         x++;

   double pi = (double)x / (double)n;
//--- likelihood under the promise, then under the observed rate
   double l0 = CvXLog(n - x, 1.0 - p) + CvXLog(x, p);
   double l1 = CvXLog(n - x, 1.0 - pi) + CvXLog(x, pi);
   double lr = -2.0 * (l0 - l1);
   if(lr < 0.0)
      lr = 0.0;

   out.stat       = lr;
   out.pvalue     = CvChiSquareUpper(lr, 1);
   out.applicable = true;
   out.rejected   = (out.pvalue < alpha);
   out.note       = "";
   return(true);
  }

It asks one question, whether there were the right number of breaches. Both sequences in Fig. 1 hand it the same answer.

Christoffersen: does a breach make another breach likelier?

Christoffersen's independence test fits a first-order Markov chain to the breach indicator and asks whether a breach depends on whether the previous period breached. It needs the four transition counts, gathered below as a two-bit index.

//--- the pair (previous, current) as a two-bit index, which beats
//--- a four-branch chain and cannot silently miss a combination
   int cell[4];
   ArrayInitialize(cell, 0);
   for(int i = 1; i < n; i++)
      cell[(hit[i - 1] ? 2 : 0) + (hit[i] ? 1 : 0)]++;
   n00 = cell[0];
   n01 = cell[1];
   n10 = cell[2];
   n11 = cell[3];

   int tot = n00 + n01 + n10 + n11;
//--- with no breach ever following another period there is simply
//--- nothing to compare, and saying so beats returning p = 1
   if(n01 + n11 == 0)
     {
      out.note = "no breaches in the transition sample";
      return(false);
     }
   if(n00 + n10 == 0)
     {
      out.note = "every period breached";
      return(false);
     }
//--- an empty row leaves its breach probability unidentified, and
//--- the ratio would then collapse to an unearned p = 1
   if(n00 + n01 == 0 || n10 + n11 == 0)
     {
      out.note = "a transition row has no observations";
      return(false);
     }

All three guards refuse rather than return a comfortable number. With no breach ever following another, or with the only breach in the last period so that the "after a breach" row is empty, the ratio would otherwise read as a perfect pass on a test that had nothing to work with.

The remainder builds the two likelihoods: the restricted model uses one breach probability for both states, the unrestricted allows a different one after a quiet period and after a breach.

   double d0   = (double)(n00 + n01);
   double d1   = (double)(n10 + n11);
   double pi01 = (d0 > 0.0 ? (double)n01 / d0 : 0.0);
   double pi11 = (d1 > 0.0 ? (double)n11 / d1 : 0.0);
   double pi   = (double)(n01 + n11) / (double)tot;

//--- restricted: one breach probability for both states
   double l0 = CvXLog(n00 + n10, 1.0 - pi) + CvXLog(n01 + n11, pi);
//--- unrestricted: a separate probability after a quiet period and
//--- after a breach, which is exactly the dependence being tested
   double l1 = CvXLog(n00, 1.0 - pi01) + CvXLog(n01, pi01) +
               CvXLog(n10, 1.0 - pi11) + CvXLog(n11, pi11);
   double lr = -2.0 * (l0 - l1);
   if(lr < 0.0)
      lr = 0.0;

   out.stat       = lr;
   out.pvalue     = CvChiSquareUpper(lr, 1);
   out.applicable = true;
   out.rejected   = (out.pvalue < alpha);
   out.note       = "";
   return(true);

Conditional coverage

The two likelihood ratios add, and so do their degrees of freedom. The joint test is reported separately because a joint rejection says the model is wrong without saying how, and it runs only when both parts ran, since a sum with a missing term has no defined p-value.

//+------------------------------------------------------------------+
//| Conditional coverage: the two likelihood ratios add, and so do   |
//| their degrees of freedom. Reported separately from its parts     |
//| because a joint rejection says the model is wrong without        |
//| saying HOW, and the two component tests are what say how.        |
//| It runs only when both of its parts ran.                         |
//+------------------------------------------------------------------+
bool CoverageConditional(const SCoverageTest &uc, const SCoverageTest &ind,
                         const double alpha, SCoverageTest &out)
  {
   out.Clear();
   out.name = "Conditional coverage";
   out.dof  = 2;
   if(!uc.applicable)
     {
      out.note = "unconditional test did not run";
      return(false);
     }
//--- Kupiec alone read against chi-square(2) is not a joint test
   if(!ind.applicable)
     {
      out.note = "independence test did not run";
      return(false);
     }
   double lr = uc.stat + ind.stat;
   out.stat       = lr;
   out.pvalue     = CvChiSquareUpper(lr, 2);
   out.applicable = true;
   out.rejected   = (out.pvalue < alpha);
   out.note       = "";
   return(true);
  }

Duration: how long since the last one?

The Markov test looks only one period back, so clustering that spans a week slips past it. The Christoffersen-Pelletier duration test looks at the whole gap: having waited forty quiet days should tell you nothing about how much longer the wait will be. That memorylessness is a Weibull shape of exactly 1, and concentrating the scale out in closed form leaves a bounded golden-section search.

//+------------------------------------------------------------------+
//| Profile log-likelihood of the Weibull duration model at shape    |
//| b, with the scale concentrated out in closed form. Splitting     |
//| this off is what turns a two-parameter fit into a search over    |
//| one bounded number.                                              |
//+------------------------------------------------------------------+
double CvWeibullProfile(const double &d[], const int m, const double b)
  {
   if(m < 1 || b <= 0.0)
      return(-1.0e300);
   double sb = 0.0, sl = 0.0;
   for(int i = 0; i < m; i++)
     {
      sb += MathPow(d[i], b);
      sl += MathLog(d[i]);
     }
   if(sb <= CV_EPS)
      return(-1.0e300);
   return((double)m * MathLog((double)m / sb) + (double)m * MathLog(b) +
          (b - 1.0) * sl - (double)m);
  }

The price is that the test needs several gaps between breaches, which at a 99% limit takes years of data; with fewer, it refuses with a stated reason rather than fitting four observations.

Dynamic quantile: is anything left to predict?

Engle and Manganelli's test regresses the demeaned breach indicator on several of its own lags and on the limit level itself, then asks whether any coefficient is non-zero; under a correct model the indicator is unforecastable noise. Including the limit catches what no hit-only test can: a model that breaches mostly when already quoting a wide limit.

   for(int t = t0; t < n; t++)
     {
      row[0] = 1.0;
      for(int j = 0; j < lags; j++)
         row[1 + j] = (hit[t - 1 - j] ? 1.0 : 0.0) - p;
      if(use_limit)
         row[k - 1] = (limit[t] - mu) / sd;
      double y = (hit[t] ? 1.0 : 0.0) - p;
      for(int r = 0; r < k; r++)
        {
         xty[r] += row[r] * y;
         for(int c = 0; c < k; c++)
            xtx[r * k + c] += row[r] * row[c];
        }
     }

The statistic is the quadratic form beta' X'X beta / (p*(1-p)), read against chi-square with as many degrees of freedom as there are regressors. At the least-squares solution it collapses to something cheaper.

//--- beta' X'X beta reduces to beta' X'y at the least-squares fit
   double q = 0.0;
   for(int r = 0; r < k; r++)
      q += b[r] * xty[r];
   double stat = q / (p * (1.0 - p));
   if(stat < 0.0)
      stat = 0.0;

   out.stat       = stat;
   out.pvalue     = CvChiSquareUpper(stat, k);
   out.applicable = true;
   out.rejected   = (out.pvalue < alpha);
   out.note       = StringFormat("%d lags, %d rows", lags, m);
   return(true);

Expected shortfall: was the loss the right size?

Everything so far grades the frequency of breaches, none of it their size, and a limit breached exactly as often as promised can still be breached by three times the amount predicted. Expected shortfall has no distribution-free test, because it is not elicitable on its own, so Acerbi and Szekely's second statistic compares the losses on breach days with the shortfall forecast for those days, against a simulated null in which each draw rebuilds the sample under the model's own claim.

   double z2 = 1.0 - acc / ((double)n * p);
   z2_out    = z2;

//--- simulate the null: breaches at rate p, tail draws from the
//--- reference normal each period's own (mu, sigma) describes
   CCvRng rng;
   rng.Seed(seed);
   int worse = 0;
   for(int s = 0; s < sims; s++)
     {
      double tot = 0.0;
      for(int t = 0; t < n; t++)
        {
         double u = rng.Uniform();
         if(u >= p)
            continue;
         //--- u already carries the position inside the tail, so it
         //--- is reused rather than drawing a second variate
         double z = CvNormalQuantileFast(1.0 - p + u);
         tot += (mu[t] + sg[t] * z) / shortfall[t];
        }
      double zs = 1.0 - tot / ((double)n * p);
      if(zs <= z2)
         worse++;
     }

The reference shape used to invert the pair is the normal, a choice the code states openly. It centres the null correctly for any model, but it understates the spread a fat-tailed model claims. For Student-t and historical simulation the test therefore leans towards rejection, and a shortfall rejection there is partly a statement about the reference shape.

The supervisory zones, derived rather than copied

The Basel traffic light is the one published rule that turns a breach count into an instruction: green, usable as it stands; yellow, usable only after the output is inflated; red, not usable at all. Rather than hard-code the Committee's 250-day table, we derive the boundaries as it did: yellow where the cumulative binomial probability of the count reaches 95%, red at 99.99%.

//+------------------------------------------------------------------+
//| Basel zone boundaries for an arbitrary (n, p), derived the way   |
//| the Committee derived its own 250-day table: the yellow zone     |
//| opens where the cumulative probability of the observed count     |
//| first reaches 95%, and the red zone where it reaches 99.99%.     |
//| Deriving them rather than hard-coding the table is what lets     |
//| the same function grade a 500-day sample, or a 95% limit,        |
//| without pretending the published numbers still apply.            |
//+------------------------------------------------------------------+
void CvBaselBounds(const int n, const double p, int &green_max, int &red_min)
  {
   green_max = n;
   red_min   = n + 1;
   bool got_green = false, got_red = false;
   for(int k = 0; k <= n; k++)
     {
      double cdf = CvBinomialCdf(k, n, p);
      if(!got_green && cdf >= 0.95)
        {
         green_max = k - 1;                  // yellow opens at k
         got_green = true;
        }
      if(!got_red && cdf >= 0.9999)
        {
         red_min = k;                        // red opens at k
         got_red = true;
         break;
        }
     }
   if(green_max < 0)
      green_max = 0;
   if(red_min <= green_max)
      red_min = green_max + 1;
  }

Deriving rather than copying lets the same function grade a 500-day sample or a 95% limit, and it reproduces the official boundaries at the canonical setting: 250 observations at 99%, green up to 4 breaches, red from 10.

The multipliers can only half be derived. Green is 3.00 and red 4.00 by definition, but the five yellow values, 3.40 through 3.85, are a supervisory judgement. CvBaselMultiplier returns them verbatim on the canonical sample and otherwise interpolates linearly across the derived band, which is our choice, not a published rule.

The engine

The class that accumulates the sample has two entry points. AddHit takes one bit per period and powers the four tests that read only the hit sequence; Update takes the realized loss and the limit quoted for it, enabling the dynamic quantile test, and UpdateWithES adds the shortfall forecast.

//--- full entry: the realized loss and the limit quoted for it.
//--- The breach is derived here rather than by the caller so the
//--- comparison is made in one place with one convention.
   bool              Update(const double loss, const double limit)
     {
      if(!m_ready)
         return(false);
      if(m_locked && !m_levels)
         return(false);
      if(!MathIsValidNumber(loss) || !MathIsValidNumber(limit))
         return(false);
      m_locked = true;
      m_levels = true;
      Grow();
      m_loss[m_n - 1]  = loss;
      m_limit[m_n - 1] = limit;
      m_hit[m_n - 1]   = (loss > limit);
      m_es[m_n - 1]    = 0.0;
      Trim();
      return(true);
     }

//--- as Update(), plus the shortfall forecast that lets the tail
//--- SIZE be graded rather than only the breach frequency
   bool              UpdateWithES(const double loss, const double limit,
                                  const double shortfall)
     {
      if(!Update(loss, limit))
         return(false);
      m_es[m_n - 1] = shortfall;
      m_shortfall   = true;
      return(true);
     }

Running the battery is a single pass. This is the body of Compute after its guard clause; tests that cannot run say so.

      rep.exceptions    = Exceptions();
      rep.expected      = (double)m_n * m_cfg.p;
      rep.observed_rate = (double)rep.exceptions / (double)m_n;

      CoverageKupiec(m_hit, m_n, m_cfg.p, m_cfg.alpha, rep.kupiec);
      CoverageIndependence(m_hit, m_n, m_cfg.alpha, rep.independence,
                           rep.n00, rep.n01, rep.n10, rep.n11);
      CoverageConditional(rep.kupiec, rep.independence, m_cfg.alpha,
                          rep.conditional);
      CoverageDuration(m_hit, m_n, m_cfg.alpha, m_cfg.min_durations,
                       rep.duration);

      if(m_levels)
         CoverageDQ(m_hit, m_limit, m_n, m_cfg.p, m_cfg.dq_lags,
                    m_cfg.dq_use_limit, m_cfg.alpha, rep.dq);
      else
         rep.dq.note = "needs losses and limits, not just hits";

      if(m_shortfall)
         CoverageES(m_loss, m_limit, m_es, m_n, m_cfg.p, m_cfg.es_sims,
                    m_cfg.es_seed, m_cfg.alpha, rep.es, rep.es_z2);
      else
         rep.es.note = "needs a shortfall forecast per period";

      CvBaselBounds(m_n, m_cfg.p, rep.green_max, rep.red_min);
      rep.zone       = CvBaselZone(rep.exceptions, rep.green_max, rep.red_min);
      rep.multiplier = CvBaselMultiplier(rep.exceptions, rep.green_max,
                                         rep.red_min);
     }


Four ways to quote a limit

The library judges risk models; it does not build them. To have something concrete to grade, it ships four standard forecasters behind one interface.

//+------------------------------------------------------------------+
//| CRiskModel -- what every forecaster here promises.               |
//|                                                                  |
//| Limit() and Shortfall() are forecasts for the period that has    |
//| NOT yet been observed, both quoted as positive losses. A model   |
//| that cannot yet forecast returns Ready() == false rather than    |
//| a guess, because a warm-up value fed into the battery is a       |
//| breach or a non-breach on no evidence and quietly biases every   |
//| test in the report.                                              |
//+------------------------------------------------------------------+
class CRiskModel
  {
protected:
   double            m_p;        // promised breach rate
   bool              m_use_mean; // estimate drift, or assume it is zero
public:
                     CRiskModel() : m_p(0.01), m_use_mean(false) {}
   virtual          ~CRiskModel() { }

   virtual void      Init(const int window, const double p,
                          const bool use_mean)
     {
      m_p        = (p <= 0.0 || p >= 1.0 ? 0.01 : p);
      m_use_mean = use_mean;
     }
   virtual void      Reset()                          { }
   virtual void      Update(const double ret)         { }
   virtual bool      Ready()      const { return(false); }
   virtual double    Limit()      const { return(0.0);   }
   virtual double    Shortfall()  const { return(0.0);   }
   virtual string    Name()       const { return("base"); }
   double            Rate()       const { return(m_p);    }
  };

Limit and Shortfall are forecasts for a period not yet observed, and a model still warming up returns Ready() == false rather than a guess.

Model
Shape
Scale
What it cannot do
Normal
Fixed, Gaussian
Rolling window
React quickly (yesterday weighs 1/250)
EWMA (0.94)
Fixed, Gaussian
Recursive, O(1)
Represent a fat tail
Historical
None, empirical
Rolling window
Show a tail it has not already seen
Student-t (5)
Fixed, fat-tailed
Rolling window
React quickly (yesterday weighs 1/250)

The split that decides the results later is not parametric against empirical, it is how fast the scale moves. All four update every bar, but a 250-bar window gives yesterday's return a weight of 1/250, or 0.004, in the next estimate, while EWMA at 0.94 gives it 0.06, fifteen times as much. A slow scale lets breaches cluster, because after a large move the limit is still quoted from mostly calm history.

   virtual void      Reset()
     {
      m_seed.Reset();
      m_var     = 0.0;
      m_started = false;
     }

   virtual void      Update(const double ret)
     {
      if(!m_started)
        {
         m_seed.Push(ret);
         if(m_seed.Full())
           {
            double sd = m_seed.StdDev();
            m_var     = sd * sd;
            m_started = true;
           }
         return;
        }
      m_var = m_lambda * m_var + (1.0 - m_lambda) * ret * ret;
     }

   virtual bool      Ready() const { return(m_started && m_var > 0.0); }
   virtual string    Name()  const { return("EWMA(0.94)");             }

   virtual double    Limit() const
     {
      return(Ready() ? m_z * MathSqrt(m_var) : 0.0);
     }

   virtual double    Shortfall() const
     {
      return(Ready() ? m_e * MathSqrt(m_var) : 0.0);
     }

That excerpt is the recursive half of the EWMA model. Lambda is fixed at J.P. Morgan's published 0.94 rather than fitted, since fitting it on the sample the battery then grades would be look-ahead.

The order of operations, which is where this goes wrong

There is exactly one way to run a model past the battery honestly, and it is worth isolating in a single function so that all four models are treated alike.

//+------------------------------------------------------------------+
//| Run one model over the whole return series and grade it. The     |
//| forecast-then-observe-then-update order lives here and nowhere   |
//| else, so all four models are guaranteed to be treated alike.     |
//+------------------------------------------------------------------+
void Grade(CRiskModel &model, const double &ret[], const int n,
           const SCoverageConfig &cfg, SCoverageReport &rep)
  {
   CCoverageTest test;
   string why;
   if(!test.Init(cfg, why))
     {
      Print("configuration rejected: ", why);
      return;
     }
   model.Reset();
   for(int i = 0; i < n; i++)
     {
      if(model.Ready())
         test.UpdateWithES(-ret[i], model.Limit(), model.Shortfall());
      model.Update(ret[i]);
     }
   test.Compute(rep);
  }

Important: forecast, then observe, then test, then update. Reading the limit after folding in the new return fits the model on the day it is graded; it then passes every test, and nothing in the battery's outputs can reveal it.


Does the battery actually work?

Before pointing this at real prices, we need to know the tests can tell the two failure modes apart, which takes synthetic breach sequences whose answer is known by construction.

The interesting generator is the clustered one. It must breach at exactly the promised long-run rate, or the count-based test would have something legitimate to find. A two-state Markov chain does it, with the entry probability solved rather than tuned:

rate = entry / (1 + entry - persist)
//+------------------------------------------------------------------+
//| Clustered breaches at EXACTLY the given long-run rate. A         |
//| two-state chain breaches with probability `persist` after a      |
//| breach; the entry probability is then solved so the stationary   |
//| rate is the one asked for:                                       |
//|                                                                  |
//|     rate = entry / (1 + entry - persist)                         |
//|                                                                  |
//| Solving it rather than tuning it by hand is what makes the       |
//| third row of experiment 1 an argument instead of an anecdote --  |
//| the long-run rate is right BY CONSTRUCTION, so the rate is not   |
//| what is wrong and the clustering is all that is left.            |
//+------------------------------------------------------------------+
void FillClustered(bool &hit[], const int n, const double rate,
                   const double persist)
  {
   double entry = rate * (1.0 - persist) / (1.0 - rate);
   bool   state = false;
   for(int i = 0; i < n; i++)
     {
      double u = g_rng.Uniform();
      state  = (state ? (u < persist) : (u < entry));
      hit[i] = state;
     }
  }

Four cells, one thousand sequences of one thousand periods each, a promised breach rate of 0.05 and every test at alpha = 0.05; the figures are rejection rates. The shortfall test needs loss magnitudes that a hit sequence does not carry, so it waits for real prices in the next section.

Every setting is an input of ProvingGround.mq5, so the table can be regenerated exactly. The two clustered rows use persist = 0.50: a breach is followed by another half the time, against 5% unconditionally. The two wrong-rate rows breach at 0.125, two and a half times the promise, and "both wrong" feeds that rate through the same chain at persist = 0.50. Every test still grades against the promised 0.05. The duration test needs at least ten gaps before it runs, and the dynamic-quantile test regresses on four lags of the hit series alone, since a hit-only sample has no limit column to add. A single xorshift generator, seeded once with 20260829, supplies every draw in the script: the four cells run in the table's order and the two experiments below continue the same stream, so changing the seed or the order changes the draws.

What is wrong with the model
Kupiec
Indep.
Cond.
Duration
DQ
Nothing (control) 0.045
0.089
0.057
0.109
0.060
Rate 2.5x too high
1.000
0.037
1.000
0.596
1.000
Rate CORRECT, but clustered
0.238
1.000
1.000
0.997
1.000
Both wrong
1.000
1.000
1.000
0.999
1.000

In the third row the long-run breach rate is correct by construction, and Kupiec misses the model roughly three times in four; every test that reads arrival catches it essentially always.

Kupiec's 0.238 in that row needs a precise reading. Its statistic depends on the count alone, so the order of breaches never reaches it directly. Clustering does make the count in one sample far more variable than a binomial, and that over-dispersion pushes some samples past a threshold calibrated for binomial variation. So Kupiec rejects more often than 5%, but nothing in its output says why, and a quarter of the time is not detection anyone could act on.

Note: on the control row, Christoffersen's independence test fires on 8.9% of correct models and the duration test on 10.9%, against a nominal 5%. Both are known to be oversized in finite samples: a real limitation, not an implementation defect.

A rule that acts when any of several tests rejects also has a false-alarm rate above any single test's, though less than if the tests were independent, since they read the same breaches. Either tighten each test (alpha divided by the number of tests is the crude, safe version) or require the rejections to agree in pattern, as the EURUSD reading below does.

How much data does any of this need?

The second experiment sweeps sample size (250, 500, 1,000 and 2,500 periods) against severity for the count-based test, with 4,000 sequences per point. Fig. 2 plots a model breaching twice as often as promised.

Rejection rate against sample size for a model breaching twice as often as promised

Fig. 2. Rejection rate for a model breaching twice as often as promised, at a 99% limit and a 95% limit. The dashed line is the nominal test size.

At a 99% limit over 250 days, a model breaching twice as often as it claims is caught 24% of the time; at 95% over the same days, 88%, because 250 days at 99% produce only two and a half expected breaches. Worse, at 99% over 250 days the false-alarm rate is 0.095, not 0.05, because the statistic is too coarsely discretised to attain its nominal size: there the test is not merely weak, it is mis-sized.

The practical response is to audit a limit at 95% as well when you report it at 99%, where there are enough breaches to count. That audit grades the 95% quantile, not the 99% one. A scale that reacts too slowly shifts every quantile together, so clustering at 95% is a strong warning about 99%; a wrong tail shape does not carry over. A clean 95% audit is evidence about the scale, not a certificate for the 99% tail.

What the traffic light costs a model that is right

The third experiment runs 20,000 independent replications of a correct 99% limit over 250 days each, and records where the supervisory zones put it.

Zone
Frequency
Green
0.891
Yellow
0.109
Red
0.000

Nothing is wrong with this model, yet roughly one year in ten penalises it, and the average multiplier a correct model pays is 3.0502 rather than the floor of 3.00. That is the price of judging a one-in-a-hundred event on 250 observations.

The right shape, estimated with noise, can still fail the battery

One last result decides how the next section reads. Feed the EWMA model independent normal returns with genuinely constant volatility, so its distributional assumption is the true one. It still draws duration, dynamic-quantile and shortfall rejections, a breach rate of 0.0122 against a promised 0.0100, and a yellow zone.

The run uses 6,000 normal draws with sigma = 0.01 from a generator seeded with 8888. A 99% EWMA limit at lambda = 0.94 warms up on the first 250 and is graded on the remaining 5,750, and the shortfall null uses 2,000 draws.

The distinction is between the assumption and the estimator. The right forecast here never moves, but EWMA re-estimates the variance every bar from a short memory, so its limit is the right quantity measured with noise. Every test assumes the quoted limit is the true quantile; with a noisy estimate, breaches become likelier exactly where the estimate came out low. These are correct rejections of the forecast as quoted, and they point at the estimator, not the normal assumption.

So the battery reads as a pattern, not six independent verdicts. The fitted duration shape is a useful companion to the p-values because it is a size rather than a significance: a shape far below 1 says breaches cluster, though not why.


Grading four limits on EURUSD

With the battery calibrated, we can point it at something nobody controls. The bakeoff script quotes all four limits over EURUSD daily history as one-step-ahead forecasts. Its 4,000 daily bars yield 3,998 returns from 2011.04.07 to 2026.08.28; the first 250 only fill the estimation window, because a model that is not yet Ready() is never graded, so each model is graded on the remaining 3,748 forecasts, at a 99% limit and alpha = 0.05. Expected breaches are 3,748 x 0.01 = 37.5, and the derived zones are green at 47 or fewer, red at 62 or more.

Model
Breaches
Rate
Kupiec
Indep.
Cond.
Duration
DQ
ES
Zone
Normal
53
0.0141
0.0165
0.0069
0.0015
0.0000
0.0000
0.0002
YELLOW
EWMA (0.94)
49
0.0131
0.0709
0.2545
0.1023
0.8612
0.0286
0.0014
YELLOW
Historical
45
0.0120
0.2314
0.0175
0.0291
0.0008
0.0000
0.0238
GREEN
Student-t (5)
36
0.0096
0.8068
0.0492
0.1403
0.0000
0.0000
0.5345
GREEN

Take the Historical row. Forty-five breaches against an expected 37.5 is unremarkable, Kupiec returns p = 0.2314, and the zones colour it green. Yet independence rejects at 0.0175, conditional coverage rejects, duration rejects hard at 0.0008, and the dynamic quantile and shortfall tests reject outright, the last subject to the reference-shape caveat. This model breaches the right number of times, in the wrong order, and by count it is the second-healthiest of the four.

Ranked by count the order is Student-t, Historical, EWMA, Normal; ranked by arrival it is EWMA and nothing else close. The traffic light, being count-based, sides with the first ordering: green for the two models the arrival tests reject, a yellow and a 3.43 multiplier for EWMA.

The clustering is visible in the fitted duration shapes. A shape below 1 is a decreasing hazard, which is clustering: Historical fits 0.698, Student-t 0.608 and Normal 0.640, while EWMA fits 0.980, very nearly memoryless. So is n11, breaches arriving immediately after another, which is 0 for EWMA against 4 for Normal and 3 for Historical. In this sample EWMA never breaches twice running, which is what a scale that widens after a large move would be expected to do.

Reading the two failure signatures apart

EWMA is not clean either. It passes every test that reads arrival alone (Kupiec 0.0709, independence 0.2545, conditional coverage 0.1023, duration 0.8612) and fails the two that read a magnitude, DQ at 0.0286 and ES at 0.0014. That matches the constant-volatility signature, so a noisy variance is the most likely reading, though not the only one: the dynamic quantile test also responds to omitted dynamics, regime shifts and a misjudged tail.

Historical shows the other signature, and Normal and Student-t share it. A shape below 1 identifies clustering, not its cause; calendar effects, regime switches or the tail model could all contribute. What points at the scale is the comparison: fed exactly the same returns, the three window models cluster, and EWMA, whose scale reacts fifteen times faster, does not.

So the honest summary is not "EWMA passes and the rest fail". Three of the four cluster their breaches, and the one that does not still quotes its limit from an estimate noisy enough for the magnitude tests to see.

What this comparison does and does not show

This is one symbol, one timeframe and one fifteen-year sample, graded at standard rather than fitted settings (lambda 0.94, five degrees of freedom for the Student-t, a 250-bar window), and different settings or markets could reorder the models. The general claim rests on the synthetic third row, where the answer is known; EURUSD shows that the disagreement between count and arrival occurs on real prices. ModelBakeoff takes the symbol, timeframe, window, confidence level and degrees of freedom as inputs, so repeating the comparison on your own market is one run.


Watching the verdict on a chart

Two indicators put the same information on the chart. The first, CoverageBands, draws the limit as the price it forbids and marks every bar that closed below it.

Both face the same problem: the models are stateful and sequential, while OnCalculate may ask for only the tail to be recomputed. Neither tries to resume; each resets the model and replays the window of returns immediately before start.

The drawing loop makes the article's ordering discipline visible.

   for(int i = start; i < rates_total; i++)
     {
      LimitBuffer[i]  = EMPTY_VALUE;
      EsBuffer[i]     = EMPTY_VALUE;
      BreachBuffer[i] = EMPTY_VALUE;

      //--- the forecast for bar i, made from returns ending at i-1
      if(g_model.Ready() && close[i - 1] > 0.0)
        {
         double lim = g_model.Limit();
         double es  = g_model.Shortfall();
         double lp  = close[i - 1] * MathExp(-lim);
         LimitBuffer[i] = lp;
         if(InpShowES)
            EsBuffer[i] = close[i - 1] * MathExp(-es);
         //--- only now is bar i allowed to be seen
         if(close[i] < lp)
            BreachBuffer[i] = low[i];
        }

      g_model.Update(LogReturn(close[i - 1], close[i]));
     }

The limit arrives as a return, so multiplying the previous close by MathExp(-lim) turns it into a price. The forecast for bar i uses information through bar i-1 only: close[i] is read after the line is fixed, and the model is fed bar i on the last statement.

Fig. 3 shows both models drawing over the same EURUSD daily bars.

 EWMA and Normal limit lines drawn over the same EURUSD daily bars

Fig. 3. CoverageBands on EURUSD D1, EWMA on the left and Normal on the right over the same bars.

The second indicator, CoverageVerdict, plots the rolling Kupiec and independence p-values in a separate window, on one 0 to 1 scale with a level line at alpha. The thing to watch is the gap between them.

It rebuilds the breach indicator as CoverageBands does, keeping the bits in a global g_hit because the rolling window reaches back into bars the current call does not recompute, then runs the battery at every bar.

//--- pass two: the battery over a sliding window of those bits
   bool win[];
   ArrayResize(win, InpTestWindow);
   for(int i = start; i < rates_total; i++)
     {
      RateBuffer[i]  = EMPTY_VALUE;
      IndepBuffer[i] = EMPTY_VALUE;
      BothBuffer[i]  = EMPTY_VALUE;
      if(i < g_first)
         continue;

      int from = i - InpTestWindow + 1;
      for(int k = 0; k < InpTestWindow; k++)
         win[k] = g_hit[from + k];

      SCoverageTest uc, ind, cc;
      int a, b, c, d;
      CoverageKupiec(win, InpTestWindow, InpRate, InpAlpha, uc);
      CoverageIndependence(win, InpTestWindow, InpAlpha, ind, a, b, c, d);
      CoverageConditional(uc, ind, InpAlpha, cc);

      if(uc.applicable)
         RateBuffer[i] = uc.pvalue;
      //--- a window with no breaches leaves the independence test
      //--- nothing to read; the gap in the line is the honest
      //--- rendering of that, and a flat 1.0 would not be
      if(ind.applicable)
         IndepBuffer[i] = ind.pvalue;
      if(cc.applicable)
         BothBuffer[i] = cc.pvalue;
     }

Here the applicable flag becomes visible. When a quiet window leaves the independence test nothing to read, the buffer stays at EMPTY_VALUE and the line breaks, instead of sitting at 1.0 and drawing a pass for a test that never ran.

Rolling Kupiec and independence p-values diverging for a slow volatility model

Fig. 4. CoverageVerdict on EURUSD D1, Normal on the left and EWMA on the right. What matters is the gap between the rate line and the independence line: wide and shifting for the slow model, steadier for the recursive one.

The disagreement in Fig. 4 is easier to size as counts. Over 2,500 EURUSD daily bars, with a 500-bar test window at a 95% limit, here is how many bars each line spent below alpha.

Model
Bars the count line rejects
Bars the independence line rejects
Normal
818
578
EWMA (0.94)
233
1

The count line separates the two models by a factor of about three and a half, which a practitioner would shrug at; the independence line separates them by a factor of 578.

The counts cover overlapping windows, which share 499 of their 500 observations, so one cluster can hold a line below alpha for hundreds of bars: the table describes the chart, not a failure rate.


From verdict to position size

A battery of p-values is a diagnosis, not a decision. The last piece lets the grade change the size of the next position. One call per completed period drives the whole cycle, and the order inside it is the reason the class exists.

//--- feed one COMPLETED period's return. Grades the standing quote
//--- against it, folds it into the model, and leaves a fresh quote
//--- for the period about to begin.
   bool              OnReturn(const double ret)
     {
      if(!m_ready || !MathIsValidNumber(ret))
         return(false);

      //--- 1. judge the period that just ended, against the limit
      //--- that was standing before it began
      if(m_quoted)
         m_test.UpdateWithES(-ret, m_quote_lim, m_quote_es);

      //--- 2. only now may the model see it
      m_model.Update(ret);

      //--- 3. quote for the period about to begin
      if(m_model.Ready())
        {
         m_quote_lim = m_model.Limit();
         m_quote_es  = m_model.Shortfall();
         m_quoted    = (m_quote_lim > 0.0);
        }

      //--- 4. re-grade. Cheap while es_sims is 0, which is why the
      //--- gate defaults to leaving the simulated ES test out: it
      //--- is a report-time question, not a per-bar one.
      if(m_test.Count() > 0)
         m_test.Compute(m_rep);
      return(true);
     }

The mapping from grade to action is borrowed from Basel, published since 1996: place the rolling breach count in a zone and pay a multiplier rising from 3.0 to 4.0. Driving the gate by a count, after arguing that a count is the weakest grade, needs a reason: the supervisory zone is the only published mapping from a grade to an action, and at the Expert Advisor's setting, 250 periods at 99%, it applies exactly as published. No rule says "an independence p-value of 0.017 means multiply your risk budget by 0.83", and inventing one would present a made-up number as authority.

It is still a heuristic: the multiplier was set for a bank's regulatory capital, not a retail lot size, and it inherits the count's weakness measured above. The gate is a conservative brake, not a precise instrument.

So the two halves do different jobs. The count drives the gate; the arrival tests drive the model choice. What they say is not "trade smaller" but "breaches cluster; look at the forecaster", because a multiplier widens the limit without changing how quickly the scale responds.

//--- the capital multiplier the zone implies
   double            Multiplier() const
     {
      if(!m_cfg.enabled)
         return(CV_BASE_MULTIPLIER);
      if(!Tested())
         return(m_cfg.strict_warmup ? 4.0 : CV_BASE_MULTIPLIER);
      return(m_rep.multiplier);
     }

//--- the limit to actually size against: the model's own quote,
//--- inflated by however much the grade says it cannot be trusted
   double            Limit() const
     {
      return(m_quote_lim * Multiplier() / CV_BASE_MULTIPLIER);
     }

Two design choices matter. An untested model pays the worst multiplier, not the best, so absent evidence is never treated as favourable; strict_warmup selects this and defaults to true. And the gate reads a rolling sample, so a model that failed in 2015 is not still paying for it, and one failing now is not shielded by ten good years.

Turning a multiplier into a lot size

In an account the multiplier does the obvious thing, with one trap. The stop sits at a fixed number of raw limits, decided by the volatility model alone; the gate acts on the risk budget instead.

//--- The stop sits at a fixed number of RAW limits, so the distance
//--- is set by the volatility model alone. The gate acts on the
//--- risk BUDGET instead, cutting it by 3/multiplier: a green model
//--- risks the full InpRiskPct, a yellow one about 88% of it, a red
//--- one 75%. Scaling both the stop and the lot would leave the
//--- money risked unchanged and the gate would do nothing at all.
   double stopReturn = InpStopMult * g_gate.RawLimit();
   double budget     = AccountInfoDouble(ACCOUNT_EQUITY) * InpRiskPct / 100.0
                       * CV_BASE_MULTIPLIER / g_gate.Multiplier();
   double px         = SymbolInfoDouble(_Symbol, SYMBOL_BID);
   double lot        = CvLotForLimit(_Symbol, px, stopReturn, budget);

If the gate scaled both the stop distance and the lot size, the money at risk would be unchanged and the gate would do nothing. Cutting the budget by 3/multiplier means a green model risks the full percentage, a yellow one about 88% of it, and a red one 75%.

The sizing arithmetic is separated from the symbol lookup for a reason. A terminal without a connected account answers 0 to SYMBOL_TRADE_TICK_VALUE, and a routine exercisable only against a live broker is one nobody exercises.

//+------------------------------------------------------------------+
//| Lot size at which a loss of one LIMIT costs exactly riskMoney.   |
//|                                                                  |
//| The limit arrives as a RETURN, so it becomes money in three      |
//| steps: a return of r on a price P is a move of P*r, that move    |
//| is P*r/point points, and each point is worth                     |
//| CvValuePerPointPerLot per lot. Normalised to the broker's        |
//| volume limits at the end, and 0 whenever the answer would be     |
//| below the minimum -- a lot the broker will reject is not a       |
//| smaller position, it is a failed order.                          |
//+------------------------------------------------------------------+
double CvLotFromParts(const double price, const double limitReturn,
                      const double riskMoney, const double point,
                      const double valuePerPoint, const double minLot,
                      const double maxLot, const double step)
  {
   if(price <= 0.0 || limitReturn <= 0.0 || riskMoney <= 0.0)
      return(0.0);
   if(point <= 0.0 || valuePerPoint <= 0.0)
      return(0.0);

   double points     = price * limitReturn / point;
   double lossPerLot = points * valuePerPoint;
   if(lossPerLot <= 0.0)
      return(0.0);

   double lot = riskMoney / lossPerLot;
   if(step > 0.0)
      lot = MathFloor(lot / step) * step;
   if(maxLot > 0.0 && lot > maxLot)
      lot = maxLot;
   if(lot < minLot)
      return(0.0);
//--- kill the binary dust a division leaves on a stepped volume
   int digits = (step >= 1.0 || step <= 0.0
                 ? 0 : (int)MathCeil(-MathLog10(step)));
   return(NormalizeDouble(lot, digits));
  }

The conversion is linear, a move of P*r, even though the limit is a log return. That is deliberate. The EA places its stop with the same arithmetic, a buy's at ask * (1 - stopReturn) and a sell's at bid * (1 + stopReturn), so the money lost at the stop matches the budget the lot was sized for, before volume rounding. Converting with an exponential here while the stop stayed linear would break exactly that agreement. The only consequence of the linear choice is what "three limits" means: three times a log-return limit, applied as a simple return. For a 4% stop that differs from the exact log distance by about 2%, farther than it for a buy and nearer for a sell.

Two clocks in OnTick

The Expert Advisor runs the dullest signal available, a two-EMA crossover, only so that the account holds a position and there is a loss to grade. What is worth copying is the structure of OnTick, which runs on two separate clocks. The first half is below.

//--- the once-per-bar half
   if(IsNewBar())
     {
      double ret = 0.0;
      if(CompletedReturn(ret))
         g_gate.OnReturn(ret);

      //--- record where the verdict stood, so the run can report how
      //--- much of its life the model spent under penalty
      if(g_gate.Tested())
        {
         ENUM_CV_ZONE z = g_gate.Zone();
         if(z == CV_ZONE_GREEN)
            g_green++;
         else
            if(z == CV_ZONE_YELLOW)
               g_yellow++;
            else
               g_red++;
        }
      g_pending = true;
     }

The grade advances exactly once per completed bar, because feeding the same return twice would corrupt the sample everything rests on. The trade is retried on later ticks until the market accepts it: a daily bar opens near midnight and the session may not start for another hour, so a single attempt would silently drop nearly every signal.

Retrying blindly on every tick is not the answer either, because it produces tens of thousands of rejected orders. The EA asks first.

//+------------------------------------------------------------------+
//| Is the symbol inside one of its quoted trading sessions?         |
//|                                                                  |
//| SymbolInfoSessionTrade reports each session for a weekday as an  |
//| offset from midnight, so the comparison is done in seconds of    |
//| the day rather than on datetimes. A symbol that declares no      |
//| session for today is closed, not always-open.                    |
//+------------------------------------------------------------------+
bool MarketOpen()
  {
   MqlDateTime t;
   TimeToStruct(TimeCurrent(), t);
   int now = t.hour * 3600 + t.min * 60 + t.sec;
   datetime from = 0, to = 0;
   for(int i = 0; SymbolInfoSessionTrade(_Symbol,
                                         (ENUM_DAY_OF_WEEK)t.day_of_week,
                                         i, from, to); i++)
     {
      if(now >= (int)from && now <= (int)to)
         return(true);
     }
   return(false);
  }

What the gate is worth

The comparison is a single input: with the gate off, the raw model limit sizes every trade, as an ordinary risk-sized EA does; with it on, the same signal is sized through the verdict. Both arms log the full battery.

The runs below cover EURUSD D1 from 2010 to the end of 2025 on 1-minute OHLC modelling, with a 10,000 deposit, 1% risk per trade, a stop at three raw limits, and 250-bar estimation and test windows.

The account is a MetaQuotes demo in USD. EURUSD there is quoted to five digits with a 100,000-unit contract, a minimum volume and volume step of 0.01 lots, and a floating spread. Orders use market execution with the tester's default fills and no added delay. Over the 81 trades of the Normal gate-off arm, the account paid 11.06 in commission and 634.37 in swap, the tester charging swap at the symbol's current rates. Positions ran from 0.01 to 0.04 lots, small enough that leverage never binds: the same arm at 1:100 and at 1:500 gives identical results. Another broker's history, spread or swap will move these figures, so read the table as the output of this environment, not as a property of the gate.

Arm
Trades
Profit
Max DD %
Profit factor
Sharpe
EWMA, gate off
78
-776.59
13.58
0.701
-0.269
EWMA, gate on
74
-285.66
13.04
0.884
-0.089
Normal, gate off
81
-976.92
13.05
0.612
-0.366
Normal, gate on
81
-862.10
11.85
0.639
-0.330
Normal, gate on plus halt
68
-581.53
8.96
0.722
-0.263

Fig. 5 puts the gated and ungated balance curves on the same axis.

Account balance for the Normal model with the coverage gate on and off

Fig. 5. Account balance for the Normal model, gate off against gate on, same signal and same period. Both arms trade the same 81 trades, so the only difference is how much was risked on each.

Every arm loses money. A 20/60 EMA crossover on EURUSD is not an edge and was never intended to be one.

The obvious objection is that the gate simply makes positions smaller, and smaller positions on a losing strategy lose less. But profit factor and Sharpe ratio are invariant to uniform position scaling, and both move here, so the scaling was not uniform.

The gate is one source of the unevenness, since it cuts the budget only in yellow or red. It is not the only one. At these settings positions are a few hundredths of a lot, so one volume step is a large fraction of each, and each arm sizes from its own equity, so once the curves part the same signal is sized from a different base. Either can move a profit factor by a few hundredths on 81 trades.

The Normal pair is the cleanest comparison, because both arms trade the same 81 trades. Profit factor rises from 0.612 to 0.639, and Sharpe from -0.366 to -0.330. That is consistent with the gate cutting exposure ahead of bad periods, but this run cannot separate it from rounding and equity-path effects. Separating them would take a control arm that cuts the budget by the same average amount at random times.

The EWMA pair moves further, profit factor 0.701 to 0.884, but is a less clean comparison: the gated arm takes 74 trades against 78, because the inflated limit shrank four lots below the broker's minimum volume, where CvLotFromParts returns 0.

The strongest single result is the halt arm. Refusing to trade a rejected model cuts maximum drawdown from 13.05% to 8.96%, nearly a third, by sitting out the 9.6% of its life the Normal model spent in the red zone. It gives up 13 of its 81 trades, more than its share of time, because the red-zone stretches fell in volatile periods when the crossover fired often. A skipped trade contributes nothing either way, so the mechanism is direct, but it is still one path.

Important: between 68 and 81 trades establishes nothing statistically. The direction is consistent across all five arms, but treat the table as an engineering demonstration, its figures as directional rather than as evidence that the gate adds a trading edge, and run the comparison on your own strategy and symbol. A limit with the right shape but a noisy variance will also spend some of its life in yellow, and the gate cannot tell that apart from a broken model.


Conclusion

A risk limit is a hypothesis with a number attached, and one of the few in trading that is cheap to test. The machinery is a handful of likelihood ratios, a binomial CDF and a simulated null, none of which needs an external library.

A limit promises a rate and an arrival pattern, and counting breaches grades only the first. On this EURUSD sample the two gradings disagreed almost completely: the model whose count looked best was rejected by both arrival tests, while the one model those tests cleared was handed a yellow card.

Here is what to do with your own limit, whatever produced it:

  1. Record hit = 1 whenever the realized loss exceeds the limit that was quoted before the period began. Nothing else recovers that ordering.
  2. Run Kupiec. If it rejects, you are probably not getting your stated confidence level, and the observed rate is the best estimate of what you have. At 99% over 250 observations it is both weak and mis-sized.
  3. Run the independence and duration tests. If either rejects while Kupiec passes, your breaches cluster, most commonly because the scale reacts too slowly. Try a forecaster that reacts faster to yesterday and start again from step 1. This step has the largest payoff.
  4. If only the dynamic quantile and shortfall tests reject, suspect estimation noise in the scale first: a reason to look closer, not proof that the forecaster must go.
  5. Map the count to a supervisory zone and take its multiplier, as a conservative heuristic.
  6. Cut your risk budget by 3/multiplier, or refuse to trade the model at all while it sits in the red zone.
  7. Stop when the model is green and Kupiec and the independence test both return p above alpha over at least 250 observations. Below that at 99%, conclude nothing about the rate, and audit at 95% as well.

That last step is the one most likely to be skipped and the one most worth keeping. A test that cannot run has not cleared your model, and a battery that says so beats a number that never admits it.

Read the steps as a pattern rather than a tripwire: a single rejection just under alpha is a reason to look, and agreement between tests is a reason to act.

Files attached to the article

File
Type
Description
CoverageTypes.mqh
Include
Distribution functions and the derived Basel zone boundaries
CoverageTests.mqh
Include The six tests and the CCoverageTest accumulator
RiskModels.mqh
Include
Normal, EWMA, Historical and Student-t limit forecasters
CoverageGate.mqh
Include
The decision rule and the position sizing arithmetic
CoverageBands.mq5
Indicators
The limit drawn as a price band, with breach markers
CoverageVerdict.mq5
Indicators
Rolling Kupiec, independence and conditional p-values
ProvingGround.mq5
Scripts
Synthetic experiments: the four corners, power, zone error rate
ModelBakeoff.mq5
Scripts
Grades all four models on a real symbol
CoverageGateEA.mq5
Experts
Expert Advisor sizing through the coverage verdict
Attached files |
MQL5.zip (48.68 KB)
Features of Custom Indicators Creation Features of Custom Indicators Creation
Creation of Custom Indicators in the MetaTrader trading system has a number of features.
Native MQL5 to ClickHouse Integration via HTTP Interface and RowBinary Native MQL5 to ClickHouse Integration via HTTP Interface and RowBinary
We implement a direct MT5→ClickHouse pipeline without intermediate services: RowBinary encoding at the byte level and an HTTP client that authenticates and posts inserts. The article details schema and field mapping, VarUInt and Float64 encoding, Nullable rules, and why POST is required for inserts and DDL. An EA streams live ticks and deals, and scripts verify round‑trip correctness and perform historical backfill, enabling consistent storage for downstream queries.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
Account-Wide Position Sizing in MQL5: Capping Each New Trade by the Risk Already Open Account-Wide Position Sizing in MQL5: Capping Each New Trade by the Risk Already Open
When an EA trades several symbols, each new lot size must account for the risk already open. CRiskBudget returns the largest volume that five caps allow: risk per trade, open risk budget, free margin share, SYMBOL_VOLUME_MAX, and SYMBOL_VOLUME_LIMIT, and it names the cap that decided. Unit tests, a tester EA, and a Python consistency check cover these decisions. In the tested runs, the budget did not reduce drawdown.