preview
Detrended Cross-Correlation Analysis (DCCA) for Pairs-Trading Pair Selection Under Nonstationarity

Detrended Cross-Correlation Analysis (DCCA) for Pairs-Trading Pair Selection Under Nonstationarity

MetaTrader 5 — Statistics and analysis |
246 0
Bosede Gbadebo
Bosede Gbadebo

Introduction

Pairs trading starts with a question that sounds simple and usually isn't: which two instruments actually move together? The standard answer is a Pearson correlation over some lookback window, fine for a short window on a well-behaved pair. The trouble starts with instruments that trend — gold against silver over a quarter where both have been climbing, or a Tokyo-session cross against a London-session one with a visible drift in each.

The Pearson coefficient is computed the same way regardless; what changes is how to read it. A level-to-level correlation between two independently trending series can come out high even when the trends have nothing to do with each other — two unrelated upward drifts covary with the calendar, not one another — so a high reading doesn't by itself mean the instruments are related at the time scales that matter for trading them as a pair.

Detrended Cross-Correlation Analysis (DCCA) was built for exactly this case: it correlates what's left after a local trend has been removed from each series, at a chosen scale. Repeating that across several scales turns one correlation number into a curve — how related are these two instruments over 10 bars, over 50, over 200? A pair can be weakly related at a scalper's scale and strongly related at a swing trader's, and DCCA shows that difference instead of averaging it away.

This article builds a native MQL5 implementation of DCCA (no DLLs, no ALGLIB — just matrices/vectors and loops), then uses it to rank candidate pairs by scale-dependent correlation instead of a single Pearson number, and to gate a simple mean-reversion spread trade. Every figure in the Testing section comes from real MetaTrader-history runs, including losing ones — a correlation tool can be useful even when the trading rule built on it isn't, and this article says plainly which of the two it demonstrates.


The Math: Detrended Cross-Correlation Analysis

DCCA works on the cumulative, de-meaned profile of each series rather than the raw series itself. For a series x of length n:

X(k) = sum_{i=1..k} (x_i - mean(x)),   k = 1..n

and the same construction gives Y(k) from the second series y. This profile is the standard first step in detrended fluctuation analysis generally — it turns the correlation question into a question about a random-walk-like curve, which is the form the detrending step below is built to handle.

The profile is then split into non-overlapping boxes of length s, starting from index 0. In each box, a local order-1 (linear) polynomial is fit by ordinary least squares and subtracted, leaving a detrended residual. Doing this independently per box at a fixed scale s is what makes the result local rather than one global detrend over the whole series — a box 2,000 bars into a dataset isn't dragged around by a trend that happened 2,000 bars earlier.

Averaging the cross-product of the two series' detrended residuals over every box of size s gives the DCCA fluctuation function, and averaging each series' own squared residual gives the two DFA fluctuation functions:

F_DCCA^2(s) = (1 / (N_s * s)) * sum over boxes, sum over box {  X~(k) * Y~(k)  }
F_DFA,x^2(s) = (1 / (N_s * s)) * sum over boxes, sum over box {  X~(k)^2  }
F_DFA,y^2(s) = (1 / (N_s * s)) * sum over boxes, sum over box {  Y~(k)^2  }

where X~ and Y~ are the detrended residuals and N_s is the number of complete boxes of size s. The DCCA correlation coefficient at scale s is the normalized ratio of these three:

rho_DCCA(s) = F_DCCA^2(s) / ( F_DFA,x(s) * F_DFA,y(s) )

bounded in [-1, 1] the same way an ordinary correlation coefficient is, except defined per scale instead of once for the whole series. A pair can show rho_DCCA near zero at s=10 and near 0.8 at s=100 — related over a swing-trade horizon, unrelated tick-to-tick — while Pearson reports one number blending both regimes. The implementation below computes this curve across a configurable range of box sizes, then averages it over a chosen scale band for the single ranking number the scanner and gate use.


Architecture

Five files make up this project: DCCACore.mqh (the DCCA engine plus shared history-fetching/alignment helper), PairRanker.mqh (runs it across a basket, ranks against Pearson), DCCA_PairScanner_EA.mq5 (schedules the basket scan, writes results to CSV), DCCA_SpreadTrading_EA.mq5 (trades the z-scored spread of one pair with the DCCA band mean as a live entry gate), and DCCA_SelfTest.mq5 (validates the engine against synthetic series with known correlation before trusting it on real data).

DCCA Project Pipeline

Fig. 1. Data flow from history fetch through the DCCA engine to the scanner and the trading EA.

The pipeline runs top to bottom in the diagram: both legs' price history is fetched and time-aligned, the engine builds a cumulative profile for each leg and sweeps every configured box size, and the resulting rho_DCCA(s) curve feeds two consumers — the scanner, which ranks a whole basket, and the trading EA, which uses the same number as a live gate on one chosen pair.


DCCACore.mqh — The DCCA Engine

This file has two jobs: compute rho_DCCA(s) for a pair of series (the CDCCAEngine class), and fetch/align two symbols' price history so there's something real to feed it (AlignSeries, a static helper both EAs call). Four constants control the engine's behavior:

//+------------------------------------------------------------------+
//| Defines                                                          |
//| Tunable constants for the DCCA engine: the smallest scale a box  |
//| fit is trusted at, the minimum number of boxes a scale must      |
//| provide to be used, the sentinel value returned in place of a    |
//| correlation coefficient whenever a scale could not be computed,  |
//| and the maximum time AlignSeries waits for a symbol's price      |
//| history to finish synchronizing before reading it.               |
//+------------------------------------------------------------------+

#define DCCA_MIN_BOX_SIZE        4    // smallest box length a linear fit is trusted at
#define DCCA_MIN_BOXES_PER_SCALE 4    // a scale needs at least this many boxes to be used
#define DCCA_INVALID_RHO         -2.0 // sentinel: outside [-1,1], marks a scale that could not be computed
#define DCCA_HISTORY_WAIT_MS     5000 // max time to wait for a symbol's history to synchronize

//+------------------------------------------------------------------+
//| CDCCAEngine                                                      |
//| Detrended Cross-Correlation Analysis engine. Builds the          |
//| de-meaned cumulative profile of two input series, removes a      |
//| local linear trend inside non-overlapping boxes of a given size, |
//| and measures the covariance and individual variances of the      |
//| detrended residuals at that scale. Repeating this across a range |
//| of box sizes yields rho_DCCA(s), the scale-dependent             |
//| cross-correlation coefficient this project uses to rank          |
//| pairs-trading candidates without assuming either series is       |
//| stationary. Boxes are laid out forward from the start of the     |
//| series only; any remainder shorter than one box at the tail is   |
//| dropped from that scale's estimate.                              |
//+------------------------------------------------------------------+

class CDCCAEngine
  {
private:
   //--- raw input series and their de-meaned cumulative profiles
   vector            m_x;                  // input series X, as supplied to SetSeries
   vector            m_y;                  // input series Y, as supplied to SetSeries
   vector            m_profile_x;          // cumulative de-meaned profile of X
   vector            m_profile_y;          // cumulative de-meaned profile of Y
   int               m_n;                  // number of points currently loaded
   bool              m_profiles_built;     // true once SetSeries has built valid profiles

   //--- internal computation steps, implemented out of line below
   void              BuildProfile(const vector &series,vector &profile);
   void              FitLinearBox(const vector &profile,int start,int len,vector &residual);
   void              BoxFluctuations(int s,double &f_dcca_sq,double &f_dfa_x_sq,double &f_dfa_y_sq);

public:
                     CDCCAEngine(void);
                    ~CDCCAEngine(void);
   bool              SetSeries(const double &x[],const double &y[]);
   bool              Run(const int &scales[],vector &rho_out);
   double            MeanRhoOverBand(const vector &rho,const int &scales[],int s_min,int s_max);
   static bool       AlignSeries(string symbol_a,string symbol_b,ENUM_TIMEFRAMES tf,int bars,
                                  double &out_a[],double &out_b[]);
   static bool       WaitForHistory(string symbol,ENUM_TIMEFRAMES tf,int bars);
  };

DCCA_MIN_BOX_SIZE and DCCA_MIN_BOXES_PER_SCALE exist because a box fit on too few points, or a scale producing only one or two boxes, is noise dressed up as a number — the engine refuses to compute such a scale rather than return a misleadingly precise coefficient. DCCA_INVALID_RHO is a sentinel outside [-1,1], used wherever a scale couldn't be computed, so a caller that forgets to check it gets an obviously-wrong value, not a silently-wrong one.

Two vectors (m_profile_x, m_profile_y) hold the cumulative profiles built once in SetSeries() and reused by every scale in a Run() call, rather than rebuilt per scale — the profile doesn't change when the box size changes, only how it's chopped up and detrended does.

BuildProfile turns a raw series into the cumulative de-meaned profile the rest of the engine operates on. The de-meaning step runs before the cumulative sum specifically so the profile's own drift isn't an artifact of the series' average level:

//+------------------------------------------------------------------+
//| CDCCAEngine::BuildProfile                                        |
//| Converts one raw series into its cumulative de-meaned profile:   |
//| X(k) = sum_{i=1..k} (x_i - mean(x)). This is the standard DCCA   |
//| profile construction; everything downstream (box detrending,     |
//| fluctuation functions) operates on the profile, never on the raw |
//| series directly.                                                 |
//+------------------------------------------------------------------+

FitLinearBox is the box-level detrending step: an order-1 least-squares fit against a local time index 0..len-1, using the closed-form normal-equation solution rather than a general solver, since the same fixed-degree fit runs thousands of times across every box and every scale in a typical sweep:

//+------------------------------------------------------------------+
//| CDCCAEngine::FitLinearBox                                        |
//| Fits a single order-1 (linear) polynomial to profile[start ..    |
//| start+len-1] by ordinary least squares against a local time      |
//| index t=0..len-1, using the closed-form normal-equation solution |
//| rather than a general solver, and returns the box-local residual |
//| (profile minus the fitted line). A zero-denominator guard        |
//| protects against a degenerate box (len<=1 after a caller         |
//| misuse); in normal use len is always >=DCCA_MIN_BOX_SIZE, so the |
//| guard is never expected to trigger.                              |
//+------------------------------------------------------------------+

void CDCCAEngine::FitLinearBox(const vector &profile,int start,int len,vector &residual)
  {
   residual.Resize(len);
  //--- accumulate the four sums the closed-form OLS normal equations
  //--- need; a general least-squares solver would be overkill for a
  //--- fixed order-1 fit repeated thousands of times across scales
   double sum_t=0.0,sum_t2=0.0,sum_y=0.0,sum_ty=0.0;
   for(int t=0;t<len;t++)
     {
      double y=profile[start+t];
      sum_t+=t;
      sum_t2+=(double)t*t;
      sum_y+=y;
      sum_ty+=t*y;
     }
  //--- denom is zero only if len<=1, which never happens here because
  //--- Run() already enforces DCCA_MIN_BOX_SIZE before calling in; the
  //--- guard exists so a future caller change fails safe, not silently
   double denom=len*sum_t2-sum_t*sum_t;
   double b=(denom!=0.0) ? (len*sum_ty-sum_t*sum_y)/denom : 0.0;
   double a=(sum_y-b*sum_t)/len;
  //--- residual is what is actually measured downstream: the local
  //--- trend itself is discarded once it has done its job here
   for(int t=0;t<len;t++)
      residual[t]=profile[start+t]-(a+b*t);
  }

Only the slope and intercept are used to build the residual — the fitted line itself is discarded once it has done its job. The zero-denominator guard on denom only matters if len<=1, which Run()'s own scale validation already prevents from reaching this function; it stays in as a fail-safe for a future caller rather than a condition expected to fire in normal use.

BoxFluctuations walks both profiles box by box at one fixed scale s, calls FitLinearBox on each box of each series, and accumulates the three running sums the DCCA/DFA formulas need — the cross term for F_DCCA-squared, and the two self terms for F_DFA,x-squared and F_DFA,y-squared:

//+------------------------------------------------------------------+
//| CDCCAEngine::BoxFluctuations                                     |
//| Walks the profiles in non-overlapping boxes of length s,         |
//| starting at index 0, detrends each box in both series via        |
//| FitLinearBox, and accumulates the three sums the DCCA/DFA        |
//| fluctuation functions need: the cross term rx*ry (for            |
//| F_DCCA-squared) and the two self terms rx*rx / ry*ry (for        |
//| F_DFA,x-squared and F_DFA,y-squared). Any trailing points        |
//| shorter than one full box are not included in this scale's       |
//| estimate; this is a direct consequence of the forward-only,      |
//| non-overlapping box layout, not an error path.                   |
//+------------------------------------------------------------------+

void CDCCAEngine::BoxFluctuations(int s,double &f_dcca_sq,double &f_dfa_x_sq,double &f_dfa_y_sq)
  {
   int n_boxes=m_n/s;
   double sum_dcca=0.0,sum_dfa_x=0.0,sum_dfa_y=0.0;
   vector rx,ry;
  //--- boxes are laid out forward from index 0 only; any remainder
  //--- shorter than one full box at the tail is simply not visited by
  //--- this loop, so it never enters the scale-s estimate
   for(int b=0;b<n_boxes;b++)
     {
      int start=b*s;
      FitLinearBox(m_profile_x,start,s,rx);
      FitLinearBox(m_profile_y,start,s,ry);
     //--- the cross term feeds F_DCCA-squared, the two self terms feed
     //--- the individual F_DFA-squared values used to normalize it below
      for(int t=0;t<s;t++)
        {
         sum_dcca+=rx[t]*ry[t];
         sum_dfa_x+=rx[t]*rx[t];
         sum_dfa_y+=ry[t]*ry[t];
        }
     }
  //--- average over every point actually visited, not over m_n, since
  //--- a dropped tail remainder must not dilute the scale-s estimate
   int total_pts=n_boxes*s;
   f_dcca_sq =(total_pts>0) ? sum_dcca/total_pts  : 0.0;
   f_dfa_x_sq=(total_pts>0) ? sum_dfa_x/total_pts : 0.0;
   f_dfa_y_sq=(total_pts>0) ? sum_dfa_y/total_pts : 0.0;
  }

Boxes are laid out forward from index 0 only, so any remainder shorter than one full box at the tail of the series is simply never visited by the loop — it's excluded from the average, not zero-padded into it, which would otherwise quietly bias every scale's estimate toward whatever that partial box happened to contain.

Run ties the box-level computation to a whole scale array, producing the rho_DCCA(s) curve. Each scale is validated and computed independently, so one unusable scale in the caller's array doesn't abort the rest of the sweep — it's marked with the sentinel and the loop moves on:

//+------------------------------------------------------------------+
//| CDCCAEngine::Run                                                 |
//| Runs the full DCCA computation across every scale in the         |
//| supplied scale array, filling rho_out with rho_DCCA(s) for each  |
//| box size: F_DCCA-squared(s) divided by the product of F_DFA,x(s) |
//| and F_DFA,y(s). A scale smaller than DCCA_MIN_BOX_SIZE, larger   |
//| than half the loaded series, or that yields fewer than           |
//| DCCA_MIN_BOXES_PER_SCALE boxes is skipped and logged, with       |
//| DCCA_INVALID_RHO written in its place rather than a fabricated   |
//| number; callers must filter that sentinel out, which             |
//| MeanRhoOverBand already does.                                    |
//+------------------------------------------------------------------+

bool CDCCAEngine::Run(const int &scales[],vector &rho_out)
  {
   if(!m_profiles_built)
     {
      Print("CDCCAEngine::Run refused: call SetSeries with valid data first");
      return false;
     }
   int count=ArraySize(scales);
   rho_out.Resize(count);
  //--- every scale is evaluated independently; one unusable scale (too
  //--- few boxes, out of range) is recorded as DCCA_INVALID_RHO and the
  //--- loop moves on, rather than aborting the whole sweep for one bad
  //--- entry in the caller's scale array
   for(int i=0;i<count;i++)
     {
      int s=scales[i];
      int n_boxes=(s>0) ? m_n/s : 0;
      if(s<DCCA_MIN_BOX_SIZE || s>m_n/2 || n_boxes<DCCA_MIN_BOXES_PER_SCALE)
        {
         PrintFormat("CDCCAEngine::Run: scale s=%d skipped (n_boxes=%d, need>=%d, n=%d)",
                     s,n_boxes,DCCA_MIN_BOXES_PER_SCALE,m_n);
         rho_out[i]=DCCA_INVALID_RHO;
         continue;
        }
      double f_dcca_sq,f_dfa_x_sq,f_dfa_y_sq;
      BoxFluctuations(s,f_dcca_sq,f_dfa_x_sq,f_dfa_y_sq);
     //--- rho_DCCA(s) = F_DCCA^2(s) / (F_DFA,x(s) * F_DFA,y(s)); the
     //--- square roots turn the two variance-squared terms back into
     //--- the fluctuation-function scale the coefficient is defined at
      double denom=MathSqrt(f_dfa_x_sq)*MathSqrt(f_dfa_y_sq);
      rho_out[i]=(denom>0.0) ? f_dcca_sq/denom : DCCA_INVALID_RHO;
     }
   return true;
  }

The normalization at the end — dividing F_DCCA-squared by the square roots of the two F_DFA-squared terms — is what turns the raw fluctuation functions into a coefficient bounded in [-1,1]; the square roots convert the squared quantities computed in BoxFluctuations back onto the same scale the correlation coefficient is defined at.

MeanRhoOverBand is the step that turns a whole curve into the single number the scanner ranks by and the trading EA gates on: the average of rho_DCCA(s) over a caller-chosen scale band, skipping any scale Run marked invalid:

//+------------------------------------------------------------------+
//| CDCCAEngine::MeanRhoOverBand                                     |
//| Averages rho_DCCA(s) over the caller's chosen scale band [s_min, |
//| s_max], skipping any scale that Run() marked invalid. This band  |
//| average, not any single scale's value, is what the pair scanner  |
//| and the spread-trading gate both use as the ranking/gating       |
//| number, since a single scale is one arbitrary point on the       |
//| correlation-vs-scale curve. Returns DCCA_INVALID_RHO if no scale |
//| in the band produced a usable value.                             |
//+------------------------------------------------------------------+

double CDCCAEngine::MeanRhoOverBand(const vector &rho,const int &scales[],int s_min,int s_max)
  {
   double sum=0.0;
   int cnt=0;
   int n=(int)rho.Size();
   for(int i=0;i<n;i++)
     {
      if(scales[i]<s_min || scales[i]>s_max)
         continue;
      if(rho[i]==DCCA_INVALID_RHO)
         continue;
      sum+=rho[i];
      cnt++;
     }
   return (cnt>0) ? sum/cnt : DCCA_INVALID_RHO;
  }

A single scale is one arbitrary point on the correlation-vs-scale curve; averaging over a band is a deliberate choice to use a range of horizons rather than picking one and hoping it's the right one for the pair in question.

WaitForHistory exists because of how MQL5's terminal actually behaves, not as a defensive guess. SymbolSelect(symbol, true) only adds a symbol to Market Watch — it doesn't wait for the terminal to download the symbol's history. A symbol already open on a chart has its history ready immediately, but one added moments earlier by a script or EA can make the first CopyRates call come back short or empty, because the download is still running when the call fires.

A basket scan over a pair whose second leg has never been opened on a chart reads zero usable bars for that pair; a pair whose history sync is still in progress reads a short, partial series instead of the full requested count. WaitForHistory polls the actual synchronization state and bar count every 100ms until both are ready or DCCA_HISTORY_WAIT_MS expires:

//+------------------------------------------------------------------+
//| CDCCAEngine::WaitForHistory                                      |
//| SymbolSelect(symbol,true) only adds a symbol to Market Watch; it |
//| does not block until the terminal has actually downloaded that   |
//| symbol's price history, so a symbol added moments ago (rather    |
//| than already open on a chart) can make CopyRates come back short |
//| or empty on the very first call. This polls SERIES_SYNCHRONIZED  |
//| together with the actually-available bar count every 100ms for   |
//| up to DCCA_HISTORY_WAIT_MS, and returns false (logged by the     |
//| caller) if history is still not ready when the wait expires, so  |
//| a short read is a visible, explained outcome rather than a       |
//| silent one.                                                      |
//+------------------------------------------------------------------+

bool CDCCAEngine::WaitForHistory(string symbol,ENUM_TIMEFRAMES tf,int bars)
  {
   ulong start=GetTickCount64();
   while(GetTickCount64()-start<DCCA_HISTORY_WAIT_MS)
     {
      bool synced   =SeriesInfoInteger(symbol,tf,SERIES_SYNCHRONIZED);
      int  available=(int)SeriesInfoInteger(symbol,tf,SERIES_BARS_COUNT);
      if(synced && available>=bars)
         return true;
      Sleep(100);
     }
   return false;
  }

This matters specifically for live/demo chart use — the Strategy Tester has its own, separately-synchronized history cache and Sleep() is effectively a no-op inside it, so WaitForHistory changes behavior for the scanner and for a freshly-attached trading EA, not for a backtest.

AlignSeries is the shared fetch-and-align step both EAs call: it calls WaitForHistory on each symbol, then fetches each leg's closed bars via CopyRates with start_pos=1, not 0 — position 0 is the currently forming bar, which keeps changing, and feeding that moving target into the engine would make every reading jitter with whatever fraction of the bar has printed. The two rate arrays are then merged by bar open time (two-pointer merge), not raw index:

//+------------------------------------------------------------------+
//| CDCCAEngine::AlignSeries                                         |
//| Shared static helper used by both the pair scanner and the       |
//| spread-trading EA: waits for each symbol's history to            |
//| synchronize via WaitForHistory, fetches 'bars' closed bars of    |
//| each symbol on timeframe tf via CopyRates (which always returns  |
//| oldest-bar-first regardless of the chart's series flag), then    |
//| two-pointer-merges the two rate arrays on matching bar open time |
//| so symbols with different session calendars (for example a metal |
//| against a Tokyo-session FX cross) do not get silently misaligned |
//| by raw index. Returns false, with the reason logged, if either   |
//| symbol cannot supply enough bars or fewer than                   |
//| DCCA_MIN_BOX_SIZE*2 bars survive the alignment.                  |
//+------------------------------------------------------------------+

bool CDCCAEngine::AlignSeries(string symbol_a,string symbol_b,ENUM_TIMEFRAMES tf,int bars,
                               double &out_a[],double &out_b[])
  {
  //--- a symbol just added via SymbolSelect may not have its history
  //--- downloaded yet; proceeding straight to CopyRates in that case
  //--- is exactly what produced the 0-bar / short-bar reads this guard
  //--- exists to prevent
   if(!WaitForHistory(symbol_a,tf,bars))
      PrintFormat("CDCCAEngine::AlignSeries: %s history not fully synchronized after %dms wait, proceeding with what is available",
                  symbol_a,DCCA_HISTORY_WAIT_MS);
   if(!WaitForHistory(symbol_b,tf,bars))
      PrintFormat("CDCCAEngine::AlignSeries: %s history not fully synchronized after %dms wait, proceeding with what is available",
                  symbol_b,DCCA_HISTORY_WAIT_MS);
  //--- start_pos=1, not 0: position 0 in CopyRates is the currently
  //--- forming bar, which keeps changing mid-bar and would make the
  //--- DCCA reading jitter as it fills in; position 1 is the last
  //--- fully closed bar, which is what "closed bars" below means
   MqlRates rates_a[],rates_b[];
   int na=CopyRates(symbol_a,tf,1,bars,rates_a);
   int nb=CopyRates(symbol_b,tf,1,bars,rates_b);
   if(na<DCCA_MIN_BOX_SIZE*2 || nb<DCCA_MIN_BOX_SIZE*2)
     {
      PrintFormat("CDCCAEngine::AlignSeries: insufficient bars for %s/%s (%d/%d of %d requested)",
                  symbol_a,symbol_b,na,nb,bars);
      return false;
     }
  //--- na/nb can still be below 'bars' even after passing the minimum-
  //--- box-size check above; a caller that assumes every run used the
  //--- full requested window would be wrong, so the actual counts are
  //--- logged here rather than only at the final aligned-bar check
   if(na<bars || nb<bars)
      PrintFormat("CDCCAEngine::AlignSeries: %s/%s returned fewer bars than requested (%d/%d of %d), results below use the shorter window",
                  symbol_a,symbol_b,na,nb,bars);
   double tmp_a[],tmp_b[];
   ArrayResize(tmp_a,0);
   ArrayResize(tmp_b,0);
  //--- two-pointer merge on bar open time rather than raw index: two
  //--- symbols on the same timeframe can still miss different bars
  //--- (holidays, differing session calendars), so matching by index
  //--- alone would silently pair the wrong bars together
   int ia=0,ib=0;
   while(ia<na && ib<nb)
     {
      if(rates_a[ia].time==rates_b[ib].time)
        {
         int sz=ArraySize(tmp_a);
         ArrayResize(tmp_a,sz+1);
         ArrayResize(tmp_b,sz+1);
         tmp_a[sz]=rates_a[ia].close;
         tmp_b[sz]=rates_b[ib].close;
         ia++;
         ib++;
        }
      else if(rates_a[ia].time<rates_b[ib].time)
         ia++;
      else
         ib++;
     }
   if(ArraySize(tmp_a)<DCCA_MIN_BOX_SIZE*2)
     {
      PrintFormat("CDCCAEngine::AlignSeries: only %d time-aligned bars for %s/%s, below minimum",
                  ArraySize(tmp_a),symbol_a,symbol_b);
      return false;
     }
   ArrayCopy(out_a,tmp_a);
   ArrayCopy(out_b,tmp_b);
   return true;
  }

Matching by open time, not index, matters because two symbols on the same nominal timeframe don't necessarily produce the same bar count over the same wall-clock window — different session calendars (a metal against a Tokyo-session FX cross) can mean one symbol has a bar the other doesn't. Merging on index alone would silently pair the wrong bars together, feeding the engine a corrupted alignment with no error raised anywhere.


PairRanker.mqh — Basket Scanning and Comparison

This file adds a basket-ranking layer on top of the engine: given a list of candidate pairs, score every one of them by both DCCA band mean and plain Pearson correlation, then sort by DCCA descending. Two small structs carry the configuration and the scored result:

//+------------------------------------------------------------------+
//| SPairDef / SPairResult                                           |
//| Plain data structures: SPairDef is one candidate pair as         |
//| configured by the caller; SPairResult is that pair's scored      |
//| outcome after a scan, holding both the DCCA band-mean            |
//| coefficient and the whole-window Pearson coefficient so the two  |
//| can be compared side by side.                                    |
//+------------------------------------------------------------------+

struct SPairDef
  {
   string            symbol_a;
   string            symbol_b;
  };

struct SPairResult
  {
   string            symbol_a;
   string            symbol_b;
   double            dcca_mean;      // mean rho_DCCA(s) over the configured scale band
   double            pearson;       // whole-window Pearson correlation, for comparison
   int              aligned_bars; // actual time-aligned bars AlignSeries returned
  };

The class declaration again collapses to one header box, with the private member list and method list left as plain block comments inside it:

//+------------------------------------------------------------------+
//| CPairRanker                                                      |
//| Scans a configured basket of candidate pairs, running            |
//| CDCCAEngine on each one's time-aligned close-price series and    |
//| recording both its DCCA band-mean correlation and a plain        |
//| Pearson correlation computed over the same window, then sorts    |
//| the basket by DCCA band-mean descending. This class only scores  |
//| and ranks; it places no trades and reads no open positions.      |
//+------------------------------------------------------------------+

class CPairRanker
  {
private:
   //--- configured basket and scan parameters
   SPairDef          m_pairs[];
   SPairResult       m_results[];
   int               m_scales[];
   int               m_s_min;
   int               m_s_max;
   int               m_lookback;
   ENUM_TIMEFRAMES   m_tf;

   //--- internal steps, implemented out of line below
   double            PearsonCorrelation(const double &x[],const double &y[]);
   void              SortResultsDescending(void);

public:
                     CPairRanker(void);
                    ~CPairRanker(void);
   void              Configure(const int &scales[],int s_min,int s_max,int lookback,ENUM_TIMEFRAMES tf);
   void              AddPair(string symbol_a,string symbol_b);
   bool              RankAll(void);
   int               ResultCount(void);
   bool              GetResult(int index,SPairResult &out);
   bool              WriteCsv(string filename);
  };

PearsonCorrelation is the deliberate point of comparison the whole article is built around: a plain, whole-window Pearson coefficient computed natively, with no scale-awareness and no detrending — exactly the usual stationary-moments assumption DCCA is built to avoid making:

//+------------------------------------------------------------------+
//| CPairRanker::PearsonCorrelation                                  |
//| Plain whole-window Pearson correlation coefficient between two   |
//| equal-length arrays, computed natively (no ALGLIB). This is the  |
//| article's point of comparison against the DCCA band mean: a      |
//| single-scale-blind number that assumes the usual                 |
//| stationary-moments picture, which is exactly the assumption DCCA |
//| does not need to make.                                           |
//+------------------------------------------------------------------+

double CPairRanker::PearsonCorrelation(const double &x[],const double &y[])
  {
   int n=ArraySize(x);
   if(n<2 || ArraySize(y)!=n)
      return DCCA_INVALID_RHO;
  //--- plain two-pass computation: mean first, then covariance/variance
  //--- against that mean, rather than a one-pass sum-of-products form,
  //--- which loses precision on long, large-magnitude price series
   double mean_x=0.0,mean_y=0.0;
   for(int i=0;i<n;i++)
     {
      mean_x+=x[i];
      mean_y+=y[i];
     }
   mean_x/=n;
   mean_y/=n;
   double cov=0.0,var_x=0.0,var_y=0.0;
   for(int i=0;i<n;i++)
     {
      double dx=x[i]-mean_x;
      double dy=y[i]-mean_y;
      cov  +=dx*dy;
      var_x+=dx*dx;
      var_y+=dy*dy;
     }
   double denom=MathSqrt(var_x)*MathSqrt(var_y);
   return (denom>0.0) ? cov/denom : DCCA_INVALID_RHO;
  }

A two-pass computation — mean first, then covariance/variance against that mean — is used instead of a one-pass sum-of-products form, which loses precision on long series of large-magnitude prices like XAUUSD's.

RankAll is the actual scan: for every configured pair, fetch and align via AlignSeries, run a fresh CDCCAEngine over the scale array, and compute both the DCCA band mean and the comparison Pearson coefficient on the same aligned data. A pair that fails alignment, fails the scale sweep, or returns no usable scale in the requested band is skipped rather than inserted with a sentinel score — the band-mean helper's "no usable scale" return is checked explicitly, not assumed filtered upstream:

//+------------------------------------------------------------------+
//| CPairRanker::RankAll                                             |
//| Runs the full basket: for each configured pair, fetches          |
//| time-aligned close series via CDCCAEngine::AlignSeries, runs a   |
//| fresh CDCCAEngine over the scale array, averages rho_DCCA(s)     |
//| over [m_s_min, m_s_max], computes the comparison Pearson         |
//| coefficient on the same aligned data, and appends the scored     |
//| result. A pair that fails alignment or produces no usable scale  |
//| is skipped (logged by AlignSeries/Run) rather than inserted with |
//| a fabricated score. Results are sorted descending by DCCA band   |
//| mean before returning.                                           |
//+------------------------------------------------------------------+

bool CPairRanker::RankAll(void)
  {
   int n=ArraySize(m_pairs);
   if(n==0)
     {
      Print("CPairRanker::RankAll: no pairs configured, nothing to rank");
      return false;
     }
   ArrayResize(m_results,0);
  //--- one pair failing alignment or the scale sweep is skipped and
  //--- logged (inside AlignSeries/Run), not treated as a reason to
  //--- abort scoring the rest of the basket
   for(int i=0;i<n;i++)
     {
      double series_a[],series_b[];
      if(!CDCCAEngine::AlignSeries(m_pairs[i].symbol_a,m_pairs[i].symbol_b,m_tf,m_lookback,series_a,series_b))
         continue;
      CDCCAEngine engine;
      if(!engine.SetSeries(series_a,series_b))
         continue;
      vector rho;
      if(!engine.Run(m_scales,rho))
         continue;
      double mean_rho=engine.MeanRhoOverBand(rho,m_scales,m_s_min,m_s_max);
     //--- MeanRhoOverBand returns DCCA_INVALID_RHO when none of the
     //--- requested scales had enough valid boxes inside [s_min,s_max];
     //--- without this check that sentinel would be inserted as if it
     //--- were a real score, contradicting the "skipped, not fabricated"
     //--- guarantee this function documents above
      if(mean_rho==DCCA_INVALID_RHO)
         continue;
      double pearson=PearsonCorrelation(series_a,series_b);
      int sz=ArraySize(m_results);
      ArrayResize(m_results,sz+1);
      m_results[sz].symbol_a   =m_pairs[i].symbol_a;
      m_results[sz].symbol_b   =m_pairs[i].symbol_b;
      m_results[sz].dcca_mean =mean_rho;
      m_results[sz].pearson    =pearson;
      //--- the actual aligned-bar count, not just the requested lookback,
      //--- travels with the result so a published number can be traced
      //--- back to how much history it actually came from
      m_results[sz].aligned_bars=ArraySize(series_a);
     }
   SortResultsDescending();
   return ArraySize(m_results)>0;
  }

WriteCsv persists the ranked table to MQL5\Files using MQL5's default UTF-16 CSV encoding — a downstream Python reader needs encoding="utf-16" to read it back, the same convention used for every CSV export here. Each row also carries AlignedBars, the real number of time-aligned bars that score was computed from, since requested lookback and the actual window AlignSeries returned aren't always equal — a published result should be traceable to the run that happened, not the one asked for:

//+------------------------------------------------------------------+
//| CPairRanker::WriteCsv                                            |
//| Writes the current ranked result list to a CSV file under        |
//| MQL5\Files, one row per pair, in rank order. Uses MQL5's default |
//| UTF-16 CSV encoding (FILE_CSV without FILE_ANSI); a downstream   |
//| Python reader should open it with encoding="utf-16" to match,    |
//| per this project's standing CSV convention. Logs and returns     |
//| false if the file cannot be opened, instead of silently          |
//| discarding the scan results.                                     |
//+------------------------------------------------------------------+

bool CPairRanker::WriteCsv(string filename)
  {
  //--- FILE_CSV without FILE_ANSI writes UTF-16, MQL5's default for
  //--- this flag combination; a downstream Python reader must open
  //--- with encoding="utf-16" or every field comes back garbled
   int handle=FileOpen(filename,FILE_WRITE|FILE_CSV,',');
   if(handle==INVALID_HANDLE)
     {
      PrintFormat("CPairRanker::WriteCsv: FileOpen failed for %s, error %d",filename,GetLastError());
      return false;
     }
   FileWrite(handle,"SymbolA","SymbolB","DCCA_Mean","Pearson","AlignedBars");
   for(int i=0;i<ArraySize(m_results);i++)
      FileWrite(handle,m_results[i].symbol_a,m_results[i].symbol_b,
                DoubleToString(m_results[i].dcca_mean,5),
                DoubleToString(m_results[i].pearson,5),
                m_results[i].aligned_bars);
   FileClose(handle);
   return true;
  }


DCCA_PairScanner_EA.mq5 — Scheduling the Scan

This EA places no trades. It's a scheduler and a reporter wrapped around CPairRanker: parse a configured basket, run it on a timer, write the ranked CSV, and print the top results to the log. The basket and scale sweep are both configurable as plain inputs:

input group "=== Basket ==="
input string InpBasket             ="XAUUSD:XAGUSD,EURUSD:GBPUSD,USDJPY:AUDJPY"; // Pairs, SymbolA:SymbolB comma-separated
input ENUM_TIMEFRAMES InpTimeframe =PERIOD_M15;                                  // Timeframe each pair is fetched on
input int InpLookbackBars          =1000;                                        // Bars fetched per symbol before alignment

input group "=== DCCA scale sweep ==="
input int InpScaleMin  =10;  // Smallest box size s in the sweep
input int InpScaleMax  =200; // Largest box size s in the sweep
input int InpScaleStep =10;  // Step between successive box sizes
input int InpBandMin   =20;  // Lower bound of the scale band averaged for ranking
input int InpBandMax   =100; // Upper bound of the scale band averaged for ranking

input group "=== Scheduling and output ==="
input int InpScanIntervalSec =3600;                   // Seconds between rescans
input string InpCsvFilename  ="DCCA_PairRanking.csv"; // Output file under MQL5\Files

BuildScaleArray expands the three scale-sweep inputs into the concrete array CPairRanker.Configure needs, refusing a non-positive step or an inverted range outright instead of silently producing an empty sweep:

//+------------------------------------------------------------------+
//| BuildScaleArray                                                  |
//| Expands InpScaleMin/Max/Step into the concrete scale array       |
//| CPairRanker.Configure needs. Logs and returns false if the step  |
//| is non-positive or the range is empty, rather than silently      |
//| producing a zero-length sweep that would make every later Run()  |
//| call a no-op.                                                    |
//+------------------------------------------------------------------+

bool BuildScaleArray(int &scales[])
  {
   if(InpScaleStep<=0 || InpScaleMax<InpScaleMin)
     {
      PrintFormat("DCCA Scanner: bad scale range (min=%d max=%d step=%d)",
                  InpScaleMin,InpScaleMax,InpScaleStep);
      return false;
     }
   ArrayResize(scales,0);
   for(int s=InpScaleMin;s<=InpScaleMax;s+=InpScaleStep)
     {
      int sz=ArraySize(scales);
      ArrayResize(scales,sz+1);
      scales[sz]=s;
     }
   return ArraySize(scales)>0;
  }

ParseBasket splits the comma-separated InpBasket string on commas and then each entry on its colon, feeding valid SymbolA:SymbolB pairs into the ranker. A malformed entry or a symbol that SymbolSelect can't find in Market Watch is logged and skipped rather than aborting the whole basket parse:

//+------------------------------------------------------------------+
//| ParseBasket                                                      |
//| Splits InpBasket on commas, then each entry on its colon,        |
//| feeding valid SymbolA:SymbolB entries into the ranker via        |
//| AddPair. An entry missing a colon, or naming a symbol not        |
//| present in Market Watch, is logged and skipped rather than       |
//| aborting the whole basket.                                       |
//+------------------------------------------------------------------+

void ParseBasket(string basket)
  {
   string pairs[];
   int n=StringSplit(basket,',',pairs);
   for(int i=0;i<n;i++)
     {
      string one=pairs[i];
      StringTrimLeft(one);
      StringTrimRight(one);
      string sides[];
      int parts_n=StringSplit(one,':',sides);
      if(parts_n!=2)
        {
         PrintFormat("DCCA Scanner: skipping malformed basket entry '%s' (expected SymbolA:SymbolB)",one);
         continue;
        }
      string sym_a=sides[0];
      string sym_b=sides[1];
      if(!SymbolSelect(sym_a,true) || !SymbolSelect(sym_b,true))
        {
         PrintFormat("DCCA Scanner: skipping '%s:%s', one symbol not available in Market Watch",sym_a,sym_b);
         continue;
        }
      g_ranker.AddPair(sym_a,sym_b);
     }
  }

RunScanAndReport is the single path both the initial scan and every timer-driven rescan go through, so there's exactly one place that defines what "a scan" means:

//+------------------------------------------------------------------+
//| RunScanAndReport                                                 |
//| Runs CPairRanker.RankAll over the configured basket, writes the  |
//| full ranked table to InpCsvFilename, and prints the top three    |
//| results (or fewer, if the basket is smaller) to the Experts log  |
//| so the ranking is visible without opening the file. Returns the  |
//| same boolean RankAll returned.                                   |
//+------------------------------------------------------------------+

bool RunScanAndReport(void)
  {
   if(!g_ranker.RankAll())
     {
      Print("DCCA Scanner: RankAll produced no usable results this cycle");
      return false;
     }
   g_ranker.WriteCsv(InpCsvFilename);
  //--- the scale sweep is basket-wide, not per-pair, so it is logged
  //--- once here rather than repeated on every ranked row; this is
  //--- the exact array every pair in this scan was actually run over
   string scales_str="";
   for(int s=0;s<ArraySize(g_scales);s++)
      scales_str+=(s>0?",":"")+IntegerToString(g_scales[s]);
   int shown=MathMin(3,g_ranker.ResultCount());
   PrintFormat("DCCA Scanner: ranked %d pair(s) over scales [%s], band [%d,%d], top %d:",
                g_ranker.ResultCount(),scales_str,InpBandMin,InpBandMax,shown);
   for(int i=0;i<shown;i++)
     {
      SPairResult r;
      g_ranker.GetResult(i,r);
      PrintFormat("  #%d %s/%s  DCCA_mean=%.4f  Pearson=%.4f  aligned_bars=%d",
                  i+1,r.symbol_a,r.symbol_b,r.dcca_mean,r.pearson,r.aligned_bars);
     }
   return true;
  }

OnInit builds the scale array, configures the ranker, parses the basket, and runs one scan immediately rather than waiting for the first timer fire — so the CSV exists the moment the EA attaches, not up to InpScanIntervalSec seconds later. That first scan's return value is checked, not discarded: a basket that parses to zero pairs, or produces none that survive alignment and the scale sweep, fails initialization outright rather than starting a rescan timer with nothing to scan:

//+------------------------------------------------------------------+
//| OnInit                                                           |
//| Builds the scale array, configures the ranker, parses the        |
//| basket, runs one scan immediately so the CSV exists before the   |
//| first timer fire, and starts the rescan timer. Fails             |
//| initialization if the scale array cannot be built or the basket  |
//| yields zero usable pairs, rather than starting a timer that      |
//| would have nothing to scan.                                      |
//+------------------------------------------------------------------+

int OnInit(void)
  {
   int scales[];
   if(!BuildScaleArray(scales))
      return(INIT_PARAMETERS_INCORRECT);
   ArrayCopy(g_scales,scales);
   g_ranker.Configure(g_scales,InpBandMin,InpBandMax,InpLookbackBars,InpTimeframe);
   ParseBasket(InpBasket);
  //--- scan once immediately so InpCsvFilename exists before the first
  //--- timer fire, rather than leaving the user with no file for up to
  //--- InpScanIntervalSec seconds after attaching the EA; its return
  //--- value is checked below, not discarded, so a basket that parses
  //--- to zero pairs or produces zero usable results actually fails
  //--- initialization instead of silently starting a timer with
  //--- nothing to scan
   if(!RunScanAndReport())
      return(INIT_FAILED);
   EventSetTimer(InpScanIntervalSec);
   return(INIT_SUCCEEDED);
  }


DCCA_SpreadTrading_EA.mq5 — Trading the Spread

This EA trades one pair chosen by the user from the scanner's ranked output — it does not read the ranked CSV itself, the two symbols are plain inputs. Four input groups separate the pair, the DCCA gate, the spread model, and trade management:

input group "=== Pair ==="
input string InpSymbolA            ="XAUUSD";   // First leg
input string InpSymbolB            ="XAGUSD";   // Second leg
input ENUM_TIMEFRAMES InpTimeframe =PERIOD_M15; // Bar timeframe for hedge ratio, spread and new-bar checks

input group "=== DCCA gate ==="
input int InpGateLookbackBars =1000; // Bars fetched per symbol for the gate
input int InpScaleMin         =10;   // Smallest box size s in the sweep
input int InpScaleMax         =200;  // Largest box size s in the sweep
input int InpScaleStep        =10;   // Step between successive box sizes
input int InpBandMin          =20;   // Lower bound of the scale band averaged for the gate
input int InpBandMax          =100;  // Upper bound of the scale band averaged for the gate
input double InpMinDccaGate   =0.30; // Minimum band-mean rho_DCCA required to open a new position

input group "=== Spread model ==="
input int InpHedgeLookback =250; // Bars used to fit the OLS hedge ratio beta
input int InpZLookback     =100; // Bars used for the spread mean and standard deviation
input double InpEntryZ     =2.0; // Absolute z-score that opens a new spread position
input double InpExitZ      =0.5; // Absolute z-score below which an open position is closed

input group "=== Trade management ==="
input double InpLotsA =0.10;   // Fixed lot size for the SymbolA leg
input int InpMagic    =778800; // Magic number for this EA's positions
input int InpSlippage =20;     // Maximum allowed slippage, in points

FitHedgeRatio is an ordinary least-squares slope of SymbolB's close on SymbolA's close over InpHedgeLookback bars — the spread is defined as closeB - beta*closeA, with no separate intercept term. This is stated plainly rather than implied: it's an OLS hedge ratio, not a cointegration test, so a genuine long-run equilibrium relationship between the two legs is assumed by this EA's design, not independently verified by it:

//+------------------------------------------------------------------+
//| FitHedgeRatio                                                    |
//| Ordinary least squares slope of SymbolB's close on SymbolA's     |
//| close over InpHedgeLookback time-aligned bars: beta minimizes    |
//| sum((closeB - (alpha + beta*closeA))^2). Only beta is kept; the  |
//| spread is defined as closeB - beta*closeA, with no separate      |
//| intercept term, which is the standard minimal spread             |
//| construction and is restated plainly here rather than implied:   |
//| this is an OLS hedge ratio, not a cointegration test, so a       |
//| statistically significant long-run relationship is assumed by    |
//| the EA's design, not verified by it.                             |
//+------------------------------------------------------------------+

bool FitHedgeRatio(double &beta)
  {
   double series_a[],series_b[];
   if(!CDCCAEngine::AlignSeries(InpSymbolA,InpSymbolB,InpTimeframe,InpHedgeLookback,series_a,series_b))
      return false;
   int n=ArraySize(series_a);
  //--- closed-form OLS slope: beta = (n*sum(ab) - sum(a)*sum(b)) /
  //--- (n*sum(aa) - sum(a)^2); only the slope is used downstream, so
  //--- the intercept term is never separately computed or stored
   double sum_a=0.0,sum_b=0.0,sum_ab=0.0,sum_aa=0.0;
   for(int i=0;i<n;i++)
     {
      sum_a +=series_a[i];
      sum_b +=series_b[i];
      sum_ab+=series_a[i]*series_b[i];
      sum_aa+=series_a[i]*series_a[i];
     }
   double denom=n*sum_aa-sum_a*sum_a;
   if(denom==0.0)
     {
      Print("DCCA SpreadTrading: hedge-ratio fit degenerate (zero variance in SymbolA window)");
      return false;
     }
   beta=(n*sum_ab-sum_a*sum_b)/denom;
   return true;
  }

UpdateSpreadStats refits beta, then builds the spread series over the shorter InpZLookback window and recomputes its mean, standard deviation, and current z-score from that window fresh on every single call. Beta from the longer lookback is deliberately applied across the shorter window rather than refit on it — beta is the one value this function does not recompute from InpZLookback; the mean and standard deviation are:

//+------------------------------------------------------------------+
//| UpdateSpreadStats                                                |
//| Refits beta via FitHedgeRatio, then builds the spread series     |
//| closeB[i] - beta*closeA[i] over the shorter InpZLookback window, |
//| and recomputes its mean, standard deviation and current z-score  |
//| from that window fresh on every call. g_have_spread is left      |
//| false if either the hedge fit or the alignment for the z-score   |
//| window fails, or if the window's standard deviation is zero (a   |
//| flat spread, which would make the z-score undefined rather than  |
//| merely large).                                                   |
//+------------------------------------------------------------------+

void UpdateSpreadStats(void)
  {
   g_have_spread=false;
   double beta;
   if(!FitHedgeRatio(beta))
      return;
   double series_a[],series_b[];
   if(!CDCCAEngine::AlignSeries(InpSymbolA,InpSymbolB,InpTimeframe,InpZLookback,series_a,series_b))
      return;
   int n=ArraySize(series_a);
  //--- beta comes from the longer InpHedgeLookback fit and is not
  //--- refitted here; the spread's mean and standard deviation below
  //--- ARE recomputed from scratch over the InpZLookback window on
  //--- every single call, so only beta carries over between calls,
  //--- not the mean/stdev
   double spread[];
   ArrayResize(spread,n);
   double sum=0.0;
   for(int i=0;i<n;i++)
     {
      spread[i]=series_b[i]-beta*series_a[i];
      sum+=spread[i];
     }
   double mean=sum/n;
   double sq=0.0;
   for(int i=0;i<n;i++)
      sq+=(spread[i]-mean)*(spread[i]-mean);
   double std=MathSqrt(sq/n);
   if(std==0.0)
     {
      Print("DCCA SpreadTrading: spread window has zero standard deviation, z-score undefined");
      return;
     }
  //--- only the most recent bar's z-score drives trading decisions;
  //--- the rest of the window exists solely to define the mean/stdev
   g_beta        =beta;
   g_spread_mean =mean;
   g_spread_std  =std;
   g_z           =(spread[n-1]-mean)/std;
   g_have_spread =true;
  }

OpenSpread sizes the second leg by abs(beta) — rounded to that symbol's volume step and floored at its minimum, so a beta far from 1.0 doesn't silently round to zero lots on a coarse-step instrument — then places both legs in the fixed direction that fades the spread toward its mean. That direction only makes sense when beta is positive, which a pair clearing the gate normally has; a non-positive beta needs the mirror-image direction, so OpenSpread checks for it and refuses the trade.

The sizing is a lot-count hedge, not a full price-value hedge — it tracks the OLS relationship between the two closes, not contract size, tick value, currency conversion, or volatility. The two legs are sent one after another, not atomically, so the function checks whether the first leg filled before sending the second, and closes it again if the second fails rather than leaving a one-sided position open — that close attempt isn't guaranteed either, which is why CloseSpread checks the result:

LegConfirmed is what OpenSpread actually relies on to know a leg went through: CTrade::Buy/Sell returning true only means the request was sent, not that it was filled, so this checks the trade result's own retcode for a completed (or partially completed) deal and confirms a live position exists for that symbol before the rest of the function treats the leg as real:

//+------------------------------------------------------------------+
//| LegConfirmed                                                     |
//| Treats a leg as actually filled only when five things all hold:  |
//| the most recent CTrade result reports a completed or partially   |
//| completed deal (not just a successfully sent request), that      |
//| deal has a nonzero deal ticket, the filled volume is not short   |
//| of what was actually requested (a partial fill would leave       |
//| this leg smaller than the hedge ratio sized it for), a live      |
//| position exists for the given symbol, and that position          |
//| belongs to this EA's own magic number rather than a              |
//| pre-existing or another strategy's position on the same symbol.  |
//+------------------------------------------------------------------+

bool LegConfirmed(string symbol,double requested_volume)
  {
   ulong retcode=g_trade.ResultRetcode();
  //--- a sent-but-not-filled request (requote, partial reject, no
  //--- quotes) still returns true from Buy/Sell on some brokers; only
  //--- TRADE_RETCODE_DONE / DONE_PARTIAL mean a deal actually happened
   if(retcode!=TRADE_RETCODE_DONE && retcode!=TRADE_RETCODE_DONE_PARTIAL)
      return(false);
  //--- a DONE retcode can still carry a zero deal ticket on some
  //--- broker/terminal combinations; ResultDeal()==0 means no deal
  //--- was actually recorded, whatever the retcode claims
   if(g_trade.ResultDeal()==0)
      return(false);
  //--- TRADE_RETCODE_DONE_PARTIAL means the broker filled less than
  //--- requested; a short fill here would leave this leg smaller than
  //--- the hedge ratio sized it for, so it is treated as unconfirmed
  //--- rather than accepted at a mismatched size. Half a volume step
  //--- of tolerance only covers floating-point rounding
   double step=SymbolInfoDouble(symbol,SYMBOL_VOLUME_STEP);
   if(g_trade.ResultVolume()<requested_volume-step/2.0)
      return(false);
  //--- PositionSelect alone would also return true for a pre-existing
  //--- position on this symbol that has nothing to do with this leg
  //--- (a manual position, or another EA's), so the magic number is
  //--- checked too, confirming the position is actually this EA's own
   if(!PositionSelect(symbol))
      return(false);
   return(PositionGetInteger(POSITION_MAGIC)==InpMagic);
  }

HasOpenPosition and CloseSpread are the two helpers OpenSpread and ManagePositions lean on: HasOpenPosition tells ManagePositions whether the EA holds a spread, and CloseSpread attempts to unwind it — a clean two-leg exit, or the one-sided position left when a second leg never confirms (covered under LegConfirmed/OpenSpread). As with LegConfirmed, a true CTrade return is only a sent request, so CloseSpread checks ResultRetcode() rather than trusting PositionClose()'s own return value:

//+------------------------------------------------------------------+
//| HasOpenPosition                                                  |
//| True once a position tied to this EA's own magic number exists   |
//| on either leg. Checking both symbols (not just InpSymbolA)       |
//| matters here: a second leg that failed to confirm (see           |
//| LegConfirmed/OpenSpread) can leave a one-sided position open on  |
//| just one of the two symbols, and ManagePositions still needs to  |
//| see that as "a position is open" so it gets closed on the next   |
//| mean-reversion exit rather than ignored.                         |
//+------------------------------------------------------------------+

bool HasOpenPosition(void)
  {
   if(PositionSelect(InpSymbolA) && PositionGetInteger(POSITION_MAGIC)==InpMagic)
      return(true);
   if(PositionSelect(InpSymbolB) && PositionGetInteger(POSITION_MAGIC)==InpMagic)
      return(true);
   return(false);
  }
//+------------------------------------------------------------------+
//| CloseSpread                                                      |
//| Closes whichever leg(s) this EA actually holds right now,        |
//| rather than assuming both are open: OpenSpread calls this when   |
//| the second leg fails to confirm, and at that point only the      |
//| first leg exists. Each symbol is checked with PositionSelect     |
//| plus the magic number before a close is attempted, so calling    |
//| this when only one leg is open -- or when neither is -- never    |
//| errors on the symbol that has nothing to close. A true return    |
//| from PositionClose only means the close request was sent, not    |
//| that the position is actually gone, so ResultRetcode() is        |
//| checked the same way LegConfirmed checks it for opening a leg    |
//| -- this function attempts the close, it does not guarantee it.   |
//+------------------------------------------------------------------+

void CloseSpread(void)
  {
   if(PositionSelect(InpSymbolA) && PositionGetInteger(POSITION_MAGIC)==InpMagic)
      {
       g_trade.PositionClose(InpSymbolA);
       if(g_trade.ResultRetcode()!=TRADE_RETCODE_DONE && g_trade.ResultRetcode()!=TRADE_RETCODE_DONE_PARTIAL)
          PrintFormat("DCCA SpreadTrading: failed to close %s position (retcode=%d)",
                    InpSymbolA,g_trade.ResultRetcode());
      }
   if(PositionSelect(InpSymbolB) && PositionGetInteger(POSITION_MAGIC)==InpMagic)
      {
       g_trade.PositionClose(InpSymbolB);
       if(g_trade.ResultRetcode()!=TRADE_RETCODE_DONE && g_trade.ResultRetcode()!=TRADE_RETCODE_DONE_PARTIAL)
          PrintFormat("DCCA SpreadTrading: failed to close %s position (retcode=%d)",
                    InpSymbolB,g_trade.ResultRetcode());
      }
  }
//+------------------------------------------------------------------+
//| OpenSpread                                                       |
//| Opens both legs of the spread trade. 'long_spread' true means    |
//| the spread (closeB - beta*closeA) is below its band and expected |
//| to rise: buy SymbolB, sell SymbolA; false is the mirror image.   |
//| This fixed direction assumes beta is positive, which is the      |
//| normal case for a pair that cleared the positive-rho_DCCA gate;  |
//| OpenSpread refuses the trade rather than guessing a direction    |
//| when beta is not positive (see the guard below). SymbolB's lot   |
//| size is abs(beta)*InpLotsA, normalized to that symbol's own      |
//| volume step and clamped to its minimum, so a beta far from 1.0   |
//| does not silently round to zero lots on an instrument with a     |
//| coarse volume step.                                              |
//+------------------------------------------------------------------+

void OpenSpread(bool long_spread)
  {
  //--- a negative beta means the two legs move opposite each other,
  //--- which needs the mirror-image direction (both legs same side)
  //--- rather than the long/short pair coded below; rather than
  //--- silently trading the wrong direction, refuse and log instead
   if(g_beta<=0.0)
     {
      Print("DCCA SpreadTrading: beta is not positive, skipping entry (fixed-direction sizing below assumes beta>0)");
      return;
     }
  //--- SymbolB's lot size tracks abs(beta) so the position scales with
  //--- the price relationship the hedge fit found, not just lot-for-
  //--- lot; this is a lot-count hedge, not a true price-value hedge,
  //--- since it does not account for contract size, tick value,
  //--- currency conversion, or either instrument's volatility.
  //--- Rounding to the symbol's own volume step (and flooring at its
  //--- minimum) keeps a small beta from silently rounding to zero lots
   double step_b=SymbolInfoDouble(InpSymbolB,SYMBOL_VOLUME_STEP);
   double min_b =SymbolInfoDouble(InpSymbolB,SYMBOL_VOLUME_MIN);
   double lots_b=MathAbs(g_beta)*InpLotsA;
   lots_b=MathMax(min_b,MathRound(lots_b/step_b)*step_b);
   g_trade.SetDeviationInPoints(InpSlippage);
   g_trade.SetExpertMagicNumber(InpMagic);
  //--- the two legs are sent one after another, not atomically; if the
  //--- first leg fails outright there is nothing open yet and nothing
  //--- to unwind, but if the first succeeds and the second is rejected
  //--- (requote, margin, symbol trade-disabled) the position would be
  //--- one-sided with no hedge until the next tick, so the first leg
  //--- is closed immediately rather than left open unhedged. A true
  //--- return from Buy/Sell only means the request was sent, not that
  //--- it was actually filled, so LegConfirmed below is what decides
  //--- whether a leg really went through
   if(long_spread)
     g_trade.Sell(InpLotsA,InpSymbolA);
   else
     g_trade.Buy(InpLotsA,InpSymbolA);
   if(!LegConfirmed(InpSymbolA,InpLotsA))
     {
      PrintFormat("DCCA SpreadTrading: first leg (%s SymbolA) not confirmed filled (retcode=%d), no position opened",
                long_spread?"sell":"buy",g_trade.ResultRetcode());
      return;
     }
   if(long_spread)
     g_trade.Buy(lots_b,InpSymbolB);
   else
     g_trade.Sell(lots_b,InpSymbolB);
   if(!LegConfirmed(InpSymbolB,lots_b))
     {
      PrintFormat("DCCA SpreadTrading: second leg not confirmed filled (retcode=%d), closing the unhedged first leg",
                g_trade.ResultRetcode());
      CloseSpread();
     }
  }

ManagePositions is the single decision point reached once per new bar, after the gate and spread model have refreshed. With a position open, it exits purely on mean reversion — the DCCA gate is never consulted on the way out, since closing a trade just because the correlation regime moved is a separate design decision this EA doesn't make. With no position open, both the gate and spread model must be valid this bar, and the gate must clear InpMinDccaGate, before an entry is considered:

//+------------------------------------------------------------------+
//| ManagePositions                                                  |
//| The single decision point reached once per new bar, after        |
//| UpdateGate and UpdateSpreadStats have both run. With a position  |
//| open: closes it once |z|<InpExitZ. With no position open:        |
//| requires g_have_gate, g_have_spread, and                         |
//| g_gate_rho>=InpMinDccaGate before considering an entry, then     |
//| opens on |z|>=InpEntryZ in the direction that fades the spread   |
//| back toward its mean. A gate reading below InpMinDccaGate blocks |
//| new entries only; it does not touch a position already open.     |
//+------------------------------------------------------------------+

void ManagePositions(void)
  {
  //--- exit path only: a position already open is managed purely on
  //--- mean reversion, never on the DCCA gate, since closing a
  //--- controlled trade just because the correlation regime moved is
  //--- a separate decision this EA deliberately does not make
   if(HasOpenPosition())
     {
      if(g_have_spread && MathAbs(g_z)<InpExitZ)
         CloseSpread();
      return;
     }
  //--- entry path: both the gate and the spread model must be valid
  //--- this bar, and the gate itself must clear InpMinDccaGate, before
  //--- a new position is even considered
   if(!g_have_gate || !g_have_spread)
      return;
   if(g_gate_rho<InpMinDccaGate)
      return;
   if(g_z>=InpEntryZ)
      OpenSpread(false);   // spread rich vs its mean: sell B, buy A
   else if(g_z<=-InpEntryZ)
      OpenSpread(true);    // spread cheap vs its mean: buy B, sell A
  }


DCCA_SelfTest.mq5 — Validating the Engine

Before trusting CDCCAEngine against real market data, this script checks it against synthetic series with a known, constructed correlation structure. BuildSyntheticPair constructs two random-walk series that share a common innovation stream weighted by shared_weight, plus an independent noise component weighted by the complement:

//+------------------------------------------------------------------+
//| BuildSyntheticPair                                               |
//| Constructs two length-n series that share a common random-walk   |
//| innovation stream weighted by 'shared_weight' (0..1) plus an     |
//| independent noise component weighted by (1-shared_weight) on     |
//| each side, then cumulatively sums both into price-like series.   |
//| shared_weight=1 makes X and Y the same walk (rho_DCCA should     |
//| read near +1 at every scale); shared_weight=0 makes them         |
//| independent walks (rho_DCCA should read small and scale-noisy,   |
//| not cleanly zero, since two independent random walks can still   |
//| show a nonzero sample correlation over a finite window).         |
//+------------------------------------------------------------------+

void BuildSyntheticPair(int n,double shared_weight,double &x[],double &y[])
  {
   ArrayResize(x,n);
   ArrayResize(y,n);
  //--- each step blends a shared innovation with a side-specific one;
  //--- at shared_weight=1 both series take the identical shared draw
  //--- every step, so X and Y become the exact same walk by construction
   double level_x=0.0,level_y=0.0;
   for(int i=0;i<n;i++)
     {
      double shared =(SeededRand()-0.5)*2.0;
      double noise_x=(SeededRand()-0.5)*2.0;
      double noise_y=(SeededRand()-0.5)*2.0;
      level_x+=shared_weight*shared+(1.0-shared_weight)*noise_x;
      level_y+=shared_weight*shared+(1.0-shared_weight)*noise_y;
      x[i]=level_x;
      y[i]=level_y;
     }
  }

At shared_weight=1 both series take the identical shared draw on every step, so X and Y become the exact same walk by construction — the engine should report rho_DCCA at or extremely close to 1.0 at every scale, which the Python-side verification of this exact construction confirmed (rho=1.0000) before any of this code was trusted.

RunCase runs one engine pass over a given pair and prints both the band-mean rho_DCCA and the full per-scale curve, labeled by case name, so the three cases below can be read and compared directly in the Experts log:

//+------------------------------------------------------------------+
//| RunCase                                                          |
//| Runs one engine pass over a given (x,y) pair and prints the      |
//| band-mean rho_DCCA along with the per-scale curve, labeled with  |
//| the caller-supplied case name, so the three cases below can be   |
//| read and compared directly in the Experts log.                   |
//+------------------------------------------------------------------+

void RunCase(string label,const double &x[],const double &y[],const int &scales[])
  {
   CDCCAEngine engine;
   if(!engine.SetSeries(x,y))
     {
      PrintFormat("[%s] SetSeries failed",label);
      return;
     }
   vector rho;
   if(!engine.Run(scales,rho))
     {
      PrintFormat("[%s] Run failed",label);
      return;
     }
   double mean_rho=engine.MeanRhoOverBand(rho,scales,InpBandMin,InpBandMax);
   PrintFormat("[%s] band-mean rho_DCCA(%d..%d) = %.4f",label,InpBandMin,InpBandMax,mean_rho);
   string line="";
   for(int i=0;i<(int)rho.Size();i++)
      line+=StringFormat("s=%d:%.3f ",scales[i],rho[i]);
   PrintFormat("[%s] full curve: %s",label,line);
  }

OnStart runs three cases through the identical engine path: a genuinely shared pair (positive control), two independent walks (noise floor), and the shared pair's own Y series with its time order destroyed by a Fisher-Yates shuffle (structural control — same values and marginal distribution, no temporal relationship left). The shuffled case collapsing toward the independent case, not staying near the shared case, is the actual evidence the engine reads real time structure, not just the values:

//+------------------------------------------------------------------+
//| OnStart                                                          |
//| Builds the scale array once, then runs three cases through the   |
//| same engine path: a strongly shared pair (expected rho_DCCA well |
//| above zero across scales), an independent pair (expected         |
//| rho_DCCA small relative to the shared case, not necessarily      |
//| exactly zero on any one finite run), and the shared pair's Y     |
//| series with its time order shuffled (expected rho_DCCA collapsed |
//| toward the independent case, demonstrating the engine is reading |
//| real temporal structure rather than something order-independent  |
//| like the marginal value distribution). This script prints its    |
//| findings; it does not assert pass/fail thresholds, since what    |
//| counts as 'close enough' to zero depends on InpN and is for the  |
//| reader to judge from the printed numbers, not a hidden           |
//| hard-coded bound.                                                |
//+------------------------------------------------------------------+

void OnStart(void)
  {
   int scales[];
   ArrayResize(scales,0);
   for(int s=InpScaleMin;s<=InpScaleMax;s+=InpScaleStep)
     {
      int sz=ArraySize(scales);
      ArrayResize(scales,sz+1);
      scales[sz]=s;
     }

   g_rand_state=(ulong)InpRandomSeed;

  //--- case 1: a genuinely shared series pair, the positive control --
  //--- rho_DCCA should read clearly above zero across the scale band
   double shared_x[],shared_y[];
   BuildSyntheticPair(InpN,InpSharedWeight,shared_x,shared_y);
   RunCase("shared, weight="+DoubleToString(InpSharedWeight,2),shared_x,shared_y,scales);

  //--- case 2: two fully independent walks -- rho_DCCA should read
  //--- small relative to case 1, establishing the baseline noise floor
   double indep_x[],indep_y[];
   BuildSyntheticPair(InpN,0.0,indep_x,indep_y);
   RunCase("independent, weight=0.00",indep_x,indep_y,scales);

  //--- case 3: case 1's own Y series with its time order destroyed --
  //--- same values, same marginal distribution, no temporal structure
  //--- left; rho_DCCA collapsing toward case 2 here is the evidence
  //--- that the engine reads actual time structure, not just the
  //--- values each series happens to contain
   double shuffled_y[];
   ArrayCopy(shuffled_y,shared_y);
   ShuffleSeries(shuffled_y);
   RunCase("shared series, Y time-shuffled",shared_x,shuffled_y,scales);
  }

The real compiled output from this script, run with the default inputs ( InpN=2000, InpSharedWeight=0.8 ), confirmed exactly this pattern:

Case band-mean rho_DCCA(20..100)
shared, weight=0.80 0.9542
independent, weight=0.00 0.0283
shared series, Y time-shuffled 0.0210

Self-Test rho_DCCA(s) Curves

Fig. 2. Real DCCA_SelfTest.mq5 output: the shared pair holds near 0.95 at every scale, while the independent pair and the shuffled control both sit near zero with comparable sample noise.

The shared case's curve sits in a tight 0.933–0.967 band across every scale from 10 to 200 bars — high and stable, exactly as a genuinely shared walk should read. The independent and shuffled curves both wander in a noisier −0.22 to +0.43 band around zero, with no systematic separation between them; what separates "related" from "unrelated" here is the overall band-mean level, not any single scale's reading — why the engine's consumers use a band average rather than one scale.


Testing

Three things were tested, each described plainly: the engine's math against synthetic data (covered above), the pair scanner against three real candidate pairs, and the trading EA against two of those three in the Strategy Tester. The test matrix was XAUUSD/XAGUSD, EURUSD/GBPUSD, and USDJPY/AUDJPY on M15, chosen to include one historically trending pair (metals) alongside two FX crosses with different regime behavior.

The scanner's basket run is the headline result. Each pair was scored by both its DCCA band mean (scales 20–100) and a whole-window Pearson coefficient on the same time-aligned close data, real output from DCCA_PairScanner_EA.mq5 on 1000 M15 bars per symbol, M15 timeframe, run on a demo trading account whose server clock runs on GMT, confirmed from the terminal's own Journal log for that run:

Field Value
Timeframe/bars per symbol M15, 1000 bars
Scan run date/time 2026.10.11 20:56:59 (server time, GMT), from the terminal's Journal log for this run. This is a Sunday, with the Forex and metals market closed — the scanner's OnTimer fires on wall-clock schedule, not on market activity, so it ran and logged normally even though no new price data had arrived since the prior session
Last (most recent) bar in the window 2026.10.09 23:45 (M15 bar closing 2026.10.10 00:00), the last fully closed M15 bar from the prior Friday session. The market had been closed since that session through the 20:56:59 Sunday run, so no bar dated later than this one existed yet for AlignSeries to read
Server timezone GMT
Data source MetaTrader 5 terminal history from a demo trading server
Rank Pair DCCA band mean Pearson AlignedBars
1 XAUUSD/XAGUSD 0.8709 0.8743 1000
2 EURUSD/GBPUSD 0.8149 0.5662 1000
3 USDJPY/AUDJPY 0.7102 0.2815 1000

Pair Scanner: DCCA Band Mean vs Pearson

Fig. 3. Real DCCA_PairScanner_EA output across the three-pair basket, DCCA band mean against whole-window Pearson.

XAUUSD/XAGUSD is the one pair where the two measures roughly agree — both liquid, heavily co-driven precious metals, so Pearson already captures most of what DCCA finds. The other two pull apart: EURUSD/GBPUSD's DCCA band mean (0.81) sits above its Pearson reading (0.57), and USDJPY/AUDJPY's gap is wider still — 0.71 against 0.28. These are real, reproducible differences on the same closes, but the gap alone doesn't say which is more useful for selecting a candidate — that needs a check this run doesn't provide.

The ratio between the two readings on USDJPY/AUDJPY is a fact about these two coefficients, not a measure of how much better the pair's relationship is — correlation coefficients don't carry a linear "twice as related" meaning. The gap shows the two methods disagree more on the FX crosses than the metals pair, and Pearson alone would have ranked USDJPY/AUDJPY last by a wider margin — whether that reordering is correct is the open question this section and the next look at.

Two of the three ranked pairs were then run through DCCA_SpreadTrading_EA.mq5 in the Strategy Tester: XAUUSD/XAGUSD and EURUSD/GBPUSD, both over 2026.06.01–2026.08.25, 1-minute OHLC modeling, a $10,000 deposit, 1:100 leverage, and the EA's default spread-model and gate inputs ( InpEntryZ=2.0, InpExitZ=0.5, InpMinDccaGate=0.30, InpLotsA=0.10 ). USDJPY/AUDJPY was not backtested; no result is reported for it here rather than an estimated or illustrative one.

Metric XAUUSD/XAGUSD EURUSD/GBPUSD
Net profit −1,946.26 −225.62
Profit factor 0.86 0.87
Total trades 166 152
Win rate 57.83% 51.97%
Average profit trade 128.09 18.54
Average loss trade −203.48 −23.16
Max equity drawdown 32.96% 2.85%
Sharpe ratio −1.86 −3.29

These numbers only reproduce under the environment they were measured in. The table below collects the parameters already stated above (deposit, leverage, modeling quality, EA inputs) alongside the broker, symbol specifications, account currency, timezone, swap rates, and the Strategy Tester's own execution setting for this run:

Parameter Value
Deposit/leverage $10,000/1:100 (as stated above)
Strategy Tester modeling quality 1-minute OHLC (as stated above)
EA gate/entry inputs InpEntryZ=2.0, InpExitZ=0.5, InpMinDccaGate=0.30, InpLotsA=0.10 (as stated above)
Quote source/broker server Demo trading server
Exact symbol specification XAUUSD: 2 digits, 100 oz/lot contract, floating spread. XAGUSD: 3 digits, 5,000 oz/lot contract, floating spread. EURUSD: 5 digits, 100,000 EUR/lot contract, floating spread. GBPUSD: 5 digits, 100,000 GBP/lot contract, floating spread. All four: Market execution, 0.01/500/0.01 min/max/step lot, instrument specifications recorded for the test environment
Tick size/tick value XAUUSD: 0.01 / $1.00 per lot. XAGUSD: 0.001 / $5.00 per lot. EURUSD: 0.00001 / $1.00 per lot. GBPUSD: 0.00001 / $1.00 per lot. All four read directly from SYMBOL_TRADE_TICK_SIZE / SYMBOL_TRADE_TICK_VALUE on the test account, the same values MQL5's own trade functions use internally
Account currency USD
Server/account timezone GMT
Spread model used in the tester Floating, broker-quoted (each symbol's own specification states a floating spread, not a fixed one)
Swap rates In points, triple on Wednesday for all four: XAUUSD long -69.95 / short +24.91. XAGUSD long -49.45 / short 0. EURUSD long -7.7 / short +2. GBPUSD long -2.91 / short -1.15
Execution model/slippage Strategy Tester Delays setting: "Zero latency, ideal execution" (no simulated delay or requotes); live/demo account execution mode is Market
Commission Confirmed zero — the account's own History summary (netting account) shows Commission: 0.00 across its trade record, separate from and in addition to the swap figures stated above

Real Backtest Results by Pair

Fig. 4. Net profit and maximum equity drawdown, real Strategy Tester output, XAUUSD/XAGUSD and EURUSD/GBPUSD.

Both runs lost money: profit factor 0.86 and 0.87, both below the 1.0 breakeven line, reported as the tester produced it. One pattern in both: XAUUSD/XAGUSD's win rate (57.83%) beats a coin flip and EURUSD/GBPUSD's (51.97%) — entries aren't simply wrong more often than right, and losing trades average 203.48 against winning trades' 128.09, roughly 1.6x larger; EURUSD/GBPUSD shows the same shape at a smaller scale, average loss 23.16 against average win 18.54.

The exit rule is one plausible contributor to that asymmetry: InpExitZ=0.5 closes a winning trade once the spread reverts most of the way to its mean, while a losing trade that keeps drifting away has no stop and rides until the z-score crosses back through InpExitZ, however far it travelled. It isn't shown to be the only contributor — sizing, spread cost, beta drift, and the spread not being cointegrated could each push the same direction, and this backtest doesn't isolate which dominates.

The scale difference between the two pairs' losses — XAUUSD/XAGUSD's drawdown is more than ten times EURUSD/GBPUSD's — comes from InpLotsA being a fixed 0.10 lots applied to both. Gold and silver move far more account-currency value per point than EUR and GBP, and the hedge-ratio-scaled second leg corrects only the price relationship between the legs, not that volatility gap. The fixed lot size was a deliberate simplification to keep sizing easy to follow, not a claim 0.10 lots suits every pair.


Limitations and Practical Considerations

DCCA ranks co-movement; neither the trading rule nor the ranking itself is independently validated. A high band-mean rho_DCCA says two instruments' detrended fluctuations are related at the chosen scales — it says nothing about whether the spread mean-reverts cleanly, quickly, or widely enough to clear costs and the backtests' asymmetric win/loss sizes. Scoring higher than Pearson isn't, by itself, evidence of economically relevant structure — that takes out-of-sample stability, a cointegration test, or realized performance, none of which ran here. Selection and strategy are separate problems: what's built is a measurement tool, not proof it measures right.

Order-1 box detrending does not fully remove a linear trend from the original price series. It fits a local linear trend to the cumulative, de-meaned profile, not the raw prices, and removing a linear component from the profile isn't equivalent to removing one from the prices — a genuinely linear trend can leave a higher-order component after a first-order fit. For gold and silver, this is a partial, scale-local correction, not a guarantee trend is gone before the correlation is computed.

Averaging rho_DCCA(s) over a scale band repeats the averaging problem raised against Pearson. The Math section emphasizes the value of the full rho_DCCA(s) curve, but the scanner's ranking and gate collapse it to one number, MeanRhoOverBand across [InpBandMin, InpBandMax]. A curve that changes sign or shifts sharply within that band gets averaged into one figure the same way whole-window Pearson averages over regimes — a practical simplification, not proof the curve's shape is used.

Non-overlapping, forward-only boxes leave the most recent bars out of the calculation. Boxes are laid out from the oldest bar forward, so any remainder shorter than one full box is dropped at the tail — and since data runs oldest to newest, that tail is the most recent bars. For a live gate checked every new bar, some freshest price action never enters that scale's reading; the effect worsens for larger box sizes, where the dropped remainder can be a meaningful fraction of InpGateLookbackBars.

DCCA is applied to price levels here, not returns or log prices. Feeding raw close levels into a tool built for nonstationary series is a deliberate choice, but not a cost-free one: stochastic trends in price levels can still dominate a level-based DCCA reading in ways a returns-based version would handle differently. Whether levels or returns give a more decision-useful ranking for a given instrument class is left open, since that comparison wasn't run.

The gate and ranking only accept positive correlation. InpMinDccaGate and the scanner's descending-dcca_mean ranking both treat rho_DCCA as signed and require it at or above a positive threshold. A pair with a strong, persistent negative rho_DCCA — tradable via a negative hedge ratio, buying both legs together — is excluded by design, not merely scored lower, and nothing surfaces that distinction to the user.

The hedge ratio is OLS, not a cointegration test. FitHedgeRatio minimizes squared spread error over a lookback window; it doesn't test whether the two legs actually share a stationary long-run equilibrium, the formal condition a classical pairs-trading approach (an Engle-Granger or Johansen test) would check before treating a spread as mean-reverting at all. A pair can have a well-defined OLS beta and still not be cointegrated in any rigorous sense.

Fixed lot sizing doesn't account for cross-instrument volatility. As the Testing section shows, the same InpLotsA value produces a drawdown an order of magnitude apart on two different pairs. A volatility-normalized position size (ATR-scaled, or sized to a fixed account-currency risk per trade) would be a more honest scheme for a basket where the scanner can recommend pairs spanning metals, majors, and crosses with very different point values.

The exit rule is asymmetric by construction. InpExitZ closes a position once the spread reverts most of the way back; nothing closes a position that keeps moving against entry. Both real backtests show average losses meaningfully larger than average wins despite win rates at or above 50%, which is the direct, measured consequence of that asymmetry rather than a property of the DCCA gate.

The self-test checks sensitivity to a shared component, not robustness. DCCA_SelfTest.mq5 confirms the engine reads near-1.0 on a genuinely shared synthetic series and near-zero on an independent or shuffled one — valid against ground truth, but it doesn't test different random seeds, trend types, heteroskedasticity, price jumps, missing bars, or microstructure noise, any of which could behave differently under box detrending than this one case.

A freshly-added symbol needs its history to sync before it can be read. WaitForHistory handles this for the scanner and live EA: SymbolSelect only adds a symbol to Market Watch, and the terminal downloads its history asynchronously afterward. A tool calling CopyRates right after selecting a symbol, without polling first, risks a short or empty series. This doesn't apply inside the Strategy Tester, which keeps its own pre-synchronized history cache and treats Sleep() as a no-op.

The scale sweep and band are fixed inputs, not optimized. InpScaleMin/Max/Step and InpBandMin/Max were chosen to cover a reasonable intraday-to-swing range on M15 data and were not swept or optimized against the test basket. A different instrument class, or a different base timeframe, would likely need a different scale range to find the horizon where the pair's genuine co-movement actually lives.


Conclusion

Detrended Cross-Correlation Analysis gives pairs-trading candidate selection a correlation measure that doesn't assume the two instruments' means are holding still. The self-test shows the engine working as the math predicts: a known-shared pair reads near 1.0 at every scale, a shuffled control collapses to noise. On real data, the basket shows DCCA and whole-window Pearson disagreeing by a real, reproducible margin on two of three pairs — genuine, but one window isn't enough to claim it generalizes.

What this project delivers is narrower and more concrete: a native, DLL-free engine that computes the DCCA measure correctly (shown against synthetic ground truth) and a basket scanner that applies it to real data (shown against three real pairs) — whether that measure is the better one for selecting profitable pairs-trading candidates is the open question the rest of this Conclusion and the Limitations section above are honest about leaving unresolved.

The trading EA built on top of that ranking is a reference implementation of how to wire the gate into a trade decision, not a demonstration of a profitable system, and both backtests are reported honestly as losses. The Limitations section isn't hypothetical — every point is a mechanism directly visible in this article's own results: the asymmetric exit, the unscaled lot size, the untested cointegration assumption. A reader taking this further has a specific, evidenced list of what to fix first.

File Type Description
DCCACore.mqh Include CDCCAEngine: profile build, box detrending, scale sweep, rho_DCCA(s); AlignSeries history fetch/sync/merge helper
PairRanker.mqh Include CPairRanker: basket scan, DCCA vs Pearson scoring, descending sort, CSV export
DCCA_PairScanner_EA.mq5 Expert Advisor Timer-driven basket scan and ranked CSV/log output; places no trades
DCCA_SpreadTrading_EA.mq5 Expert Advisor OLS hedge ratio, z-scored spread, DCCA-gated mean-reversion entries
DCCA_SelfTest.mq5 Script Synthetic shared/independent/shuffled-control validation of the engine
Attached files |
MQL5.zip (22.58 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 a Zone-Aware Rollover Window Gate in MQL5 Implementing a Zone-Aware Rollover Window Gate in MQL5
CTradeWindows blocks EA entries during the daily rollover spread spike. Each window is a clock time in a zone such as New York, so it follows that zone through DST. CSpreadProfile learns the windows from tick spreads and saves them to a file that an EA can load. Unit tests and Strategy Tester runs on one server show that a window fixed in server time misses the spike in weeks when the US and EU DST dates differ.
Features of Experts Advisors Features of Experts Advisors
Creation of expert advisors in the MetaTrader trading system has a number of features.
Using the MQL5 Economic Calendar for News Filter (Part 6): A Filter an EA Can Hold Two Of Using the MQL5 Economic Calendar for News Filter (Part 6): A Filter an EA Can Hold Two Of
This article describes refactoring an EA‑scoped news filter into a reusable MQL5 class. Inputs move into a configuration struct, while events, currency mapping, saved stops, a suspension flag, and a private CTrade object become per‑instance state. The class lets one EA run multiple filters with different thresholds and responses, share one rule table, and reduce duplicated code while keeping each filter independently configurable.