Building a Daily OHLCV Aggregator from M1 Bars in MQL5
Introduction
Every MetaTrader chart draws daily candles the same way: one per calendar day, rolling over whenever the broker's server clock says midnight. Usually nobody notices. But once a strategy needs a specific session convention instead of an arbitrary server-clock one, that assumption starts to cost real accuracy, and MQL5 has no built-in way to ask for something different.
Take the New York close convention, common in forex: a trading day runs 5 p.m. to the next day's 5 p.m. Some traders label that day by its end date (“Tuesday's candle”). This project does not do that. It stores each daily bar's time as the first real tick of the session, matching how MetaTrader already treats a bar's time field, as an open, not a close. Anyone who wants an end-date label can compute one separately; it is not what gets written to the symbol.
MetaTrader's native D1 timeframe does not support this convention. It rolls over at the broker's server time, which is rarely UTC and almost never exactly 5 pm New York time. So a trader reading native D1 bars as if they followed session-close logic is looking at bars that are simply wrong for that purpose: highs and lows near the edges of the day belong partly to the wrong day, and the close price reflects the broker's midnight rather than the true session close. Any per-day statistic inherits that misalignment.
There is no setting that fixes this. A trader who needs session-aligned daily bars either eyeballs the misalignment by hand each time, which does not scale, or rebuilds the daily bars from lower timeframe data using the correct boundary. This article builds the second option: a script that regroups M1 history into daily bars aligned to a session close hour the trader supplies, in the terminal's own time, not a guaranteed New York time. Matching true New York close means working out the correct hour against the broker's server offset, and rechecking it across daylight saving changes. The entire tool hinges on one piece of arithmetic: correctly deciding which session-aligned day any given M1 bar belongs to.

Figure 1. Architecture of the daily OHLCV aggregation pipeline, from reading M1 bars through to writing the custom symbol and logging the summary.
The Day-Boundary Problem and the Shift-Truncate-Restore Technique
It is tempting to compute "which day does this bar belong to" inline, directly inside the aggregation loop. That is also the easiest way to introduce a bug that never announces itself. An off-by-one at a day boundary quietly shifts a few bars into the wrong group; the script still runs cleanly, and the output still looks plausible even though some bars have the wrong open or close.
The fix is architectural: isolate the boundary calculation into a small, pure function with no terminal dependency, no CopyRates() call, no side effects. A function like that can be tested by hand with synthetic timestamps, at the boundary itself, one second before it, and one second after. Passing those three tests shows the function is sound at the boundary, where off-by-one errors are most likely. It does not prove correctness across all dates, hours, daylight-saving transitions, or incomplete data; it only confirms the arithmetic at its most common failure point. Folding the same logic into the aggregation loop makes it much harder to isolate and test.
The technique itself is standard date arithmetic, and it generalizes to any session close hour with no special cases:
- Shift the timestamp backward by the session close offset.
- Truncate the result down to midnight.
- Shift it forward again by the same offset.
Shifting backward maps the session boundary onto ordinary calendar midnight. Truncating to midnight then groups everything by that boundary. Shifting forward undoes the remapping, so the result is expressed on the original clock but labeled at the true session boundary. Because it is pure arithmetic with no special-cased hour, it works identically whether the session close is 0, 9, 17, or 23. A close hour of 0 is a useful sanity check: shifting by zero seconds is a no-op, so the technique gracefully reduces to an ordinary calendar day.
The boundary itself is where this can go wrong, so it is the one place worth testing directly. A bar exactly at the session close hour, one second before it, and one second after it should land in three specific groups: the start of a new session day, the end of the previous one, and a continuation of the new one. Getting the middle of a day right is easy. Getting the exact second of the boundary right is the whole problem.
Session day key for a 17:00 session close, bar at 16:59:59

Result: this bar is grouped under the session day that began on 14 March 2024
Figure 2: the shift-truncate-restore technique applied to the 16:59:59 boundary case, showing how a bar one second before rollover is correctly assigned to the previous session day.
A short example makes this concrete, using a session close hour of 17 (5 p.m., expressed as an offset from the terminal's own time handling rather than a guaranteed UTC):
| Bar timestamp | Session close hour | Resulting day key |
|---|---|---|
| 2024-03-15 10:30:00 | 0 | 2024-03-15 00:00:00 |
| 2024-03-15 10:00:00 | 17 | 2024-03-14 17:00:00 |
| 2024-03-15 16:59:59 | 17 | 2024-03-14 17:00:00 |
| 2024-03-15 17:00:00 | 17 | 2024-03-15 17:00:00 |
| 2024-03-15 17:00:01 | 17 | 2024-03-15 17:00:00 |
Consider the pair at 16:59:59 and 17:00:00. They are one second apart on the clock, yet land in two different session days. That is exactly the discontinuity a session-close convention demands, and exactly what a naive "just check the hour" implementation tends to get wrong by a second in one direction or the other.
Custom Symbols as a Charting Mechanism
A custom symbol charts, scrolls, and runs indicators exactly as a real symbol does. That equivalence is about charting only. It carries no live quote stream, no trading permissions, and none of a broker symbol's contract or margin settings, just whatever bars CustomRatesUpdate() has written. It is for looking at realigned history, not for trading.
That is why this project writes a custom symbol instead of, for example, drawing rectangles on the source symbol's own chart. Rectangles would only be a visual overlay: no moving average could scroll through them, no daily-timeframe indicator could read them, and no other tool expecting a real symbol-and-timeframe pair could use them. A custom symbol, once populated, is a first-class citizen of the terminal. Once the pipeline finishes, opening the custom symbol at the D1 timeframe produces an ordinary candlestick chart built on a boundary convention MetaTrader has no native way to produce on its own.
Two Assumptions Worth Stating Explicitly
Ordering: A daily bar's open must come from whichever M1 bar happened first, and its close from whichever happened last. This project relies on the documented guarantee that CopyRates() returns bars in ascending chronological order, so the aggregation logic can simply treat "first bar seen for a day" as the open and "most recent bar seen" as the close, with no sorting required. If that guarantee did not hold, this would fail silently: the open would become whatever bar happened to appear first in the array, with no error to flag it. That is why it is worth stating the assumption outright rather than leaving it implicit.
Gaps: A session day with zero M1 bars never becomes a group, which cleanly handles weekends and full holidays. It says nothing, though, about a session that gets some bars but not a full set, a Sunday evening open, a thin holiday session, an ordinary internal gap. Those produce a daily bar indistinguishable from a complete one. GetSampleCount() exists so a reader can check this; the project does not check it automatically.
The Data Model — DailyAggregatorTypes.mqh
Before examining any pipeline stage, it helps to settle on the two small data classes everything else is built around. CM1BarSample is the minimal reduction of one M1 bar: its timestamp, its four prices, and its tick volume. CDailyBar is the result of aggregating a whole group of those samples into one synthetic daily candle, along with a running count of how many M1 bars contributed to it.
Both classes keep their fields private and expose only getters, plus the specific methods each needs to be constructed or updated. This keeps every field read-only from the outside once it has been set, which matters once these objects are passed around between the reader, the aggregator, and the writer.
//+------------------------------------------------------------------+ //| DailyAggregatorTypes.mqh | //| Minimal data holders for the aggregator | //+------------------------------------------------------------------+ #ifndef DAILYAGGREGATORTYPES_MQH #define DAILYAGGREGATORTYPES_MQH //+------------------------------------------------------------------+ //| CM1BarSample | //| A minimal, immutable reduction of one M1 bar: just the fields the| //| rest of the pipeline actually needs. | //+------------------------------------------------------------------+ class CM1BarSample { private: datetime m_time; double m_open; double m_high; double m_low; double m_close; long m_tick_volume; public: CM1BarSample(void); CM1BarSample(const datetime time, const double open, const double high, const double low, const double close, const long tick_volume); datetime GetTime(void) const; double GetOpen(void) const; double GetHigh(void) const; double GetLow(void) const; double GetClose(void) const; long GetTickVolume(void) const; };
The default constructor exists only so that arrays of CM1BarSample can be resized before real values are assigned; it produces a placeholder with every field at zero. The parameterized constructor is the one actually used, taking values lifted directly from a single element of the array returned by CopyRates().
//+------------------------------------------------------------------+ //| Default constructor. | //+------------------------------------------------------------------+ CM1BarSample::CM1BarSample(void) { //--- Returns a sample with every field zeroed, useful only as an //--- array placeholder before real data is assigned. m_time = 0; m_open = 0.0; m_high = 0.0; m_low = 0.0; m_close = 0.0; m_tick_volume = 0; } //+------------------------------------------------------------------+ //| Parameterized constructor. | //+------------------------------------------------------------------+ CM1BarSample::CM1BarSample(const datetime time, const double open, const double high, const double low, const double close, const long tick_volume) { m_time = time; m_open = open; m_high = high; m_low = low; m_close = close; m_tick_volume = tick_volume; }
The six getters are simple accessors, each returning exactly one private field, and there is little to say about any one of them individually beyond noting that they are what the rest of the codebase uses to read a sample rather than reaching into its fields directly.
//+------------------------------------------------------------------+ //| CM1BarSample::GetTime | //| Returns: the bar's open time. | //+------------------------------------------------------------------+ datetime CM1BarSample::GetTime(void) const { return(m_time); } //+------------------------------------------------------------------+ //| CM1BarSample::GetOpen | //| Returns: the bar's open price. | //+------------------------------------------------------------------+ double CM1BarSample::GetOpen(void) const { return(m_open); } //+------------------------------------------------------------------+ //| CM1BarSample::GetHigh | //| Returns: the bar's high price. | //+------------------------------------------------------------------+ double CM1BarSample::GetHigh(void) const { return(m_high); } //+------------------------------------------------------------------+ //| CM1BarSample::GetLow | //| Returns: the bar's low price. | //+------------------------------------------------------------------+ double CM1BarSample::GetLow(void) const { return(m_low); } //+------------------------------------------------------------------+ //| CM1BarSample::GetClose | //| Returns: the bar's close price. | //+------------------------------------------------------------------+ double CM1BarSample::GetClose(void) const { return(m_close); } //+------------------------------------------------------------------+ //| CM1BarSample::GetTickVolume | //| Returns: the bar's tick volume. | //+------------------------------------------------------------------+ long CM1BarSample::GetTickVolume(void) const { return(m_tick_volume); }
CDailyBar is a little more involved, because it stores two different timestamps rather than one, and because it owns the logic for how it gets built up from a sequence of samples rather than leaving that logic to whichever class happens to be aggregating.
//+------------------------------------------------------------------+ //| CDailyBar | //| One aggregated synthetic daily bar, plus the session day key it | //| was grouped under and a count of contributing M1 bars. | //+------------------------------------------------------------------+ class CDailyBar { private: datetime m_day_key; datetime m_open_time; double m_open; double m_high; double m_low; double m_close; long m_volume; int m_sample_count; public: CDailyBar(void); void InitializeFromFirstSample(const datetime day_key,const CM1BarSample &first_sample); void ApplySubsequentSample(const CM1BarSample &sample); datetime GetDayKey(void) const; datetime GetOpenTime(void) const; double GetOpen(void) const; double GetHigh(void) const; double GetLow(void) const; double GetClose(void) const; long GetVolume(void) const; int GetSampleCount(void) const; };
The two stored timestamps are not interchangeable. The session day key is the value produced by the shift-truncate-restore calculation, and its only purpose is to answer the question of whether two bars belong to the same daily group; for a nonzero session close hour it represents the start of the session rather than any actual price event. The open time, in contrast, is the real timestamp of whichever M1 bar happened to be chronologically first inside the group, and this is the value that eventually gets written into the custom symbol. The default constructor simply zeroes both, since a freshly constructed CDailyBar is not yet valid for use.
//+------------------------------------------------------------------+ //| CDailyBar::CDailyBar | //| Default constructor. | //+------------------------------------------------------------------+ CDailyBar::CDailyBar(void) { m_day_key = 0; m_open_time = 0; m_open = 0.0; m_high = 0.0; m_low = 0.0; m_close = 0.0; m_volume = 0; m_sample_count = 0; }
InitializeFromFirstSample() and ApplySubsequentSample() are best read together, since between them they define the entire aggregation behavior of this class. Initialization sets every field, open, high, low, and close alike, from the single sample that starts a new group; this is precisely why a session day that receives only one M1 bar still ends up with a fully correct daily bar rather than one with partially uninitialized fields. Every subsequent sample then folds into the existing bar: high becomes the running maximum, low the running minimum, close is overwritten with the newest sample's close, and volume and sample count accumulate. That close is the last M1 bar this project actually received, not a guaranteed true closing tick; a short range, a late to_time, or a gap near the boundary all show up here unflagged.
//+------------------------------------------------------------------+ //| CDailyBar::InitializeFromFirstSample | //+------------------------------------------------------------------+ void CDailyBar::InitializeFromFirstSample(const datetime day_key,const CM1BarSample &first_sample) { m_day_key = day_key; m_open_time = first_sample.GetTime(); m_open = first_sample.GetOpen(); m_high = first_sample.GetHigh(); m_low = first_sample.GetLow(); m_close = first_sample.GetClose(); m_volume = first_sample.GetTickVolume(); m_sample_count = 1; } //+------------------------------------------------------------------+ //| CDailyBar::ApplySubsequentSample | //+------------------------------------------------------------------+ void CDailyBar::ApplySubsequentSample(const CM1BarSample &sample) { m_high = MathMax(m_high,sample.GetHigh()); m_low = MathMin(m_low,sample.GetLow()); m_close = sample.GetClose(); m_volume += sample.GetTickVolume(); m_sample_count++; }
The remaining eight getters follow the same pattern as those on CM1BarSample: each exposes exactly one private field, read-only, to the rest of the codebase.
//+------------------------------------------------------------------+ //| CDailyBar::GetDayKey | //| Returns: the session day key this bar was grouped under. | //+------------------------------------------------------------------+ datetime CDailyBar::GetDayKey(void) const { return(m_day_key); } //+------------------------------------------------------------------+ //| CDailyBar::GetOpenTime | //| Returns: the actual timestamp of the first contributing M1 bar, | //| which is what gets written to the custom symbol. | //+------------------------------------------------------------------+ datetime CDailyBar::GetOpenTime(void) const { return(m_open_time); } //+------------------------------------------------------------------+ //| CDailyBar::GetOpen | //| Returns: the daily open price. | //+------------------------------------------------------------------+ double CDailyBar::GetOpen(void) const { return(m_open); } //+------------------------------------------------------------------+ //| CDailyBar::GetHigh | //| Returns: the daily high price. | //+------------------------------------------------------------------+ double CDailyBar::GetHigh(void) const { return(m_high); } //+------------------------------------------------------------------+ //| CDailyBar::GetLow | //| Returns: the daily low price. | //+------------------------------------------------------------------+ double CDailyBar::GetLow(void) const { return(m_low); } //+------------------------------------------------------------------+ //| CDailyBar::GetClose | //| Returns: the daily close price. | //+------------------------------------------------------------------+ double CDailyBar::GetClose(void) const { return(m_close); } //+------------------------------------------------------------------+ //| CDailyBar::GetVolume | //| Returns: the summed tick volume across all contributing M1 bars. | //+------------------------------------------------------------------+ long CDailyBar::GetVolume(void) const { return(m_volume); } //+------------------------------------------------------------------+ //| CDailyBar::GetSampleCount | //| Returns: how many M1 bars contributed to this daily bar. | //+------------------------------------------------------------------+ int CDailyBar::GetSampleCount(void) const { return(m_sample_count); }
Reading M1 Bars — M1BarReader.mqh
With the data model settled, the next stage is getting raw M1 history off the source symbol and into an array of CM1BarSample records. CM1BarReader is a thin wrapper around CopyRates() whose job is essentially translation: MqlRates carries more fields than this project needs, so this class reduces every returned element down to the six fields that matter.
//+------------------------------------------------------------------+ //| M1BarReader.mqh | //| Reads M1 history for a symbol and time range | //+------------------------------------------------------------------+ #ifndef M1BARREADER_MQH #define M1BARREADER_MQH #include "DailyAggregatorTypes.mqh" //+------------------------------------------------------------------+ //| CM1BarReader | //| Wraps CopyRates() and reduces MqlRates elements into | //| CM1BarSample records. | //+------------------------------------------------------------------+ class CM1BarReader { private: string m_symbol; public: CM1BarReader(void); ~CM1BarReader(void); void SetSymbol(const string symbol); bool ReadBars(const datetime from,const datetime to,CM1BarSample &out_samples[]); };
The constructor and destructor carry no real behavior; the constructor leaves the symbol unset, and SetSymbol() is the method that actually configures which symbol subsequent calls to ReadBars() will read from.
//+------------------------------------------------------------------+ //| CM1BarReader::CM1BarReader | //| Returns: a reader with no symbol set yet; SetSymbol() must be | //| called before ReadBars() is useful. | //+------------------------------------------------------------------+ CM1BarReader::CM1BarReader(void) { m_symbol=""; } //+------------------------------------------------------------------+ //| CM1BarReader::~CM1BarReader | //| Returns: nothing; there is no owned resource to release. | //+------------------------------------------------------------------+ CM1BarReader::~CM1BarReader(void) { } //+------------------------------------------------------------------+ //| CM1BarReader::SetSymbol | //| Assumptions: symbol is a nonempty symbol name. | //| Returns: nothing. Stores the symbol used by subsequent ReadBars()| //| calls. | //+------------------------------------------------------------------+ void CM1BarReader::SetSymbol(const string symbol) { m_symbol=symbol; }
ReadBars() is where the actual work happens. It first resets the output array, then confirms the symbol is actually known and selected in the terminal, so a missing or misspelled symbol is reported distinctly from a genuine CopyRates() failure rather than being mixed in with it. Only then does it call CopyRates() for the requested range at the M1 timeframe. A negative return value from CopyRates() is treated as an outright failure and reported back to the caller as false, with the underlying error available through GetLastError().
A return value of zero, meaning the requested range held no bars at all, is not treated as an error; it is entirely ordinary for a range to fall on a weekend or before the earliest stored history, and the method simply reports success with an empty output. Whenever bars are found, each one is reduced into a CM1BarSample and appended to the output array.
//+-------------------------------------------------------------------+ //| CM1BarReader::ReadBars | //+-------------------------------------------------------------------+ bool CM1BarReader::ReadBars(const datetime from,const datetime to,CM1BarSample &out_samples[]) { //--- reset the output before attempting to read anything ArrayResize(out_samples,0); //--- confirm the symbol is known and selected, so a missing symbol is reported distinctly //--- from a genuine CopyRates() read failure if(!::SymbolSelect(m_symbol,true)) { Print("CM1BarReader: symbol '",m_symbol,"' could not be selected, error ",::GetLastError()); return(false); } //--- request the raw M1 history from the terminal MqlRates rates[]; ArraySetAsSeries(rates,false); int copied=::CopyRates(m_symbol,PERIOD_M1,from,to,rates); if(copied<0) { Print("CM1BarReader: CopyRates failed for ",m_symbol," error ",::GetLastError()); return(false); } if(copied==0) { //--- an empty range is not a failure, it simply means there is nothing to aggregate return(true); } //--- reduce every MqlRates element into the minimal CM1BarSample representation ArrayResize(out_samples,copied); for(int i=0;i<copied;i++) { out_samples[i]=CM1BarSample(rates[i].time, rates[i].open, rates[i].high, rates[i].low, rates[i].close, rates[i].tick_volume); } return(true); }
The Session Day Key — SessionDayKey.mqh
This class implements the shift-truncate-restore technique described earlier, packaged as one pure, static method with no terminal dependency at all. Keeping it free of terminal calls is exactly what allows it to be tested with hand-built synthetic timestamps rather than live price history.
//+------------------------------------------------------------------+ //| SessionDayKey.mqh | //| Computes which session-aligned day a timestamp belongs to | //+------------------------------------------------------------------+ #ifndef SESSIONDAYKEY_MQH #define SESSIONDAYKEY_MQH //+------------------------------------------------------------------+ //| CSessionDayKey | //| Exposes one pure, directly testable method: Calculate(). | //+------------------------------------------------------------------+ class CSessionDayKey { public: static datetime Calculate(const datetime bar_time,const int session_close_hour); };
Calculate() performs the conversion and the three steps described earlier, one line each: converting the session close hour into a seconds offset, shifting backward, truncating to midnight using the modulo of a full day in seconds, and shifting forward again to restore the true boundary.
//+--------------------------------------------------------------------+ //| CSessionDayKey::Calculate | //+--------------------------------------------------------------------+ datetime CSessionDayKey::Calculate(const datetime bar_time,const int session_close_hour) { //--- convert the session close hour into a seconds offset int offset_seconds=session_close_hour*3600; //--- shift backward so the session boundary lines up with calendar midnight datetime shifted=bar_time-offset_seconds; //--- truncate to midnight on the shifted value, discarding the time of day datetime truncated=shifted-(shifted%86400); //--- shift forward by the same offset to restore the true session boundary datetime restored=truncated+offset_seconds; return(restored); }
Grouping and Aggregating into Daily Bars — DailyAggregator.mqh
CDailyAggregator brings the session day key and the CDailyBar initialization logic together. Its task is to walk through every M1 sample in chronological order, compute a session day key for each one, and either start a new daily bar group for that key or fold the sample into a group that already exists.
//+------------------------------------------------------------------+ //| DailyAggregator.mqh | //| Groups M1 samples into session-aligned daily bars | //+------------------------------------------------------------------+ #ifndef DAILYAGGREGATOR_MQH #define DAILYAGGREGATOR_MQH #include "DailyAggregatorTypes.mqh" #include "SessionDayKey.mqh" //+------------------------------------------------------------------+ //| CDailyAggregator | //| Groups an array of CM1BarSample records into CDailyBar records, | //| one per session-aligned day. | //+------------------------------------------------------------------+ class CDailyAggregator { private: int FindGroupIndex(const CDailyBar &groups[],const datetime key) const; public: CDailyAggregator(void); ~CDailyAggregator(void); bool Aggregate(const CM1BarSample &samples[],const int session_close_hour,CDailyBar &out_daily_bars[]); }; //+------------------------------------------------------------------+ //| CDailyAggregator::CDailyAggregator | //| Returns: an aggregator with no internal state to initialize. | //+------------------------------------------------------------------+ CDailyAggregator::CDailyAggregator(void) { } //+------------------------------------------------------------------+ //| CDailyAggregator::~CDailyAggregator | //| Returns: nothing; there is no owned resource to release. | //+------------------------------------------------------------------+ CDailyAggregator::~CDailyAggregator(void) { }
FindGroupIndex() is a private helper performing a linear search over whatever groups have been created so far, comparing day keys directly. For the realistic scale this project targets, a lookback window measured in months producing at most a few thousand distinct days, a linear search is entirely fast enough, and it keeps the logic straightforward to follow.
//+------------------------------------------------------------------+ //| CDailyAggregator::FindGroupIndex | //+------------------------------------------------------------------+ int CDailyAggregator::FindGroupIndex(const CDailyBar &groups[],const datetime key) const { int total=ArraySize(groups); for(int i=0;i<total;i++) { if(groups[i].GetDayKey()==key) return(i); } return(-1); }
Aggregate() is the method that ties everything together. It resets the output, returns early if there is nothing to aggregate, and otherwise loops over every sample, computing its day key and either appending a newly initialized group or updating an existing one. Because CopyRates() guarantees ascending chronological order and the day key function is itself non-decreasing over time, new groups are always appended in the same order their days actually occurred in, which matters later when the resulting array is handed to the custom symbol writer.
//+---------------------------------------------------------------------+ //| CDailyAggregator::Aggregate | //+---------------------------------------------------------------------+ bool CDailyAggregator::Aggregate(const CM1BarSample &samples[],const int session_close_hour,CDailyBar &out_daily_bars[]) { //--- reset the output before aggregating anything ArrayResize(out_daily_bars,0); int total=ArraySize(samples); if(total<=0) return(true); //--- walk every sample in chronological order and place it into its session day group for(int i=0;i<total;i++) { datetime key=CSessionDayKey::Calculate(samples[i].GetTime(),session_close_hour); int group_index=FindGroupIndex(out_daily_bars,key); if(group_index<0) { //--- no existing group for this day yet, create one from this sample int new_size=ArraySize(out_daily_bars)+1; ArrayResize(out_daily_bars,new_size); out_daily_bars[new_size-1].InitializeFromFirstSample(key,samples[i]); } else { //--- fold this sample into the existing group for its day out_daily_bars[group_index].ApplySubsequentSample(samples[i]); } } return(true); }
Writing to a Custom Symbol — CustomSymbolWriter.mqh
CCustomSymbolWriter turns the finished CDailyBar array into something MetaTrader can actually chart. It performs four distinct steps, each corresponding to a real MQL5 API call, and each capable of failing independently.
//+------------------------------------------------------------------+ //| CustomSymbolWriter.mqh | //| Creates and populates a custom symbol from daily bars | //+------------------------------------------------------------------+ #ifndef CUSTOMSYMBOLWRITER_MQH #define CUSTOMSYMBOLWRITER_MQH #include "DailyAggregatorTypes.mqh" //+-------------------------------------------------------------------+ //| CCustomSymbolWriter | //| Ensures a custom symbol exists, configures its digits, clears any | //| pre-existing bars, and writes an array of CDailyBar records into | //| it. | //+-------------------------------------------------------------------+ class CCustomSymbolWriter { private: string m_custom_folder; public: CCustomSymbolWriter(void); ~CCustomSymbolWriter(void); bool EnsureSymbolExists(const string symbol_name,bool &out_was_created); bool ConfigureDigits(const string symbol_name,const string source_symbol); bool ClearExistingRange(const string symbol_name); bool WriteDailyBars(const string symbol_name,const CDailyBar &daily_bars[]); }; //+------------------------------------------------------------------+ //| CCustomSymbolWriter::CCustomSymbolWriter | //| Returns: a writer that will create new custom symbols under a | //| dedicated "Custom\\DailyAggregator" path in the Symbols | //| tree. | //+------------------------------------------------------------------+ CCustomSymbolWriter::CCustomSymbolWriter(void) { m_custom_folder = "Custom\\DailyAggregator"; } //+------------------------------------------------------------------+ //| CCustomSymbolWriter::~CCustomSymbolWriter | //| Returns: nothing; there is no owned resource to release. | //+------------------------------------------------------------------+ CCustomSymbolWriter::~CCustomSymbolWriter(void) { }
EnsureSymbolExists() is the first step, and it is worth reading its real dependency carefully. SymbolExist() reports whether a symbol with the given name exists at all through its return value, and separately reports whether that existing symbol is a custom one through a boolean passed by reference. If a custom symbol by this name already exists, nothing further needs to happen. If a symbol exists but is not a custom one, this method refuses to proceed rather than risk colliding with a real broker symbol. Only when no symbol exists at all does it call CustomSymbolCreate() to register a new one under a dedicated folder in the Symbols tree, reporting failure and the underlying error code if that call does not succeed.
//+---------------------------------------------------------------------+ //| CCustomSymbolWriter::EnsureSymbolExists | //+---------------------------------------------------------------------+ bool CCustomSymbolWriter::EnsureSymbolExists(const string symbol_name,bool &out_was_created) { //--- SymbolExist() reports existence via its return value and writes into //--- is_custom whether that existing symbol is a custom one bool is_custom = false; bool exists = ::SymbolExist(symbol_name,is_custom); if(exists && is_custom) { out_was_created=false; return(true); } if(exists && !is_custom) { //--- a real, non-custom symbol already occupies this name, refuse to proceed Print("CCustomSymbolWriter: '",symbol_name,"' already exists as a non-custom symbol, choose a different name"); out_was_created = false; return(false); } //--- the symbol does not exist yet, so create it under a dedicated custom folder bool created=::CustomSymbolCreate(symbol_name,m_custom_folder); if(!created) { Print("CCustomSymbolWriter: CustomSymbolCreate failed for ",symbol_name," error ",::GetLastError()); out_was_created = false; return(false); } out_was_created = true; return(true); }
ConfigureDigits() is the second step. It first confirms the source symbol is selected, then reads its SYMBOL_DIGITS property using the boolean-returning overload of SymbolInfoInteger(), which reports a failed read explicitly instead of returning an ambiguous value. The digits are then applied to the custom symbol using CustomSymbolSetInteger(), so the synthetic symbol displays prices with the same precision as the symbol it was derived from.
//+---------------------------------------------------------------------+ //| CCustomSymbolWriter::ConfigureDigits | //+---------------------------------------------------------------------+ bool CCustomSymbolWriter::ConfigureDigits(const string symbol_name,const string source_symbol) { //--- confirm the source symbol is actually selected and known to the terminal before reading from it if(!::SymbolSelect(source_symbol,true)) { Print("CCustomSymbolWriter: source symbol '",source_symbol,"' could not be selected, error ",::GetLastError()); return(false); } //--- read digits with the boolean-returning overload, which reports success or failure explicitly //--- instead of returning an ambiguous value when the read fails long source_digits=0; if(!::SymbolInfoInteger(source_symbol,SYMBOL_DIGITS,source_digits)) { Print("CCustomSymbolWriter: failed to read SYMBOL_DIGITS from '",source_symbol,"' error ",::GetLastError()); return(false); } bool result = ::CustomSymbolSetInteger(symbol_name,SYMBOL_DIGITS,source_digits); if(!result) Print("CCustomSymbolWriter: CustomSymbolSetInteger(SYMBOL_DIGITS) failed for ",symbol_name," error ",::GetLastError()); return(result); }
ClearExistingRange() is the new third step, and the reason it exists is that CustomRatesUpdate() only adds or overwrites bars in the range it is given; it never removes bars left over from an earlier run. Without this step, rerunning the script with a shorter lookback window, a different session close hour, or corrected logic would leave stale bars sitting alongside the fresh ones. This method deletes all existing bars with CustomRatesDelete() before writing, so each run starts clean.
//+---------------------------------------------------------------------+ //| CCustomSymbolWriter::ClearExistingRange | //+---------------------------------------------------------------------+ bool CCustomSymbolWriter::ClearExistingRange(const string symbol_name) { int deleted=::CustomRatesDelete(symbol_name,0,D'2099.12.31 23:59:59'); if(deleted<0) { Print("CCustomSymbolWriter: CustomRatesDelete failed for ",symbol_name," error ",::GetLastError()); return(false); } Print("CCustomSymbolWriter: cleared ",deleted," pre-existing bars from ",symbol_name," before writing"); return(true); }
WriteDailyBars() is the fourth step, and the one that actually populates the chart. It converts the CDailyBar array into an MqlRates array, the same structure CopyRates() itself returns rather than a separate structure, and hands that array to CustomRatesUpdate(), which reports either the number of bars it wrote or a negative value on failure. A nonnegative result is not automatically treated as complete success, though: if CustomRatesUpdate() reports writing fewer bars than were actually requested, that is logged as a failure in its own right, since a short write would otherwise leave the custom symbol silently incomplete.
//+---------------------------------------------------------------------+ //| CCustomSymbolWriter::WriteDailyBars | //+---------------------------------------------------------------------+ bool CCustomSymbolWriter::WriteDailyBars(const string symbol_name,const CDailyBar &daily_bars[]) { int total = ArraySize(daily_bars); if(total<=0) { Print("CCustomSymbolWriter: no daily bars to write for ",symbol_name); return(false); } //--- convert each aggregated daily bar into the MqlRates structure CustomRatesUpdate() expects MqlRates rates[]; ArrayResize(rates,total); for(int i=0;i<total;i++) { rates[i].time = daily_bars[i].GetOpenTime(); rates[i].open = daily_bars[i].GetOpen(); rates[i].high = daily_bars[i].GetHigh(); rates[i].low = daily_bars[i].GetLow(); rates[i].close = daily_bars[i].GetClose(); rates[i].tick_volume = daily_bars[i].GetVolume(); rates[i].real_volume = 0; rates[i].spread = 0; } int written = ::CustomRatesUpdate(symbol_name,rates); if(written<0) { Print("CCustomSymbolWriter: CustomRatesUpdate failed for ",symbol_name," error ",::GetLastError()); return(false); } if(written!=total) { Print("CCustomSymbolWriter: WARNING, requested ",total," bars but only ", written," were written for ",symbol_name,", the custom symbol may be incomplete"); return(false); } Print("CCustomSymbolWriter: wrote ",written," daily bars to ",symbol_name); return(true); }
A caller ought to treat each of these four steps as a genuine decision point. If symbol creation fails, there is no symbol left to configure or write to. If digit configuration fails, the symbol will still function but may display the wrong number of decimal places, which this project treats as reason enough to stop rather than proceed with a misconfigured symbol. If clearing the existing range fails, the run stops rather than risk writing fresh bars on top of whatever was already there. If writing fails, nothing has actually been written, and the terminal has no data to show for the run.
The Experts Tab Summary — AggregationSummaryPrinter.mqh
CAggregationSummaryPrinter has the simplest task in the project: report what happened. It accepts the raw M1 bar count, the finished CDailyBar array, whether the custom symbol was newly created, and the symbol's name, and prints a short summary to the Experts tab.
//+------------------------------------------------------------------+ //| AggregationSummaryPrinter.mqh | //| Prints a pipeline summary to the Experts tab | //+------------------------------------------------------------------+ #ifndef AGGREGATIONSUMMARYPRINTER_MQH #define AGGREGATIONSUMMARYPRINTER_MQH #include "DailyAggregatorTypes.mqh" //+------------------------------------------------------------------+ //| CAggregationSummaryPrinter | //| Stateless utility that prints a summary of one aggregation run. | //+------------------------------------------------------------------+ class CAggregationSummaryPrinter { public: static void PrintSummary(const int m1_bar_count, const CDailyBar &daily_bars[], const bool symbol_was_created, const string symbol_name); };
Because the daily bars array arrives already in ascending chronological order, the earliest and latest dates are simply its first and last elements, with no additional sorting or scanning required.
//+--------------------------------------------------------------------+ //| CAggregationSummaryPrinter::PrintSummary | //+--------------------------------------------------------------------+ void CAggregationSummaryPrinter::PrintSummary(const int m1_bar_count, const CDailyBar &daily_bars[], const bool symbol_was_created, const string symbol_name) { int group_count=ArraySize(daily_bars); //--- print the headline counts first Print("=== Daily OHLCV Aggregation Summary ==="); Print("M1 bars read: ",m1_bar_count); Print("Session-aligned daily groups formed: ",group_count); //--- report the date range covered, if any groups were formed if(group_count>0) { datetime earliest=daily_bars[0].GetOpenTime(); datetime latest=daily_bars[group_count-1].GetOpenTime(); Print("Date range covered: ",::TimeToString(earliest,TIME_DATE)," to ",::TimeToString(latest,TIME_DATE)); } else { Print("Date range covered: none, no daily groups were produced"); } //--- report whether the destination custom symbol was newly created if(symbol_was_created) Print("Custom symbol '",symbol_name,"' was newly created and updated"); else Print("Custom symbol '",symbol_name,"' already existed and was updated"); Print("=== End of summary ==="); }
Building the Main Script — DailyOHLCVAggregator.mq5
Every supporting class exists to serve this script, where all of the pieces are wired together into a single pipeline. The inputs let a trader choose the source symbol, how far back to look, the session close hour, the name of the destination custom symbol, and whether the still-forming current session should be written anyway rather than excluded by default.
//+------------------------------------------------------------------+ //| DailyOHLCVAggregator.mq5 | //| Builds session-aligned daily OHLCV bars from M1 history and | //| writes them into a custom symbol | //+------------------------------------------------------------------+ #property script_show_inputs #include <DailyOHLCVAggregator/DailyAggregatorTypes.mqh> #include <DailyOHLCVAggregator/M1BarReader.mqh> #include <DailyOHLCVAggregator/SessionDayKey.mqh> #include <DailyOHLCVAggregator/DailyAggregator.mqh> #include <DailyOHLCVAggregator/CustomSymbolWriter.mqh> #include <DailyOHLCVAggregator/AggregationSummaryPrinter.mqh> input string InpSourceSymbol = "EURUSD"; // Source symbol to read M1 bars from input int InpLookbackDays = 90; // How many days of M1 history to read input int InpSessionCloseHour = 17; // Session close hour (0-23), terminal time, NOT automatically New York time input string InpCustomSymbolName = "EURUSD.NYC"; // Name of the custom symbol to create or update input bool InpIncludeCurrentSession = false; // Include the still-forming current session (logged as incomplete)
OnStart() opens by validating the two numeric inputs before doing any real work, since a negative lookback or an out-of-range session close hour would otherwise propagate silently into nonsensical results further down the pipeline.
//+-------------------------------------------------------------------+ //| OnStart | //+-------------------------------------------------------------------+ void OnStart(void) { //--- validate inputs before doing any work if(InpLookbackDays<=0 || InpLookbackDays>3650) { Print("DailyOHLCVAggregator: InpLookbackDays must be between 1 and 3650"); return; } if(InpSessionCloseHour<0 || InpSessionCloseHour>23) { Print("DailyOHLCVAggregator: InpSessionCloseHour must be between 0 and 23"); return; }
Once the inputs are validated, the script computes the lookback window, reads the raw M1 bars for the source symbol, and stops immediately if reading fails outright or if the requested window happens to contain no bars at all.
//--- compute the lookback window in the terminal's own time handling datetime to_time=::TimeCurrent(); datetime from_time=to_time-InpLookbackDays*86400; //--- read the raw M1 bars for the source symbol CM1BarReader reader; reader.SetSymbol(InpSourceSymbol); CM1BarSample samples[]; if(!reader.ReadBars(from_time,to_time,samples)) { Print("DailyOHLCVAggregator: failed to read M1 bars for ",InpSourceSymbol); return; } int m1_count=ArraySize(samples); if(m1_count==0) { Print("DailyOHLCVAggregator: no M1 bars available for ",InpSourceSymbol," in the requested window"); return; }
With M1 samples in hand, the script aggregates them into session-aligned daily bars, checks the result for a partial first bar or a still-forming current session, then walks through the four custom symbol writer steps in sequence: ensuring the symbol exists, configuring its digits, clearing any bars left from an earlier run, and writing the fresh daily bars into it, stopping at whichever step fails first.
//--- group and aggregate the M1 bars into session-aligned daily bars CDailyAggregator aggregator; CDailyBar daily_bars[]; if(!aggregator.Aggregate(samples,InpSessionCloseHour,daily_bars)) { Print("DailyOHLCVAggregator: aggregation failed"); return; } //--- warn when the lookback window began partway through a session day, since that means //--- the very first daily bar produced only reflects the part of that session seen by this run datetime window_start_key=CSessionDayKey::Calculate(from_time,InpSessionCloseHour); if(ArraySize(daily_bars)>0 && daily_bars[0].GetDayKey()==window_start_key && from_time!=window_start_key) { Print("DailyOHLCVAggregator: WARNING, the first daily bar (", ::TimeToString(daily_bars[0].GetOpenTime(),TIME_DATE), ") may be partial, the lookback window started partway through that session day"); } //--- the current session day is still forming; exclude it unless told otherwise datetime current_session_key=CSessionDayKey::Calculate(::TimeCurrent(),InpSessionCloseHour); int last_index=ArraySize(daily_bars)-1; bool last_is_incomplete=(last_index>=0 && daily_bars[last_index].GetDayKey()==current_session_key); if(last_is_incomplete) { if(InpIncludeCurrentSession) { Print("DailyOHLCVAggregator: WARNING, the current session (", ::TimeToString(daily_bars[last_index].GetOpenTime(),TIME_DATE), ") is still forming and is being written anyway because InpIncludeCurrentSession is true"); } else { Print("DailyOHLCVAggregator: the current session is still forming and has been excluded from the write, ", "set InpIncludeCurrentSession to true to include it anyway"); ArrayResize(daily_bars,last_index); } } //--- ensure the destination custom symbol exists and is configured CCustomSymbolWriter writer; bool was_created=false; if(!writer.EnsureSymbolExists(InpCustomSymbolName,was_created)) return; if(!writer.ConfigureDigits(InpCustomSymbolName,InpSourceSymbol)) return; if(!writer.ClearExistingRange(InpCustomSymbolName)) return; //--- write the aggregated daily bars into the custom symbol if(!writer.WriteDailyBars(InpCustomSymbolName,daily_bars)) return;
Finally, once writing has succeeded, the script prints the pipeline summary and opens a chart on the resulting custom symbol so the trader can see the outcome immediately, without needing to locate the symbol manually in Market Watch.
//--- print the pipeline summary to the Experts tab CAggregationSummaryPrinter::PrintSummary(m1_count,daily_bars,was_created,InpCustomSymbolName); //--- open a chart on the resulting custom symbol so the reader sees it right away long chart_id=::ChartOpen(InpCustomSymbolName,PERIOD_D1); if(chart_id==0) Print("DailyOHLCVAggregator: ChartOpen failed for ",InpCustomSymbolName," error ",::GetLastError()); }
Every failure path above has already printed an explanation before returning, so a trader watching the Experts tab never sees the script stop without a reason.
Verification and Testing — TestDailyOHLCVAggregator.mq5
This script verifies the session day key and the aggregation logic against synthetic data, needing no live terminal history at all. An ASSERT macro records each check, and a BuildTime() helper constructs exact synthetic timestamps from individual date and time fields using MqlDateTime and StructToTime().
//+------------------------------------------------------------------+ //| TestDailyOHLCVAggregator.mq5 | //| Verifies the session day key and aggregation logic in | //| isolation from any live terminal state | //+------------------------------------------------------------------+ #property script_show_inputs #include <DailyOHLCVAggregator/DailyAggregatorTypes.mqh> #include <DailyOHLCVAggregator/SessionDayKey.mqh> #include <DailyOHLCVAggregator/DailyAggregator.mqh> int g_test_count = 0; int g_pass_count = 0; int g_fail_count = 0; //+------------------------------------------------------------------+ //| ASSERT | //| Records the result of one check, printing a message only on | //| failure. | //| Assumptions: none. | //| Returns: nothing, via the underlying TestAssert() call. | //+------------------------------------------------------------------+ #define ASSERT(condition,message) TestAssert((condition),(message)) //+--------------------------------------------------------------------+ //| TestAssert | //| Returns: nothing. Increments the running pass or fail counters and | //| prints a failure message when condition is false. | //+--------------------------------------------------------------------+ void TestAssert(const bool condition,const string message) { g_test_count++; if(condition) { g_pass_count++; } else { g_fail_count++; Print("FAIL: ",message); } } //+-------------------------------------------------------------------+ //| BuildTime | //| Assumptions: the supplied fields form a valid calendar date and | //| time. | //| Returns: a datetime built from the individual date and time | //| fields, via TimeToStruct/StructToTime style construction.| //+-------------------------------------------------------------------+ datetime BuildTime(const int year,const int mon,const int day,const int hour,const int min,const int sec) { MqlDateTime dt; ::ZeroMemory(dt); dt.year = year; dt.mon = mon; dt.day = day; dt.hour = hour; dt.min = min; dt.sec = sec; return(::StructToTime(dt)); }
The first four test functions all exercise CSessionDayKey::Calculate(), and are best read as one group: a session close hour of zero reducing to an ordinary calendar boundary, a nonzero offset shifting a bar into the previous session day, the exact boundary second along with the seconds immediately before and after it, and finally the same boundary checked at realistic M1 spacing.
That last check matters because CopyRates(PERIOD_M1) returns bars a minute apart, 16:59:00 and 17:00:00, not a second apart; confirming the function still separates them correctly at that spacing is what actually mirrors the input this project receives in practice, rather than only the idealized one-second case.
//+------------------------------------------------------------------+ //| TestSessionDayKeyCalendarDay | //| Returns: nothing. Verifies that a session close hour of 0 reduces| //| the day key to an ordinary calendar day boundary. | //+------------------------------------------------------------------+ void TestSessionDayKeyCalendarDay(void) { datetime bar_time = BuildTime(2024,3,15,10,30,0); datetime expected = BuildTime(2024,3,15,0,0,0); datetime actual = CSessionDayKey::Calculate(bar_time,0); ASSERT(actual==expected,"session close hour 0 should reduce to calendar day boundary"); } //+---------------------------------------------------------------------+ //| TestSessionDayKeyNonzeroOffset | //| Returns: nothing. Verifies that a nonzero session close hour shifts | //| the day boundary to the previous calendar day for a bar | //| that falls before that hour. | //+---------------------------------------------------------------------+ void TestSessionDayKeyNonzeroOffset(void) { datetime bar_time = BuildTime(2024,3,15,10,0,0); datetime expected = BuildTime(2024,3,14,17,0,0); datetime actual = CSessionDayKey::Calculate(bar_time,17); ASSERT(actual==expected,"nonzero session close hour should shift the day boundary correctly"); } //+------------------------------------------------------------------+ //| TestSessionDayKeyBoundary | //| Returns: nothing. Verifies correctness at the exact boundary | //| second, one second before it, and one second after it. | //+------------------------------------------------------------------+ void TestSessionDayKeyBoundary(void) { datetime at_boundary = BuildTime(2024,3,15,17,0,0); datetime before_boundary = BuildTime(2024,3,15,16,59,59); datetime after_boundary = BuildTime(2024,3,15,17,0,1); datetime key_at = CSessionDayKey::Calculate(at_boundary,17); datetime key_before = CSessionDayKey::Calculate(before_boundary,17); datetime key_after = CSessionDayKey::Calculate(after_boundary,17); ASSERT(key_at==BuildTime(2024,3,15,17,0,0),"bar exactly at the boundary should start the new session day"); ASSERT(key_before==BuildTime(2024,3,14,17,0,0),"bar one second before the boundary should belong to the previous session day"); ASSERT(key_after==key_at,"bar one second after the boundary should belong to the same session day as the boundary bar"); } //+---------------------------------------------------------------------+ //| TestSessionDayKeyRealisticM1Boundary | //| Returns: nothing. Verifies the boundary at realistic M1 spacing: | //| real M1 bars straddling a session close arrive a minute | //| apart (16:59:00, 17:00:00), not a second apart, and this | //| confirms the function separates them correctly there too. | //+---------------------------------------------------------------------+ void TestSessionDayKeyRealisticM1Boundary(void) { datetime last_bar_of_day = BuildTime(2024,3,15,16,59,0); datetime first_bar_of_next = BuildTime(2024,3,15,17,0,0); datetime key_last = CSessionDayKey::Calculate(last_bar_of_day,17); datetime key_first = CSessionDayKey::Calculate(first_bar_of_next,17); ASSERT(key_last==BuildTime(2024,3,14,17,0,0),"the 16:59:00 M1 bar should belong to the previous session day"); ASSERT(key_first==BuildTime(2024,3,15,17,0,0),"the 17:00:00 M1 bar should start the new session day"); ASSERT(key_last!=key_first,"the last bar of one session and the first bar of the next must land in different groups"); }
The remaining three test functions exercise CDailyAggregator::Aggregate(), covering a multi-bar group, a single-bar group, and grouping across two distinct session days. The multi-bar test confirms open, high, low, close, and summed volume all come out correctly; the single-bar test confirms that a lone M1 bar produces a daily bar whose four prices all equal that bar's own values rather than being left partially set; and the multi-day test confirms that bars from two different session days remain in two separate, correctly distinguished groups.
//+------------------------------------------------------------------+ //| TestAggregationMultiBar | //| Returns: nothing. Verifies open, high, low, close, and summed | //| volume for a group of three M1 bars in the same session | //| day. | //+------------------------------------------------------------------+ void TestAggregationMultiBar(void) { CM1BarSample samples[]; ArrayResize(samples,3); samples[0] = CM1BarSample(BuildTime(2024,3,15,17,0,0),1.1000,1.1005,1.0995,1.1002,100); samples[1] = CM1BarSample(BuildTime(2024,3,15,17,1,0),1.1002,1.1010,1.1000,1.1008,150); samples[2] = CM1BarSample(BuildTime(2024,3,15,17,2,0),1.1008,1.1009,1.0990,1.1001,120); CDailyAggregator aggregator; CDailyBar daily_bars[]; bool ok=aggregator.Aggregate(samples,17,daily_bars); ASSERT(ok,"aggregation call should succeed for a valid multi-bar group"); ASSERT(ArraySize(daily_bars)==1,"three bars in the same session day should produce exactly one daily bar"); if(ArraySize(daily_bars)==1) { ASSERT(MathAbs(daily_bars[0].GetOpen()-1.1000)<0.00001,"open should come from the first bar"); ASSERT(MathAbs(daily_bars[0].GetHigh()-1.1010)<0.00001,"high should be the maximum across the group"); ASSERT(MathAbs(daily_bars[0].GetLow()-1.0990)<0.00001,"low should be the minimum across the group"); ASSERT(MathAbs(daily_bars[0].GetClose()-1.1001)<0.00001,"close should come from the last bar"); ASSERT(daily_bars[0].GetVolume()==370,"volume should be the sum of tick volumes across the group"); ASSERT(daily_bars[0].GetSampleCount()==3,"sample count should equal the number of contributing M1 bars"); } } //+--------------------------------------------------------------------+ //| TestAggregationSingleBar | //| Returns: nothing. Verifies that a session day with only one M1 bar | //| produces a daily bar whose open, high, low, and close all | //| equal that one bar's own values. | //+--------------------------------------------------------------------+ void TestAggregationSingleBar(void) { CM1BarSample samples[]; ArrayResize(samples,1); samples[0]=CM1BarSample(BuildTime(2024,3,15,17,0,0),1.2000,1.2003,1.1998,1.2001,90); CDailyAggregator aggregator; CDailyBar daily_bars[]; bool ok=aggregator.Aggregate(samples,17,daily_bars); ASSERT(ok,"aggregation call should succeed for a single-bar group"); ASSERT(ArraySize(daily_bars)==1,"a single M1 bar should still produce exactly one daily bar"); if(ArraySize(daily_bars)==1) { ASSERT(daily_bars[0].GetOpen()==1.2000,"open should equal the lone bar's open"); ASSERT(daily_bars[0].GetHigh()==1.2003,"high should equal the lone bar's high"); ASSERT(daily_bars[0].GetLow()==1.1998,"low should equal the lone bar's low"); ASSERT(daily_bars[0].GetClose()==1.2001,"close should equal the lone bar's close"); ASSERT(daily_bars[0].GetVolume()==90,"volume should equal the lone bar's tick volume"); } } //+------------------------------------------------------------------+ //| TestAggregationMultiDay | //| Returns: nothing. Verifies that bars from two distinct session | //| days are grouped into two distinct daily bars. | //+------------------------------------------------------------------+ void TestAggregationMultiDay(void) { CM1BarSample samples[]; ArrayResize(samples,4); samples[0] = CM1BarSample(BuildTime(2024,3,15,17,0,0),1.1000,1.1004,1.0996,1.1002,100); samples[1] = CM1BarSample(BuildTime(2024,3,15,18,0,0),1.1002,1.1006,1.0998,1.1003,110); samples[2] = CM1BarSample(BuildTime(2024,3,16,17,0,0),1.1010,1.1015,1.1005,1.1012,120); samples[3] = CM1BarSample(BuildTime(2024,3,16,18,0,0),1.1012,1.1016,1.1008,1.1013,130); CDailyAggregator aggregator; CDailyBar daily_bars[]; bool ok=aggregator.Aggregate(samples,17,daily_bars); ASSERT(ok,"aggregation call should succeed across more than one session day"); ASSERT(ArraySize(daily_bars)==2,"bars from two distinct session days should produce two daily bars"); if(ArraySize(daily_bars)==2) { ASSERT(daily_bars[0].GetSampleCount()==2,"the first day group should contain exactly two M1 bars"); ASSERT(daily_bars[1].GetSampleCount()==2,"the second day group should contain exactly two M1 bars"); ASSERT(daily_bars[0].GetDayKey()!=daily_bars[1].GetDayKey(),"the two daily bars should have distinct session day keys"); } }
OnStart() runs every test in sequence and prints a final tally, so a passing run ends with an unambiguous verdict rather than requiring the reader to count FAIL: lines manually.
//+-------------------------------------------------------------------+ //| OnStart | //+-------------------------------------------------------------------+ void OnStart(void) { TestSessionDayKeyCalendarDay(); TestSessionDayKeyNonzeroOffset(); TestSessionDayKeyBoundary(); TestSessionDayKeyRealisticM1Boundary(); TestAggregationMultiBar(); TestAggregationSingleBar(); TestAggregationMultiDay(); Print("=== Test Summary ==="); Print("Total: ",g_test_count," Passed: ",g_pass_count," Failed: ",g_fail_count); if(g_fail_count==0) Print("ALL TESTS PASSED"); else Print("SOME TESTS FAILED"); }
One thing this script deliberately does not attempt is testing CCustomSymbolWriter directly. Every method on that class depends on live terminal state: whether a symbol already exists in this particular terminal, what the terminal currently reports for a source symbol's digits, and whether a real write into custom symbol storage succeeds. None of that can be tested with a synthetic timestamp the way the day key and aggregation logic can.
Extending the Tool
The design leaves a few natural extension points. The most direct is session close hour granularity: this project accepts a whole-hour offset, but some traders think in terms of half-hour or even minute-level boundaries. Because CSessionDayKey::Calculate() already operates in seconds internally, extending it to accept a full time-of-day offset rather than just an hour would be a small, contained change that would not touch any other class.
A second extension is aggregating into something other than daily bars. The grouping logic inside CDailyAggregator does not actually know or care that its groups happen to represent one session day each; it only knows how to group samples by whatever key it is given. A weekly aggregator could reuse the exact same CDailyBar class and CCustomSymbolWriter class, substituting a different key-calculation function that groups by week rather than by session day.
A third extension is writing more than one derived symbol per run, for a trader who wants to compare, for instance, a 5 p.m. New York close alignment against a midnight UTC alignment side by side. Nothing in this design prevents running the aggregation twice with two different session close hours and two different destination symbol names within a single script execution.
Limitations and Design Tradeoffs
A few limitations are worth stating plainly rather than discovering them by surprise. The session close hour is a fixed whole-hour offset applied uniformly across the entire lookback window, so daylight saving transitions receive no special handling. A New York close convention genuinely shifts by an hour relative to UTC across the spring and fall transitions, and this project's single fixed offset does not track that shift automatically; a trader who cares about the distinction needs either to run the aggregation separately on each side of a transition with a different offset, or to accept a controlled amount of imprecision around those transition dates.
The linear search inside CDailyAggregator is entirely appropriate for the scale this project targets, but would become a genuine performance concern across an unusually long multi-decade history in a single pass. A hash-based lookup keyed on the day key would resolve that if it ever became necessary, at the cost of additional complexity not worth carrying for the realistic case.
Finally, this project writes an entire lookback window's worth of daily bars in a single CustomRatesUpdate() call rather than updating incrementally as new M1 data arrives. That is a deliberate simplification appropriate for a script run on demand. A trader wanting this running continuously, updating the custom symbol as new M1 bars arrive in real time, would want to convert this into an Expert Advisor that tracks the most recent bar already written and aggregates only new data on each tick or timer event, rather than recomputing everything from scratch on every run.
Conclusion
The key challenge was making one small function correct at the point that matters most: the second on either side of the day boundary. Everything else in this pipeline, reading history, grouping records, summing volumes, writing a custom symbol, is standard, well-documented MQL5 work. What tends to go wrong in a project like this is the arithmetic nobody thought to test at the edge, and isolating that arithmetic into a small, pure, directly testable function is what turns "probably works" into "demonstrably works." A trader who adopts a New York close convention, or any session the broker's clock does not share, now has a chart built on boundary arithmetic checked at its most likely failure point. That arithmetic is one of several conditions a trustworthy daily bar depends on, alongside complete M1 history, a correctly chosen hour, and a session that has actually finished; this revision now surfaces each of those explicitly instead of assuming them.
Programs used in the article:
| # | Name | Type | Description |
|---|---|---|---|
| 1 | DailyAggregatorTypes.mqh | Include File | Defines CM1BarSample and CDailyBar, the minimal data holders used throughout the pipeline. |
| 2 | M1BarReader.mqh | Include File | Reads M1 history for a symbol and time range via CopyRates() and reduces it to CM1BarSample records. |
| 3 | SessionDayKey.mqh | Include File | Computes the session-aligned day key for a timestamp using the shift-truncate-restore technique. |
| 4 | DailyAggregator.mqh | Include File | Groups M1 samples by session day key and aggregates each group into one CDailyBar. |
| 5 | CustomSymbolWriter.mqh | Include File | Ensures a custom symbol exists, configures it, clears any pre-existing bars, and writes aggregated daily bars into it. |
| 6 | AggregationSummaryPrinter.mqh | Include File | Prints a summary of one aggregation run to the Experts tab. |
| 7 | DailyOHLCVAggregator.mq5 | Script | The main script that wires every stage together into a complete pipeline. |
| 8 | TestDailyOHLCVAggregator.mq5 | Script | Verifies the session day key and aggregation logic against synthetic timestamps. |
| 9 | DailyOHLCVAggregator.zip | Zip Archive | Zip archive containing all the attached files and their paths relative to the terminal's root folder. |
Warning: All rights to these materials are reserved by MetaQuotes Ltd. Copying or reprinting of these materials in whole or in part is prohibited.
This article was written by a user of the site and reflects their personal views. MetaQuotes Ltd is not responsible for the accuracy of the information presented, nor for any consequences resulting from the use of the solutions, strategies or recommendations described.