preview
Multi-Timeframe Bar Aggregator with Conflict Detection in MQL5

Multi-Timeframe Bar Aggregator with Conflict Detection in MQL5

MetaTrader 5 — Trading |
124 0
Ushana Kevin Iorkumbul
Ushana Kevin Iorkumbul

Introduction

A strategy reads the last closed M15, H1, and H4 bars with three separate calls. Between the second and the third call, the H4 series rolls to a new bar. The strategy now pairs an M15 bar that ended at 11:45 with an H4 bar that ends at 12:00, fifteen minutes later. Nothing in the code complains, and the result looks plausible.

This article presents a small MQL5 library that makes that mistake visible. The CMultiTFAggregator class reads one closed bar per requested timeframe and checks every open time against four rules. It returns either an aligned bundle or a structured error, and it never returns partial data as valid.

You will learn how to derive alignment rules from bar open times and why raw bar counts cannot serve as the test. You will also see how a bounded re-read detects a base bar that changed during the read. An abstract bar source lets you test the logic with synthetic series, without a terminal.

The package has five include files, one demo indicator, and one test script. The test script needs no chart history, because it feeds the logic with scripted series. You can verify the rules before you attach anything to a live chart.

MTF Architectural diagram

Figure 1: How the library fits together. The aggregator reads bars from a bar source and checks them with the validator. A build returns either a valid bundle that opens the gate or an error that blocks it, and CMtfReport writes both as log lines.


The Multi-Timeframe Look-Ahead Problem

This section defines the failure that the rules in the next section prevent.

Indicators often read several timeframes with separate iCustom() or CopyRates() calls. Each call happens at its own moment, and each series updates independently. If one timeframe rolls to a new bar between two calls, the code silently mixes bars from different moments.

Take base M15 with H4 also requested. The base read returns a forming bar that opens at 11:45. Before the H4 read, a tick arrives at 12:00 and H4 starts a new bar. A naive shift 1 read of H4 now returns the bar that opened at 08:00. That bar ends at 12:00, fifteen minutes after the closed M15 bar ended. This is a look-ahead error.

The opposite case is staleness. The forming base bar opens at 12:00, but H4 still shows 08:00 as its newest bar. A naive shift 1 read returns the 04:00 bar, one full period out of date.

The rules rely on one calculation: the newest bar that contains time F opens at floor(F / p) * p. The rules assume that each series updates independently, that shift 0 is the forming bar, and that open times are server-time seconds on a fixed grid. I make no claim about the Strategy Tester.

When two timeframes disagree

Figure 2: In panel A, H4 is stale: its newest bar opens at 08:00, but the rules expect 12:00. In panel B, H4 is ahead: its newest bar opens at 12:00, but the rules expect 08:00. The diagram is built from the worked examples, not from recorded data.


Alignment Rules and Theory

This section turns the failure into four rules, which the CAlignmentValidator class implements.

Let B be the open time of the last closed base bar (shift 1), F the open time of the forming base bar (shift 0), and p_base the base period in seconds. The snapshot time is T = B + p_base. For each timeframe k with period p_k:

  • Rule 1, grid check. Every returned bar must open at a multiple of p_k. Otherwise the result is a grid error. The code never guesses an offset.
  • Rule 2, recency check. The newest bar must open at floor(F / p_k) * p_k. A smaller value means the series is stale. A larger value means it is ahead. Each case has its own error.
  • Rule 3, closed bar choice. The closed bar is the bar at shift 1. Its end time, open plus p_k, must not be greater than T. Otherwise the result is a look-ahead error.
  • Rule 4, diagnostic counts. Bar counts are logged for context and never used in the test, because gaps make counts differ legitimately.

Every requested period must also be an integer multiple of the base period. The code rejects W1 and MN1. MN1 has no fixed length. W1 has a fixed length, but its bars open on a Sunday, and the epoch fell on a Thursday, so they are not on the 604800-second grid.

The table lists the worked examples. All times are server time on 2026.10.07 unless a date is shown.

CaseFTResult
Example 112:0012:00Closed bars M15 11:45, H1 11:00, H4 08:00
Example 211:4511:45Closed bars M15 11:30, H1 10:00, H4 04:00
Race, ahead11:4511:45Error ahead for H4: expected 08:00, actual 12:00
Stale12:0012:00Error stale for H4: expected 12:00, actual 08:00
Weekend gapSun 10.04 22:00Sat 10.03 00:00Pass: M15 Fri 23:45, H1 Fri 23:00, H4 Fri 20:00
Daily break22:0021:00Pass: M15 20:45, H1 20:00, H4 16:00
Early session closeSun 10.04 22:00Fri 10.02 22:00Look-ahead error for H4 (conservative)

In example 1, the newest H4 bar must open at 12:00. Its shift 1 neighbor opens at 08:00 and ends at 12:00, which is not greater than T, so the bundle passes. In the ahead case, rule 2 expects an H4 open of 08:00 but the series shows 12:00. In the stale case, it expects 12:00 and the series shows 08:00.

The weekend gap assumes that trading stops at 00:00 on Saturday, so the shift 1 bars end exactly at T.

The last row shows the cost of rule 3. If the Friday session ends at 22:00, the H4 bar that opened at 20:00 never reaches its nominal end, so rule 3 reports a look-ahead error. This heuristic errs toward rejection, and the test script pins it. The same rule can reject a bundle after a quiet period on a thin feed, as the limitations section shows.


The Data Model: MultiTFTypes.mqh

This section builds the shared vocabulary of the project: limits, status codes, a bar structure, an error structure, and the bundle. Every later file includes it. Every result object starts in a state that cannot pass for a valid result.

The constants set the maximum timeframe count and the minimum bar count. The enum gives every outcome its own code. MTF_NOT_COMPUTED equals zero, so an untouched variable can never read as MTF_OK.

//+------------------------------------------------------------------+
//|                                                 MultiTFTypes.mqh |
//|              Shared types for the multi-timeframe bar aggregator |
//+------------------------------------------------------------------+
#ifndef MULTITFTYPES_MQH
#define MULTITFTYPES_MQH

//--- limits and sentinel values
#define MTF_MAX_TIMEFRAMES      8
#define MTF_MIN_BARS_REQUIRED   2
#define MTF_MAX_RETRIES_LIMIT   10
#define MTF_CODE_NONE           0
#define MTF_CODE_UNKNOWN        (-1)

//+------------------------------------------------------------------+
//| Status codes for every outcome of configuration and building.    |
//| MTF_NOT_COMPUTED is the initial state, so an untouched result    |
//| can never look valid.                                            |
//+------------------------------------------------------------------+
enum ENUM_MTF_STATUS
  {
   MTF_NOT_COMPUTED         = 0,
   MTF_OK                   = 1,
   MTF_ERR_NOT_CONFIGURED   = 2,
   MTF_ERR_BAD_CONFIG       = 3,
   MTF_ERR_UNSUPPORTED_TF   = 4,
   MTF_ERR_NOT_MULTIPLE     = 5,
   MTF_ERR_DATA_UNAVAILABLE = 6,
   MTF_ERR_NOT_SYNCHRONIZED = 7,
   MTF_ERR_TOO_FEW_BARS     = 8,
   MTF_ERR_INVALID_TIME     = 9,
   MTF_ERR_GRID             = 10,
   MTF_ERR_STALE            = 11,
   MTF_ERR_AHEAD            = 12,
   MTF_ERR_LOOKAHEAD        = 13,
   MTF_ERR_SNAPSHOT_RACE    = 14
  };

MtfStatusName(), MtfStatusText(), MtfTimeframeName()

Three pure functions turn codes into text. The report class prints these strings unchanged, so the log format stays fixed. MtfTimeframeName() uses a switch instead of EnumToString(), so the labels are short and certain.

//+------------------------------------------------------------------+
//| Returns the identifier name of a status code.                    |
//| Pure function. Unknown values return "MTF_UNKNOWN".              |
//+------------------------------------------------------------------+
string MtfStatusName(const ENUM_MTF_STATUS status)
  {
   switch(status)
     {
      case MTF_NOT_COMPUTED:
         return("MTF_NOT_COMPUTED");
      case MTF_OK:
         return("MTF_OK");
      case MTF_ERR_NOT_CONFIGURED:
         return("MTF_ERR_NOT_CONFIGURED");
      case MTF_ERR_BAD_CONFIG:
         return("MTF_ERR_BAD_CONFIG");
      case MTF_ERR_UNSUPPORTED_TF:
         return("MTF_ERR_UNSUPPORTED_TF");
      case MTF_ERR_NOT_MULTIPLE:
         return("MTF_ERR_NOT_MULTIPLE");
      case MTF_ERR_DATA_UNAVAILABLE:
         return("MTF_ERR_DATA_UNAVAILABLE");
      case MTF_ERR_NOT_SYNCHRONIZED:
         return("MTF_ERR_NOT_SYNCHRONIZED");
      case MTF_ERR_TOO_FEW_BARS:
         return("MTF_ERR_TOO_FEW_BARS");
      case MTF_ERR_INVALID_TIME:
         return("MTF_ERR_INVALID_TIME");
      case MTF_ERR_GRID:
         return("MTF_ERR_GRID");
      case MTF_ERR_STALE:
         return("MTF_ERR_STALE");
      case MTF_ERR_AHEAD:
         return("MTF_ERR_AHEAD");
      case MTF_ERR_LOOKAHEAD:
         return("MTF_ERR_LOOKAHEAD");
      case MTF_ERR_SNAPSHOT_RACE:
         return("MTF_ERR_SNAPSHOT_RACE");
     }
   return("MTF_UNKNOWN");
  }

//+------------------------------------------------------------------+
//| Returns the fixed description sentence of a status code.         |
//| Pure function. The report class prints this text unchanged.      |
//+------------------------------------------------------------------+
string MtfStatusText(const ENUM_MTF_STATUS status)
  {
   switch(status)
     {
      case MTF_NOT_COMPUTED:
         return("No result has been computed.");
      case MTF_OK:
         return("The bundle is aligned and valid.");
      case MTF_ERR_NOT_CONFIGURED:
         return("The aggregator is not configured.");
      case MTF_ERR_BAD_CONFIG:
         return("The configuration is invalid.");
      case MTF_ERR_UNSUPPORTED_TF:
         return("The timeframe is not supported.");
      case MTF_ERR_NOT_MULTIPLE:
         return("The period is not an integer multiple of the base period.");
      case MTF_ERR_DATA_UNAVAILABLE:
         return("Bar data could not be read.");
      case MTF_ERR_NOT_SYNCHRONIZED:
         return("The series is not synchronized.");
      case MTF_ERR_TOO_FEW_BARS:
         return("The series holds too few bars.");
      case MTF_ERR_INVALID_TIME:
         return("A bar time is not positive or is out of order.");
      case MTF_ERR_GRID:
         return("A bar open time is off the period grid.");
      case MTF_ERR_STALE:
         return("The series is stale relative to the base snapshot.");
      case MTF_ERR_AHEAD:
         return("The series is ahead of the base snapshot.");
      case MTF_ERR_LOOKAHEAD:
         return("The closed bar ends after the snapshot time.");
      case MTF_ERR_SNAPSHOT_RACE:
         return("The base forming bar changed during the read.");
     }
   return("Unknown status.");
  }

//+------------------------------------------------------------------+
//| Returns a short timeframe label such as "M15" or "H4".           |
//| Pure function. Unknown values return "UNKNOWN".                  |
//+------------------------------------------------------------------+
string MtfTimeframeName(const ENUM_TIMEFRAMES timeframe)
  {
   switch(timeframe)
     {
      case PERIOD_CURRENT:
         return("CURRENT");
      case PERIOD_M1:
         return("M1");
      case PERIOD_M2:
         return("M2");
      case PERIOD_M3:
         return("M3");
      case PERIOD_M4:
         return("M4");
      case PERIOD_M5:
         return("M5");
      case PERIOD_M6:
         return("M6");
      case PERIOD_M10:
         return("M10");
      case PERIOD_M12:
         return("M12");
      case PERIOD_M15:
         return("M15");
      case PERIOD_M20:
         return("M20");
      case PERIOD_M30:
         return("M30");
      case PERIOD_H1:
         return("H1");
      case PERIOD_H2:
         return("H2");
      case PERIOD_H3:
         return("H3");
      case PERIOD_H4:
         return("H4");
      case PERIOD_H6:
         return("H6");
      case PERIOD_H8:
         return("H8");
      case PERIOD_H12:
         return("H12");
      case PERIOD_D1:
         return("D1");
      case PERIOD_W1:
         return("W1");
      case PERIOD_MN1:
         return("MN1");
     }
   return("UNKNOWN");
  }

The bar structure: CTimeframeBar

CTimeframeBar holds one bar of one timeframe. Its Reset() method sets times to zero, prices to EMPTY_VALUE, and the valid flag to false. Only the aggregator ever sets valid to true.

//+------------------------------------------------------------------+
//| One bar of one timeframe.                                        |
//+------------------------------------------------------------------+
struct CTimeframeBar
  {
   ENUM_TIMEFRAMES   timeframe;
   datetime          open_time;
   datetime          end_time;
   double            open_price;
   double            high_price;
   double            low_price;
   double            close_price;
   long              tick_volume;
   bool              valid;
                     CTimeframeBar(void);
   void              Reset(void);
  };

//+------------------------------------------------------------------+
//| Constructor: starts from the reset state.                        |
//+------------------------------------------------------------------+
CTimeframeBar::CTimeframeBar(void)
  {
   Reset();
  }

//+------------------------------------------------------------------+
//| Puts every field into a state that cannot pass for a real bar.   |
//| The caller can rely on valid being false after this call.        |
//+------------------------------------------------------------------+
void CTimeframeBar::Reset(void)
  {
//--- times are zero, prices are EMPTY_VALUE, volume is negative
   timeframe   = PERIOD_CURRENT;
   open_time   = (datetime)0;
   end_time    = (datetime)0;
   open_price  = EMPTY_VALUE;
   high_price  = EMPTY_VALUE;
   low_price   = EMPTY_VALUE;
   close_price = EMPTY_VALUE;
   tick_volume = -1;
   valid       = false;
  }
The error structure: CMtfError

CMtfError carries the status, the offending timeframe, the expected and actual times, the terminal error code, and a text. The Set() method builds the text from the fixed status sentence plus an optional detail. A time of zero means "not applicable" and prints as "n/a" later. For MTF_ERR_LOOKAHEAD, expected_time holds the snapshot time T and actual_time holds the end time of the closed bar. For the stale and ahead errors, both fields hold open times.

//+------------------------------------------------------------------+
//| Structured description of one failure or of success.             |
//+------------------------------------------------------------------+
struct CMtfError
  {
   ENUM_MTF_STATUS   status;
   ENUM_TIMEFRAMES   timeframe;
   datetime          expected_time;
   datetime          actual_time;
   int               error_code;
   string            text;
                     CMtfError(void);
   void              Reset(void);
   void              Set(const ENUM_MTF_STATUS new_status,const ENUM_TIMEFRAMES tf,
                         const datetime expected,const datetime actual,
                         const int code,const string detail);
  };

//+------------------------------------------------------------------+
//| Constructor: starts from the reset state.                        |
//+------------------------------------------------------------------+
CMtfError::CMtfError(void)
  {
   Reset();
  }

//+------------------------------------------------------------------+
//| Clears the error to MTF_NOT_COMPUTED.                            |
//| The caller can rely on status never being MTF_OK afterward.      |
//+------------------------------------------------------------------+
void CMtfError::Reset(void)
  {
   status        = MTF_NOT_COMPUTED;
   timeframe     = PERIOD_CURRENT;
   expected_time = (datetime)0;
   actual_time   = (datetime)0;
   error_code    = MTF_CODE_NONE;
   text          = MtfStatusText(MTF_NOT_COMPUTED);
  }

//+------------------------------------------------------------------+
//| Fills every field. The text is the fixed status sentence, with   |
//| the optional detail appended in parentheses.                     |
//| A zero time means "not applicable" and prints as "n/a".          |
//+------------------------------------------------------------------+
void CMtfError::Set(const ENUM_MTF_STATUS new_status,const ENUM_TIMEFRAMES tf,
                    const datetime expected,const datetime actual,
                    const int code,const string detail)
  {
//--- copy the structured fields
   status        = new_status;
   timeframe     = tf;
   expected_time = expected;
   actual_time   = actual;
   error_code    = code;
//--- build the text from the fixed sentence and the optional detail
   text=MtfStatusText(new_status);
   if(::StringLen(detail)>0)
      text=text+" ("+detail+")";
  }

The bundle: CAlignedBundle

CAlignedBundle stores up to eight closed bars in fixed-size arrays and uses no dynamic arrays. Use Assign() for copying by convention, because the compiler does not forbid the default assignment operator. AddBar() accepts only bars that carry a valid flag and positive times, and any add clears the bundle valid flag until MarkValid() runs.

//+------------------------------------------------------------------+
//| The aligned set of one closed bar per requested timeframe.       |
//| Storage is fixed-size. Copy a bundle with Assign().              |
//+------------------------------------------------------------------+
class CAlignedBundle
  {
private:
   CTimeframeBar     m_bars[MTF_MAX_TIMEFRAMES];
   int               m_bar_counts[MTF_MAX_TIMEFRAMES];
   int               m_count;
   string            m_symbol;
   ENUM_TIMEFRAMES   m_base_tf;
   datetime          m_base_open;
   datetime          m_snapshot;
   bool              m_valid;

public:
                     CAlignedBundle(void);
                    ~CAlignedBundle(void);
   void              Reset(void);
   void              SetHeader(const string symbol,const ENUM_TIMEFRAMES base_tf,
                               const datetime base_open,const datetime snapshot);
   bool              AddBar(const CTimeframeBar &bar,const int terminal_bar_count);
   bool              MarkValid(void);
   bool              Assign(const CAlignedBundle &source);
   bool              IsValid(void) const;
   int               Count(void) const;
   string            SymbolName(void) const;
   ENUM_TIMEFRAMES   BaseTimeframe(void) const;
   datetime          BaseOpenTime(void) const;
   datetime          SnapshotTime(void) const;
   bool              GetBar(const int index,CTimeframeBar &bar) const;
   int               BarCountAt(const int index) const;
  };

//+------------------------------------------------------------------+
//| Constructor: starts empty and invalid.                           |
//+------------------------------------------------------------------+
CAlignedBundle::CAlignedBundle(void)
  {
   Reset();
  }

//+------------------------------------------------------------------+
//| Destructor: nothing to release.                                  |
//+------------------------------------------------------------------+
CAlignedBundle::~CAlignedBundle(void)
  {
  }

//+------------------------------------------------------------------+
//| Empties the bundle and marks it invalid.                         |
//| The aggregator calls this on every failure, so a caller never    |
//| receives a partial bundle.                                       | 
//+------------------------------------------------------------------+
void CAlignedBundle::Reset(void)
  {
//--- reset every stored bar and its diagnostic count
   for(int i=0;i<MTF_MAX_TIMEFRAMES;i++)
     {
      m_bars[i].Reset();
      m_bar_counts[i]=-1;
     }
//--- reset the header
   m_count     = 0;
   m_symbol    = "";
   m_base_tf   = PERIOD_CURRENT;
   m_base_open = (datetime)0;
   m_snapshot  = (datetime)0;
   m_valid     = false;
  }

//+------------------------------------------------------------------+
//| Stores the header fields. Does not make the bundle valid.        |
//+------------------------------------------------------------------+
void CAlignedBundle::SetHeader(const string symbol,const ENUM_TIMEFRAMES base_tf,
                               const datetime base_open,const datetime snapshot)
  {
   m_symbol    = symbol;
   m_base_tf   = base_tf;
   m_base_open = base_open;
   m_snapshot  = snapshot;
  }

//+------------------------------------------------------------------+
//| Appends one closed bar that carries the valid flag, with its     |
//| terminal bar count. Returns false when the bundle is full or the |
//| bar is not valid. Any successful add clears the valid flag until |
//| MarkValid().                                                     |
//+------------------------------------------------------------------+ 
bool CAlignedBundle::AddBar(const CTimeframeBar &bar,const int terminal_bar_count)
  {
//--- reject a full bundle and bars that do not carry the valid flag
   if(m_count>=MTF_MAX_TIMEFRAMES)
      return(false);
   if(!bar.valid || (long)bar.open_time<=0 || (long)bar.end_time<=0)
      return(false);
//--- store the bar
   m_bars[m_count]=bar;
   m_bar_counts[m_count]=terminal_bar_count;
   m_count++;
   m_valid=false;
   return(true);
  }

//+-------------------------------------------------------------------+
//| Marks the bundle valid when it holds at least one bar and a       |
//| positive snapshot time. Returns false and stays invalid otherwise.|
//+-------------------------------------------------------------------+
bool CAlignedBundle::MarkValid(void)
  {
   if(m_count<=0 || (long)m_snapshot<=0)
     {
      m_valid=false;
      return(false);
     }
   m_valid=true;
   return(true);
  }

//+------------------------------------------------------------------+
//| Explicit copy of every field from another bundle.                |
//| Always returns true. Use it instead of the assignment operator.  |
//+------------------------------------------------------------------+
bool CAlignedBundle::Assign(const CAlignedBundle &source)
  {
//--- copy the stored bars and counts
   for(int i=0;i<MTF_MAX_TIMEFRAMES;i++)
     {
      source.GetBar(i,m_bars[i]);
      m_bar_counts[i]=source.BarCountAt(i);
     }
//--- copy the header and the flags
   m_count      = source.Count();
   m_symbol     = source.SymbolName();
   m_base_tf    = source.BaseTimeframe();
   m_base_open  = source.BaseOpenTime();
   m_snapshot   = source.SnapshotTime();
   m_valid      = source.IsValid();
   return(true);
  }

//+------------------------------------------------------------------+
//| Accessors. Each is a plain read of one member.                   |
//+------------------------------------------------------------------+
bool CAlignedBundle::IsValid(void) const
  {
   return(m_valid);
  }

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

//+------------------------------------------------------------------+
//| SymbolName()                                                     |
//+------------------------------------------------------------------+
string CAlignedBundle::SymbolName(void) const
  {
   return(m_symbol);
  }

//+------------------------------------------------------------------+
//| BaseTimeframe()                                                  |
//+------------------------------------------------------------------+
ENUM_TIMEFRAMES CAlignedBundle::BaseTimeframe(void) const
  {
   return(m_base_tf);
  }

//+------------------------------------------------------------------+
//| BaseOpenTime()                                                   |
//+------------------------------------------------------------------+
datetime CAlignedBundle::BaseOpenTime(void) const
  {
   return(m_base_open);
  }

//+------------------------------------------------------------------+
//| SnapshotTime()                                                   |
//+------------------------------------------------------------------+
datetime CAlignedBundle::SnapshotTime(void) const
  {
   return(m_snapshot);
  }

//+------------------------------------------------------------------+
//| Copies the stored bar at index into bar. Slots at or beyond      |
//| Count() hold reset bars, so the copy is safe for any valid index.|
//| Returns false and resets bar when index is out of range.         |
//+------------------------------------------------------------------+
bool CAlignedBundle::GetBar(const int index,CTimeframeBar &bar) const
  {
   if(index<0 || index>=MTF_MAX_TIMEFRAMES)
     {
      bar.Reset();
      return(false);
     }
   bar=m_bars[index];
   return(true);
  }

//+------------------------------------------------------------------+
//| Returns the terminal bar count stored for a slot, or -1 when the |
//| index is out of range or the slot is unused.                     |
//+------------------------------------------------------------------+
int CAlignedBundle::BarCountAt(const int index) const
  {
   if(index<0 || index>=MTF_MAX_TIMEFRAMES)
      return(-1);
   return(m_bar_counts[index]);
  }



Reading Bars Through a Bar Source: BarSource.mqh

This section builds the only place where the project touches the terminal. The aggregator needs bars, but it should not know where they come from. An abstract class defines what it needs, and one concrete class implements it with terminal calls.

The abstract class: CBarSourceBase

CBarSourceBase has four pure virtual methods: the symbol it reads, a synchronization check, a bar count, and a single bar read at a shift. It has a virtual destructor, so deleting a derived object through a base pointer is safe. The symbol method is the base information, and the aggregator uses it to reject a configuration for a different symbol.

//+------------------------------------------------------------------+
//|                                                    BarSource.mqh |
//|              Abstract bar source and the terminal implementation |
//+------------------------------------------------------------------+
#ifndef BARSOURCE_MQH
#define BARSOURCE_MQH

#include "MultiTFTypes.mqh"

//+------------------------------------------------------------------+
//| Abstract source of bars. The aggregator talks only to this class,|
//| so tests can replace the terminal with scripted data.            |
//+------------------------------------------------------------------+
class CBarSourceBase
  {
public:
                     CBarSourceBase(void);
   virtual          ~CBarSourceBase(void);
   virtual string    SymbolName(void)=0;
   virtual bool      IsSynchronized(const ENUM_TIMEFRAMES timeframe)=0;
   virtual int       BarCount(const ENUM_TIMEFRAMES timeframe)=0;
   virtual bool      ReadBar(const ENUM_TIMEFRAMES timeframe,const int shift,
                             CTimeframeBar &bar,int &error_code)=0;
  };

//+------------------------------------------------------------------+
//| Constructor: nothing to initialize.                              |
//+------------------------------------------------------------------+
CBarSourceBase::CBarSourceBase(void)
  {
  }

//+------------------------------------------------------------------+
//| Virtual destructor, so derived objects delete correctly through  |
//| a base pointer.                                                  |
//+------------------------------------------------------------------+
CBarSourceBase::~CBarSourceBase(void)
  {
  }

The terminal implementation: CTerminalBarSource

CTerminalBarSource is the single impure class. Its small methods wrap SeriesInfoInteger() and Bars(). The class declaration, constructor, destructor, and the three simple methods come first.

//+------------------------------------------------------------------+
//| The single impure class of the project. It reads real terminal   |
//| data for one symbol.                                             |
//+------------------------------------------------------------------+
class CTerminalBarSource : public CBarSourceBase
  {
private:
   string            m_symbol;

public:
                     CTerminalBarSource(const string symbol);
   virtual          ~CTerminalBarSource(void);
   virtual string    SymbolName(void);
   virtual bool      IsSynchronized(const ENUM_TIMEFRAMES timeframe);
   virtual int       BarCount(const ENUM_TIMEFRAMES timeframe);
   virtual bool      ReadBar(const ENUM_TIMEFRAMES timeframe,const int shift,
                             CTimeframeBar &bar,int &error_code);
  };

//+------------------------------------------------------------------+
//| Constructor: remembers the symbol name. The symbol is not        |
//| checked here, because every read reports its own failure.        |
//+------------------------------------------------------------------+
CTerminalBarSource::CTerminalBarSource(const string symbol)
  {
   m_symbol=symbol;
  }

//+------------------------------------------------------------------+
//| Destructor: nothing to release.                                  |
//+------------------------------------------------------------------+
CTerminalBarSource::~CTerminalBarSource(void)
  {
  }

//+------------------------------------------------------------------+
//| Returns the symbol this source reads.                            |
//+------------------------------------------------------------------+
string CTerminalBarSource::SymbolName(void)
  {
   return(m_symbol);
  }

//+------------------------------------------------------------------+
//| Reports whether the terminal considers the series synchronized.  |
//| Returns false when the property cannot be read.                  |
//+------------------------------------------------------------------+
bool CTerminalBarSource::IsSynchronized(const ENUM_TIMEFRAMES timeframe)
  {
   return(::SeriesInfoInteger(m_symbol,timeframe,SERIES_SYNCHRONIZED)!=0);
  }

//+------------------------------------------------------------------+
//| Returns the number of bars the terminal holds for the series.    |
//| The value is diagnostic context only. Zero means no data.        |
//+------------------------------------------------------------------+
int CTerminalBarSource::BarCount(const ENUM_TIMEFRAMES timeframe)
  {
   return(::Bars(m_symbol,timeframe));
  }

ReadBar() copies exactly one row with CopyRates(). On failure it resets the bar, records GetLastError(), and returns false. If the copy fails with no error code, it reports MTF_CODE_UNKNOWN. On success the valid flag stays false, because only the aggregator may grant it.

//+------------------------------------------------------------------+
//| ReadBar()                                                        |
//+------------------------------------------------------------------+
bool CTerminalBarSource::ReadBar(const ENUM_TIMEFRAMES timeframe,const int shift,
                                 CTimeframeBar &bar,int &error_code)
  {
   bar.Reset();
   error_code=MTF_CODE_NONE;
//--- a negative shift is a caller error
   if(shift<0)
     {
      error_code=MTF_CODE_UNKNOWN;
      return(false);
     }
//--- copy exactly one row
   MqlRates rates[];
   ::ResetLastError();
   int copied=::CopyRates(m_symbol,timeframe,shift,1,rates);
   if(copied!=1 || ::ArraySize(rates)<1)
     {
      error_code=::GetLastError();
      if(error_code==MTF_CODE_NONE)
         error_code=MTF_CODE_UNKNOWN;
      return(false);
     }
//--- translate the row into the project structure
   bar.timeframe    = timeframe;
   bar.open_time    = rates[0].time;
   bar.open_price   = rates[0].open;
   bar.high_price   = rates[0].high;
   bar.low_price    = rates[0].low;
   bar.close_price  = rates[0].close;
   bar.tick_volume  = rates[0].tick_volume;
   return(true);
  }



Validating Alignment: AlignmentValidator.mqh

This section implements the four rules as small, stateless methods. The class holds no members and makes no terminal calls, so every method can be tested with plain numbers. The aggregator calls these methods in a fixed order later.

//+------------------------------------------------------------------+
//|                                           AlignmentValidator.mqh |
//|                      Pure alignment rules for the bar aggregator |
//+------------------------------------------------------------------+
#ifndef ALIGNMENTVALIDATOR_MQH
#define ALIGNMENTVALIDATOR_MQH

#include "MultiTFTypes.mqh"

//+------------------------------------------------------------------+
//| Implements the grid, recency, and closed bar rules.              |
//| The class holds no state and makes no terminal calls.            |
//+------------------------------------------------------------------+
class CAlignmentValidator
  {
public:
                     CAlignmentValidator(void);
                    ~CAlignmentValidator(void);
   int               SupportedPeriodSeconds(const ENUM_TIMEFRAMES timeframe) const;
   bool              IsSupported(const ENUM_TIMEFRAMES timeframe) const;
   bool              IsPeriodMultiple(const int base_seconds,const int period_seconds) const;
   bool              IsOnGrid(const datetime open_time,const int period_seconds) const;
   datetime          ExpectedNewestOpen(const datetime forming_base_open,const int period_seconds) const;
   ENUM_MTF_STATUS   CheckRecency(const datetime newest_open,const datetime expected_open) const;
   datetime          SnapshotTime(const datetime closed_base_open,const int base_seconds) const;
   bool              ClosedBarEndOk(const datetime closed_open,const int period_seconds,
                                    const datetime snapshot_time) const;
  };

//+------------------------------------------------------------------+
//| Constructor: nothing to initialize.                              |
//+------------------------------------------------------------------+
CAlignmentValidator::CAlignmentValidator(void)
  {
  }

//+------------------------------------------------------------------+
//| Destructor: nothing to release.                                  |
//+------------------------------------------------------------------+
CAlignmentValidator::~CAlignmentValidator(void)
  {
  }

SupportedPeriodSeconds() maps M1 through D1 to fixed periods and returns zero for everything else, including W1 and MN1. IsSupported() and IsPeriodMultiple() build on it. A period shorter than the base is not a multiple.

//+------------------------------------------------------------------+
//| Returns the fixed period in seconds of a supported timeframe.    |
//| Supported means M1 through D1. W1, MN1, and PERIOD_CURRENT return|
//| zero, because their open times do not sit on a fixed epoch grid. |
//+------------------------------------------------------------------+
int CAlignmentValidator::SupportedPeriodSeconds(const ENUM_TIMEFRAMES timeframe) const
  {
   switch(timeframe)
     {
      case PERIOD_M1:
         return(60);
      case PERIOD_M2:
         return(120);
      case PERIOD_M3:
         return(180);
      case PERIOD_M4:
         return(240);
      case PERIOD_M5:
         return(300);
      case PERIOD_M6:
         return(360);
      case PERIOD_M10:
         return(600);
      case PERIOD_M12:
         return(720);
      case PERIOD_M15:
         return(900);
      case PERIOD_M20:
         return(1200);
      case PERIOD_M30:
         return(1800);
      case PERIOD_H1:
         return(3600);
      case PERIOD_H2:
         return(7200);
      case PERIOD_H3:
         return(10800);
      case PERIOD_H4:
         return(14400);
      case PERIOD_H6:
         return(21600);
      case PERIOD_H8:
         return(28800);
      case PERIOD_H12:
         return(43200);
      case PERIOD_D1:
         return(86400);
     }
   return(0);
  }

//+------------------------------------------------------------------+
//| True when the timeframe has a fixed period in this project.      |
//+------------------------------------------------------------------+
bool CAlignmentValidator::IsSupported(const ENUM_TIMEFRAMES timeframe) const
  {
   return(SupportedPeriodSeconds(timeframe)>0);
  }

//+------------------------------------------------------------------+
//| True when period_seconds is a positive integer multiple of       |
//| base_seconds. A period shorter than the base is not a multiple.  |
//+------------------------------------------------------------------+
bool CAlignmentValidator::IsPeriodMultiple(const int base_seconds,const int period_seconds) const
  {
   if(base_seconds<=0 || period_seconds<=0)
      return(false);
   if(period_seconds<base_seconds)
      return(false);
   return((period_seconds%base_seconds)==0);
  }

IsOnGrid() implements rule 1. It counts seconds from the epoch and applies no offset. ExpectedNewestOpen() computes floor(F / p) * p with integer division on positive values, using explicit long casts to avoid signed and unsigned surprises.

//+------------------------------------------------------------------+
//| Rule 1. True when the open time is positive and a multiple of    |
//| the period, counted in seconds from the epoch. No offset is      |
//| guessed or applied.                                              |
//+------------------------------------------------------------------+
bool CAlignmentValidator::IsOnGrid(const datetime open_time,const int period_seconds) const
  {
   if((long)open_time<=0 || period_seconds<=0)
      return(false);
   return(((long)open_time%(long)period_seconds)==0);
  }

//+------------------------------------------------------------------+
//| Rule 2 helper. Returns floor(F / p) * p, the open time the       |
//| newest bar of a series must have when F is the base forming bar. |
//| Returns zero when either input is not positive.                  |
//+------------------------------------------------------------------+
datetime CAlignmentValidator::ExpectedNewestOpen(const datetime forming_base_open,
      const int period_seconds) const
  {
   if((long)forming_base_open<=0 || period_seconds<=0)
      return((datetime)0);
   long f=(long)forming_base_open;
   long p=(long)period_seconds;
   return((datetime)((f/p)*p));
  }

CheckRecency() implements rule 2 and returns one of three statuses. SnapshotTime() returns T. ClosedBarEndOk() implements rule 3 and allows an end time equal to T, because a bar that ends exactly at T has fully closed.

//+------------------------------------------------------------------+
//| Rule 2. Compares the newest open time with the expected one.     |
//| Returns MTF_OK when equal, MTF_ERR_STALE when smaller, and       |
//| MTF_ERR_AHEAD when larger. Zero or negative inputs return        |
//| MTF_ERR_INVALID_TIME.                                            |
//+------------------------------------------------------------------+
ENUM_MTF_STATUS CAlignmentValidator::CheckRecency(const datetime newest_open,
      const datetime expected_open) const
  {
   if((long)newest_open<=0 || (long)expected_open<=0)
      return(MTF_ERR_INVALID_TIME);
   if(newest_open<expected_open)
      return(MTF_ERR_STALE);
   if(newest_open>expected_open)
      return(MTF_ERR_AHEAD);
   return(MTF_OK);
  }

//+------------------------------------------------------------------+
//| Returns T = B + p_base, the end time of the last closed base bar.|
//| Returns zero when either input is not positive.                  |
//+------------------------------------------------------------------+
datetime CAlignmentValidator::SnapshotTime(const datetime closed_base_open,
      const int base_seconds) const
  {
   if((long)closed_base_open<=0 || base_seconds<=0)
      return((datetime)0);
   return((datetime)((long)closed_base_open+(long)base_seconds));
  }

//+------------------------------------------------------------------+
//| Rule 3. True when open + period does not exceed the snapshot     |
//| time. Equality is allowed, because a bar ending exactly at T has |
//| fully closed. Any non-positive input returns false.              |
//+------------------------------------------------------------------+
bool CAlignmentValidator::ClosedBarEndOk(const datetime closed_open,const int period_seconds,
      const datetime snapshot_time) const
  {
   if((long)closed_open<=0 || period_seconds<=0 || (long)snapshot_time<=0)
      return(false);
   long end_time=(long)closed_open+(long)period_seconds;
   return(end_time<=(long)snapshot_time);
  }



Aggregating the Bundle: MultiTFAggregator.mqh

This section assembles the pieces. The aggregator takes a bar source, validates a request, reads the bars, applies the rules from the validator, and returns a bundle or an error. It makes no terminal calls except through the bar source.

The private section holds the source pointer, the validator, and the stored configuration. The aggregator does not own the source, so the destructor releases nothing.

//+------------------------------------------------------------------+
//|                                            MultiTFAggregator.mqh |
//|             Builds one aligned bundle of closed bars per request |
//+------------------------------------------------------------------+
#ifndef MULTITFAGGREGATOR_MQH
#define MULTITFAGGREGATOR_MQH

#include "MultiTFTypes.mqh"
#include "BarSource.mqh"
#include "AlignmentValidator.mqh"

//+------------------------------------------------------------------+
//| Reads the closed bar of every requested timeframe through a bar  |
//| source, applies the alignment rules, and returns either a valid  |
//| bundle or a structured error. It makes no terminal calls itself. |
//+------------------------------------------------------------------+
class CMultiTFAggregator
  {
private:
   CBarSourceBase    *m_source;
   CAlignmentValidator m_validator;
   string            m_symbol;
   ENUM_TIMEFRAMES   m_base_tf;
   ENUM_TIMEFRAMES   m_tfs[MTF_MAX_TIMEFRAMES];
   int               m_periods[MTF_MAX_TIMEFRAMES];
   int               m_count;
   int               m_base_index;
   int               m_max_retries;
   int               m_last_attempts;
   bool              m_configured;

   bool              PrepareSeries(const ENUM_TIMEFRAMES timeframe,int &bar_count,CMtfError &error);
   bool              ReadChecked(const ENUM_TIMEFRAMES timeframe,const int shift,
                                 CTimeframeBar &bar,CMtfError &error);
   ENUM_MTF_STATUS   CheckSeries(const int index,const CTimeframeBar &newest,
                                 const CTimeframeBar &closed,const int terminal_bars,
                                 const datetime forming_base_open,const datetime snapshot,
                                 CAlignedBundle &bundle,CMtfError &error);
   ENUM_MTF_STATUS   TryBuildOnce(CAlignedBundle &bundle,CMtfError &error);

public:
                     CMultiTFAggregator(CBarSourceBase *source);
                    ~CMultiTFAggregator(void);
   bool              Configure(const string symbol,const ENUM_TIMEFRAMES base_tf,
                               const ENUM_TIMEFRAMES &timeframes[],const int count,
                               const int max_retries,CMtfError &error);
   bool              Build(CAlignedBundle &bundle,CMtfError &error);
   bool              IsConfigured(void) const;
   int               TimeframeCount(void) const;
   int               MaxRetries(void) const;
   int               LastAttempts(void) const;
   ENUM_TIMEFRAMES   BaseTimeframe(void) const;
  };

//+------------------------------------------------------------------+
//| Constructor: stores the bar source pointer without owning it.    |
//| The aggregator stays unconfigured until Configure() succeeds.    |
//+------------------------------------------------------------------+
CMultiTFAggregator::CMultiTFAggregator(CBarSourceBase *source)
  {
   m_source        = source;
   m_symbol        = "";
   m_base_tf       = PERIOD_CURRENT;
   m_count         = 0;
   m_base_index    = -1;
   m_max_retries   = 0;
   m_last_attempts = 0;
   m_configured    = false;
   for(int i=0;i<MTF_MAX_TIMEFRAMES;i++)
     {
      m_tfs[i]=PERIOD_CURRENT;
      m_periods[i]=0;
     }
  }

//+------------------------------------------------------------------+
//| Destructor: the bar source belongs to the caller.                |
//+------------------------------------------------------------------+
CMultiTFAggregator::~CMultiTFAggregator(void)
  {
  }

Configure() checks the request in a fixed order and stores nothing unless every check passes. The base timeframe must appear in the list. W1 and MN1 fail as unsupported before the multiple check runs. A failed call leaves the aggregator unconfigured, so Build() returns MTF_ERR_NOT_CONFIGURED. The accessors may still report the old values.

//+------------------------------------------------------------------+
//| Configure                                                        |
//+------------------------------------------------------------------+
bool CMultiTFAggregator::Configure(const string symbol,const ENUM_TIMEFRAMES base_tf,
                                   const ENUM_TIMEFRAMES &timeframes[],const int count,
                                   const int max_retries,CMtfError &error)
  {
   m_configured=false;
   error.Reset();
//--- basic argument checks
   if(::CheckPointer(m_source)==POINTER_INVALID)
     {
      error.Set(MTF_ERR_BAD_CONFIG,PERIOD_CURRENT,0,0,MTF_CODE_NONE,"no bar source");
      return(false);
     }
   if(::StringLen(symbol)==0 || symbol!=m_source.SymbolName())
     {
      error.Set(MTF_ERR_BAD_CONFIG,PERIOD_CURRENT,0,0,MTF_CODE_NONE,"symbol is empty or differs from the bar source");
      return(false);
     }
   if(count<1 || count>MTF_MAX_TIMEFRAMES || count>::ArraySize(timeframes))
     {
      error.Set(MTF_ERR_BAD_CONFIG,PERIOD_CURRENT,0,0,MTF_CODE_NONE,"timeframe count is out of range");
      return(false);
     }
   if(max_retries<0 || max_retries>MTF_MAX_RETRIES_LIMIT)
     {
      error.Set(MTF_ERR_BAD_CONFIG,PERIOD_CURRENT,0,0,MTF_CODE_NONE,"retry limit is out of range");
      return(false);
     }
//--- the base timeframe needs a fixed period
   int base_seconds=m_validator.SupportedPeriodSeconds(base_tf);
   if(base_seconds<=0)
     {
      error.Set(MTF_ERR_UNSUPPORTED_TF,base_tf,0,0,MTF_CODE_NONE,"base timeframe");
      return(false);
     }
//--- check every requested timeframe into temporary storage
   ENUM_TIMEFRAMES tmp_tfs[MTF_MAX_TIMEFRAMES];
   int tmp_periods[MTF_MAX_TIMEFRAMES];
   int tmp_base_index=-1;
   for(int i=0;i<count;i++)
     {
      ENUM_TIMEFRAMES tf=timeframes[i];
      int seconds=m_validator.SupportedPeriodSeconds(tf);
      if(seconds<=0)
        {
         error.Set(MTF_ERR_UNSUPPORTED_TF,tf,0,0,MTF_CODE_NONE,"");
         return(false);
        }
      for(int j=0;j<i;j++)
        {
         if(tmp_tfs[j]==tf)
           {
            error.Set(MTF_ERR_BAD_CONFIG,tf,0,0,MTF_CODE_NONE,"duplicate timeframe");
            return(false);
           }
        }
      if(!m_validator.IsPeriodMultiple(base_seconds,seconds))
        {
         error.Set(MTF_ERR_NOT_MULTIPLE,tf,0,0,MTF_CODE_NONE,
                   "period="+::IntegerToString(seconds)+" base="+::IntegerToString(base_seconds));
         return(false);
        }
      tmp_tfs[i]=tf;
      tmp_periods[i]=seconds;
      if(tf==base_tf)
         tmp_base_index=i;
     }
   if(tmp_base_index<0)
     {
      error.Set(MTF_ERR_BAD_CONFIG,base_tf,0,0,MTF_CODE_NONE,"base timeframe is not in the list");
      return(false);
     }
//--- commit
   for(int i=0;i<count;i++)
     {
      m_tfs[i]=tmp_tfs[i];
      m_periods[i]=tmp_periods[i];
     }
   m_symbol        = symbol;
   m_base_tf       = base_tf;
   m_count         = count;
   m_base_index    = tmp_base_index;
   m_max_retries   = max_retries;
   m_last_attempts = 0;
   m_configured    = true;
   error.Set(MTF_OK,base_tf,0,0,MTF_CODE_NONE,"");
   return(true);
  }

Two private helpers turn terminal problems into structured errors. PrepareSeries() checks synchronization and the bar count before any bar is read. ReadChecked() reads one bar and rejects a failed copy, recording the terminal error code, or a time of zero or less.

//+------------------------------------------------------------------+
//| PrepareSeries()                                                  |
//+------------------------------------------------------------------+
bool CMultiTFAggregator::PrepareSeries(const ENUM_TIMEFRAMES timeframe,int &bar_count,
                                       CMtfError &error)
  {
   bar_count=0;
//--- the series must report synchronized history
   if(!m_source.IsSynchronized(timeframe))
     {
      error.Set(MTF_ERR_NOT_SYNCHRONIZED,timeframe,0,0,MTF_CODE_NONE,"");
      return(false);
     }
//--- the series must hold bars for shift 0 and shift 1
   bar_count=m_source.BarCount(timeframe);
   if(bar_count<MTF_MIN_BARS_REQUIRED)
     {
      error.Set(MTF_ERR_TOO_FEW_BARS,timeframe,0,0,MTF_CODE_NONE,"bars="+::IntegerToString(bar_count));
      return(false);
     }
   return(true);
  }

//+------------------------------------------------------------------+
//| ReadChecked()                                                   |
//+------------------------------------------------------------------+
bool CMultiTFAggregator::ReadChecked(const ENUM_TIMEFRAMES timeframe,const int shift,
                                     CTimeframeBar &bar,CMtfError &error)
  {
   int code=MTF_CODE_NONE;
//--- the copy itself can fail
   if(!m_source.ReadBar(timeframe,shift,bar,code))
     {
      bar.Reset();
      error.Set(MTF_ERR_DATA_UNAVAILABLE,timeframe,0,0,code,"shift="+::IntegerToString(shift));
      return(false);
     }
//--- a bar time of zero or less is never real
   if((long)bar.open_time<=0)
     {
      error.Set(MTF_ERR_INVALID_TIME,timeframe,0,bar.open_time,MTF_CODE_NONE,"shift="+::IntegerToString(shift));
      bar.Reset();
      return(false);
     }
   return(true);
  }

CheckSeries() applies rules 1, 2, and 3 in that order. It uses the newest bar only for rule 2 and never stores it. On success it stamps the closed bar with its end time, marks it valid, and appends it to the bundle. A failed AddBar() becomes an error instead of being ignored.

//+------------------------------------------------------------------+
//| CheckSeries()                                                    |
//+------------------------------------------------------------------+
ENUM_MTF_STATUS CMultiTFAggregator::CheckSeries(const int index,const CTimeframeBar &newest,
      const CTimeframeBar &closed,const int terminal_bars,
      const datetime forming_base_open,
      const datetime snapshot,
      CAlignedBundle &bundle,CMtfError &error)
  {
   const ENUM_TIMEFRAMES tf=m_tfs[index];
   const int period=m_periods[index];
//--- rule 1: both open times must sit on the period grid
   if(!m_validator.IsOnGrid(newest.open_time,period))
     {
      error.Set(MTF_ERR_GRID,tf,0,newest.open_time,MTF_CODE_NONE,"newest bar");
      return(MTF_ERR_GRID);
     }
   if(!m_validator.IsOnGrid(closed.open_time,period))
     {
      error.Set(MTF_ERR_GRID,tf,0,closed.open_time,MTF_CODE_NONE,"closed bar");
      return(MTF_ERR_GRID);
     }
//--- rule 2: the newest bar must be the one that contains F
   datetime expected=m_validator.ExpectedNewestOpen(forming_base_open,period);
   ENUM_MTF_STATUS recency=m_validator.CheckRecency(newest.open_time,expected);
   if(recency!=MTF_OK)
     {
      error.Set(recency,tf,expected,newest.open_time,MTF_CODE_NONE,"");
      return(recency);
     }
//--- rule 3: the closed bar must end at or before T
   datetime end_time=(datetime)((long)closed.open_time+(long)period);
   if(!m_validator.ClosedBarEndOk(closed.open_time,period,snapshot))
     {
      error.Set(MTF_ERR_LOOKAHEAD,tf,snapshot,end_time,MTF_CODE_NONE,"");
      return(MTF_ERR_LOOKAHEAD);
     }
//--- store a copy of the closed bar, marked valid
   CTimeframeBar stored;
   stored=closed;
   stored.timeframe=tf;
   stored.end_time=end_time;
   stored.valid=true;
   if(!bundle.AddBar(stored,terminal_bars))
     {
      error.Set(MTF_ERR_BAD_CONFIG,tf,0,0,MTF_CODE_NONE,"bundle rejected the bar");
      return(MTF_ERR_BAD_CONFIG);
     }
   return(MTF_OK);
  }

TryBuildOnce() is the core of the race handling. Read failures return at once, because they are data problems and not races. Alignment conflicts are held until the re-read of F. A conflict seen during a race may only be a symptom of the base change, so a changed F wins and the attempt reports a race.

//+------------------------------------------------------------------+
//| TryBuildOnce                                                     |
//+------------------------------------------------------------------+
ENUM_MTF_STATUS CMultiTFAggregator::TryBuildOnce(CAlignedBundle &bundle,CMtfError &error)
  {
   bundle.Reset();
   error.Reset();
   CTimeframeBar forming,closed_base,newest,closed,again;
   int base_bars=0;
   int bars=0;
//--- read F and B on the base timeframe first
   if(!PrepareSeries(m_base_tf,base_bars,error))
      return(error.status);
   if(!ReadChecked(m_base_tf,0,forming,error))
      return(error.status);
   if(!ReadChecked(m_base_tf,1,closed_base,error))
      return(error.status);
   if(closed_base.open_time>=forming.open_time)
     {
      error.Set(MTF_ERR_INVALID_TIME,m_base_tf,forming.open_time,closed_base.open_time,
                MTF_CODE_NONE,"closed base bar is not older than the forming bar");
      return(MTF_ERR_INVALID_TIME);
     }
   const datetime snapshot=m_validator.SnapshotTime(closed_base.open_time,m_periods[m_base_index]);
//--- check every requested timeframe in list order
   ENUM_MTF_STATUS conflict=MTF_OK;
   for(int i=0;i<m_count;i++)
     {
      if(i==m_base_index)
        {
         newest=forming;
         closed=closed_base;
         bars=base_bars;
        }
      else
        {
         if(!PrepareSeries(m_tfs[i],bars,error))
            return(error.status);
         if(!ReadChecked(m_tfs[i],0,newest,error))
            return(error.status);
         if(!ReadChecked(m_tfs[i],1,closed,error))
            return(error.status);
        }
      ENUM_MTF_STATUS result=CheckSeries(i,newest,closed,bars,forming.open_time,snapshot,bundle,error);
      if(result!=MTF_OK)
        {
         conflict=result;
         break;
        }
     }
//--- re-read the base forming bar after all other reads
   if(!ReadChecked(m_base_tf,0,again,error))
      return(error.status);
   if(again.open_time!=forming.open_time)
     {
      error.Set(MTF_ERR_SNAPSHOT_RACE,m_base_tf,forming.open_time,again.open_time,
                MTF_CODE_NONE,"attempts="+::IntegerToString(m_last_attempts));
      return(MTF_ERR_SNAPSHOT_RACE);
     }
//--- the base held still, so a held conflict is a real conflict
   if(conflict!=MTF_OK)
      return(conflict);
//--- finish the bundle
   bundle.SetHeader(m_symbol,m_base_tf,closed_base.open_time,snapshot);
   if(!bundle.MarkValid())
     {
      error.Set(MTF_ERR_BAD_CONFIG,m_base_tf,0,0,MTF_CODE_NONE,"bundle could not be marked valid");
      return(MTF_ERR_BAD_CONFIG);
     }
   error.Set(MTF_OK,m_base_tf,0,0,MTF_CODE_NONE,"");
   return(MTF_OK);
  }

Build() runs a bounded retry loop. Only a race triggers a retry; any other failure resets the bundle and returns. After the last attempt, the error still holds the last race. The accessors are plain reads.

//+------------------------------------------------------------------+
//| Build()                                                          |
//+------------------------------------------------------------------+
bool CMultiTFAggregator::Build(CAlignedBundle &bundle,CMtfError &error)
  {
   bundle.Reset();
   error.Reset();
   m_last_attempts=0;
//--- the request must be complete
   if(!m_configured)
     {
      error.Set(MTF_ERR_NOT_CONFIGURED,PERIOD_CURRENT,0,0,MTF_CODE_NONE,"");
      return(false);
     }
   if(::CheckPointer(m_source)==POINTER_INVALID)
     {
      error.Set(MTF_ERR_NOT_CONFIGURED,PERIOD_CURRENT,0,0,MTF_CODE_NONE,"no bar source");
      return(false);
     }
//--- bounded attempt loop
   const int attempts=m_max_retries+1;
   for(int attempt=1;attempt<=attempts;attempt++)
     {
      m_last_attempts=attempt;
      ENUM_MTF_STATUS result=TryBuildOnce(bundle,error);
      if(result==MTF_OK)
         return(true);
      if(result!=MTF_ERR_SNAPSHOT_RACE)
        {
         bundle.Reset();
         return(false);
        }
     }
//--- every attempt raced: the error holds the last race
   bundle.Reset();
   return(false);
  }

//+------------------------------------------------------------------+
//| Accessors. Each is a plain read of one member.                   |
//+------------------------------------------------------------------+
bool CMultiTFAggregator::IsConfigured(void) const
  {
   return(m_configured);
  }

//+------------------------------------------------------------------+
//| TimeframeCount()                                                 |
//+------------------------------------------------------------------+
int CMultiTFAggregator::TimeframeCount(void) const
  {
   return(m_count);
  }

//+------------------------------------------------------------------+
//| MaxRetries()                                                     |
//+------------------------------------------------------------------+
int CMultiTFAggregator::MaxRetries(void) const
  {
   return(m_max_retries);
  }

//+------------------------------------------------------------------+
//| LastAttempts()                                                   |
//+------------------------------------------------------------------+
int CMultiTFAggregator::LastAttempts(void) const
  {
   return(m_last_attempts);
  }

//+------------------------------------------------------------------+
//| BaseTimeframe()                                                  |
//+------------------------------------------------------------------+
ENUM_TIMEFRAMES CMultiTFAggregator::BaseTimeframe(void) const
  {
   return(m_base_tf);
  }



Formatting Reports: MultiTFReport.mqh

This section presents the pure formatter that turns a bundle or an error into log lines. The formats are fixed, so the article, the tests, and the log all agree. The class makes no terminal calls apart from TimeToString().

//+------------------------------------------------------------------+
//|                                                MultiTFReport.mqh |
//|                  Pure log line formatting for bundles and errors |
//+------------------------------------------------------------------+
#ifndef MULTITFREPORT_MQH
#define MULTITFREPORT_MQH

#include "MultiTFTypes.mqh"

//+------------------------------------------------------------------+
//| Formats results into fixed, documented log lines.                |
//|                                                                  |
//| Header line:                                                     |
//| MTF bundle | state=VALID | symbol=S | base=TF | snapshot=T |     |
//| timeframes=N                                                     |
//| Bar line:                                                        |
//| MTF bar | tf=TF | open=T | end=T | bars=N                        |
//| Error line:                                                      |
//| MTF error | status=NAME | tf=TF | expected=T | actual=T |        |
//| code=N | text=SENTENCE                                           |
//|                                                                  |
//| Times use TimeToString() with date and minutes. A time of zero   |
//| or less prints as "n/a". Each line is one string, with no breaks.|
//+------------------------------------------------------------------+
class CMtfReport
  {
public:
                     CMtfReport(void);
                    ~CMtfReport(void);
   string            FormatTime(const datetime value) const;
   string            BundleHeaderLine(const CAlignedBundle &bundle) const;
   string            BarLine(const CAlignedBundle &bundle,const int index) const;
   string            ErrorLine(const CMtfError &error) const;
   int               FormatBundle(const CAlignedBundle &bundle,string &lines[]);
  };

//+------------------------------------------------------------------+
//| Constructor: nothing to initialize.                              |
//+------------------------------------------------------------------+
CMtfReport::CMtfReport(void)
  {
  }

//+------------------------------------------------------------------+
//| Destructor: nothing to release.                                  |
//+------------------------------------------------------------------+
CMtfReport::~CMtfReport(void)
  {
  }

FormatTime() prints yyyy.mm.dd hh:mi through TimeToString() with TIME_DATE|TIME_MINUTES. Methods that only read data are const. FormatBundle() writes into an array parameter, so it is not.

//+------------------------------------------------------------------+
//| Formats a time as "yyyy.mm.dd hh:mi", or "n/a" when the value is |
//| zero or negative.                                                |
//+------------------------------------------------------------------+
string CMtfReport::FormatTime(const datetime value) const
  {
   if((long)value<=0)
      return("n/a");
   return(::TimeToString(value,TIME_DATE|TIME_MINUTES));
  }

BundleHeaderLine() prints state=INVALID and zero timeframes for an invalid bundle, so it never looks usable. BarLine() returns an empty string for an index without a bar. ErrorLine() prints the offending timestamps and the fixed status sentence.

//+------------------------------------------------------------------+
//| Builds the header line. An invalid bundle prints state=INVALID   |
//| and zero timeframes, so it never looks usable.                   |
//+------------------------------------------------------------------+
string CMtfReport::BundleHeaderLine(const CAlignedBundle &bundle) const
  {
   string state="INVALID";
   int count=0;
   if(bundle.IsValid())
     {
      state="VALID";
      count=bundle.Count();
     }
   return("MTF bundle | state="+state+
          " | symbol="+bundle.SymbolName()+
          " | base="+MtfTimeframeName(bundle.BaseTimeframe())+
          " | snapshot="+FormatTime(bundle.SnapshotTime())+
          " | timeframes="+::IntegerToString(count));
  }

//+------------------------------------------------------------------+
//| Builds the line for one bundle slot. Returns an empty string     |
//| when the index does not hold a bar.                              |
//+------------------------------------------------------------------+
string CMtfReport::BarLine(const CAlignedBundle &bundle,const int index) const
  {
   CTimeframeBar bar;
   if(index<0 || index>=bundle.Count())
      return("");
   if(!bundle.GetBar(index,bar))
      return("");
   return("MTF bar | tf="+MtfTimeframeName(bar.timeframe)+
          " | open="+FormatTime(bar.open_time)+
          " | end="+FormatTime(bar.end_time)+
          " | bars="+::IntegerToString(bundle.BarCountAt(index)));
  }

//+------------------------------------------------------------------+
//| Builds the error line with the offending timestamps.             |
//+------------------------------------------------------------------+
string CMtfReport::ErrorLine(const CMtfError &error) const
  {
   return("MTF error | status="+MtfStatusName(error.status)+
          " | tf="+MtfTimeframeName(error.timeframe)+
          " | expected="+FormatTime(error.expected_time)+
          " | actual="+FormatTime(error.actual_time)+
          " | code="+::IntegerToString(error.error_code)+
          " | text="+error.text);
  }

FormatBundle() sizes the output array, checks the result of ArrayResize(), and fills the header and one line per timeframe. An invalid bundle yields the header line only.

//+------------------------------------------------------------------+
//| Writes the header line and one bar line per slot into lines.     |
//| Returns the number of lines, or -1 when the array cannot be      |
//| resized. An invalid bundle yields the header line only.          |
//+------------------------------------------------------------------+
int CMtfReport::FormatBundle(const CAlignedBundle &bundle,string &lines[])
  {
   int total=1;
   if(bundle.IsValid())
      total=1+bundle.Count();
//--- size the output array and check the result
   if(::ArrayResize(lines,total)!=total)
      return(-1);
//--- fill the header and the bar lines
   lines[0]=BundleHeaderLine(bundle);
   for(int i=1;i<total;i++)
      lines[i]=BarLine(bundle,i-1);
   return(total);
  }



Building the Demo Indicator: MtfAlignmentDemo.mq5

This section shows how a consumer uses the library. The indicator draws a demonstration agreement score in a separate sub-window, but only when the bundle is aligned. The score appears as one dot on each closed base bar. The score counts the timeframes whose last closed bar closed above its open, minus those that closed below. An exact tie counts as zero.

The score is a demonstration of gating and not a trading signal. The point is the gate: an invalid bundle plots EMPTY_VALUE, never zero, and computes nothing. The indicator scores only the latest closed base bar, so earlier history stays empty by design. A line plot needs two neighboring values, so the plot uses single dots, which also show a lone value.

The base timeframe is always the chart timeframe. Three optional inputs add timeframes, and PERIOD_CURRENT means unused. The plot style is DRAW_ARROW, and the vertical scale is fixed from -4.5 to 4.5, because at most four timeframes give a score from -4 to 4. The indicator logs only when the status changes, so it keeps the last status in a global.

//+------------------------------------------------------------------+
//|                                             MtfAlignmentDemo.mq5 |
//|         Demonstrates gating on an aligned multi-timeframe bundle |
//+------------------------------------------------------------------+
#property description "Plots a demonstration agreement score only when the bundle is aligned."
#property description "The score is a gating demonstration, not a trading signal."
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_label1  "MtfAgreementScore"
#property indicator_type1   DRAW_ARROW
#property indicator_color1  clrDodgerBlue
#property indicator_width1  3
#property indicator_minimum -4.5
#property indicator_maximum 4.5

#include <MultiTFAggregator\MultiTFAggregator.mqh>
#include <MultiTFAggregator\MultiTFReport.mqh>

//--- inputs: the base timeframe is always the chart timeframe
input ENUM_TIMEFRAMES InpTimeframe2 = PERIOD_H1;      // Second timeframe
input ENUM_TIMEFRAMES InpTimeframe3 = PERIOD_H4;      // Third timeframe
input ENUM_TIMEFRAMES InpTimeframe4 = PERIOD_CURRENT; // Fourth timeframe (CURRENT means unused)
input int             InpMaxRetries = 3;              // Maximum extra read attempts (0 to 10)

//--- plot buffer
double g_score[];

//--- project objects
CTerminalBarSource *g_source=NULL;
CMultiTFAggregator *g_aggregator=NULL;
CMtfReport          g_report;

//--- state
datetime            g_done_time=0;
ENUM_MTF_STATUS     g_last_status=MTF_NOT_COMPUTED;

DeinitReasonText() turns a deinit reason into readable text. ComputeAgreementScore() implements the demonstration score. LogOnStatusChange() prints the bundle lines for a valid result and the error line otherwise, but only when the status differs from the last one. ReleaseObjects() deletes the aggregator before the source.

//+------------------------------------------------------------------+
//| Converts a deinitialization reason into readable text.           |
//+------------------------------------------------------------------+
string DeinitReasonText(const int reason)
  {
   switch(reason)
     {
      case REASON_PROGRAM:
         return("the program stopped itself");
      case REASON_REMOVE:
         return("the indicator was removed from the chart");
      case REASON_RECOMPILE:
         return("the indicator was recompiled");
      case REASON_CHARTCHANGE:
         return("the symbol or timeframe changed");
      case REASON_CHARTCLOSE:
         return("the chart was closed");
      case REASON_PARAMETERS:
         return("the input parameters changed");
      case REASON_ACCOUNT:
         return("another account was activated");
      case REASON_TEMPLATE:
         return("a new template was applied");
      case REASON_INITFAILED:
         return("initialization failed");
      case REASON_CLOSE:
         return("the terminal was closed");
     }
   return("an unknown reason");
  }

//+------------------------------------------------------------------+
//| Counts closes above open minus closes below open across a valid  |
//| bundle. An exact tie adds zero.                                  |
//+------------------------------------------------------------------+
int ComputeAgreementScore(const CAlignedBundle &bundle)
  {
   int score=0;
   CTimeframeBar bar;
   for(int i=0;i<bundle.Count();i++)
     {
      if(!bundle.GetBar(i,bar))
         continue;
      if(bar.close_price>bar.open_price)
         score++;
      else
         if(bar.close_price<bar.open_price)
            score--;
     }
   return(score);
  }

//+------------------------------------------------------------------+
//| Logs a bundle or an error, but only when the status changed.     |
//+------------------------------------------------------------------+
void LogOnStatusChange(const CAlignedBundle &bundle,const CMtfError &error)
  {
   if(error.status==g_last_status)
      return;
   g_last_status=error.status;
//--- a valid bundle prints its header and one line per timeframe
   if(error.status==MTF_OK)
     {
      string lines[];
      int total=g_report.FormatBundle(bundle,lines);
      for(int i=0;i<total;i++)
         Print(lines[i]);
      return;
     }
//--- any other status prints the error line
   Print(g_report.ErrorLine(error));
  }

//+------------------------------------------------------------------+
//| Deletes the aggregator and the bar source, in that order.        |
//+------------------------------------------------------------------+
void ReleaseObjects(void)
  {
   if(CheckPointer(g_aggregator)!=POINTER_INVALID)
      delete g_aggregator;
   g_aggregator=NULL;
   if(CheckPointer(g_source)!=POINTER_INVALID)
      delete g_source;
   g_source=NULL;
  }

OnInit() validates the inputs, builds the timeframe list with the base first, rejects repeated timeframes, and creates the objects. It then calls Configure() and prints any structured error. The plot setup selects the dot symbol with PlotIndexSetInteger(). Every call that can fail is checked, and every failure path releases what was created.

//+------------------------------------------------------------------+
//| Validates inputs, builds the aggregator, and binds the buffer.   |
//+------------------------------------------------------------------+
int OnInit(void)
  {
//--- validate the retry input
   if(InpMaxRetries<0 || InpMaxRetries>MTF_MAX_RETRIES_LIMIT)
     {
      Print("MtfAlignmentDemo: InpMaxRetries must be between 0 and ",MTF_MAX_RETRIES_LIMIT,".");
      return(INIT_PARAMETERS_INCORRECT);
     }
//--- collect the timeframe list: base first, then the optional inputs
   const ENUM_TIMEFRAMES base_tf=(ENUM_TIMEFRAMES)_Period;
   ENUM_TIMEFRAMES list[MTF_MAX_TIMEFRAMES];
   int count=0;
   list[count++]=base_tf;
   ENUM_TIMEFRAMES extra[3];
   extra[0]=InpTimeframe2;
   extra[1]=InpTimeframe3;
   extra[2]=InpTimeframe4;
   for(int i=0;i<3;i++)
     {
      if(extra[i]==PERIOD_CURRENT)
         continue;
      for(int j=0;j<count;j++)
        {
         if(list[j]==extra[i])
           {
            Print("MtfAlignmentDemo: a timeframe input repeats the base timeframe or another input.");
            return(INIT_PARAMETERS_INCORRECT);
           }
        }
      list[count++]=extra[i];
     }
//--- create the source and the aggregator
   g_source=new CTerminalBarSource(_Symbol);
   if(CheckPointer(g_source)==POINTER_INVALID)
     {
      Print("MtfAlignmentDemo: could not create the bar source.");
      return(INIT_FAILED);
     }
   g_aggregator=new CMultiTFAggregator(g_source);
   if(CheckPointer(g_aggregator)==POINTER_INVALID)
     {
      Print("MtfAlignmentDemo: could not create the aggregator.");
      ReleaseObjects();
      return(INIT_FAILED);
     }
//--- configure the aggregator and report any structured error
   CMtfError error;
   if(!g_aggregator.Configure(_Symbol,base_tf,list,count,InpMaxRetries,error))
     {
      Print(g_report.ErrorLine(error));
      ReleaseObjects();
      return(INIT_PARAMETERS_INCORRECT);
     }
//--- bind the single plot buffer and set its empty value
   if(!SetIndexBuffer(0,g_score,INDICATOR_DATA))
     {
      Print("MtfAlignmentDemo: SetIndexBuffer failed, error ",GetLastError(),".");
      ReleaseObjects();
      return(INIT_FAILED);
     }
   if(!ArraySetAsSeries(g_score,false) || !PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,EMPTY_VALUE)
      || !PlotIndexSetInteger(0,PLOT_ARROW,159)
      || !IndicatorSetString(INDICATOR_SHORTNAME,"MtfAlignmentDemo"))
     {
      Print("MtfAlignmentDemo: plot setup failed, error ",GetLastError(),".");
      ReleaseObjects();
      return(INIT_FAILED);
     }
   g_done_time=0;
   g_last_status=MTF_NOT_COMPUTED;
   Print("MtfAlignmentDemo attached: symbol=",_Symbol,", base=",MtfTimeframeName(base_tf),
         ", timeframes=",count,", retries=",InpMaxRetries,".");
   return(INIT_SUCCEEDED);
  }

//+------------------------------------------------------------------+
//| Releases the objects and prints a readable detach message.       |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   ReleaseObjects();
   Print("MtfAlignmentDemo detached: ",DeinitReasonText(reason),".");
  }

OnCalculate() first marks every new buffer element as EMPTY_VALUE. It works once per closed base bar, tracked by g_done_time. An invalid bundle leaves EMPTY_VALUE, logs on a status change, and is retried on the next tick. This retry costs extra reads on every tick until the bundle becomes valid, which is the price of a gate that never uses stale data.

A valid bundle must also describe the same closed bar that the chart shows. The check compares BaseOpenTime() with time[closed_index]. All arrays use the default non-series indexing, and the code never changes that flag.

//+------------------------------------------------------------------+
//| Runs Build() once per closed base bar. A valid bundle plots the  |
//| score at the closed bar. An invalid bundle plots EMPTY_VALUE,    |
//| computes nothing, and is retried on the next tick.               |
//| All arrays use the default non-series indexing.                  |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
  {
   if(rates_total<3)
      return(0);
   if(CheckPointer(g_aggregator)==POINTER_INVALID)
      return(0);
//--- mark every new element as empty, never as zero
   int first=0;
   if(prev_calculated>0 && prev_calculated<=rates_total)
      first=prev_calculated;
   if(first==0)
      g_done_time=0;
   for(int i=first;i<rates_total;i++)
      g_score[i]=EMPTY_VALUE;
//--- work only once per closed base bar
   const int closed_index=rates_total-2;
   if(time[closed_index]==g_done_time)
      return(rates_total);
//--- build the bundle and log only when the status changes
   CAlignedBundle bundle;
   CMtfError error;
   bool ok=g_aggregator.Build(bundle,error);
   LogOnStatusChange(bundle,error);
//--- an invalid bundle blocks the calculation for this bar
   if(!ok)
     {
      g_score[closed_index]=EMPTY_VALUE;
      return(rates_total);
     }
//--- the bundle must describe the same closed bar that the chart shows
   if(bundle.BaseOpenTime()!=time[closed_index])
     {
      g_score[closed_index]=EMPTY_VALUE;
      return(rates_total);
     }
//--- compute and plot the score
   g_score[closed_index]=(double)ComputeAgreementScore(bundle);
   g_done_time=time[closed_index];
   return(rates_total);
  }



Verification and Testing: TestMultiTFAggregator.mq5

The test script runs every rule against a fake bar source with scripted series, so it needs no terminal and no market data. CFakeBarSource derives from CBarSourceBase and returns gap-free series that a test can override bar by bar. It can also script a base bar that rolls during a read, which imitates a race. The script prints a summary of passed and failed assertions at the end.

Fifteen test groups cover the pure validator rules, the data model, the two worked examples, and the ahead and stale cases. They also cover the weekend, daily break, and early session close gaps, every configuration error, failed reads, grid and time errors, a race retry that succeeds and one that fails, and the exact report text. Every status code is produced by at least one group.

The script does not test the real CTerminalBarSource, history synchronization, or live races. A passing run proves the logic against scripted inputs, and it proves nothing about live terminal behavior. The listing below shows only the entry point, which runs every group and prints the summary. The full script is in the attached source files.

//+------------------------------------------------------------------+
//| Script entry point: runs every test group and prints a summary.  |
//+------------------------------------------------------------------+
void OnStart(void)
  {
   Print("TestMultiTFAggregator started. Synthetic data only.");
   TestValidatorUnits();
   TestBundleBehavior();
   TestWorkedExampleOne();
   TestWorkedExampleTwo();
   TestRaceAhead();
   TestStale();
   TestWeekendGap();
   TestDailyBreakGap();
   TestEarlySessionClose();
   TestConfigureErrors();
   TestReadErrors();
   TestGridAndTimeErrors();
   TestRaceRetrySucceeds();
   TestRaceRetryFails();
   TestReports();
   PrintFormat("TestMultiTFAggregator finished. Passed: %d, Failed: %d.",g_pass,g_fail);
   if(g_fail==0)
      Print("RESULT: ALL ASSERTIONS PASSED");
   else
      Print("RESULT: SOME ASSERTIONS FAILED");
  }



Interpreting the Logs

This section shows what the two programs print. The first two figures come from the test script, which uses scripted synthetic data. The live lines come from the demo indicator on real charts.

An aligned bundle: every bar ends at T = 12:00

An aligned bundle logged by the report test

Legend: green is the state VALID, blue is times, gray is field names, and black is ordinary values.

Figure 3: An aligned bundle logged by the report test. All three bars end exactly at the snapshot time 12:00.

Expected output:

---- Aligned bundle: base M15, forming bar 2026.10.07 12:00 ----
MTF bundle | state=VALID | symbol=TESTSYM | base=M15 | snapshot=2026.10.07 12:00 | timeframes=3
MTF bar | tf=M15 | open=2026.10.07 11:45 | end=2026.10.07 12:00 | bars=5000
MTF bar | tf=H1 | open=2026.10.07 11:00 | end=2026.10.07 12:00 | bars=1250
MTF bar | tf=H4 | open=2026.10.07 08:00 | end=2026.10.07 12:00 | bars=312

Read the header first. The state is VALID, and the snapshot time T is 12:00. Then check that every end value is at or before T. Here all three bars end exactly at 12:00, so all three timeframes describe the same moment.

The bars value is a diagnostic count. It is not part of the alignment test, but a sudden drop in it points to a history problem.

A rejected bundle: H4 is ahead of the snapshot

A rejected bundle from injected synthetic data, not from a live market.

Legend: red is the error status and the time the series reported, green is the time the rules required, amber is fixed message text, and gray is field names and code=0.

Figure 4: A rejected bundle from injected synthetic data, not from a live market. The base series reports a forming bar at 11:45, while H4 already shows 12:00. The gate blocks and no partial bundle is returned.

This output does not come from a live market. The test script injects the case on purpose: the base series reports a forming bar at 11:45, while the H4 series already shows 12:00.

Expected output:

---- Injected race case (synthetic data): base F=11:45, H4 already at 12:00 ----
MTF error | status=MTF_ERR_AHEAD | tf=H4 | expected=2026.10.07 08:00 | actual=2026.10.07 12:00 | code=0 | text=The series is ahead of the base snapshot.
Gate: blocked | valid=false | timeframes=0

The error line names the first offending timeframe, the open time the rules required, and the open time the series reported. The code field is 0 because no terminal call failed. A failed copy would carry the value of GetLastError() there.

The last line shows the gate. An invalid bundle has no bars, so no calculation can use half of a snapshot.

The script ends with a summary. In a terminal run, it printed these lines:

TestMultiTFAggregator finished. Passed: 205, Failed: 0.
RESULT: ALL ASSERTIONS PASSED

Live lines from the demo indicator

The demo indicator was also attached to ETHUSD and BTCUSD charts on a demo account. A valid bundle on an M1 chart looked like this:

MtfAlignmentDemo attached: symbol=ETHUSD, base=M1, timeframes=3, retries=3.
MTF bundle | state=VALID | symbol=ETHUSD | base=M1 | snapshot=2026.10.11 13:56 | timeframes=3
MTF bar | tf=M1 | open=2026.10.11 13:55 | end=2026.10.11 13:56 | bars=100032
MTF bar | tf=M5 | open=2026.10.11 13:50 | end=2026.10.11 13:55 | bars=100003
MTF bar | tf=M15 | open=2026.10.11 13:30 | end=2026.10.11 13:45 | bars=36520

At 13:56, the M5 bar that opened at 13:55 and the M15 bar that opened at 13:45 are still forming, so the bundle correctly holds the older closed bars. The bars values stop near 100000, which looks like the terminal limit for bars in a chart. They are diagnostics only.

Three kinds of rejection appeared in the live logs.

The first is MTF_ERR_TOO_FEW_BARS with bars=0, which appears right after attaching the indicator, or when the terminal refreshes history. For example:

MTF error | status=MTF_ERR_TOO_FEW_BARS | tf=H1 | expected=n/a | actual=n/a | code=0 | text=The series holds too few bars. (bars=0)

The terminal was still building the series for the second timeframe. The next valid bundle followed within seconds, with no action needed. Opening a chart for each requested timeframe first avoids most of these lines.

The second is the attach failure on a chart whose timeframe equals one of the inputs. The indicator prints a plain message and stops, because a repeated timeframe is a configuration error.

The third is a look-ahead conflict at a minute boundary on ETHUSD M1:

MTF error | status=MTF_ERR_LOOKAHEAD | tf=M5 | expected=2026.10.11 13:54 | actual=2026.10.11 13:55 | code=0 | text=The closed bar ends after the snapshot time.

For this status, the expected field holds the snapshot time T, and the actual field holds the end time of the closed bar. Here T is 13:54, but the closed M5 bar ends at 13:55. That pattern fits a base series with no bar for 13:54: the last closed M1 bar ended at 13:54, while the forming M1 bar already opened at 13:55. The next valid bundle came one minute later, at snapshot 13:56. The limitations section explains why the rule behaves this way.

The agreement score appears as one dot on each closed base bar. A score of 3 means that all three timeframes closed above their open. A score of -1 means that two closed below and one above, or one closed below and the other two tied. A tie adds zero.

The demo indicator on a live ETHUSD M1 chart.

Figure 5: The demo indicator on a live ETHUSD M1 chart. The sub-window shows one dot for each closed base bar that passed the aggregator. The dot height is the agreement score on a fixed scale from -4.5 to 4.5, and a bar that fails the check gets no dot.



Extending the Aggregator

The design keeps the extension points narrow.

A new data source needs only a class that derives from CBarSourceBase and implements SymbolName(), IsSynchronized(), BarCount(), and ReadBar(). The aggregator never calls the terminal directly. A source that reads from a file, a database, or a custom symbol therefore works without changes to the rules.

A new rule belongs in CAlignmentValidator. Its methods are stateless, so a new check is a new const method plus a new status code. Add the code to ENUM_MTF_STATUS, then to MtfStatusName() and MtfStatusText(), and add a test group that produces it.

A larger timeframe list is a change to MTF_MAX_TIMEFRAMES. The fixed arrays inside CAlignedBundle grow with it. Keep the limit small, because every extra series adds reads to every Build() call.

Consumers can also change. The demo indicator gates a simple score. An expert advisor can call Build() once per new base bar and skip the bar when the result is invalid. The only contract is that a failed call returns no partial bundle.



Limitations and Design Tradeoffs

The rules assume that every timeframe starts on the same grid. Some brokers use sessions that shift the H4 or D1 boundary, or move the daily boundary with daylight saving time. On such a symbol, the grid check reports an error instead of guessing, so the aggregator is strict but not universal. MN1 is rejected because months have no fixed length. W1 is rejected because week bars open on a Sunday, which is not on the 604800-second grid, since the epoch fell on a Thursday. Data from indicator handles is not covered either. The bundle holds price bars only, and a moving average read through a handle on another timeframe has its own calculation delay.

A consistent snapshot does not prove a strategy correct. It only removes one class of error: mixing bars from different moments. The library checks times, not prices: a bar passes when its open time fits the rules, and the OHLC values and volume are not checked. Each build attempt costs one BarCount() call and two ReadBar() calls per timeframe, plus one extra ReadBar() call to re-read the forming base bar. Only that base bar is re-read, so a higher timeframe series that changes after it was read, while the base stays the same, is not detected. The retry loop is bounded and has no Sleep(). The demo retries only when a tick arrives, so a program that must recover on a closed market needs its own timer.

A thin feed can cause a false rejection. If the base series has no bar for a quiet period, the snapshot time falls behind a higher-timeframe bar that has in fact closed. The conservative rule then reports MTF_ERR_LOOKAHEAD until the next base bar closes. In one live run on ETHUSD M1, this blocked the bundle for about one minute.



Conclusion

The aggregator turns a vague problem into a short list of testable rules. Each timeframe is compared with a single snapshot time, and any mismatch becomes a structured error instead of a silent wrong value.

The structure also makes the code easy to verify. A fake bar source drives fifteen test groups without a terminal, and every status code has a test that produces it. Live runs on two symbols showed aligned bundles at each closed bar, and they showed the guard blocking while history loaded. These runs illustrate the behavior on two symbols of a demo account. They do not show that the rules hold for every broker, session schedule, or time zone.


Programs used in the article:

#NameTypeDescription
1MultiTFTypes.mqhInclude FileDefines the status codes, the error and bar structures, and the aligned bundle class.
2BarSource.mqhInclude FileDefines the abstract bar source and the terminal implementation that reads real history.
3AlignmentValidator.mqhInclude File
Holds the stateless alignment rules for grid, recency, and closed-bar checks.
4MultiTFAggregator.mqhInclude File
Builds an aligned bundle with a bounded retry loop for base changes.
5MultiTFReport.mqhInclude File
Formats bundles and errors into fixed log lines.
6MtfAlignmentDemo.mq5Custom IndicatorPlots a demonstration score only when the bundle is aligned.
7TestMultiTFAggregator.mq5ScriptRuns the assertion groups against a fake bar source and prints the log text.
8MultiTFAggregator.zipZip ArchiveZip archive containing all the attached files and their paths relative to the terminal's root folder.
Automating Trading Strategies in MQL5 (Part 54): Consolidation Breakout and Retest Entry Model Automating Trading Strategies in MQL5 (Part 54): Consolidation Breakout and Retest Entry Model
We implement an MQL5 program that validates consolidations by counting edge switches, height capped to the typical candle, and net drift, then requires a buffered close beyond an edge and a move away before arming. Entry follows a return to the broken edge and a strong close back on the breakout side. The stop anchors beyond the retest extreme; the target is an R-multiple, and failed attempts can rearm the same range after a fresh breakout and retest.
Neural Networks in Trading: Difference-Based Modeling of Market Microstructure (EDCFlow) Neural Networks in Trading: Difference-Based Modeling of Market Microstructure (EDCFlow)
In the article, we explore the EDCFlow framework, which offers a new approach to analyzing market microstructure. It combines state correlation with a difference map, making it possible to identify subtle dynamic changes in the market. The model's architecture effectively aggregates multiscale features with minimal computational cost, making it suitable for real-time analysis.
Building a PDF Creation Library in MQL5 (Part 4): Lines Boxes and Color Building a PDF Creation Library in MQL5 (Part 4): Lines Boxes and Color
The article turns drawing primitives into PDF output: one cm flip installs a top‑left, y‑down system, while CPdfPage writes m/l/c/h/re, S/f/B, W n, and transforms from calls on CPdfSurface. PdfColor keeps RGB bytes and fixes MQL5 byte order when writing fractions. It also covers caps, joins, dashes, clipping, and Bezier circles. Demos include a printable ruler, a feature sampler, and a ready letterhead script.
Detrended Cross-Correlation Analysis (DCCA) for Pairs-Trading Pair Selection Under Nonstationarity Detrended Cross-Correlation Analysis (DCCA) for Pairs-Trading Pair Selection Under Nonstationarity
A complete, native MQL5 toolkit for Detrended Cross-Correlation Analysis: engine, validator, basket scanner, and a reference spread-trading EA. The engine produces a scale-by-scale rho_DCCA(s) curve and a band-mean score to rank pairs, contrasted with a standard Pearson correlation. The article details the box-detrending approach and shows real Strategy Tester results to illustrate how the gate integrates into trade decisions.