preview
The Brunner-Munzel Test for MQL5: Comparing Trade Outcomes When the Variances Don't Agree

The Brunner-Munzel Test for MQL5: Comparing Trade Outcomes When the Variances Don't Agree

MetaTrader 5 — Statistics and analysis |
83 0
Adewumi Babatunde Gbadebo
Adewumi Babatunde Gbadebo

Contents

  1. Introduction
  2. Why Mann-Whitney struggles here
  3. The Brunner-Munzel test in code
  4. Comparison and verification of implementation
  5. Does the normal approximation hold under unequal variance?
  6. The regime-gated Expert Advisor
  7. Logging real trades and the shadow outcomes behind blocked signals
  8. The rolling indicator
  9. Strategy Tester results across twelve runs
  10. The one run where the gate actually fired
  11. Limitations
  12. Final thoughts


Introduction

Comparing trade outcomes between two volatility regimes — a high-ATR percentile and a low one — with the standard Mann-Whitney U test runs into a real problem: its normal approximation assumes both groups share the same variance, and a volatility-gated system's two regimes almost never do. Brunner and Munzel's 2000 generalized Wilcoxon test asks the same stochastic-comparison question without that assumption, using a Welch-Satterthwaite-style correction built from each sample's own placement variance. This article implements it from scratch in native MQL5, with no external libraries, and uses it as a live one-sided filter inside a Donchian breakout Expert Advisor, blocking a regime when it tests as stochastically worse than the other.

Bottom line, across a twelve-run Strategy Tester matrix (three symbols, two timeframes, gate on and off): the filter only fired on one of six symbol/timeframe configurations, and even there it did not demonstrate a proven improvement in profitability — exposure changed along with the block, so the two effects aren't cleanly separable. What follows is the test's math, its MQL5 implementation, the EA built around it, and exactly what that one case does and doesn't show.


Why Mann-Whitney struggles here

Mann-Whitney's U statistic is built from pooled ranks and a normal approximation whose variance formula assumes the two populations are exchangeable under the null beyond a location shift — equal variance is baked into the usual tie-corrected variance term. When the variances differ, that variance estimate is wrong, and how wrong depends on both the variance ratio and the relative sample sizes n1/n2. With the larger group also the more variable one, Mann-Whitney's actual rejection rate at a true null falls well below its nominal alpha in exactly this configuration, measured directly in the Monte Carlo study below. That is a type-I-error result, not a power result, and the two are not the same claim: under-rejecting when there is truly no difference is suggestive that the same test would also be slow to flag a real one, but this article does not simulate a genuine alternative to confirm that, so the power concern is read as a plausible consequence of the measured type-I behavior, not as something demonstrated on its own.

Brunner-Munzel replaces the shared variance with two separate placement variances, one per sample, each measuring how a sample's own values rank against the pooled sample relative to how they rank among themselves. The test statistic divides the difference in pooled rank means by a standard error built from both placement variances separately, and the degrees of freedom come from a Welch-Satterthwaite combination of the two — so a sample with more spread in its placements gets proportionally more say in the degrees of freedom, the same logic Welch's t-test applies to ordinary variances. The cost is a test that needs both samples to have at least two observations with some separation in their placements; when the two samples don't overlap at all, that denominator can collapse to zero, and that failure mode is handled explicitly in the code below rather than silently producing a nonsense statistic.


The Brunner-Munzel test in code

The library implements the test from scratch: log-gamma, the regularized incomplete beta function, a Student-t quantile computed by bisection, and the rank utilities the test itself needs, all native MQL5, no external libraries. The two result structures below carry a one-sided or two-sided alternative, matching the usual convention of stating a test's direction relative to sample1 versus sample2. What Brunner-Munzel actually tests is the relative effect, P(sample1 < sample2) + 0.5·P(tie), not full first-order stochastic dominance — BM_GREATER asks whether that relative effect sits below 0.5 (sample1 tends to rank higher, i.e. greater, than sample2), BM_LESS asks the mirror question (relative effect above 0.5, sample1 tending to rank lower). "Stochastically greater/less" shows up as shorthand later in this article the way it does in the Brunner-Munzel literature itself, but the quantity actually being compared throughout is this relative effect, and every call site in this project states its direction explicitly — there is no implicit default.

//+------------------------------------------------------------------+
//| ENUM_BM_ALTERNATIVE                                              |
//| Direction of the alternative hypothesis, always stated relative  |
//| to sample1 versus sample2                                        |
//+------------------------------------------------------------------+
enum ENUM_BM_ALTERNATIVE
  {
   BM_TWO_SIDED,  // sample1 and sample2 are not stochastically equal
   BM_GREATER,    // sample1 is stochastically greater than sample2
   BM_LESS        // sample1 is stochastically less than sample2
  };

//+------------------------------------------------------------------+
//| SBrunnerMunzelResult                                             |
//| Full output of BM_BrunnerMunzelTest: effect size, test statistic,|
//| degrees of freedom, p-value, confidence interval and failure flag|
//+------------------------------------------------------------------+
struct SBrunnerMunzelResult
  {
   double            p_hat;         // relative effect: P(sample1<sample2)+0.5*P(tie)
   double            w_stat;        // Brunner-Munzel W statistic
   double            df;            // Welch-Satterthwaite degrees of freedom
   double            p_value;       // p-value for the chosen alternative
   double            ci_lower;      // confidence interval lower bound for p_hat
   double            ci_upper;      // confidence interval upper bound for p_hat
   double            s1_placement;  // placement variance, sample1
   double            s2_placement;  // placement variance, sample2
   int               n1;            // sample1 size
   int               n2;            // sample2 size
   bool              is_valid;      // false when the statistic is undefined
   int               error_code;    // BM_OK / BM_ERR_SEPARATION / BM_ERR_TOO_SMALL
  };

The test itself builds pooled midranks over the combined sample, then within-sample midranks computed on each sample alone, and takes the difference between the two to get each observation's placement. s1_placement and s2_placement are the sample variances of those placements, and p_hat is the relative effect P(sample1 < sample2) + 0.5·P(tie) — 0.5 means the two samples are indistinguishable by this measure, above 0.5 means sample1 tends to rank lower (smaller) than sample2. The BM_ERR_SEPARATION branch is the failure mode mentioned above: when both placement variances collapse to zero, which happens when the two samples are perfectly separated with no ties crossing the boundary, the statistic's denominator is zero and the function returns false rather than dividing by it.

//+------------------------------------------------------------------+
//| BM_BrunnerMunzelTest                                             |
//| Brunner-Munzel generalized Wilcoxon test (Brunner & Munzel 2000):|
//| tests whether sample1 is stochastically smaller, larger, or      |
//| simply different from sample2, without assuming equal variances  |
//| or shapes                                                        |
//+------------------------------------------------------------------+
bool BM_BrunnerMunzelTest(const double &sample1[],const double &sample2[],
                          const ENUM_BM_ALTERNATIVE alternative,
                          const double confidence_level,
                          SBrunnerMunzelResult &result)
  {
   int n1 = ArraySize(sample1);
   int n2 = ArraySize(sample2);
   result.n1 = n1;
   result.n2 = n2;
   result.is_valid = false;
   if(n1 < 2 || n2 < 2)
     {
      result.error_code = BM_ERR_TOO_SMALL;
      return(false);
     }
//--- pooled midranks over the combined sample
   double combined[];
   ArrayResize(combined, n1 + n2);
   for(int i = 0; i < n1; i++)
      combined[i] = sample1[i];
   for(int i = 0; i < n2; i++)
      combined[n1 + i] = sample2[i];
   double pooled_rank[];
   BM_AssignMidRanks(combined, pooled_rank);
//--- within-sample midranks, computed on each sample alone
   double within1[], within2[];
   BM_AssignMidRanks(sample1, within1);
   BM_AssignMidRanks(sample2, within2);
   double rank1_mean = 0.0, rank2_mean = 0.0;
   for(int i = 0; i < n1; i++)
      rank1_mean += pooled_rank[i];
   rank1_mean /= n1;
   for(int i = 0; i < n2; i++)
      rank2_mean += pooled_rank[n1 + i];
   rank2_mean /= n2;
//--- placement variances (Brunner & Munzel 2000, eq. 2)
   double s1 = 0.0, s2 = 0.0;
   for(int i = 0; i < n1; i++)
     {
      double d = pooled_rank[i] - within1[i] - rank1_mean + (n1 + 1) / 2.0;
      s1 += d * d;
     }
   s1 /= (n1 - 1);
   for(int i = 0; i < n2; i++)
     {
      double d = pooled_rank[n1 + i] - within2[i] - rank2_mean + (n2 + 1) / 2.0;
      s2 += d * d;
     }
   s2 /= (n2 - 1);
   result.s1_placement = s1;
   result.s2_placement = s2;
   result.p_hat = (rank2_mean - rank1_mean) / (n1 + n2) + 0.5;
   double variance_term = n1 * s1 + n2 * s2;
   if(variance_term <= 0.0)
     {
      result.error_code = BM_ERR_SEPARATION;
      return(false);
     }
//--- Brunner-Munzel W statistic and Welch-Satterthwaite degrees of freedom
   double denom = (n1 + n2) * MathSqrt(variance_term);
   double w     = n1 * n2 * (rank2_mean - rank1_mean) / denom;
   double df_denominator = MathPow(n1 * s1, 2) / (n1 - 1) + MathPow(n2 * s2, 2) / (n2 - 1);
   double df = MathPow(variance_term, 2) / df_denominator;
   double p_value = 0.0;
   if(alternative == BM_TWO_SIDED)
      p_value = 2.0 * BM_StudentTCDF(-MathAbs(w), df);
   else
      if(alternative == BM_GREATER)
         p_value = BM_StudentTCDF(w, df);
      else
         p_value = 1.0 - BM_StudentTCDF(w, df);
//--- confidence interval for the relative effect p_hat, using the same
//--- standard error that w itself is built from (w = (p_hat-0.5)/se),
//--- so the CI is consistent with the p-value above rather than a
//--- separately-derived normalization
   double se    = MathSqrt(n1 * s1 + n2 * s2) / (n1 * n2);
   double alpha = 1.0 - confidence_level;
   double tcrit = BM_StudentTQuantile(1.0 - alpha / 2.0, df);
   result.w_stat   = w;
   result.df       = df;
   result.p_value  = p_value;
   result.ci_lower = result.p_hat - tcrit * se;
   result.ci_upper = result.p_hat + tcrit * se;
   result.is_valid  = true;
   result.error_code = BM_OK;
   return(true);
  }

The alternative is applied once, right where the p-value is computed: two-sided doubles the smaller tail. w is proportional to rank2_mean − rank1_mean, so when sample1 genuinely ranks higher (greater) than sample2, rank1_mean > rank2_mean and w comes out negative — BM_GREATER reads the lower tail of the Student-t CDF at w, which is correctly small at that negative w. The mirror case, sample1 ranking lower than sample2, pushes w positive, and BM_LESS reads the upper tail, small at that positive w. Nothing downstream re-derives direction from the sign of w_stat or p_hat — the caller's stated alternative is the only thing that decides which tail gets reported, which matters later when the gate always asks the same one-sided question.

The direction and the confidence interval compress to one block:

  • p_hat = P(sample1 < sample2) + 0.5·P(tie)
  • p_hat > 0.5 means sample1 more often takes the smaller value than sample2
  • BM_LESS checks exactly this direction; BM_GREATER checks the mirror
  • standard error se = sqrt(n1·s1 + n2·s2) / (n1·n2) — the same quantity w itself is built from (w = (p_hat − 0.5)/se), so the confidence interval's endpoints cross 0.5 exactly when the two-sided p-value crosses the matching alpha

That internal consistency between the interval and the p-value is a property of the formula, not something checked separately — I haven't verified this interval's coverage by simulation the way the next section checks the p-value's type-I behavior.


Comparison and verification of implementation

The Mann-Whitney implementation here is not a convenience shim; the Monte Carlo study in the next section runs it directly against Brunner-Munzel on the same synthetic samples, with its own tie correction (summing t^3−t over every group of tied values in the combined sample) and the standard continuity correction on the z-statistic. The full function, BM_MannWhitneyUTest(), is below and ships in BrunnerMunzelCore.mqh:

//+------------------------------------------------------------------+
//| BM_MannWhitneyUTest                                              |
//| Mann-Whitney U test with the tie-corrected, continuity-corrected |
//| normal approximation; run alongside Brunner-Munzel for direct    |
//| comparison                                                       |
//+------------------------------------------------------------------+
bool BM_MannWhitneyUTest(const double &sample1[],const double &sample2[],
                         const ENUM_BM_ALTERNATIVE alternative,
                         SMannWhitneyResult &result)
  {
   int n1 = ArraySize(sample1);
   int n2 = ArraySize(sample2);
   result.n1 = n1;
   result.n2 = n2;
   result.is_valid = false;
   if(n1 < 1 || n2 < 1)
      return(false);
   double combined[];
   ArrayResize(combined, n1 + n2);
   for(int i = 0; i < n1; i++)
      combined[i] = sample1[i];
   for(int i = 0; i < n2; i++)
      combined[n1 + i] = sample2[i];
   double pooled_rank[];
   BM_AssignMidRanks(combined, pooled_rank);
   int N = n1 + n2;
   double rank1_sum = 0.0;
   for(int i = 0; i < n1; i++)
      rank1_sum += pooled_rank[i];
   double u1 = rank1_sum - n1 * (n1 + 1) / 2.0;
   double mu = n1 * n2 / 2.0;
//--- tie correction: group identical combined values and sum t^3-t per group
   double sorted_vals[];
   ArrayCopy(sorted_vals, combined);
   ArraySort(sorted_vals);
   double tie_term = 0.0;
   int    i = 0;
   while(i < N)
     {
      int j = i;
      while(j + 1 < N && sorted_vals[j + 1] == sorted_vals[i])
         j++;
      double t = j - i + 1;
      tie_term += t * t * t - t;
      i = j + 1;
     }
   double sigma2 = (n1 * n2 / 12.0) * ((N + 1) - tie_term / (N * (N - 1)));
   if(sigma2 <= 0.0)
      return(false);
   double sigma = MathSqrt(sigma2);
   double z = 0.0, p_value = 0.0;
   if(alternative == BM_TWO_SIDED)
     {
      double cc = (u1 > mu) ? 0.5 : ((u1 < mu) ? -0.5 : 0.0);
      z = (u1 - mu - cc) / sigma;
      p_value = 2.0 * (1.0 - BM_NormalCDF(MathAbs(z)));
     }
   else
      if(alternative == BM_GREATER)
        {
         z = (u1 - mu - 0.5) / sigma;
         p_value = 1.0 - BM_NormalCDF(z);
        }
      else
        {
         z = (u1 - mu + 0.5) / sigma;
         p_value = BM_NormalCDF(z);
        }
   result.u_stat  = u1;
   result.z_stat  = z;
   result.p_value = p_value;
   result.is_valid = true;
   return(true);
  }

BM_RunSelfTest() checks the ten math helpers (log-gamma, incomplete beta, Student-t CDF and quantile, normal CDF) against independently computed reference values, then five Brunner-Munzel/Mann-Whitney test cases against values cross-checked outside MQL5 against scipy.stats.brunnermunzel and scipy.stats.mannwhitneyu before being embedded as constants:

Case What it checks n1 / n2
A Unequal variance, unequal n — two-sided, greater, less and the Mann-Whitney U in parallel 20/30
B Heavy ties on both sides 10/12
C Identical samples — W must be exactly 0, p exactly 1, p_hat exactly 0.5 8/8
D Complete separation — the asymptotic test must flag BM_ERR_SEPARATION, and the permutation fallback must find p < 0.05 5/5
E Large shift, no overlap through the middle of the range 15/20

Case D is the one that matters for honesty about the method: an asymptotic test that silently returned a p-value under complete separation would be reporting a number its own math can't support, so the self-test insists on seeing the failure flag before it will call this group of checks a pass. When BM_BrunnerMunzelTest returns BM_ERR_SEPARATION, the asymptotic test is undefined, and BM_BrunnerMunzelPermutationTest is the library's fallback for that case: it reshuffles the pooled sample into random groups of size n1/n2 using a seeded linear-congruential generator and counts how often the permuted relative effect is at least as extreme as the one actually observed.

The regime gate described below does not call this fallback, though — it treats an undefined asymptotic test the same as "no evidence yet" and leaves the regime open, rather than falling back to a permutation p-value. The function still ships, because complete separation is a real possibility with small rolling logs, and silently ignoring it would be worse than handling it explicitly even in a path the live gate never reaches.

What this self-test does not cover: it never touches a live tick, a position, a lot-size calculation or a CSV write. It confirms the calculation core reproduces known reference values on fixed inputs, nothing about the trading loop built around it. That loop gets its own check in the Strategy Tester sections below, by reconstructing the gate's exact decisions from the logged trades rather than trusting that a correct core implies a correct caller. Running the script against BM_RunSelfTest() prints a PASS/FAIL line per check and a final tally; attach BMSelfTest.mq5 to any chart after compiling and read the Experts log for the last line.


Does the normal approximation hold under unequal variance?

Brunner-Munzel's p-value comes from a Student-t approximation to a studentized rank statistic. The approximation is asymptotic: it gets more accurate as both sample sizes grow, and nothing in the formula guarantees good behavior at small n on its own. Calling it exact would undercut the whole point of reaching for Brunner-Munzel in the first place, since a known failure mode of the Mann-Whitney alternative is exactly what this test is meant to avoid.

To quantify the effect, BMvsMW_MonteCarlo.mq5 draws InpTrials pairs of zero-mean normal samples at three variance ratios (sample2 scaled by 1, 2 and 4 in standard deviation, i.e. variance ratios 1, 4 and 16), with unequal sample sizes (n1=20, the smaller group, n2=60, the larger group that also carries the scaled-up variance), through a reproducible Box-Muller generator (BM_BoxMullerNormal(), full code in BrunnerMunzelCore.mqh) seeded from the same linear-congruential generator the permutation test uses, so every random draw in this project traces back to one generator.

Using the same LCG, Box-Muller transform, and seed (20261007), with 5,000 trials per ratio, we estimate each test's false-rejection rate at nominal two-sided alpha=0.05, replayed through the verified math core. Both samples are drawn from the same zero-mean, symmetric normal distribution (just scaled differently in sample2), so the relative effect p_hat is exactly 0.5 by construction — the quantity these rank tests actually test, not the mean or median as such, though the two coincide here because of the symmetry. Any rejection in this design is a type-I error, not evidence of a real difference:

Variance ratio (sample2/sample1) Brunner-Munzel false-reject rate Mann-Whitney false-reject rate
1 5.14% 5.06%
4 5.52% 2.08%
16 4.72% 1.30%

At equal variance both tests sit close to their nominal 5%, as they should. As the variance ratio grows, Mann-Whitney's false-reject rate falls to roughly a quarter of nominal at a 16x variance ratio — it is not making more mistakes, it is making far fewer rejections than it should under a true null. This design never introduces an actual shift, so it cannot show which test would catch a real regime difference faster; what it shows is that Mann-Whitney's own error-rate guarantee quietly breaks down once the two regimes' variances diverge, which is reason enough to prefer a test that doesn't need that guarantee in the first place.

Brunner-Munzel stays within about half a percentage point of 5% across all three ratios in this specific configuration (n1=20, n2=60, trials=5,000, seed=20261007). That covers this sample-size combination and this range of variance ratios — it says nothing about whether the Welch-Satterthwaite correction holds equally well at every n. This is exactly the scenario the regime gate faces in practice, since a rolling log of HIGH-regime R-multiples routinely has a different spread of outcomes than the LOW-regime log it gets compared against.

Sequential testing changes the picture. The 5% figures above hold for one isolated test. EvaluateGate() runs the same alpha=0.05 comparison again on every new signal, against rolling logs that only grow, which is a different question: not "what is the false-rejection rate of one test", but "what is the probability that at least one of many sequential tests over a run rejects, purely by chance, when nothing real separates the two regimes."

A second Monte Carlo design answers that directly: the same zero-mean, variance-scaled null as above, but replayed signal-by-signal through the gate's exact logic — two FIFO logs capped at InpMaxLogSize=300, the test only live once both logs hold InpGateMinTrades=20, one-sided BM_LESS applied to whichever regime the current signal belongs to — over a 124-signal run, the length of the EURUSD H1 Gate-ON leg, with 10,000 trials per variance ratio and the same seed (20261007):

Variance ratio (HIGH/LOW) Cumulative false-block rate over 124 signals
1 30.80%
4 30.88%
16 29.63%

Across all three variance ratios the cumulative false-block rate sits near 30%, not the 5% a single test would suggest, and it barely moves with the variance ratio — unsurprising, since Brunner-Munzel's error control held flat across ratios in the single-test table above too. This is the quantified version of what the Limitations section flags as repeated testing: over a run this length, roughly one run in three would see the gate fire at least once on chance alone, with no real regime difference behind it. It does not mean any specific block in this article's results is a false positive — EURUSD H1 is one leg, not a resampled ensemble — but it does mean the 5% per-test alpha is not the right number to read as "how often does this gate cry wolf over a run."


The regime-gated Expert Advisor

BMRegimeGate_EA.mq5 trades a Donchian channel breakout, classifies every signal into a HIGH or LOW volatility regime by ranking the current ATR against its own trailing history, and keeps one rolling R-multiple log per regime capped at InpMaxLogSize entries. A regime is read, never a point-in-time flag: the cap keeps each log a FIFO window of the most recent outcomes, so an old run of losses eventually ages out and does not permanently keep a regime gated. BM_PushCapped() (full code in BMRegimeGate_EA.mq5) is the function behind that cap — it appends a value and drops the oldest entry once the log exceeds InpMaxLogSize.

Regime classification ranks the current ATR(InpATRPeriod) against the InpATRLookback bars before it and compares the resulting percentile to InpATRPercentileSplit — a straightforward empirical percentile, not a parametric volatility model, so it needs no distributional assumption about ATR itself. ClassifyRegime() (full code in BMRegimeGate_EA.mq5) does this ranking and returns REGIME_HIGH or REGIME_LOW.

The breakout signal reads the just-completed bar's close against the Donchian channel built from the InpDonchianPeriod bars immediately before it, deliberately excluding the signal bar from its own channel. OnTick() runs on every tick, but this function and the rest of the per-bar logic only execute once IsNewBar() confirms a new bar of InpTimeframe has opened, so index 1 is always the bar that just closed and index 0 is still forming. CheckDonchianSignal() (full code in BMRegimeGate_EA.mq5) returns +1 for a long signal, -1 for short, 0 for none.

The gate itself is a single one-sided Brunner-Munzel test per signal, evaluated dynamically against whatever the two rolling logs currently hold — not against a fixed, final dataset. A HIGH-regime signal asks whether HIGH is stochastically less than LOW; a LOW-regime signal asks the mirror question. Both calls use BM_LESS explicitly, so the test's own direction always matches the claim "this regime is worse," never the two-sided question of whether the regimes merely differ:

//+------------------------------------------------------------------+
//| EvaluateGate                                                     |
//| One-sided Brunner-Munzel test of this regime's logged R-multiples|
//| against the other regime's; returns true (skip the trade) only   |
//| once both logs hold at least InpGateMinTrades observations and   |
//| the test says this regime is stochastically worse at InpGateAlpha|
//+------------------------------------------------------------------+
bool EvaluateGate(const int regime)
  {
   if(!InpGateEnabled)
      return(false);
   int n_low  = ArraySize(g_r_log_low);
   int n_high = ArraySize(g_r_log_high);
   if(n_low < InpGateMinTrades || n_high < InpGateMinTrades)
      return(false);
   SBrunnerMunzelResult result;
   bool ok;
   string mode;
   if(regime == REGIME_HIGH)
     {
      ok   = BM_BrunnerMunzelTest(g_r_log_high, g_r_log_low, BM_LESS, 0.95, result);
      mode = "HIGH<LOW";
     }
   else
     {
      ok   = BM_BrunnerMunzelTest(g_r_log_low, g_r_log_high, BM_LESS, 0.95, result);
      mode = "LOW<HIGH";
     }
//--- a checksum of both rolling logs' current contents, printed with every
//--- call so a later reconciliation can confirm the exact FIFO state this
//--- decision was made against, not just the log sizes
   double checksum_low = 0.0, checksum_high = 0.0;
   for(int i = 0; i < n_low; i++)
      checksum_low += g_r_log_low[i];
   for(int i = 0; i < n_high; i++)
      checksum_high += g_r_log_high[i];
   bool blocked = (ok && result.p_value < InpGateAlpha);
   PrintFormat("EvaluateGate: regime=%s mode=%s ok=%d p=%.6g p_hat=%.6g n_low=%d n_high=%d "
               "checksum_low=%.6g checksum_high=%.6g blocked=%d",
               (regime == REGIME_HIGH) ? "HIGH" : "LOW", mode, ok,
               ok ? result.p_value : -1.0, ok ? result.p_hat : -1.0,
               n_low, n_high, checksum_low, checksum_high, blocked);
   return(blocked);
  }

A regime is skipped only once both logs hold at least InpGateMinTrades observations and the one-sided p-value falls below InpGateAlpha. Below that minimum, or when the comparison test itself returns invalid (the separation case from earlier), the function returns false and the signal trades. An untested regime gets the benefit of the doubt; the gate never defaults to guilty.

OnTick() ties this together in order: detect a closed position first, then look for a new bar, a Donchian signal, and a regime classification. The one change worth isolating is that the already-open-position check now runs before the gate is evaluated, not after — a signal that could not have become a real trade anyway must never be scored against the gate or logged as a shadow outcome, or the rolling log ends up crediting a block to the gate that was actually just the one-trade-at-a-time rule:

//--- excerpt from OnTick(): ManageOpenPosition(), the new-bar check,
//--- CheckDonchianSignal(), ClassifyRegime() and the stop/target math
//--- all run first; this is what happens once a signal is in hand
    // &hellip;
    if(g_ticket_regime >= 0)
        return;  // one real position at a time -- checked first
    if(EvaluateGate(regime))
      {
        AddVirtualTrade(regime, direction > 0, price, sl, tp, stop_distance);
        return;
      }
    // &hellip;

The full function — new-bar detection, stop/target computation from ATR, and order submission — is in the shipped BMRegimeGate_EA.mq5.

Position sizing cross-checks two independent derivations of the per-lot loss at the stop: one from SYMBOL_TRADE_TICK_VALUE, one from OrderCalcProfit() run against the actual intended direction, entry price and stop price. The fallback used to multiply stop_distance_price by SYMBOL_TRADE_CONTRACT_SIZE, which computes the loss in the instrument's profit currency, not necessarily the account currency — on a symbol where those two differ, that fallback could size a position wrong without ever raising an error. OrderCalcProfit() does the conversion itself, so the fallback it now calls into is correct in account currency regardless of what the symbol's profit currency happens to be.

The two are compared with a symmetric ratio — the larger of the two divided by the smaller — rather than always dividing by the OrderCalcProfit() figure, since either source, not only SYMBOL_TRADE_TICK_VALUE, can turn out to be the outlier; a non-positive or otherwise invalid reading from either source is treated as missing rather than compared against the other. A greater than 5x disagreement between two valid readings still falls back to the OrderCalcProfit()-derived figure and logs one warning, because tick-value metadata on some demo servers for some instruments has been observed to disagree with it by a clean order of magnitude, which would silently inflate or shrink every position by the same factor without raising an error. Full code for CalculateLotSize() is in BMRegimeGate_EA.mq5.

The clamp at vol_min can only push a position larger than the risk model asked for, never smaller, and on a symbol with a coarse minimum lot that can be a meaningful overshoot; the function flags any case where the floor pushes the actual risk more than 10% past the InpRiskPercent target, so an oversized fill shows up in the log instead of silently passing as a correctly sized trade.

Did the old contract-size fallback affect the published results? I no longer have the saved Experts logs needed to confirm whether the >5x mismatch branch ever actually triggered during these twelve runs. What can be said without that record: the old fallback's error was specifically a currency mismatch, between the symbol's profit currency and the account's currency. All three traded symbols in this matrix (XAUUSD, EURUSD, GBPUSD) quote their profit in USD on a standard MetaQuotes-Demo setup, the same currency as the account, so even on a run where that branch did fire, the contract-size figure and the correctly-converted figure would have come out identical for these particular symbols — this specific bug could not have produced a wrong position size in this matrix, whether or not it was ever exercised. That is a property of these three symbols on this account, not a general guarantee, which is exactly why the fix now goes through OrderCalcProfit() instead of relying on it.


Logging real trades and the shadow outcomes behind blocked signals

A gate that only records what it allows can never accumulate the evidence needed to ungate a regime later, because the regime it is skipping never generates new data. Three facts cover what the logging actually does: real and shadow outcomes both land in the same general journals, under the same rolling log and the same per-run CSV, with is_real the only field distinguishing them; a shadow trade's outcome is modeled against the following bars' OHLC, with the stop assumed hit first whenever both the stop and the target fall inside the same bar's range, since tick-level data isn't available in the Strategy Tester's per-bar replay to resolve the true intrabar order; and the CSV stores the time an outcome was resolved, not the time the signal fired and the gate made its decision.

AddVirtualTrade()/UpdateVirtualTrades() handle the shadow side, ManageOpenPosition() (full code in BMRegimeGate_EA.mq5) the real side — detecting a closed position and computing its realized R-multiple from the closing deal. Its magic-number check is paired with a symbol check, both on the open position and on every deal scanned in history, so two instances of this EA on different symbols sharing one magic number can't contaminate each other's logs; two instances on the same symbol with the same magic number are still indistinguishable to this check, and giving each its own number is left to whoever runs multiple instances. The history window is anchored to the position's own open time rather than a window measured back from the current time, so a position held open for any number of bars still has its entry deal inside the scanned range. Every logged outcome, real or shadow, is appended to a per-run CSV in the shared Common Files folder, with the filename itself encoding symbol, timeframe and gate state so that runs with different settings can never contaminate each other's rows.

On that resolution-time-versus-decision-time gap: capturing TimeCurrent() as signal_time and decision_time and carrying both through to whichever outcome eventually gets logged would close it, but that is a proposed improvement, not implemented in the shipped EA — the Experts log is the more exact record for any run where it was actually saved, since every EvaluateGate() call already prints its full diagnostic line, terminal-timestamped at decision time.


The rolling indicator

BMRollingShift.mq5 is a display-only companion: at each bar it splits the last 2·InpWindow one-bar close-price changes into an older half and a newer half, and plots the two-sided Brunner-Munzel relative effect (p_hat, with its confidence band) and both tests' p-values on the same pane, so any disagreement between Brunner-Munzel and Mann-Whitney on a live chart is visible directly rather than inferred from two separate numbers. The full OnCalculate() (in the shipped BMRollingShift.mq5) draws from the same BM_BrunnerMunzelTest() and BM_MannWhitneyUTest() shown above, called with BM_TWO_SIDED rather than the EA's one-sided BM_LESS. This indicator does not feed the EA and never gates a trade; it exists to let you watch the two tests track or diverge on your own symbol before trusting either one inside an automated filter.


Strategy Tester results across twelve runs

A note before the numbers: this matrix was first run against a version of OnTick() that checked the gate before the open-position slot, a since-fixed ordering issue covered in the Limitations section below. The old code always logged a shadow trade whenever the gate fired, busy or not, so n_shadow>0 is proof the gate fired at least once in that run; eleven of the twelve rows below have n_shadow=0, meaning the gate never fired in those runs at all, and the check order makes no difference to a run where the gate never fires. EURUSD H1 Gate-ON, the leg where the gate did fire, uses a Strategy Tester run with the position check ahead of the gate; the other eleven rows are unaffected either way.

Settings. MetaQuotes-Demo, real ticks, 2026.04.01 to 2026.09.30, three symbols (XAUUSD, EURUSD, GBPUSD) at two timeframes (M15, H1), gate off and on — twelve runs in total. InpRiskPercent is 0.25 for the whole matrix. A higher risk setting compounds this strategy's sub-50% win rate quickly: at 1% risk per trade the same Donchian signal stream on XAUUSD M15 draws a $10,000 starting balance down to $34.02 before the test window ends, which is a sizing fact independent of anything the statistical gate does, and 0.25% keeps drawdown from swamping the comparison the gate is actually meant to test.

Parameter Value
Donchian period (InpDonchianPeriod) 20
ATR period (InpATRPeriod) 14
ATR percentile lookback (InpATRLookback) 100 bars
ATR percentile split (InpATRPercentileSplit) 50%
Stop distance (InpStopATRMult) 2 × ATR
Reward multiple (InpRewardRMultiple) 1.5R
Risk per trade (InpRiskPercent) 0.25%
Gate significance level (InpGateAlpha) 0.05
Minimum trades before gate is live (InpGateMinTrades) 20 per regime leg
Rolling log cap (InpMaxLogSize) 300 (FIFO)
Magic number (InpMagic) 20261007
Position sizing risk-percent based only, no fixed-lot input; volume floored at the symbol's SYMBOL_VOLUME_MIN when the risk-based calculation falls below it
Initial deposit / account currency 10,000 USD
Broker / tick model MetaQuotes-Demo, real ticks
Leverage / commission not captured in the saved test artifacts for this run; everything else in this table comes directly from the EA's inputs or the Strategy Tester settings used for all twelve runs

Sample accounting. Every row in a leg's CSV is one logged outcome, real or shadow; n_total is the row count, n_real the rows with is_real=1, and n_shadow = n_total − n_real. Eleven of the twelve rows below have n_shadow=0, but that number mixes two different things: the six gate-OFF rows have n_shadow=0 trivially, since EvaluateGate() is never even called when the gate is off. Of the six gate-ON rows, five have n_shadow=0 because the one-sided comparison never crossed InpGateAlpha=0.05 on those symbol/timeframe/regime combinations in this window; only the sixth, EURUSD H1, saw it fire. Reporting that plainly is the point — nothing here points to a malfunction.

Win rate and mean R in the table are computed over real trades only (is_real=1) for every row, shadow trades excluded throughout, not only for the EURUSD H1 leg discussed in detail below. n_low/n_high below are the sizes of the two rolling logs at the end of each run, each capped at InpMaxLogSize=300 by the same FIFO rule shown earlier.

Run Gate n_total n_real n_shadow win rate mean R n_low n_high HIGH<LOW p LOW<HIGH p
XAUUSD M15 OFF 501 501 0 38.92% −0.0651 201 300 0.9064 0.0936
XAUUSD M15 ON 501 501 0 38.92% −0.0651 201 300 0.9064 0.0936
XAUUSD H1 OFF 133 133 0 36.09% −0.1457 54 79 0.7210 0.2790
XAUUSD H1 ON 133 133 0 36.09% −0.1457 54 79 0.7210 0.2790
EURUSD M15 OFF 474 474 0 40.30% −0.0047 168 300 0.2173 0.7827
EURUSD M15 ON 474 474 0 40.30% −0.0047 168 300 0.2173 0.7827
EURUSD H1 OFF 123 123 0 35.77% −0.1338 51 72 0.8173 0.1827
EURUSD H1 ON 124 113 11 38.05% −0.0792 51 73 0.7767 0.2233
GBPUSD M15 OFF 473 473 0 34.46% −0.1753 172 300 0.2942 0.7058
GBPUSD M15 ON 473 473 0 34.46% −0.1753 172 300 0.2942 0.7058
GBPUSD H1 OFF 122 122 0 37.70% −0.0773 52 70 0.2872 0.7128
GBPUSD H1 ON 122 122 0 37.70% −0.0773 52 70 0.2872 0.7128

Every row with n_shadow=0 has a gate-ON run whose reported aggregate metrics — n_total, n_real, win rate, mean R, n_low, n_high, and both one-sided p-values — are identical to its gate-OFF counterpart's, as the table shows. This is simply what a gate that never fired looks like: nothing in the EA diverges between the two runs until EvaluateGate() actually returns true at least once.

The two rightmost columns are the final-aggregate one-sided test on each leg's end-of-run logs (HIGH-less-than-LOW and the mirror, matching the exact comparisons EvaluateGate() runs), and none of the twelve crosses 0.05 — which is consistent with, and explains, why only one of six symbol/timeframe pairs ever saw the gate actually block a signal during the run itself. A final-aggregate p-value above 0.05 does not retroactively mean the gate was wrong to fire earlier in a run on a smaller, different rolling log; the two are separate calculations over separate data, covered next.

One-sided LOW-regime p-value at each of the EA's own gate checks

1. EURUSD H1, gate ON, from a chronological replay of the logged CSV that attempts to reconstruct the Brunner-Munzel(LOW, HIGH, less) calls EvaluateGate() made as the rolling logs filled, matching eleven of the twelve against the logged outcomes exactly. Blue dashed line: the alpha=0.05 threshold the gate compares against; only this one line is drawn because the gate's own test is one-sided. Red points: a decision that matched the logged outcome. Amber point: the single decision where this reconstruction and the logged CSV disagree (see below).


The one run where the gate actually fired

EURUSD H1 with the gate on is the only one of twelve legs whose real-trade count (113) differs from its gate-off counterpart (123): eleven LOW-regime signals between 2026.06.04 and 2026.07.02 were diverted into shadow trades instead, logged with is_real=0. Under the corrected ordering, a blocked signal can no longer have been holding the "one real position at a time" slot — the busy check now runs first, so a block only ever happens when a position was already free — and the real-trade count falls by ten rather than exactly eleven; the remaining one-trade gap is simply that the gate-ON and gate-OFF runs stop walking the same clock the moment the first signal diverts, since a shadow trade and a real trade can take different numbers of bars to resolve.

To confirm the gate's logged behavior actually matches what EvaluateGate() computes, I replayed this leg's CSV chronologically in Python, maintaining the same two FIFO-capped rolling logs the EA keeps and calling the same Brunner-Munzel(LOW, HIGH, less) / Brunner-Munzel(HIGH, LOW, less) comparisons at every row once both logs passed InpGateMinTrades=20. This reconstruction predicts twelve block events; the logged CSV contains eleven shadow trades, and eleven of the twelve predicted blocks land on exactly the logged shadow-trade timestamps.

One discrepancy remains unexplained: the twelfth predicted block, at 2026.07.06 20:32:25 with a reconstructed p-value of 0.0431 (n_low=31, n_high=39), is logged in the CSV as a real trade rather than a shadow one. The most plausible cause is the gap described above — the CSV timestamps an outcome's resolution, not its decision, so this trade's actual gate check may well have happened earlier against a smaller, earlier rolling log than a straight chronological replay assumes by the time it reaches that row — but without this run's saved Experts log, that explanation can't be confirmed, and it stays the best account the data supports rather than a verified one.

Fig. 1 plots this leg's p-value trajectory across the twelve decision points this reconstruction predicts, eleven of which match the logged CSV exactly and one of which does not, the LOW-regime log size on the x-axis and the one-sided p-value on the y-axis, with the single alpha=0.05 line the test actually tests against — not a symmetric pair of reference lines, since nothing about a one-sided Brunner-Munzel(LOW, HIGH, less) test has a lower tail to draw. The trajectory crosses below 0.05 at n_low=20 and stays there through n_low=31, tightening slowly as more LOW-regime outcomes accumulate, and never crosses back above the line within this leg's data.

What that shows: for roughly four weeks of this run, the LOW volatility regime's realized R-multiples were different enough from the HIGH regime's, on this particular rolling window, that the one-sided test kept finding p<0.05. What it does not show: that this difference is permanent, since the rolling log ages out old outcomes and a run long enough could see the comparison cross back; and it does not show that the gate improved trading outcomes on this leg by itself.

The real-trade count fell from 123 to 113 and the mean realized R across all real trades on this leg (computed over gate-ON's 113 real rows) is −0.0792, against −0.1338 on the gate-off leg's 123 real rows — a less negative figure, but one leg, 113 and 123 trades respectively, and a filter that simultaneously changed which ten trades were taken is not a clean test of the filter in isolation from the exposure it also reduced.

Real trades logged per symbol/timeframe, gate off against gate on

2. Gray bars: gate off. Blue bars: gate on. All six symbol/timeframe pairs, from the twelve CSVs in the table above. Only EURUSD H1 shows a visible difference between its two bars — the one leg where the gate fired.


Limitations

Scope and dependence between runs. The results cover one broker (MetaQuotes-Demo), April–September 2026, three symbols, two timeframes, and one Donchian/ATR strategy with fixed parameters. Twelve runs are not twelve independent observations of market behavior: gate-ON/OFF runs share their underlying data, M15/H1 pairs sample the same symbol’s price path, and XAUUSD, EURUSD and GBPUSD can share market drivers. The gate firing on one of six symbol/timeframe pairs therefore describes this particular sample, not an intervention frequency that can be generalized to independently drawn configurations.

Limited gate activity and unvalidated regime separation. Five of the six gate-ON configurations produced no blocks. This does not demonstrate a malfunction, but neither does it establish that the ATR-percentile split creates useful groups for this strategy. The 50th-percentile threshold may simply fail to separate outcomes into meaningfully different distributions. The article does not distinguish weak regime classification from insufficient data or a genuine absence of a relative-effect difference. Before drawing broader conclusions about Brunner-Munzel’s usefulness as a trading filter, the regime definition itself needs independent validation.

Statistical significance is not trading value. On EURUSD H1, the gate reduced real trades from 123 to 113 and improved mean realized R from −0.1338 to −0.0792. That is one configuration with changed exposure and a different sequence of trades, not an isolated estimate of the statistical trigger’s contribution. The results do not establish that blocking significant comparisons improves expectancy after execution costs, exposure changes and repeated testing are accounted for.

Restricted statistical validation. The single-test Monte Carlo study uses independent normal samples, n1=20 and n2=60, three variance ratios, and no relative-effect difference. It supports the specific conclusion that Brunner-Munzel stays near its nominal type-I error rate in that design while the implemented Mann-Whitney approximation does not. It does not establish statistical power, calibration at other sample sizes, or performance on skewed, heavy-tailed or serially dependent trade outcomes. The confidence interval is internally consistent with the test statistic, but its coverage has not been checked by simulation.

Repeated testing and outcome dependence. The gate applies a one-sided alpha=0.05 test repeatedly to overlapping rolling logs, without a sequential-testing correction. In the reported 124-signal null simulation, the probability of at least one false block is approximately 30%, not 5%. That estimate belongs to the simulated design, not every possible trading run. Actual trade outcomes may also be autocorrelated, an assumption violation the independent-draw simulations do not address.

Incomplete decision reconstruction. The CSV-based replay predicts twelve blocks, eleven of which correspond to logged shadow outcomes; one corresponds to a real trade instead. Outcome timestamps rather than decision timestamps are the most plausible explanation, but the missing Experts log prevents confirmation. This is a general limitation of the reconstruction, not merely an isolated timestamp issue: a gate decision made while an earlier shadow trade remains unresolved cannot necessarily be placed against the correct rolling-log state from the CSV alone. The eleven matches therefore do not establish a complete, independently verified decision-time audit.

Modeled shadow outcomes. Real trades use broker fills; shadow trades use hypothetical entry, stop and target levels resolved against subsequent OHLC bars, assuming the stop is hit first when both stop and target fall within one bar. Both enter the same rolling statistical sample despite these different execution models. A shadow R-multiple is a modeled counterfactual, not an observed fill. Excluding shadow outcomes from the EURUSD H1 replay still produces the same twelve predicted blocks, but freezes the LOW log at its pre-block size during that episode; it does not validate the shadow execution model.

Implementation and execution constraints. The mathematical self-test checks fixed reference cases, not the complete trading loop. Open-position checks now precede gate evaluation, preventing signals that could not trade anyway from being counted as gate blocks; the published EURUSD H1 gate-ON leg uses that corrected ordering. Multi-instance identification relies on symbol/magic-number pairs, so instances on the same symbol require distinct magic numbers. Minimum lot sizes can also push actual risk above the requested percentage.

No held-out evaluation. All twelve runs share one continuous market window, with no separate parameter-selection period and held-out evaluation period. The results demonstrate the gate’s behavior within that window, not its stability on unseen data.

Overall, the experiment demonstrates the implementation and observed behavior of a statistical gate, with a partially reconstructed decision trail. It does not establish improved profitability, robust regime separation, generalization across markets, or readiness for unrestricted live deployment.


Final thoughts

The math in BrunnerMunzelCore.mqh reproduces its reference values to within the self-test's own tolerance — BM_CheckClose() checks closeness against a stated tolerance per case, not exact floating-point equality, and that is the honest claim the self-test actually supports. The Monte Carlo study shows it holding close to its nominal false-rejection rate where Mann-Whitney visibly does not, at least for the one sample-size combination tested here. As a live trading filter, this specific twelve-run matrix shows it doing almost nothing on five of the six gate-ON legs and firing cleanly, with a traceable and mostly reproducible decision trail, on the sixth, EURUSD H1.

A filter that rarely intervenes is not a failed filter — it is a filter correctly reporting that it mostly could not find the evidence it was built to look for, in this window, on this strategy. Whether that is the right outcome for a longer run, a different regime split, or a different base strategy is exactly the kind of question a one-sided statistical gate is suited to keep re-asking, rather than answer once and stop.

File Type Description
MQL5\Include\BrunnerMunzel\BrunnerMunzelCore.mqh Include Brunner-Munzel and Mann-Whitney tests, math helpers (log-gamma, incomplete beta, Student-t CDF/quantile, normal CDF), the seeded-LCG permutation fallback, and the reference-value self-test.
MQL5\Experts\BrunnerMunzel\BMRegimeGate_EA.mq5 Expert Advisor Donchian breakout, ATR-percentile regime classification, the one-sided Brunner-Munzel gate, shadow-trade logging for blocked signals, and CSV output to Common Files.
MQL5\Indicators\BrunnerMunzel\BMRollingShift.mq5 Indicator Rolling Brunner-Munzel p_hat with its confidence band, plotted against the Mann-Whitney p-value. Display only, independent of the EA.
MQL5\Scripts\BrunnerMunzel\BMSelfTest.mq5 Script Runs BM_RunSelfTest() and prints a single PASS/FAIL verdict to the Experts log.
MQL5\Scripts\BrunnerMunzel\BMvsMW_MonteCarlo.mq5 Script Type-I error study comparing Brunner-Munzel and Mann-Whitney false-reject rates across three variance ratios; writes its results to a Common Files CSV.
Attached files |
MQL5.zip (19.95 KB)
Building a Daily OHLCV Aggregator from M1 Bars in MQL5 Building a Daily OHLCV Aggregator from M1 Bars in MQL5
Create session-aligned daily candles from M1 data by choosing the session close hour. A dedicated shift–truncate–restore day-key function prevents off-by-one errors at rollover and is easy to unit test. The script groups and aggregates M1 bars, writes a custom symbol for standard D1 charting, and reports results in the Experts tab, backed by synthetic tests.
Dirichlet Process Mixtures: How Many Market Regimes Are There, and Does the Answer Mean Anything? Dirichlet Process Mixtures: How Many Market Regimes Are There, and Does the Answer Mean Anything?
Most regime tools ask for a fixed number of states. This article implements a Dirichlet process mixture for MQL5 with truncated stick-breaking and varying coordinate ascent, so the cluster count is inferred from data and the evidence bound is monitored each iteration. The package includes a nine-file library, an out-of-sample indicator that scores each bar, a six-level test suite, and a shuffle-based null control to judge how much the recovered count means.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
Self-Optimizing Expert Advisors in MQL5 (Part 21): Wavelet Denoising With Time-Lagged Independent Component Analysis (4) Self-Optimizing Expert Advisors in MQL5 (Part 21): Wavelet Denoising With Time-Lagged Independent Component Analysis (4)
This article refines a multilayer market‑noise filter by sanitizing moving‑average inputs via Discrete Wavelet Transform and constructing a FastICA manifold on the denoised signals. We expand lag horizons (10–80 days), calibrate spectral clusters, and replace non-ONNX steps with surrogate models for MT5 deployment. The result is a reproducible MQL5 workflow that reduces forecasting error and integrates directly into an Expert Advisor.