preview
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

MetaTrader 5 — Indicators |
69 0
Olamide Daniel Adebayo
Olamide Daniel Adebayo

Introduction

Most of what a trader calls "momentum" or "mean reversion" is a claim about the order that bars arrive in, not just their count. The Wald–Wolfowitz runs test is a classic statistic built for exactly that question: given a sequence of up and down bars, does the pattern of switching between them look random, or does it cluster into runs that are too long or too short to be chance? I kept coming back to it because it answers a narrower, more honest question than most "trend detectors" do: not "is the market trending," but "given exactly this many up bars and down bars, is the order they arrived in distinguishable from a random shuffle of the same ups and downs, at this window length, right now." That's a conditional test on the observed mix of signs, not a claim that bar direction itself is a fair coin flip with p=0.5 — the runs test never assumes that, and neither does anything built on top of it here.

This article is a diagnostic and research tool, not a plug-and-play profit system. It ships a rolling runs-test engine, a chart indicator, two validation scripts, and an Expert Advisor that trades off the regime label the engine produces. The backtest section reports what that gate actually did across eighteen runs, including the runs where it lost money and the one where almost all of the profit came from a single cluster of trades. None of the numbers below are illustrative — every one is read off a real Strategy Tester report.

The architecture is small on purpose. A ring-buffer class tracks the counts a runs test needs in O(1) per bar instead of rescanning a window every tick. A placebo class draws a fake regime label from a random bar in the recent past, so the same Expert Advisor can run as a genuine test, a no-gate control, or a null control without touching its trade logic. An audit log writes one row per closed bar so every regime decision can be checked against what the account actually did.

The backtest plan behind this article runs the same fixed matrix throughout: three symbols (EURUSD, GBPUSD, XAUUSD), two timeframes (H1, M15), and three modes (Gated against the live regime, No gate as a baseline, Placebo as a null control), window and critical value held constant across all eighteen runs. That matrix exists to answer one question honestly — does trading off a real runs-test regime label beat trading off nothing, or off a fake label drawn from the same distribution — rather than to find the one configuration that happens to look best after the fact.


The statistic behind the signal

Take the sign of each bar's close-to-close move, drop the ties, and you have a sequence of pluses and minuses. A "run" is a maximal block of the same sign. With n1 pluses, n2 minuses, and R observed runs, the runs test compares R against the number of runs a random shuffle of the same pluses and minuses would produce on average.

mean = 2*n1*n2 / (n1+n2) + 1
var  = 2*n1*n2*(2*n1*n2 - n1 - n2) / ((n1+n2)^2 * (n1+n2-1))
z    = (R - mean) / sqrt(var)          // optional continuity correction

A large negative z means far fewer runs than chance — the signs are clumping into long stretches, which is what a persistent, trending sequence looks like. A large positive z means far more runs than chance — signs flip back and forth more than randomness would, the signature of an alternating, mean-reverting sequence. Near zero, the sequence looks like noise. The continuity correction shaves 0.5 off the gap between R and its mean before dividing by the standard deviation, which keeps the test from over-rejecting on short, discrete windows. Two functions carry this: one turns counts into a z-score, the other turns a z-score into a two-sided p-value using the normal CDF that ships in the standard library.

RtZFromCounts: runs Z-score, optional continuity correction

//+------------------------------------------------------------------+
//| RtZFromCounts: runs Z-score, optional continuity correction      |
//+------------------------------------------------------------------+
double RtZFromCounts(const int n1,const int n2,const int runs,const bool cc)
  {
   if(n1<=0 || n2<=0)
      return(0.0);
   double n   =(double)(n1+n2);
   double prod=2.0*(double)n1*(double)n2;
   double mean=prod/n+1.0;
   double var =prod*(prod-n)/(n*n*(n-1.0));
   if(var<=0.0)
      return(0.0);
   double diff=(double)runs-mean;
   if(cc)
     {
      double mag=MathMax(0.0,MathAbs(diff)-0.5);
      diff=(diff>0.0) ? mag : -mag;
     }
   return(diff/MathSqrt(var));
  }

RtPFromZ: two-sided normal tail for a Z value

//+------------------------------------------------------------------+
//| RtPFromZ: two-sided normal tail for a Z value                    |
//+------------------------------------------------------------------+
double RtPFromZ(const double z)
  {
   int    err=0;
   double cdf=MathCumulativeDistributionNormal(MathAbs(z),0.0,1.0,err);
   if(err!=0)
      return(1.0);  // CDF unreliable - fall back to "no evidence against the null"
   return(MathMax(0.0,2.0*(1.0-cdf)));
  }


A rolling engine instead of a full rescan

Recomputing a runs test from scratch on every new bar means rescanning the whole window, which gets expensive as the window grows and adds up over a multi-year backtest. CRunsTest keeps a fixed-size ring buffer of the last InpWindow signs and updates three counters — n1, n2, and the number of adjacent unequal pairs — by only looking at the sign that leaves the window and the sign that enters it. The run count itself is just transitions-plus-one, so Runs() never has to walk the buffer. Push() drops a zero sign (a tie, where the close-to-close move is zero) before it ever reaches the ring, so the window holds the last InpWindow non-tie bars, not strictly the last InpWindow bars on the chart — on a symbol with frequent ties that window can span noticeably more calendar bars than its slot count.

A rescan-every-bar approach costs O(InpWindow) work per bar, so a 100-slot window over a multi-year M15 backtest means tens of millions of redundant comparisons by the time the test finishes. Push() instead touches at most two buffer slots and updates four integer counters per call, regardless of how large InpWindow is. The only real cost is ArrayResize() once, at Init() time, to size the ring to the chosen window. RT_MIN_WINDOW enforces a floor of 30 bars on that window, below which a runs test has too few observations for its normal approximation to behave well — MetaTrader's Inputs validation rejects anything smaller before the engine ever runs.

CRunsTest: rolling runs engine, O(1) per sign

//+------------------------------------------------------------------+
//| CRunsTest: rolling runs engine, O(1) per sign                    |
//+------------------------------------------------------------------+
class CRunsTest
  {
private:
   char              m_buf[];  // ring of +1/-1 signs
   int               m_size;   // window capacity
   int               m_head;   // oldest slot
   int               m_count;  // signs held
   int               m_n1;     // +1 signs in window
   int               m_n2;     // -1 signs in window
   int               m_trans;  // adjacent unequal pairs
   bool              m_cc;     // continuity correction flag
public:
                     CRunsTest(void);
   bool              Init(const int size,const bool cc);
   void              Reset(void);
   void              Push(const int sign);
   int               Count(void) const;
   int               N1(void) const;
   int               N2(void) const;
   int               Runs(void) const;
   bool              IsReady(void) const;
   double            Z(void) const;
   double            PValue(void) const;
   int               Regime(const double zcrit) const;
  };

CRunsTest::CRunsTest

//+------------------------------------------------------------------+
//| CRunsTest::CRunsTest                                             |
//+------------------------------------------------------------------+
CRunsTest::CRunsTest(void)
  {
   m_size =0;
   m_head =0;
   m_count=0;
   m_n1   =0;
   m_n2   =0;
   m_trans=0;
   m_cc   =false;
  }

CRunsTest::Init

//+------------------------------------------------------------------+
//| CRunsTest::Init                                                  |
//+------------------------------------------------------------------+
bool CRunsTest::Init(const int size,const bool cc)
  {
   if(size<RT_MIN_WINDOW)
      return(false);
   if(ArrayResize(m_buf,size)!=size)
      return(false);
   m_size=size;
   m_cc  =cc;
   Reset();
   return(true);
  }

CRunsTest::Push

//+------------------------------------------------------------------+
//| CRunsTest::Push                                                  |
//+------------------------------------------------------------------+
void CRunsTest::Push(const int sign)
  {
   if(sign==0 || m_size<2)
      return;
   char s=(sign>0) ? 1 : -1;
   //--- drop the oldest sign once the window is full
   if(m_count==m_size)
     {
      char oldest=m_buf[m_head];
      char second=m_buf[(m_head+1)%m_size];
      if(oldest!=second)
         m_trans--;
      if(oldest>0)
         m_n1--;
      else
         m_n2--;
      m_head=(m_head+1)%m_size;
      m_count--;
     }
   //--- link the new sign to the current tail
   if(m_count>0)
     {
      char tail=m_buf[(m_head+m_count-1)%m_size];
      if(tail!=s)
         m_trans++;
     }
   m_buf[(m_head+m_count)%m_size]=s;
   m_count++;
   if(s>0)
      m_n1++;
   else
      m_n2++;
  }


Reading the window

Everything downstream reads off these small accessors: the live counts, whether the window is full enough to trust (RT_MIN_WINDOW bars, both signs present), the z-score, its p-value, and the regime label itself — random, persistent, or alternating, decided by comparing z against the critical value from the Inputs tab.

CRunsTest::Count / N1 / N2 / Runs / IsReady / Z / PValue / Regime

  }

//+------------------------------------------------------------------+
//| CRunsTest::Count                                                 |
//+------------------------------------------------------------------+
int CRunsTest::Count(void) const
  {
   return(m_count);
  }

//+------------------------------------------------------------------+
//| CRunsTest::N1                                                    |
//+------------------------------------------------------------------+
int CRunsTest::N1(void) const
  {
   return(m_n1);
  }

//+------------------------------------------------------------------+
//| CRunsTest::N2                                                    |
//+------------------------------------------------------------------+
int CRunsTest::N2(void) const
  {
   return(m_n2);
  }

//+------------------------------------------------------------------+
//| CRunsTest::Runs                                                  |
//+------------------------------------------------------------------+
int CRunsTest::Runs(void) const
  {
   return((m_count>0) ? m_trans+1 : 0);
  }

//+------------------------------------------------------------------+
//| CRunsTest::IsReady                                               |
//+------------------------------------------------------------------+
bool CRunsTest::IsReady(void) const
  {
   return(m_count>=RT_MIN_WINDOW && m_n1>0 && m_n2>0);
  }

//+------------------------------------------------------------------+
//| CRunsTest::Z                                                     |
//+------------------------------------------------------------------+
double CRunsTest::Z(void) const
  {
   return(RtZFromCounts(m_n1,m_n2,Runs(),m_cc));
  }

//+------------------------------------------------------------------+
//| CRunsTest::PValue                                                |
//+------------------------------------------------------------------+
double CRunsTest::PValue(void) const
  {
   return(RtPFromZ(Z()));
  }

//+------------------------------------------------------------------+
//| CRunsTest::Regime                                                |
//+------------------------------------------------------------------+
int CRunsTest::Regime(const double zcrit) const
  {
   if(!IsReady())
      return(RT_REGIME_RANDOM);
   double z=Z();
   if(z<-zcrit)
      return(RT_REGIME_TREND);
   if(z>zcrit)
      return(RT_REGIME_REVERT);
   return(RT_REGIME_RANDOM);
  }


Two helpers behind the scenes

Two small, stateless functions back the validation and null-rate tooling: a seeded xorshift generator that keeps every shuffle reproducible run to run, and a full, independent scan of a sign slice that the rolling engine gets checked against. Neither one touches the ring buffer — they exist so the incremental engine has something honest to be compared to.

RtNextRand: xorshift32 step, seeded and reproducible

//+------------------------------------------------------------------+
//| RtNextRand: xorshift32 step, seeded and reproducible             |
//+------------------------------------------------------------------+
uint RtNextRand(uint &state)
  {
   if(state==0)
      state=2463534242;
   state^=(state<<13);
   state^=(state>>17);
   state^=(state<<5);
   return(state);
  }

RtShuffleSigns: Fisher-Yates shuffle with the seeded generator

//+------------------------------------------------------------------+
//| RtShuffleSigns: Fisher-Yates shuffle with the seeded generator   |
//+------------------------------------------------------------------+
void RtShuffleSigns(char &a[],const int n,const uint seed)
  {
   uint state=seed;
   for(int i=n-1;i>0;i--)
     {
      int  j=(int)(RtNextRand(state)%(uint)(i+1));
      char t=a[i];
      a[i]=a[j];
      a[j]=t;
     }
  }

RtScanSigns: full scan of a sign slice, counts and runs

//+------------------------------------------------------------------+
//| RtScanSigns: full scan of a sign slice, counts and runs          |
//+------------------------------------------------------------------+
void RtScanSigns(const char &s[],const int start,const int len,
                 int &n1,int &n2,int &runs)
  {
   n1=0;
   n2=0;
   runs=0;
   char prev=0;
   for(int i=start;i<start+len;i++)
     {
      if(s[i]>0)
         n1++;
      else
         n2++;
      if(i==start || s[i]!=prev)
         runs++;
      prev=s[i];
     }
  }


A placebo control for the regime label

A gated Expert Advisor can look profitable just because it trades less often and at a different cadence than a no-gate baseline, with nothing to do with the regime label being right. CRegimePlacebo exists to separate those two effects. It samples uniformly from a rolling history of previously observed regime labels, going back InpPlaceboDepth bars. That pool includes the random/no-trade label, which preserves recent label frequencies far better than drawing from pure noise would. It does not preserve the temporal dependence between labels, though: this is a random-resampling control, not a permutation of the original sequence, so the exact cadence and any autocorrelation between consecutive labels are not carried over, only a similar overall frequency.

In OnTick(), the draw happens before the current bar's real regime is recorded into that ring, so the pool a given draw comes from is always strictly historical — it can never include this tick's own label. Measured against the real audit logs from the six Placebo runs below (60,291 draws total), regime_used matches regime_real 94.17% of the time. That agreement is a property of regime labels clustering into multi-bar stretches: once a trend or revert state holds for several bars in a row, a uniform draw from the last up to InpPlaceboDepth=500 observed labels is likely to land on the same state simply because that state is common in the pool, nothing more.

The Expert Advisor's trade logic never knows the difference between a real and a drawn label. Placebo mode routes the same PickDirection() call through a label pulled at random from that history, so a meaningful share of Placebo bars trade on a no-trade draw rather than a wrong trend/revert one.

CRegimePlacebo: samples from a rolling history of recorded regimes

//+------------------------------------------------------------------+
//| CRegimePlacebo: samples from rolling history of recorded regimes |
//+------------------------------------------------------------------+
class CRegimePlacebo
  {
private:
   char              m_hist[];  // recorded real regimes
   int               m_depth;   // ring capacity
   int               m_head;    // oldest slot
   int               m_count;   // slots filled
   uint              m_state;   // generator state
public:
                     CRegimePlacebo(void);
   bool              Init(const int depth,const uint seed);
   void              Record(const int regime);
   int               Draw(void);
  };

CRegimePlacebo::Init

//+------------------------------------------------------------------+
//| CRegimePlacebo::Init                                             |
//+------------------------------------------------------------------+
bool CRegimePlacebo::Init(const int depth,const uint seed)
  {
   if(depth<RT_PLACEBO_MIN)
      return(false);
   if(ArrayResize(m_hist,depth)!=depth)
      return(false);
   ArrayInitialize(m_hist,0);
   m_depth=depth;
   m_head =0;
   m_count=0;
   m_state=seed;
   return(true);
  }

CRegimePlacebo::Record

//+------------------------------------------------------------------+
//| CRegimePlacebo::Record                                           |
//+------------------------------------------------------------------+
void CRegimePlacebo::Record(const int regime)
  {
   if(m_depth<=0)
      return;
   if(m_count==m_depth)
     {
      m_hist[m_head]=(char)regime;
      m_head=(m_head+1)%m_depth;
      return;
     }
   m_hist[(m_head+m_count)%m_depth]=(char)regime;
   m_count++;
  }

CRegimePlacebo::Draw

//+------------------------------------------------------------------+
//| CRegimePlacebo::Draw                                             |
//+------------------------------------------------------------------+
int CRegimePlacebo::Draw(void)
  {
   if(m_count<RT_PLACEBO_MIN)
      return(RT_REGIME_RANDOM);
   int idx=(int)(RtNextRand(m_state)%(uint)m_count);
   return((int)m_hist[(m_head+idx)%m_depth]);
  }


Sizing within the broker's limits

RtCalcSafeLot approximates a target risk percentage from the stop distance, then caps the result against the symbol's volume limits and available margin. Those clamps can only reduce the intended exposure or skip the trade entirely — they don't guarantee the realized risk matches the stated percentage in every case, only that the order sent is one the broker will actually accept. RtMinStopDistance reads the broker's stops and freeze levels plus the current spread and adds a small pad, so the stop never sits inside a distance the broker would reject. RtCalcSafeLot turns a risk budget into a lot size. It then clamps that lot against SYMBOL_VOLUME_MAX and SYMBOL_VOLUME_LIMIT, and checks the margin OrderCalcMargin reports against free margin. It snaps the result down to the broker's volume step, and returns zero — a clean skip, not a tiny forced trade — if that result rounds below SYMBOL_VOLUME_MIN.

On XAUUSD this floor matters, but not in the direction a "clamp" usually suggests: SYMBOL_VOLUME_MAX and SYMBOL_VOLUME_LIMIT only ever shrink the computed lot, never inflate it, so the clamp itself cuts risk rather than adding to it. What actually lets a one percent risk budget cost several percent of equity on XAUUSD is everything the sizing math can't see ahead of time: a gap through the stop, slippage on a fast tick, or a tick-value quirk for the instrument that makes the stop-distance-to-cash conversion less exact than it looks. The volume floor itself only ever removes a trade, it never sends one oversized. Once the lot rounds below SYMBOL_VOLUME_MIN the function returns zero rather than rounding back up to the minimum, so it cannot be the source of an outsized loss — that's the mechanism behind the drawdowns further down, not the volume clamp.

The margin clamp is the step most Expert Advisors skip. OrderCalcMargin() is called with the proposed lot before the order is ever sent, and if the reported margin exceeds a fraction of free margin — RT_MARGIN_USE, set to 0.95 — the lot is scaled down rather than left to fail at the broker. That matters most in exactly the runs where the account has already drawn down: a fixed-percentage risk model keeps asking for a smaller and smaller dollar loss as equity falls, and without this clamp a shrinking account can still get rejected on margin before it ever reaches the volume floor below.

RtMinStopDistance: stop floor in price units

//+------------------------------------------------------------------+
//| RtMinStopDistance: stop floor in price units                     |
//+------------------------------------------------------------------+
double RtMinStopDistance(const string sym)
  {
   double point =SymbolInfoDouble(sym,SYMBOL_POINT);
   long   stops =SymbolInfoInteger(sym,SYMBOL_TRADE_STOPS_LEVEL);
   long   freeze=SymbolInfoInteger(sym,SYMBOL_TRADE_FREEZE_LEVEL);
   long   spread=SymbolInfoInteger(sym,SYMBOL_SPREAD);
   long   level =MathMax(stops,freeze);
   return((double)(level+spread+RT_STOP_PAD_POINTS)*point);
  }

RtVolumeDigits: decimals implied by the volume step

//+------------------------------------------------------------------+
//| RtVolumeDigits: decimals implied by the volume step              |
//+------------------------------------------------------------------+
int RtVolumeDigits(const double step)
  {
   int    digits=0;
   double scaled=step;
   while(digits<8 && MathAbs(scaled-MathRound(scaled))>1e-9)
     {
      scaled*=10.0;
      digits++;
     }
   return(digits);
  }

RtCalcSafeLot: risk lot clamped by caps and margin, 0 to skip

//+------------------------------------------------------------------+
//| RtCalcSafeLot: risk lot clamped by caps and margin, 0 to skip    |
//+------------------------------------------------------------------+
double RtCalcSafeLot(const string sym,const ENUM_ORDER_TYPE type,
                     const double price,const double stop_dist,
                     const double risk_pct)
  {
   double vol_min =SymbolInfoDouble(sym,SYMBOL_VOLUME_MIN);
   double vol_max =SymbolInfoDouble(sym,SYMBOL_VOLUME_MAX);
   double vol_step=SymbolInfoDouble(sym,SYMBOL_VOLUME_STEP);
   double vol_lim =SymbolInfoDouble(sym,SYMBOL_VOLUME_LIMIT);
   double tick_sz =SymbolInfoDouble(sym,SYMBOL_TRADE_TICK_SIZE);
   double tick_val=SymbolInfoDouble(sym,SYMBOL_TRADE_TICK_VALUE);
   if(vol_step<=0.0 || tick_sz<=0.0 || tick_val<=0.0 || stop_dist<=0.0)
      return(0.0);
   //--- volume from the risk budget
   double risk_cash=AccountInfoDouble(ACCOUNT_EQUITY)*risk_pct/100.0;
   double loss_lot =stop_dist/tick_sz*tick_val;
   if(loss_lot<=0.0)
      return(0.0);
   double lot=risk_cash/loss_lot;
   //--- symbol volume caps
   lot=MathMin(lot,vol_max);
   if(vol_lim>0.0)
      lot=MathMin(lot,vol_lim);
   if(lot<=0.0)
      return(0.0);
   //--- margin clamp
   double margin=0.0;
   if(!OrderCalcMargin(type,sym,lot,price,margin))
      return(0.0);
   double free_margin=AccountInfoDouble(ACCOUNT_MARGIN_FREE)*RT_MARGIN_USE;
   if(margin>free_margin && margin>0.0)
      lot*=free_margin/margin;
   //--- snap down to the step, skip below the minimum
   lot=MathFloor(lot/vol_step+1e-9)*vol_step;
   lot=NormalizeDouble(lot,RtVolumeDigits(vol_step));
   if(lot<vol_min)
      return(0.0);
   return(lot);
  }

RtEnsureFilesFolder / RtIsNewBar

//+------------------------------------------------------------------+
//| RtEnsureFilesFolder: make the subfolder before any FileOpen      |
//+------------------------------------------------------------------+
void RtEnsureFilesFolder(const string folder)
  {
   FolderCreate(folder);
  }

//+------------------------------------------------------------------+
//| RtIsNewBar: true once per new bar of the given series            |
//+------------------------------------------------------------------+
bool RtIsNewBar(const string sym,const ENUM_TIMEFRAMES tf,datetime &last)
  {
   datetime t=iTime(sym,tf,0);
   if(t==0 || t==last)
      return(false);
   last=t;
   return(true);
  }


Watching the statistic on the chart

RunsTest_ZView plots the same rolling z-score the Expert Advisor trades off, in a sub-window with two horizontal levels at plus and minus the critical value. It only processes closed bars — the forming bar is always left empty — and on a history reload it resets the engine and replays from the start rather than trusting a partial state.

OnInit

//+------------------------------------------------------------------+
//| OnInit                                                           |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(!g_runs.Init(InpWindow,InpContinuity))
     {
      PrintFormat("Runs window must be at least %d bars",RT_MIN_WINDOW);
      return(INIT_PARAMETERS_INCORRECT);
     }
   SetIndexBuffer(0,g_buf,INDICATOR_DATA);
   ArraySetAsSeries(g_buf,false);
   PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,EMPTY_VALUE);
   IndicatorSetInteger(INDICATOR_LEVELS,2);
   IndicatorSetDouble(INDICATOR_LEVELVALUE,0,InpZCrit);
   IndicatorSetDouble(INDICATOR_LEVELVALUE,1,-InpZCrit);
   IndicatorSetString(INDICATOR_SHORTNAME,
                      StringFormat("Runs Z(%d)",InpWindow));
   return(INIT_SUCCEEDED);

OnCalculate

//+------------------------------------------------------------------+
//| OnCalculate                                                      |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
   if(rates_total<InpWindow+2)
      return(0);
   //--- force oldest-first ordering: the loop below assumes index 0 is the
   //--- earliest bar and rates_total-1 is the current/forming bar, which is
   //--- the opposite of OnCalculate's documented series-array default
   ArraySetAsSeries(close,false);
   if(prev_calculated==0)
     {
      g_runs.Reset();
      g_next=1;
      ArrayInitialize(g_buf,EMPTY_VALUE);
     }
   //--- closed bars only, the forming bar stays empty
   int last=rates_total-2;
   for(int i=g_next;i<=last;i++)
     {
      double d   =close[i]-close[i-1];
      int    sign=0;
      if(d>_Point*0.5)
         sign=1;
      if(d<-_Point*0.5)
         sign=-1;
      g_runs.Push(sign);
      g_buf[i]=g_runs.IsReady() ? g_runs.Z() : EMPTY_VALUE;
     }


Proving the engine is right

RunsTest_Validate checks the rolling engine two ways. First, five fixed plus/minus sequences — alternating, blocked, and three mixed patterns — get scanned two ways: once with the independent RtScanSigns() function, once by pushing every sign through a fresh CRunsTest and reading its counters back. Second, a 5,000-step pseudo-random sequence gets pushed through a 100-bar rolling engine, and at every step past the warm-up the engine's n1, n2, and run count are checked against an independent rescan of that exact window.

ToSigns: '+' and '-' string to a +1/-1 array

//+------------------------------------------------------------------+
//| ToSigns: '+' and '-' string to a +1/-1 array                     |
//+------------------------------------------------------------------+
int ToSigns(const string seq,char &out[])
  {
   int n=StringLen(seq);
   ArrayResize(out,n);
   for(int i=0;i<n;i++)
      out[i]=(StringGetCharacter(seq,i)=='+') ? 1 : -1;
   return(n);
  }

OnStart

//+------------------------------------------------------------------+
//| OnStart                                                          |
//+------------------------------------------------------------------+
void OnStart()
  {
   int h=INVALID_HANDLE;
   if(InpWriteCsv)
     {
      RtEnsureFilesFolder("RunsTest");
      h=FileOpen("RunsTest\\validation_mql5.csv",FILE_WRITE|FILE_CSV|FILE_ANSI,',');
      if(h==INVALID_HANDLE)
         PrintFormat("csv open failed, error %d",GetLastError());
      else
         FileWrite(h,"name","n1","n2","runs","z","z_cc","p","p_cc");
     }
   //--- fixed vectors: incremental engine against a full scan
   for(int k=0;k<ArraySize(g_names);k++)
     {
      char s[];
      int  len=ToSigns(g_seqs[k],s);
      int  n1=0;
      int  n2=0;
      int  runs=0;
      RtScanSigns(s,0,len,n1,n2,runs);
      CRunsTest eng;
      eng.Init(MathMax(len,RT_MIN_WINDOW),false);
      for(int i=0;i<len;i++)
         eng.Push(s[i]);
      bool   same=(eng.N1()==n1 && eng.N2()==n2 && eng.Runs()==runs);
      double z   =RtZFromCounts(n1,n2,runs,false);
      double zc  =RtZFromCounts(n1,n2,runs,true);
      double p   =RtPFromZ(z);
      double pc  =RtPFromZ(zc);
      PrintFormat("%s: n1=%d n2=%d runs=%d z=%.6f z_cc=%.6f p=%.6f engine_match=%s",
                  g_names[k],n1,n2,runs,z,zc,p,same ? "yes" : "NO");
      if(h!=INVALID_HANDLE)
         FileWrite(h,g_names[k],n1,n2,runs,DoubleToString(z,10),
                   DoubleToString(zc,10),DoubleToString(p,10),
                   DoubleToString(pc,10));
     }
   if(h!=INVALID_HANDLE)
      FileClose(h);
   //--- eviction check: rolling window against a rescan at every step
   const int total=5000;
   const int win  =100;
   char      seq[];
   uint      state=20260929;
   ArrayResize(seq,total);
   for(int i=0;i<total;i++)
      seq[i]=((RtNextRand(state)>>16)%2==1) ? 1 : -1;
   CRunsTest roll;
   roll.Init(win,false);
   int checked=0;
   int bad    =0;
   for(int i=0;i<total;i++)
     {
      roll.Push(seq[i]);
      if(i<win-1)
         continue;
      int a=0;
      int b=0;
      int c=0;
      RtScanSigns(seq,i-win+1,win,a,b,c);
      checked++;
      if(roll.N1()!=a || roll.N2()!=b || roll.Runs()!=c)
         bad++;
     }
   PrintFormat("eviction check: %d steps, %d mismatches",checked,bad);
  }

Both checks come back clean on every run: all five fixed vectors report engine_match=yes, and the 5,000-step eviction check reports zero mismatches between the rolling engine and a from-scratch rescan at every one of the 4,901 windows it checked past the warm-up. That is the baseline everything else in this article stands on — if the counters the engine reports were wrong, the regime labels and the backtest numbers built on top of them would be meaningless.

The eviction check is the more important of the two, because it exercises the exact code path the live engine uses — dropping the oldest sign, updating three running counters, never rescanning. A fixed-vector check alone could pass while a subtle bug in the window-eviction logic still corrupted every count after the buffer first fills. Running both, over enough steps to see the buffer wrap around many times, is what makes the O(1) design trustworthy rather than just fast.


Is bar direction actually non-random?

Before trusting a regime label in a backtest, it is worth asking a calibration question: at a 1.96 critical value, the test is nominally supposed to reject randomness on about 5% of ready windows. RunsTest_NullRate measures what it actually does on real EURUSD, GBPUSD, and XAUUSD history, on H1 and M15, over 20,000 closed bars each, and compares that against the same test run on a seeded shuffle of the identical signs — a baseline conditioned on the real run's own count of up-bars versus down-bars, not an independent coin-flip null, since the shuffle only reorders the signs that were already there.

LoadCloses: closed bars, oldest first, retry while history loads

//+------------------------------------------------------------------+
//| LoadCloses: closed bars, oldest first, retry while history loads |
//+------------------------------------------------------------------+
int LoadCloses(const string sym,const ENUM_TIMEFRAMES tf,const int bars,
               double &close[])
  {
   ArraySetAsSeries(close,false);
   for(int attempt=0;attempt<5;attempt++)
     {
      int got=CopyClose(sym,tf,1,bars,close);
      if(got>0)
         return(got);
      Sleep(500);
     }
   return(0);
  }

SlideRates: share of ready windows in each rejecting regime

//+------------------------------------------------------------------+
//| SlideRates: share of ready windows in each rejecting regime      |
//+------------------------------------------------------------------+
void SlideRates(const char &signs[],const int n,double &trend_frac,
                double &revert_frac,long &ready)
  {
   CRunsTest eng;
   eng.Init(InpWindow,InpContinuity);
   long trend =0;
   long revert=0;
   ready=0;
   for(int i=0;i<n;i++)
     {
      eng.Push(signs[i]);
      if(!eng.IsReady())
         continue;
      ready++;
      int r=eng.Regime(InpZCrit);
      if(r==RT_REGIME_TREND)
         trend++;
      if(r==RT_REGIME_REVERT)
         revert++;
     }
   trend_frac =(ready>0) ? (double)trend/(double)ready : 0.0;
   revert_frac=(ready>0) ? (double)revert/(double)ready : 0.0;
  }

OnStart

//+------------------------------------------------------------------+
//| OnStart                                                          |
//+------------------------------------------------------------------+
void OnStart()
  {
   string syms[];
   int    ns=StringSplit(InpSymbols,',',syms);
   if(ns<=0)
     {
      Print("no symbols given");
      return;
     }
   ENUM_TIMEFRAMES tfs[2]={PERIOD_H1,PERIOD_M15};
   RtEnsureFilesFolder("RunsTest");
   int h=FileOpen("RunsTest\\nullrate.csv",FILE_WRITE|FILE_CSV|FILE_ANSI,',');
   if(h==INVALID_HANDLE)
      PrintFormat("csv open failed, error %d",GetLastError());
   else
      FileWrite(h,"symbol","timeframe","signs","windows","trend","revert",
                "reject","shuffled_reject","nominal");
   double nominal=RtPFromZ(InpZCrit);
   for(int i=0;i<ns;i++)
     {
      string sym=syms[i];
      StringTrimLeft(sym);
      StringTrimRight(sym);
      if(!SymbolSelect(sym,true))
        {
         PrintFormat("%s: not available, skipped",sym);
         continue;
        }
      double point=SymbolInfoDouble(sym,SYMBOL_POINT);
      for(int t=0;t<2;t++)
        {
         double close[];
         int    got=LoadCloses(sym,tfs[t],InpBars,close);
         if(got<InpWindow+2)
           {
            PrintFormat("%s %s: no history, skipped",sym,EnumToString(tfs[t]));
            continue;
           }
         //--- direction series, ties dropped
         char signs[];
         ArrayResize(signs,got);
         int m=0;
         for(int j=1;j<got;j++)
           {
            double d=close[j]-close[j-1];
            if(d>point*0.5)
               signs[m++]=1;
            if(d<-point*0.5)
               signs[m++]=-1;
           }
         //--- real series and its seeded shuffle
         double tr=0.0;
         double rv=0.0;
         long   ready=0;
         SlideRates(signs,m,tr,rv,ready);
         char shuf[];
         ArrayCopy(shuf,signs,0,0,m);
         RtShuffleSigns(shuf,m,InpSeed);
         double str=0.0;
         double srv=0.0;
         long   sready=0;
         SlideRates(shuf,m,str,srv,sready);
         PrintFormat("%s %s: signs=%d reject=%.4f (trend %.4f revert %.4f) shuffled=%.4f nominal=%.4f",
                     sym,EnumToString(tfs[t]),m,tr+rv,tr,rv,str+srv,nominal);
         if(h!=INVALID_HANDLE)
            FileWrite(h,sym,EnumToString(tfs[t]),m,ready,
                      DoubleToString(tr,6),DoubleToString(rv,6),
                      DoubleToString(tr+rv,6),DoubleToString(str+srv,6),
                      DoubleToString(nominal,6));
        }
     }
   if(h!=INVALID_HANDLE)
      FileClose(h);
  }

Every one of the six series rejects randomness less often than the nominal 5%, and in a tight band: 2.04% on EURUSD H1 up to 3.48% on XAUUSD M15. Real market data isn't a null model, so this is an observed reject rate on actual price history, not a direct measurement of the test's false-alarm rate — the continuity correction at a 100-slot window is conservative, which would itself tend to pull any true false-alarm rate down from 5%, but some or all of this gap could just as easily reflect genuine structure in bar direction rather than test conservatism.

Either reading leaves the same practical takeaway: fewer windows clear the critical value on real data than the nominal rate implies, which is worth keeping in mind before reading too much into any single flagged window. The split between the two flavors of non-random window is lopsided toward alternation rather than persistence on every series checked, which already says something about what kind of signal this test is picking up before a single trade gets placed.

That lean toward alternation is the reason PickDirection() fades the last bar on a reversion regime rather than simply following every flagged window the same way. A gate built only to follow momentum would be fighting the base rate the null-rate script measures directly: on every series tested, more windows clear the critical value by alternating too often than by persisting too long, sometimes by a wide margin. Treating both flavors the same way, or gating only on one of them, would throw away information the calibration run already paid for.

Fig. 1. Real reject rate (trend-flagged plus revert-flagged windows, as a share of all ready windows) against the nominal 5% critical level, by symbol and timeframe.


Entry and exit mechanics

The Expert Advisor only acts on a new closed bar — RtIsNewBar() gates everything in OnTick(). BarSign() reads the direction of the last closed bar off two iClose() calls. PrefillWindow() seeds the ring buffer from history on startup so the window does not have to warm up live. It actually pushes InpWindow+30 bars of history, not just InpWindow, since the ring only ever keeps the most recent InpWindow signs regardless of how many go in. The extra 30 bars are a margin against the window ever reporting ready on anything thinner than a full load. HasPosition() and CloseIfExpired() enforce one position at a time per magic number, with a hard time stop at InpMaxHoldBars.

PickDirection() is where the three modes actually diverge: Gated follows the last bar's sign only on a persistent regime and fades it only on an alternating one, No gate always follows the last bar regardless of the regime label, and Placebo routes through PickDirection() exactly like Gated but with a regime label drawn from CRegimePlacebo instead of the live one.

BarSign: direction of a closed bar versus the one before it

//+------------------------------------------------------------------+
//| BarSign: direction of a closed bar versus the one before it      |
//+------------------------------------------------------------------+
int BarSign(const int shift)
  {
   double c0=iClose(_Symbol,_Period,shift);
   double c1=iClose(_Symbol,_Period,shift+1);
   if(c0<=0.0 || c1<=0.0)
      return(0);
   double d=c0-c1;
   if(d>_Point*0.5)
      return(1);
   if(d<-_Point*0.5)
      return(-1);
   return(0);
  }

PrefillWindow: seed the window from closed history

//+------------------------------------------------------------------+
//| PrefillWindow: seed the window from closed history               |
//+------------------------------------------------------------------+
bool PrefillWindow(void)
  {
   int need=InpWindow+30;
   if(Bars(_Symbol,_Period)<need+2)
      return(false);
   for(int i=need;i>=1;i--)
      g_runs.Push(BarSign(i));
   return(true);
  }

HasPosition: open position of this EA on this symbol

//+------------------------------------------------------------------+
//| HasPosition: open position of this EA on this symbol             |
//+------------------------------------------------------------------+
bool HasPosition(void)
  {
   for(int i=PositionsTotal()-1;i>=0;i--)
     {
      ulong ticket=PositionGetTicket(i);
      if(ticket==0)
         continue;
      if(PositionGetString(POSITION_SYMBOL)!=_Symbol)
         continue;
      if((ulong)PositionGetInteger(POSITION_MAGIC)!=InpMagic)
         continue;
      return(true);
     }
   return(false);
  }

CloseIfExpired: time stop on the open position

//+------------------------------------------------------------------+
//| CloseIfExpired: time stop on the open position                   |
//+------------------------------------------------------------------+
bool CloseIfExpired(void)
  {
   for(int i=PositionsTotal()-1;i>=0;i--)
     {
      ulong ticket=PositionGetTicket(i);
      if(ticket==0)
         continue;
      if(PositionGetString(POSITION_SYMBOL)!=_Symbol)
         continue;
      if((ulong)PositionGetInteger(POSITION_MAGIC)!=InpMagic)
         continue;
      datetime opened=(datetime)PositionGetInteger(POSITION_TIME);
      int      held  =iBarShift(_Symbol,_Period,opened,false);
      if(held>=InpMaxHoldBars)
         return(g_trade.PositionClose(ticket));
     }
   return(false);
  }

PickDirection: trade side from the regime and the last bar

//+------------------------------------------------------------------+
//| PickDirection: trade side from the regime and the last bar       |
//+------------------------------------------------------------------+
int PickDirection(const int sign,const int regime)
  {
   if(sign==0)
      return(0);
   if(InpMode==RT_MODE_ALWAYS_TREND)
      return(sign);
   if(regime==RT_REGIME_TREND)
      return(sign);
   if(regime==RT_REGIME_REVERT)
      return(-sign);
   return(0);
  }


Sizing and sending the order

OpenTrade() turns a direction into an order. The stop and target distances are the larger of an ATR multiple and RtMinStopDistance(), so a quiet-ATR period never produces a stop the broker would reject. The lot size comes from RtCalcSafeLot() against that exact stop distance — a zero result is treated as a clean skip, not a smaller forced trade, and shows up in the audit log as order_skipped rather than order_sent.

The deviation is fixed at 20 points and filling mode is left to SetTypeFillingBySymbol(), which asks the broker what it actually supports rather than hardcoding a fill policy that might get rejected on a symbol with different execution rules. ResultRetcode() gets printed on any failed send, so a rejected order shows up in the Journal with the broker's own reason rather than failing silently.

OpenTrade: ATR stops, floor check, sized entry

//+------------------------------------------------------------------+
//| OpenTrade: ATR stops, floor check, sized entry                   |
//+------------------------------------------------------------------+
bool OpenTrade(const int dir)
  {
   double atr[];
   if(CopyBuffer(g_atr_handle,0,1,1,atr)!=1 || atr[0]<=0.0)
      return(false);
   //--- stop distances, never inside the broker floor
   double min_dist=RtMinStopDistance(_Symbol);
   double sl_dist =MathMax(InpSlAtr*atr[0],min_dist);
   double tp_dist =MathMax(InpTpAtr*atr[0],min_dist);
   ENUM_ORDER_TYPE type=(dir>0) ? ORDER_TYPE_BUY : ORDER_TYPE_SELL;
   double price=(dir>0) ? SymbolInfoDouble(_Symbol,SYMBOL_ASK)
                : SymbolInfoDouble(_Symbol,SYMBOL_BID);
   double sl=NormalizeDouble((dir>0) ? price-sl_dist : price+sl_dist,_Digits);
   double tp=NormalizeDouble((dir>0) ? price+tp_dist : price-tp_dist,_Digits);
   //--- size after the floor, skip if the lot rounds below minimum
   double lot=RtCalcSafeLot(_Symbol,type,price,sl_dist,InpRiskPct);
   if(lot<=0.0)
      return(false);
   bool ok=(dir>0) ? g_trade.Buy(lot,_Symbol,price,sl,tp,"RunsTest")
           : g_trade.Sell(lot,_Symbol,price,sl,tp,"RunsTest");
   if(!ok)
      PrintFormat("order failed, retcode %u",g_trade.ResultRetcode());
   return(ok);
  }


The audit trail

Every closed bar writes one row to a per-magic-number CSV: the bar's sign, the window's n1/n2/run counts, z and p, the real regime, the regime actually used to trade, and what happened — warmup, flat, hold, order_sent, or order_skipped. That log is what makes the backtest section below checkable rather than a trust exercise: regime_used can be compared against regime_real row by row, and order_sent rows can be counted against the Strategy Tester's own trade total.

OpenAuditLog: per-magic CSV, header on open

//+------------------------------------------------------------------+
//| OpenAuditLog: per-magic CSV, header on open                      |
//+------------------------------------------------------------------+
void OpenAuditLog(void)
  {
   RtEnsureFilesFolder("RunsTest");
   string name=StringFormat("RunsTest\\audit_%I64u.csv",InpMagic);
   g_audit_handle=FileOpen(name,FILE_WRITE|FILE_CSV|FILE_ANSI,',');
   if(g_audit_handle==INVALID_HANDLE)
     {
      PrintFormat("audit log open failed, error %d",GetLastError());
      return;
     }
   FileWrite(g_audit_handle,"time","sign","n1","n2","runs","z","p",
             "regime_real","regime_used","action");
  }

WriteAuditRow: one row per closed bar

//+------------------------------------------------------------------+
//| WriteAuditRow: one row per closed bar                            |
//+------------------------------------------------------------------+
void WriteAuditRow(const int sign,const int regime_real,
                   const int regime_used,const string action)
  {
   if(g_audit_handle==INVALID_HANDLE)
      return;
   string stamp=TimeToString(iTime(_Symbol,_Period,1),TIME_DATE|TIME_MINUTES);
   FileWrite(g_audit_handle,stamp,sign,g_runs.N1(),g_runs.N2(),g_runs.Runs(),
             DoubleToString(g_runs.Z(),4),DoubleToString(g_runs.PValue(),6),
             regime_real,regime_used,action);
   g_rows_since_flush++;
   if(g_rows_since_flush>=200)
     {
      FileFlush(g_audit_handle);
      g_rows_since_flush=0;
     }
  }


Wiring the Expert Advisor together

OnInit() validates the Inputs tab, builds the runs engine and the placebo ring buffer, opens the ATR handle, prefills the window, and opens the audit log. OnDeinit() closes the log handle and releases the indicator handle. OnTick() is the whole per-bar loop: push the new sign, read the regime, resolve regime_used for the active mode, record the real regime into the placebo history, enforce the time stop, decide a direction if flat, and log the result.

OnInit

//+------------------------------------------------------------------+
//| OnInit                                                           |
//+------------------------------------------------------------------+
int OnInit()
  {
   if(InpZCrit<=0.0 || InpRiskPct<=0.0 || InpAtrPeriod<1 || InpMaxHoldBars<1)
     {
      Print("invalid inputs");
      return(INIT_PARAMETERS_INCORRECT);
     }
   if(!g_runs.Init(InpWindow,InpContinuity))
     {
      PrintFormat("Runs window must be at least %d bars",RT_MIN_WINDOW);
      return(INIT_PARAMETERS_INCORRECT);
     }
   if(!g_placebo.Init(InpPlaceboDepth,InpPlaceboSeed))
     {
      Print("Placebo history depth too small");
      return(INIT_PARAMETERS_INCORRECT);
     }
   g_atr_handle=iATR(_Symbol,_Period,InpAtrPeriod);
   if(g_atr_handle==INVALID_HANDLE)
     {
      PrintFormat("iATR failed, error %d",GetLastError());
      return(INIT_FAILED);
     }
   g_trade.SetExpertMagicNumber(InpMagic);
   g_trade.SetDeviationInPoints(20);
   g_trade.SetTypeFillingBySymbol(_Symbol);
   //--- warm the window, then wait for the next bar
   if(!PrefillWindow())
      Print("history short, window warms on live bars");
   g_last_bar=iTime(_Symbol,_Period,0);
   OpenAuditLog();
   return(INIT_SUCCEEDED);
  }

OnDeinit

//+------------------------------------------------------------------+
//| OnDeinit                                                         |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   if(g_audit_handle!=INVALID_HANDLE)
     {
      FileClose(g_audit_handle);
      g_audit_handle=INVALID_HANDLE;
     }
   if(g_atr_handle!=INVALID_HANDLE)
      IndicatorRelease(g_atr_handle);
  }

OnTick

//+------------------------------------------------------------------+
//| OnTick                                                           |
//+------------------------------------------------------------------+
void OnTick()
  {
   if(!RtIsNewBar(_Symbol,_Period,g_last_bar))
      return;
   //--- fold the bar that just closed into the window
   int  sign       =BarSign(1);
   g_runs.Push(sign);
   bool ready      =g_runs.IsReady();
   int  regime_real=g_runs.Regime(InpZCrit);
   int  regime_used=regime_real;
   if(InpMode==RT_MODE_PLACEBO)
      regime_used=g_placebo.Draw();
   g_placebo.Record(regime_real);
   if(ready)
     {
      g_regime_count[regime_real]++;
      g_bars_seen++;
     }
   //--- one position at a time, time stop first
   bool   open  =HasPosition();
   string action="none";
   if(open && CloseIfExpired())
      open=false;
   if(open)
      action="hold";
   //--- entry on the new bar
   if(!open)
     {
      int dir=ready ? PickDirection(sign,regime_used) : 0;
      if(dir!=0)
         action=OpenTrade(dir) ? "order_sent" : "order_skipped";
      else
         action=ready ? "flat" : "warmup";
     }
   WriteAuditRow(sign,regime_real,regime_used,action);
  }


Scoring a run from inside the tester

OnTester() runs its own small runs test, not on bar direction but on the win/loss sequence of the Expert Advisor's own closed deals — a deal that nets to exactly zero is skipped, since it's neither a win nor a loss for the runs test. That catches a forced close that happens to net to zero, but it isn't a dedicated check for forced closes: a forced close with any non-zero profit or loss is scored like any other deal in the sequence. It prints that sequence test and the regime share the run actually traded through straight to the Journal, then returns the profit factor so the Strategy Tester's own optimizer column has something to sort on.

OnTester

//+------------------------------------------------------------------+
//| OnTester                                                         |
//+------------------------------------------------------------------+
double OnTester()
  {
   //--- runs test on the win/loss sequence of the closed trades
   CRunsTest seq;
   if(!HistorySelect(0,D'2100.01.01'))
      return(0.0);
   int total=HistoryDealsTotal();
   seq.Init(MathMax(RT_MIN_WINDOW,total+1),InpContinuity);
   for(int i=0;i<total;i++)
     {
      ulong ticket=HistoryDealGetTicket(i);
      if(ticket==0)
         continue;
      if(HistoryDealGetInteger(ticket,DEAL_ENTRY)!=DEAL_ENTRY_OUT)
         continue;
      if((ulong)HistoryDealGetInteger(ticket,DEAL_MAGIC)!=InpMagic)
         continue;
      double pnl=HistoryDealGetDouble(ticket,DEAL_PROFIT)
                 +HistoryDealGetDouble(ticket,DEAL_SWAP)
                 +HistoryDealGetDouble(ticket,DEAL_COMMISSION);
      if(pnl>0.0)
         seq.Push(1);
      else
         if(pnl<0.0)
            seq.Push(-1);
     }
   PrintFormat("trade sequence: wins=%d losses=%d runs=%d z=%.3f p=%.4f",
               seq.N1(),seq.N2(),seq.Runs(),seq.Z(),seq.PValue());
   //--- how often the window rejected randomness on this run
   if(g_bars_seen>0)
     {
      double n=(double)g_bars_seen;
      double trend =(double)g_regime_count[RT_REGIME_TREND]/n;
      double revert=(double)g_regime_count[RT_REGIME_REVERT]/n;
      PrintFormat("regime share: trend=%.4f revert=%.4f reject=%.4f nominal=%.4f bars=%I64d",
                  trend,revert,trend+revert,RtPFromZ(InpZCrit),g_bars_seen);
     }
   return(TesterStatistics(STAT_PROFIT_FACTOR));
  }


Testing the matrix

Every run used real ticks, January 1 to September 1, 2026, a 10,000 USD deposit, 1:100 leverage, with "profit in pips" unticked so every result below is real account currency. Three symbols — EURUSD, GBPUSD, XAUUSD — crossed with two timeframes — H1, M15 — crossed with three modes — Gated, No gate, Placebo — gives eighteen runs. InpWindow stayed fixed at 100 and the critical value at 1.96 across the whole matrix, so no run benefits from a parameter picked after seeing its own result. IsReady() starts scoring once RT_MIN_WINDOW (30) non-zero-sign bars have accumulated, not only once the full 100-slot ring is filled, so the earliest classifications in any run come from a smaller-than-100 window until the buffer fills — the 100 figure is the window's fixed capacity, not a floor every reading is taken at.

No gate is the control for whether the gate adds anything over just following the last closed bar on every window. Placebo is the control for whether the regime label itself carries information, by trading the identical PickDirection() logic against a regime drawn from accumulated history instead of the current window. Comparing all three against each other, on the same symbol and timeframe, is the actual test.

InpPlaceboDepth of 500 bars and InpPlaceboSeed of 12345 keep the fake regime label drawn from a pool of real labels recorded over roughly the last three weeks of H1 bars or about a week of M15 bars, so Placebo trades on a label that was genuinely observed somewhere nearby in time, rather than a fixed, always-correct one — a tougher, more honest null than drawing from pure noise would be. Every run's trade count differs from every other run's, since the number of windows that clear the critical value is itself a property of each specific symbol and timeframe, not a fixed quantity, so profit factor and win rate are read across modes rather than raw trade or net-profit totals.

Reproducing the numbers below needs more than the window and critical value — the two tables give every tester/account setting and every Input actually used.

Setting
Value
Terminal/tester build
6249
Account/quote source
MetaQuotes Ltd. demo account
Deposit currency
USD
Initial deposit
10,000.00
Leverage
1:100
Modelling mode
Every tick, based on real ticks
History quality
100% real ticks (EURUSD, GBPUSD, all modes); XAUUSD 99% on the Gated and No gate runs, 100% on the Placebo runs after a broker-side history backfill between the two rounds — a history property, not a tester setting
Spread
Real historical bid/ask from the real-tick feed, no fixed override
Commission
$0.00 on every recorded deal across all 18 runs
Swap
Genuine and nonzero past rollover; folded into every net-profit figure below
Order filling
SetTypeFillingBySymbol(), not hardcoded
Slippage/deviation
Fixed at 20 points on every order, every run
XAUUSD symbol spec
2 price digits, a point of 0.01 (e.g. 4319.16); contract size 100 oz; tick size 0.01, tick value 0.1 USD; volume min/max/step 0.01 / 100 / 0.01 lots
Program
Input (Inputs-tab name)
Value used in all 18 runs
RunsTest_Gate_EA
Runs window (bars)
100
RunsTest_Gate_EA
Z critical (two-sided)
1.96
RunsTest_Gate_EA
Continuity correction
true
RunsTest_Gate_EA
Mode
Gated/No gate/Placebo (one per run)
RunsTest_Gate_EA
ATR period
14
RunsTest_Gate_EA
Stop loss (ATR multiple)
1.5
RunsTest_Gate_EA
Take profit (ATR multiple)
2.0
RunsTest_Gate_EA
Max holding time (bars)
6
RunsTest_Gate_EA
Risk per trade (% of equity)
1.0
RunsTest_Gate_EA
Magic number
260929
RunsTest_Gate_EA
Placebo RNG seed
12345
RunsTest_Gate_EA
Placebo history depth (bars)
500
RunsTest_ZView (indicator)
Runs window (bars)
100
RunsTest_ZView (indicator)
Z critical (two-sided)
1.96
RunsTest_ZView (indicator)
Continuity correction
true

Every value above is read straight off the 18 report files or the source code.


Calibration and validation results

The validation script's two checks both came back clean, as described above: an exact match between the rolling engine and an independent scan on five fixed vectors, and zero mismatches across 4,901 rolling windows in the eviction check. The null-rate script found a real reject rate of 2.04% to 3.48% against a nominal 5%, on every series tested, with the alternating flavor outweighing the persistent one on every series. Both of these hold regardless of which mode the Expert Advisor later traded in, since they are properties of the bar-direction sequence itself, not of the trading logic layered on top of it.


Backtest results across the matrix

Every row below comes from a Strategy Tester report, verified against its own audit log: order_sent rows match the report's trade count on every run, and in Gated and Placebo runs regime_used matches regime_real on every row that is not Placebo by design. Gated trades 510 times in total across the six symbol-timeframe pairs for a combined net of -321.64 USD. No gate trades 11,114 times for a combined net of -46,921.21 USD, with four of its six runs landing an equity drawdown above 97%. Placebo trades 1,398 times for a combined net of -22,826.33 USD.

#
Symbol
Timeframe
Mode
Trades
Net profit, USD
Profit factor
Equity drawdown
1
EURUSD
H1
Gated
24
-228.24
0.79
5.05%
2
EURUSD
M15
Gated
131
-1414.93
0.76
17.44%
3
GBPUSD
H1
Gated
33
-510.67
0.70
11.34%
4
GBPUSD
M15
Gated
145
-778.06
0.87
14.62%
5
XAUUSD
H1
Gated
34
-1716.19
0.85
53.36%
6
XAUUSD
M15
Gated
143
4326.45
1.06
55.38%
7
EURUSD
H1
No gate
935
-2830.48
0.92
39.24%
8
EURUSD
M15
No gate
3712
-9658.57
0.85
97.24%
9
GBPUSD
H1
No gate
950
-4698.00
0.84
53.04%
10
GBPUSD
M15
No gate
3510
-9937.15
0.72
99.45%
11
XAUUSD
H1
No gate
503
-9845.91
0.89
99.12%
12
XAUUSD
M15
No gate
1504
-9951.10
0.95
99.81%
13
EURUSD
H1
Placebo
61
-3.97
1.00
9.65%
14
EURUSD
M15
Placebo
321
-1689.73
0.85
21.53%
15
GBPUSD
H1
Placebo
104
345.89
1.09
9.37%
16
GBPUSD
M15
Placebo
407
-5071.30
0.62
51.72%
17
XAUUSD
H1
Placebo
91
-6961.18
0.75
84.52%
18
XAUUSD
M15
Placebo
414
-9446.04
0.86
96.00%

Reading net profit alone is misleading once trade counts differ by two orders of magnitude between modes — a mode that trades a few dozen times naturally has far less room to compound a cost per trade into a large loss than one that trades thousands of times. The cleaner comparison is profit factor, symbol and timeframe held fixed.

Fig. 2. Profit factor by mode, grouped by symbol and timeframe. The dashed line marks breakeven at 1.0.

Gated beats Placebo on profit factor in three of the six pairs, and Placebo beats Gated in the other three — an even split, on the exact same symbol, timeframe, window, and critical value. If the live regime label carried real information that a random past label did not, this comparison is where it would show up as a consistent edge, and it does not. What the gate reliably does instead is cut risk: it trades roughly 3% of available bars, and its drawdowns stay far below either control's on every pair.

Fig. 3. Equity drawdown by mode, Gated against No gate, by symbol and timeframe.


What the numbers actually show

The strongest single Gated result, XAUUSD M15 at a profit factor of 1.06, is not evenly spread across its 143 trades. A single 48-bar episode on March 9 produced 9 trades and netted 6857.52 USD on its own, which is more than the entire run's net profit. Strip that one cluster out and the remaining 134 trades net roughly -2531 USD, in line with every other Gated run in the matrix. Flagged bars cluster into episodes rather than scattering evenly through the series, so a handful of trades inside one episode can carry or sink an entire run's reported result — a pattern worth watching in the equity curve directly.

Fig. 4. Account balance after each closed trade, XAUUSD M15, Gated mode. One mid-series cluster accounts for more than the run's total net profit.

Two gold runs are worth flagging on their own. In both the No gate and Placebo XAUUSD tests, the account's equity fell far enough that RtCalcSafeLot() started returning zero on most remaining bars — the risk-floor skip working exactly as designed rather than failing silently. The XAUUSD M15 No gate run went 7,092 bars, roughly the back third of the test, without a single order_sent row once that floor was hit. That is a real property of trading a volatile, wide-stop instrument at a fixed percentage risk with no equity curve control, and it belongs in this article rather than hidden in a footnote.

Most runs in this matrix land close to the breakeven win rate implied by their own average win and average loss, not far below it. XAUUSD H1 Gated, for example, closed 34 trades at a 41.2% win rate against an average win of 689.81 and an average loss of 568.67 — solving average_loss / (average_win + average_loss) puts the breakeven win rate at 45.2%, so the observed result sits well under half a standard error short of breakeven on a sample that small. None of the eighteen runs show a win rate convincingly clear of its own breakeven line once sample size is accounted for, which is consistent with a cost-of-trading story more than a broken-edge one.

Put together: the engine is exact, the calibration is honest and slightly conservative, and bar direction leans alternating rather than persistent across every series tested. The trading layer built on top of that label does not show a repeatable edge against either control once the comparison is made fairly, symbol and timeframe held fixed. What it does show is a real reduction in exposure, since trading on roughly 3% of bars caps how much compounding risk a losing streak can do to the account. That is a legitimate use for a regime filter even without a demonstrated directional edge, and it is the honest conclusion this backtest supports.


Conclusion

A Wald–Wolfowitz runs test on bar direction is cheap to compute, easy to validate exactly, and genuinely tells you something about a price series: across six symbol and timeframe combinations, real bar direction rejects randomness less often than a 5% nominal test would suggest, and leans toward alternation rather than persistence when it does. Trading on that label did not produce a repeatable edge over a no-gate baseline or a placebo control with the same trade logic — three wins and three losses on profit factor, split evenly, with the best single result traceable to one trade cluster rather than a durable pattern. What it reliably delivered was a large cut in trade frequency and drawdown, which is worth having on its own even without an edge attached to it.

If you want to take this further, the most promising next step is not a different critical value or window length on the same gate — it is combining the regime label with an entry signal that has its own edge, and using the runs test purely as a position-sizing or exposure filter on top of it, the way it behaved here by accident. The engine, the placebo control, and the audit log are all built to make that comparison checkable the same way this one was.

Files

File
Description
RunsTest_Gate_EA.mq5
Expert Advisor, three-mode runs-test regime gate
RunsTestLib.mqh
Core runs-test engine, placebo control, risk helpers
RunsTest_ZView.mq5
Sub-window indicator, rolling Z on closed bars
RunsTest_Validate.mq5
Script, engine checked against fixed vectors and a full rescan
RunsTest_NullRate.mq5
Script, real vs shuffled rejection rate by symbol and timeframe
MQL5.zip
All source files above, in MQL5 CodeBase folder layout
Attached files |
MQL5.zip (11.5 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.
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.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
Neural Networks in Trading: Difference-Based Modeling of Market Microstructure (Conclusion) Neural Networks in Trading: Difference-Based Modeling of Market Microstructure (Conclusion)
The article provides a detailed analysis of the practical implementation of the EDCFlow framework's concepts using MQL5 and their validation using real historical data. It demonstrates how a neural network model forms an internal representation of the market environment, processes correlations among features, and makes trading decisions without hand-crafted rules. The test results reveal not only the approach's potential but also its weaknesses, honestly identifying its limitations and areas for further development.