Implementing a DST-aware Trading Day Resolver in MQL5
Contents
- Introduction
- What is already published
- Architecture
- Time zones and the DST calendar
- Resolving a trading day with CTradingDay
- Finding the server time zone from Friday closes
- Detecting a new day with CDayTracker
- Assigning deals to trading days with CDealDays
- Testing against IANA reference dates
- Three years in the Strategy Tester
- Rechecking the counts with a Python consistency check
- Adding the resolver to an EA
- Limitations
- What the checks do not cover
- Conclusion
- Attached files
Introduction
A daily loss limit has two parts. One is the amount. The other is the moment at which the counting starts again. The amount is easy to put into an input. The moment is harder, because the rules that name it do so in a time zone. The Trading Objectives page of FTMO, for example, says that the daily loss limit is recalculated at 00:00 CET (CEST in summer) from the balance recorded at that time. Other firms define different reset times. I did not verify those times. What matters is that the reset is defined in a specific time zone. That zone may differ from the zone of the broker's server.
An EA normally takes the day from the server clock. Such an EA reads TimeCurrent(), sets the hours, minutes, and seconds to zero, and calls the result today. Article 23732 does this in a daily loss circuit breaker. The article gives a reason: the server stamps every deal, so the server midnight stays consistent with the broker's own records. This rationale is sound for a limit that resets at server midnight. However, it does not cover a limit that resets at 17:00 in New York or at midnight in Prague. Prague uses CET and CEST, the zone of the FTMO reset.
On the server I tested, the three obvious choices give three different day starts. Server midnight is 00:00 on the server clock. Midnight in Central Europe is 01:00 on the same clock all year. The New York close at 17:00 is 00:00 on most days and 23:00 in a few weeks of each year. The United States and Europe change their clocks on different Sundays. A daily figure computed with the wrong one of these moves deals from one day to the next.
In this article, the New York close always means the clock time 17:00 in New York. The moment at which the broker's feed stops before the weekend is a different thing, and I call it the end of the feed. The section on fitting the server clock shows a week in which the two differ by one hour.
This article builds a small set of include files around one question. Given a server time, to which trading day does that time belong, and when does the day start and end? The question takes three inputs: the zone of the server clock, the zone in which the reset is defined, and the reset time. The files consist of the following parts.
- CTradingDay resolves a server time to the start, the end, and an ID of its trading day.
- CServerClockFit finds the zone of the server clock from the hourly bars of a forex symbol.
- CDayTracker notices when a new day starts and keeps the balance and equity of that moment. The tracker can also rebuild the balance of the day start from the deal history.
- CDealDays groups the deals of the account history into the trading days of a chosen definition.
I tested the code in four ways. There are 47 unit checks, and 13 of these checks compare the date arithmetic with the IANA time zone database. Three Strategy Tester runs on MetaQuotes-Demo track three definitions side by side. A Python consistency check refits the server zone and rebuilds the day boundaries from the same database. A mutation test had to detect two wrong rules. In the runs, all logged day starts and ends matched the database clock times for the fitted server zone, New York, and Prague. The balance rebuilt from the history matched the balance noted at the day start on every finished day except the first day of each run. The CDayTracker section explains why the first day is excluded. Those statements hold for one server, one build, and the definitions listed in the Strategy Tester section.
The Python check takes the fitted zone as its input, so it does not show that the fit is right. In this article, the only check of the zone that does not come from the bars is one live reading of the server clock. That reading agrees with the fitted offset on the day it was taken.
One result of the fit matters for the New York close. The server I used follows the European rule, UTC+2 with the change on the last Sunday of March and October. In 17 of 248 weekly samples the European and the US rule predict different offsets, and in 16 of those weeks the measured offset followed the European rule. In the weeks between the US and the European change, 17:00 in New York is 23:00 on the server clock, not midnight.
What is already published
Three published articles come close to this topic. The two parts of Dealing with Time, part 1 and part 2, derive the time shifts of a broker from the last Friday hour of EURUSD in hourly bars, and from there the time in New York. Both parts use macros and global variables, and they note that the clock functions are of no help in the Strategy Tester. Article 16171 detects the broker's time zone and daylight saving time (DST) rule from the volatility of non-farm payroll releases in the economic calendar. Article 23732 builds a daily loss circuit breaker that resets at server midnight.
The MQL5 reference agrees with these articles on the clocks. For TimeGMT() it says that, in the Strategy Tester, the function is always equal to the simulated server time of TimeTradeServer(). The Strategy Tester section prints all the clock functions in the tester to confirm this for the build I used.
What I add differs in four points. The day definition is an object with a reset zone and a reset time as inputs. A reset time that falls into a skipped or repeated hour has a defined and tested result. The zone fit uses the last hourly bar of every week and scores every candidate zone, so a result that cannot be told apart from another one is reported as such. And the day boundaries, the zone rules, and the deal grouping are compared with the IANA database through a second implementation in Python, for the server zone that the fit found. I searched the MQL5 article index with several phrases and found no article that treats the reset time as an input or covers skipped and repeated reset times. A search like that does not prove that none exists.
Architecture
The core module consists of six include files. The archive also holds a seventh include file with test vectors, three scripts, one Expert Advisor, and two Python scripts. Fig. 1 shows how the parts depend on each other.
Parts of the trading day resolver
From the hourly bars and the account history to the journal and the Python check
Fig. 1. CServerClockFit turns hourly bars into a server zone, CTradingDay uses it to resolve days, CDayTracker and CDealDays build on CTradingDay, and TdCalendar.mqh holds the rules that every class uses
Every class works on three kinds of time. A server time is a reading of the server clock, the value that TimeCurrent() and the history functions use. A UTC time is the same instant without any zone. A local time is a reading of the clock in the reset zone. Every conversion between these three kinds of time goes through the calendar functions of TdCalendar.mqh.
Time zones and the DST calendar
A zone has two properties. One is the offset from UTC on standard time, and the other is a DST rule that adds one hour. I support three rules. TD_DST_NONE never changes the offset. TD_DST_US and TD_DST_EU follow the schedules of the United States and the European Union in the northern hemisphere.
//+------------------------------------------------------------------+ //| Daylight saving rule of a time zone (northern hemisphere only) | //+------------------------------------------------------------------+ enum ENUM_TD_DST { TD_DST_NONE=0, // the offset never changes TD_DST_US, // second Sunday of March to first Sunday of November, at 02:00 local time TD_DST_EU // last Sunday of March to last Sunday of October, at 01:00 UTC };
//+------------------------------------------------------------------+ //| A time zone: standard offset from UTC and a daylight saving rule | //+------------------------------------------------------------------+ struct STdZone { int std_offset; // seconds to add to UTC on standard time ENUM_TD_DST dst; // daylight saving rule, one hour when active };
The two rules differ in how they define the moment of the change. The US rule changes at 02:00 local time on the second Sunday of March and the first Sunday of November. The EU rule changes for all member states at 01:00 UTC on the last Sunday of March and October. The DST window for a given year is computed from the n-th Sunday of a month.
//+------------------------------------------------------------------+ //| TdSundayOfMonth | //| Midnight UTC of the n-th Sunday of a month. n=-1 is the last. | //+------------------------------------------------------------------+ datetime TdSundayOfMonth(const int year,const int month,const int n) { datetime first=TdMakeTime(year,month,1); if(n>0) { int shift=(7-TdDayOfWeek(first))%7; return(first+(shift+7*(n-1))*TD_DAY); } datetime last=TdMakeTime(year,month,TdDaysInMonth(year,month)); return(last-TdDayOfWeek(last)*TD_DAY); }
//+------------------------------------------------------------------+ //| TdDstWindowUtc | //| Start and end of daylight saving time in a year, as UTC. | //+------------------------------------------------------------------+ bool TdDstWindowUtc(const STdZone &zone,const int year,datetime &start,datetime &end) { switch(zone.dst) { case TD_DST_US: start=TdSundayOfMonth(year,3,2)+2*TD_HOUR-zone.std_offset; end=TdSundayOfMonth(year,11,1)+2*TD_HOUR-(zone.std_offset+TD_HOUR); return(true); case TD_DST_EU: start=TdSundayOfMonth(year,3,-1)+TD_HOUR; end=TdSundayOfMonth(year,10,-1)+TD_HOUR; return(true); default: return(false); } }
The offset at an instant is then the standard offset, plus one hour inside the window.
//+------------------------------------------------------------------+ //| TdOffsetAtUtc | //| Offset from UTC, in seconds, that the zone has at an instant. | //+------------------------------------------------------------------+ int TdOffsetAtUtc(const STdZone &zone,const datetime utc) { datetime start,end; if(TdDstWindowUtc(zone,TdYear(utc),start,end) && utc>=start && utc<end) return(zone.std_offset+TD_HOUR); return(zone.std_offset); }
The reverse direction is the difficult one. A local reading can belong to zero, one, or two instants. When the clock jumps forward, the readings in the skipped hour never appear. When it goes back, the readings in the repeated hour appear twice. In New York, a reset time of 02:30 falls into the skipped hour once a year, in March. A reset time of 01:30 falls into the repeated hour once a year, in November. The function therefore has to say what it returns in both cases.
//+------------------------------------------------------------------+ //| TdLocalToUtc | //| UTC instant for a wall clock reading. A reading that happens | //| twice follows the fold argument. A skipped reading is read with | //| the offset from before the jump, so it lands one hour later. | //+------------------------------------------------------------------+ datetime TdLocalToUtc(const STdZone &zone,const datetime local,const ENUM_TD_FOLD fold,ENUM_TD_LOCAL &kind) { datetime std_utc=local-zone.std_offset; datetime dst_utc=local-(zone.std_offset+TD_HOUR); bool std_ok=(TdOffsetAtUtc(zone,std_utc)==zone.std_offset); bool dst_ok=(zone.dst!=TD_DST_NONE && TdOffsetAtUtc(zone,dst_utc)==zone.std_offset+TD_HOUR); if(std_ok && dst_ok) { kind=TD_LOCAL_FOLD; return(fold==TD_FOLD_FIRST ? dst_utc : std_utc); } if(std_ok || dst_ok) { kind=TD_LOCAL_OK; return(std_ok ? std_utc : dst_utc); } kind=TD_LOCAL_GAP; return(std_utc); }
For a repeated reading, the caller chooses the first or the second instant with the fold argument. For a skipped reading, the function uses the offset from before the jump, so the boundary lands one hour later on the clock. The outcome is reported in the kind argument. Fig. 2 shows both cases for New York, with the values that the unit tests use.
A reset time inside a skipped hour and inside a repeated hour
New York, the two clock changes of one year, drawn on a UTC axis

Fig. 2. A reset time of 02:30 that the New York clock skips resolves to 07:30 UTC, and a reset time of 01:30 that the clock shows twice resolves to 05:30 UTC for the first reading and 06:30 UTC for the second
A skipped reading always moves forward in my version, regardless of the fold argument. Python's zoneinfo moves a skipped reading back by one hour when fold is 1. I did not copy that behavior, and the unit tests follow this choice: the vectors for skipped readings use fold 0 only.
Resolving a trading day with CTradingDay
CTradingDay holds the server zone, the reset zone, the reset time, and the fold choice. Init() takes all four. The class interface is below.
//+------------------------------------------------------------------+ //| CTradingDay | //| Finds the trading day that contains a server time. A day starts | //| at a reset time on the clock of a reset zone, for example 17:00 | //| in New York. All inputs and outputs are server times. | //+------------------------------------------------------------------+ class CTradingDay { private: STdZone m_server; // zone of the server clock STdZone m_reset; // zone whose clock decides where a day starts int m_reset_sec; // reset time as seconds after local midnight ENUM_TD_FOLD m_fold; // which instant to use when the reset time happens twice bool m_ready; // Init() succeeded datetime BoundaryUtc(const datetime local_date) const; bool ResolveUtc(const datetime server_time,datetime &from,datetime &to,long &id) const; public: CTradingDay(void); bool Init(const STdZone &server,const STdZone &reset_zone,const int reset_hour, const int reset_minute,const ENUM_TD_FOLD fold=TD_FOLD_FIRST); bool InitPreset(const ENUM_TD_PRESET preset,const STdZone &server); bool Resolve(const datetime server_time,STdDay &day) const; datetime DayStart(const datetime server_time) const; datetime DayEnd(const datetime server_time) const; long DayId(const datetime server_time) const; int SecondsLeft(const datetime server_time) const; int DayLength(const datetime server_time) const; bool SameDay(const datetime a,const datetime b) const; datetime ServerToUtc(const datetime server_time) const; datetime UtcToServer(const datetime utc) const; string Describe(void) const; };
The ready-made definitions are in an enumeration. Every preset takes the server zone as an input, because only the server's own clock knows where its midnight is.
//+------------------------------------------------------------------+ //| Ready-made definitions of where a trading day starts | //+------------------------------------------------------------------+ enum ENUM_TD_PRESET { TD_SERVER_MIDNIGHT=0, // 00:00 of the server clock TD_NEW_YORK_CLOSE, // 17:00 in New York, the FX rollover TD_CENTRAL_EUROPE_MIDNIGHT, // 00:00 in Central Europe (CET and CEST) TD_UTC_MIDNIGHT // 00:00 UTC };
//+------------------------------------------------------------------+ //| CTradingDay::InitPreset | //| Ready-made definitions. The server zone is always an input, | //| because only the server's own clock knows where its midnight is. | //+------------------------------------------------------------------+ bool CTradingDay::InitPreset(const ENUM_TD_PRESET preset,const STdZone &server) { switch(preset) { case TD_SERVER_MIDNIGHT: return(Init(server,server,0,0)); case TD_NEW_YORK_CLOSE: return(Init(server,TdZoneNewYork(),17,0)); case TD_CENTRAL_EUROPE_MIDNIGHT: return(Init(server,TdZoneCentralEurope(),0,0)); case TD_UTC_MIDNIGHT: return(Init(server,TdZoneUtc(),0,0)); } m_ready=false; return(false); }
The main method is Resolve(), and ResolveUtc() does the work. ResolveUtc() converts the server time to UTC, reads the clock of the reset zone, and picks the date on which the current day started. It then checks that candidate against the boundaries on both sides. A reset time inside a skipped hour moves by one hour, and the first guess can be a day off. Resolve() converts the two boundaries to server clock readings.
//+------------------------------------------------------------------+ //| CTradingDay::ResolveUtc | //| UTC boundaries and ID of the day that contains the server time. | //| The day found from the wall clock is checked against the | //| boundaries, because a reset time inside a skipped hour moves by | //| one hour. | //+------------------------------------------------------------------+ bool CTradingDay::ResolveUtc(const datetime server_time,datetime &from,datetime &to,long &id) const { from=0; to=0; id=0; if(!m_ready || server_time<=0) return(false); datetime utc=ServerToUtc(server_time); datetime local=TdUtcToLocal(m_reset,utc); datetime date=TdDate(local); if(local-date<m_reset_sec) date-=TD_DAY; from=BoundaryUtc(date); if(from>utc) { date-=TD_DAY; from=BoundaryUtc(date); } to=BoundaryUtc(date+TD_DAY); if(utc>=to) { date+=TD_DAY; from=to; to=BoundaryUtc(date+TD_DAY); } id=(long)date/TD_DAY; return(true); }
//+------------------------------------------------------------------+ //| CTradingDay::Resolve | //| Fills the day that contains the server time, with the start and | //| the end as server clock readings. | //+------------------------------------------------------------------+ bool CTradingDay::Resolve(const datetime server_time,STdDay &day) const { datetime from,to; long id; day.start=0; day.end=0; day.id=0; if(!ResolveUtc(server_time,from,to,id)) return(false); day.start=UtcToServer(from); day.end=UtcToServer(to); day.id=id; return(true); }
//+------------------------------------------------------------------+ //| CTradingDay::BoundaryUtc | //| UTC instant at which the day of a local date starts. | //+------------------------------------------------------------------+ datetime CTradingDay::BoundaryUtc(const datetime local_date) const { ENUM_TD_LOCAL kind; return(TdLocalToUtc(m_reset,local_date+m_reset_sec,m_fold,kind)); }
The start and end of a day are server clock readings. The elapsed time from the start to the end is not always 24 hours. When the reset zone changes its clock inside a day, the day is 23 or 25 hours long. A clock change of the server zone alone does not change the length, because it moves only the server readings of the two boundaries.
My first version of the length method subtracted the two server readings, and it reported 24 hours for every day, including the short and long ones. My second version converted both server readings back to UTC. A later check showed that it still gave 23 hours for a day whose end falls into the hour that the server clock shows twice. That reading was converted as its first instant, one hour too early. The version below takes both boundaries in UTC from ResolveUtc() and does not go through the server clock at all.
//+------------------------------------------------------------------+ //| CTradingDay::DayLength | //| Elapsed seconds of the day that contains the server time, taken | //| from its two boundaries in UTC. It is 23 or 25 hours when the | //| reset zone changes its clock inside the day. A clock change of | //| the server zone alone does not change it. | //+------------------------------------------------------------------+ int CTradingDay::DayLength(const datetime server_time) const { datetime from,to; long id; if(!ResolveUtc(server_time,from,to,id)) return(-1); return((int)(to-from)); }
The ID of a day is the number of days since 1970.01.01 of the local date on which the day starts, in the reset zone. Consecutive days differ by one. Two server times that the server clock shows only once have the same ID exactly when they belong to the same day.
A server clock with DST shows one hour twice each year. A server time alone cannot say which of the two instants is meant. The class reads such a time as the first instant. On the test server that hour runs from 03:00 to 04:00 on a Sunday in October, when the market is closed. For a definition whose boundary falls into that hour, CDayTracker reports the new day at the end of the hour. The unit tests cover each of these rules.
A day that has no deals or ticks, such as a Saturday, still has an ID. A jump of more than one between the IDs of two logged days therefore means that no call came in the days between. Such a jump happens on a weekend or a holiday, and also while the EA is not running.
The ID is the date on which the day starts. A New York close day that starts on Thursday at 17:00 therefore has the ID of the Thursday, although most of its hours fall on the Friday. An EA that names the day after its end date has to add one.
Finding the server time zone from Friday closes
CTradingDay needs the zone of the server clock, and a broker rarely states it. The fit class finds it from data. The idea is the one used in the Dealing with Time articles. I assume that the forex week ends at 17:00 in New York on Friday, as those articles do. The hour bar that ends at that moment is then the last bar of the week. Its server time minus the UTC time of 17:00 in New York is the server offset in that week.
I first planned to use the Sunday reopening as well. The script prints how many bars open on a Sunday and how many weekend gaps end with a bar at Monday 00:00. In the MetaQuotes-Demo data, no bar opens on a Sunday, and 244 of the 250 gaps end at Monday 00:00. Only the Friday close is usable there. The class looks for a gap of more than 24 hours that follows a Friday. It converts 17:00 New York on that Friday to UTC and keeps the difference to the bar time. The difference counts only if it is a whole number of hours within 14 hours of UTC. Any other gap is counted as skipped.
datetime close_server=bars[i]+TD_HOUR; datetime friday=0; for(int back=0; back<2 && friday==0; back++) { datetime day=TdDate(close_server)-back*TD_DAY; if(TdDayOfWeek(day)==5) friday=day; } if(friday==0) { m_skipped++; continue; } ENUM_TD_LOCAL kind; datetime utc=TdLocalToUtc(ny,friday+17*TD_HOUR,TD_FOLD_FIRST,kind); int measured=(int)(close_server-utc); if(MathAbs(measured)>14*TD_HOUR || measured%TD_HOUR!=0) { m_skipped++; continue; }
The class then scores every candidate zone by the number of weeks in which the zone predicts the measured offset. The candidates run from -12 to +14 hours, each with no rule, the US rule, or the EU rule. The fit keeps the candidate with the highest score. A tie goes to the candidate that the loop tries first. The loop runs from the lowest offset to the highest, and for each offset it tries no rule, the US rule, and then the EU rule. The score of the second best is kept as well, because an equal score means that the history cannot tell the two zones apart. The caller sees a tie as BestHits() equal to RunnerHits(), and the text of Summary() contains both scores. A history that covers only winter weeks, for example, fits all three rules equally well.
m_best_hits=-1; m_runner_hits=-1; for(int hours=-12; hours<=14; hours++) for(int rule=0; rule<3; rule++) { STdZone zone=TdZoneHours(hours,(ENUM_TD_DST)rule); int hits=Hits(zone); if(hits>m_best_hits) { m_runner_hits=m_best_hits; m_best_hits=hits; m_best=zone; } else if(hits>m_runner_hits) m_runner_hits=hits; }
The fit reads the server clock through the trading schedule. An early close, a holiday, a missing bar, or a special session moves the last bar of a week. A few such weeks in the same season could look like another DST rule, above all in a short history. The class does not tell a schedule effect from a clock effect. The class reports the weeks that the best zone does not explain, and the user has to look at those weeks.
The bars are not the only source. After the fit, FitServerClock.mq5 waits for a new tick and takes its server time minus the UTC clock of the computer. That reading does not use the bars, so it can confirm or reject the fitted offset of that day. It says nothing about the rule, and it depends on a correct computer clock.
I ran FitServerClock.mq5 as a script on the hourly EURUSD bars of the terminal, with the default start date of its input. The tester was not involved.
FitServerClock: best zone UTC+02:00 EU DST, 246 of 248 weeks, runner-up 231, skipped gaps 3 FitServerClock: 29575 hourly bars, 0 open on a Sunday, 251 gaps of more than 24 hours, 245 of them end with a bar at Monday 00:00 FitServerClock: server standard offset 2 hours, rule TD_DST_EU FitServerClock: week not explained, last bar closes 2023.07.14 23:00 FitServerClock: week not explained, last bar closes 2026.03.14 00:00 FitServerClock: 248 weeks written to MQL5\Files\TradingDay\server_clock_fit.csv FitServerClock: live tick minus computer UTC clock +3 hours (-22 seconds left over), the fitted zone gives +3 hours now
The fit chose UTC+2 with the EU rule. That zone explains 246 of 248 weeks, and the US rule with the same base explains 231. The Python check, described below, counts 17 weeks in which the two rules predict different offsets. The EU rule is right in 16 of those weeks and the US rule in one. Fig. 3 shows the weekly residuals of both rules.
The live reading gives +3 hours, and the tick time lay 22 seconds behind the computer clock. The fitted zone gives the same offset for that day, because Europe was still on DST. A zone of UTC+3 without DST would give the same reading. The fit tells those two zones apart through the winter weeks, and the live reading alone does not.
Residuals of two rules, week by week
Measured server offset minus the offset that the rule predicts, in hours

Fig. 3. The EU rule leaves two weeks unexplained, and the US rule leaves 17 weeks that are one hour off, 16 of those weeks around the March and the October or November changes
Two weeks stay unexplained, and I do not know why. In the first, the last bar of the week closes at 23:00 in July, one hour before the usual 00:00. The short week looks like an early close, but I did not look for the cause. In the second, the last bar closes at 00:00 although the United States had already moved to DST and the EU rule expected 23:00. In that week the feed behaved as the US rule predicts.
The resolver maps 17:00 New York to the server clock. In this week the fitted zone gives 23:00 on the server clock. However, the feed stopped one hour later, at 00:00. The bars cannot tell whether the feed ran one hour longer or the server clock followed another rule in that week. Either way, the boundary is right as a clock time and does not match the end of the feed. The Strategy Tester section compares the logged boundaries with the clock times, not with the end of the feed, and shows the trace of this week in the third tester run. The Limitations section lists both weeks.
Detecting a new day with CDayTracker
CDayTracker turns the resolver into an event. The EA calls Update() with the server time, the balance, and the equity of the moment. The first call reports TD_EVENT_FIRST. Every later call at or after the end of the current day reports TD_EVENT_NEW_DAY, and the tracker keeps the balance and equity of that call as the start values of the new day.
//+------------------------------------------------------------------+ //| CDayTracker::Update | //| Call it with the server time, balance and equity of the moment. | //| A new day is reported on the first call at or after its start. | //| A call with an earlier time than the current day is ignored. A | //| reading in the repeated server hour that resolves to the current | //| day is ignored too, so a boundary inside that hour is reported | //| at the end of the hour. | //+------------------------------------------------------------------+ ENUM_TD_EVENT CDayTracker::Update(const datetime now,const double balance,const double equity) { if(m_td==NULL) return(TD_EVENT_NONE); if(m_started && (now<m_day.end)) return(TD_EVENT_NONE); STdDay day; if(!m_td.Resolve(now,day)) return(TD_EVENT_NONE); if(m_started && day.start==m_day.start) return(TD_EVENT_NONE); ENUM_TD_EVENT event=(m_started ? TD_EVENT_NEW_DAY : TD_EVENT_FIRST); m_day=day; m_start_balance=balance; m_start_equity=equity; m_started=true; m_days++; return(event); }
Three details matter for a daily limit. The start values come from the first call of the day, not from the exact boundary second, so a day after a weekend starts with the first tick of Monday. A call with a time earlier than the current day is ignored. And a call that comes after a gap of several days reports one new day, not several.
The first detail is a significant limitation for a rule that measures the loss from the equity at the reset moment. The tracker has no equity value for that moment. After a weekend or a quiet hour, the equity of the first call already includes the price change of the open positions since the reset. The start balance is less exposed, because a trade needs a tick. A deposit or a withdrawal between the reset and the first call would still end up in the start balance.
The balance at the start of a day can also be rebuilt from the history. The balance at the end of the window minus the net result of every deal inside the window is the balance at its start. Deposits and withdrawals are balance deals, so they are included. A deposit inside the window counts as part of the change, and the rebuilt balance is the balance before it. Credit deals are skipped, because a credit changes the credit of the account and not its balance. The only balance deal in my runs is the initial deposit of the tester, and the paragraph after the code shows how it appeared. I had no account with credit deals, so the credit branch is not tested.
Every window in the module covers its start and not its end. The convention holds for a trading day, for DealsNet(), for CDealDays, and for the Python check. A deal at the exact second of a boundary therefore belongs to the day that starts there. My first version of DealsNet() included both ends, and the demo passed the day end minus one second to make up for it. The function now applies the same convention as the day, and the demo passes the start and the end of a day as they are.
//+------------------------------------------------------------------+ //| CDayTracker::DealsNet | //| Profit, swap, commission and fee of every deal from the history | //| with a time from 'from' up to, not including, 'to'. A trading | //| day uses the same convention, so the start and end of a day can | //| be passed as they are. Deposits are counted too. Credit deals | //| are skipped, they do not change the balance. | //+------------------------------------------------------------------+ bool CDayTracker::DealsNet(const datetime from,const datetime to,double &net) { net=0.0; if(to<=from) return(true); if(!HistorySelect(from,to)) return(false); int total=HistoryDealsTotal(); for(int i=0; i<total; i++) { ulong ticket=HistoryDealGetTicket(i); if(ticket==0) return(false); datetime time=(datetime)HistoryDealGetInteger(ticket,DEAL_TIME); if(time<from || time>=to) continue; if(HistoryDealGetInteger(ticket,DEAL_TYPE)==DEAL_TYPE_CREDIT) continue; net+=HistoryDealGetDouble(ticket,DEAL_PROFIT)+HistoryDealGetDouble(ticket,DEAL_SWAP) +HistoryDealGetDouble(ticket,DEAL_COMMISSION)+HistoryDealGetDouble(ticket,DEAL_FEE); } return(true); }
//+------------------------------------------------------------------+ //| CDayTracker::BalanceAtStart | //| Balance at the start of a window, rebuilt from the history: the | //| balance at the end of the window minus every deal inside it. The | //| window covers 'from' and not 'to', as in DealsNet(). The equity | //| of that moment cannot be rebuilt this way. | //+------------------------------------------------------------------+ bool CDayTracker::BalanceAtStart(const datetime from,const datetime to,const double balance_at_to,double &balance_at_from) { double net; if(!DealsNet(from,to,net)) return(false); balance_at_from=balance_at_to-net; return(true); }
The equity of the day start cannot be rebuilt this way. It needs the prices of the open positions at that moment, and the deal history does not hold them. A rule that measures the loss from the start equity has to record the equity while the EA runs. Update() records the start equity in this way.
The first check of this function showed a difference of 10,000 on the first day of every tester run. The account is funded with a balance deal at the start of the test, and the first day of the tracker starts at the first tick, after the funding. The window of the first day contains the deposit and the noted balance does not. The rebuilt value was the balance before the deposit, which is what the function promises. I now skip the first day in the check. Every later day has its window start at a day boundary, and the check applies to those days.
The rebuild assumes that every deal type other than credit changes the balance by its profit, swap, commission, and fee. A broker may book corrections, charges, or bonuses with other deal types, or split them in another way. The rebuild therefore depends on how a server writes its history, and I checked it only on the tester history of one server.
Assigning deals to trading days with CDealDays
CDealDays loads the buy and sell deals of the history and groups them into the days of a definition. The deals have to arrive in time order, and Load() returns false if the terminal returns them in another order. Summarize() then needs only one pass.
//+------------------------------------------------------------------+ //| CDealDays::Summarize | //| One entry per trading day that has at least one deal: the day, | //| the number of deals and their net result. Returns the days. | //+------------------------------------------------------------------+ int CDealDays::Summarize(const CTradingDay &td,STdDay &days[],int &deals[],double &net[]) const { ArrayResize(days,0); ArrayResize(deals,0); ArrayResize(net,0); for(int i=0; i<ArraySize(m_time); i++) { STdDay day; if(!td.Resolve(m_time[i],day)) continue; int n=ArraySize(days); if(n==0 || days[n-1].start!=day.start) { ArrayResize(days,n+1); ArrayResize(deals,n+1); ArrayResize(net,n+1); days[n]=day; deals[n]=0; net[n]=0.0; n++; } deals[n-1]++; net[n-1]+=m_net[i]; } return(ArraySize(days)); }
To see how much a choice of definition matters, CountBetween() pairs every day start of one definition with the nearest day start of the other. The deals that lie between the two boundaries belong to one day under one definition and to the next day under the other. The pairing is clear when the two boundaries lie a few hours apart, as in all pairs of this article. For two definitions about 12 hours apart, the nearest start can switch between the day before and the day after, and I did not test that case.
//+------------------------------------------------------------------+ //| CDealDays::CountBetween | //| Pairs every day start of a with the nearest day start of b and | //| counts the deals that lie between the two. Those deals belong to | //| one day under a definition and to the next under the other one. | //| The pairing is meant for boundaries a few hours apart. Near 12 | //| hours apart the nearest start can switch sides, and the count | //| is not defined well. | //+------------------------------------------------------------------+ int CDealDays::CountBetween(const CTradingDay &a,const CTradingDay &b) const { int count=0; int total=ArraySize(m_time); if(total==0) return(0); STdDay day; if(!a.Resolve(m_time[0],day)) return(0); datetime boundary=day.start; while(boundary<=m_time[total-1]) { STdDay before; if(!b.Resolve(boundary,before)) break; datetime other=before.start; if(before.start!=boundary) other=((boundary-before.start)<=(before.end-boundary) ? before.start : before.end); datetime lo=MathMin(boundary,other); datetime hi=MathMax(boundary,other); for(int i=0; i<total; i++) if(m_time[i]>=lo && m_time[i]<hi) count++; if(!a.Resolve(boundary,day)) break; boundary=day.end; } return(count); }
The count is a measure of how much the definitions disagree about the history. The count is not a measure of risk, and I do not use it as one. The count is also defined only for definitions whose boundaries lie a few hours apart. For other pairs of definitions, the count is not a general measure.
Testing against IANA reference dates
TestTradingDay.mq5 is a script that prints a PASS or FAIL line per check. Its 47 checks fall into the groups of the next table.
| Group | Checks | Reference |
|---|---|---|
| DST windows, offsets, and local readings | 6 | IANA database |
| Day starts of seven definitions | 7 | IANA database |
| Sundays of a month, leap years, and a zone without a rule | 3 | Values written by hand |
| Properties of the resolver over three years | 4 | The resolver itself |
| Clock changes of the server zone alone, and its repeated hour | 4 | Values written by hand |
| Server clock fit on synthetic weeks | 8 | Weeks built with a known zone |
| CDayTracker, Init(), and SameDay() | 13 | Values written by hand |
| Mutation checks | 2 | IANA database |
The IANA reference values are in TdVectors.mqh. A Python script, make_vectors.py, generates that file from the database, so the arithmetic of the MQL5 code is compared with values that it did not produce. They cover four groups of values. The first is the DST windows of New York and Central Europe for 21 years. The second is the offsets one second before and at every change in three years. The third is 36 conversion cases for skipped, repeated, and ordinary local readings. The fourth is the day starts of seven definitions around the clock changes of two years.
PASS New York daylight saving window, 21 years PASS Central Europe daylight saving window, 21 years PASS second and last Sunday of March 2026 PASS leap years PASS a zone without a rule has no window PASS New York offset around 12 change instants PASS Central Europe offset around 12 change instants PASS local reading to UTC, 36 cases PASS skipped, repeated and ordinary readings are told apart
The day start checks go through consecutive days around every change. For each day they test the start, the end, the ID step, and an instant in the middle of the day. Four of the seven use a reset time that the clock skips or repeats.
PASS server midnight, four daylight saving windows PASS New York close, four daylight saving windows PASS Central Europe midnight, four daylight saving windows PASS New York 02:30, a reading skipped in March PASS New York 01:30, repeated in November, first reading PASS New York 01:30, repeated in November, second reading PASS Central Europe 02:30, a reading skipped in March
Not everything is compared with the database. A scan of three years at 7-minute steps tests properties of the resolver against itself. Every instant lies inside its own day, and the day is between 23 and 25 hours long. The day of a day start is that same day, and the ID never goes down. These checks show that the logic is consistent. They do not show that the logic is right. That part rests on the comparison with the database above.
The next four checks keep the reset zone fixed and let only the server clock change. With a reset at midnight UTC on a server with the EU rule, every day of three years must be 24 hours long. With a reset at 01:00 UTC, the day that ends on the last Sunday of October 2025 ends at 03:00 on the server clock. The server shows 03:00 twice on that night, and the boundary is the second reading. The checks expect a length of 24 hours for that day, a server time of 03:30 read as its first instant, and a tracker that reports the new day at 04:00.
The fit checks build synthetic weeks of hourly bars for a server with a known zone and let the class find it. They cover a server with the EU rule, one with the US rule, and one without a rule. They also cover three early-close weeks, a history of winter weeks only, and a history that is too short. The early-close weeks have to stay unexplained, and the winter history has to end in a tie. The tracker checks follow the three details listed in the CDayTracker section, and the last checks test that Init() refuses reset times and offsets outside their range.
PASS invariants of preset 0 over 225463 instants PASS invariants of preset 1 over 225463 instants PASS invariants of preset 2 over 225463 instants PASS invariants of preset 3 over 225463 instants PASS UTC midnight on a server with the EU rule, 1096 days of 24 hours PASS a day that ends inside the repeated server hour is 24 hours long PASS a repeated server reading is resolved as its first instant PASS a boundary inside the repeated server hour is reported at the end of that hour PASS fit finds UTC+2 with the EU rule PASS the US rule scores lower on an EU server PASS bar statistics of the synthetic weeks PASS fit finds UTC+2 with the US rule PASS fit finds a server without daylight saving PASS three early-close weeks are reported as misses PASS winter-only history is reported as ambiguous PASS three weeks are too few PASS a tracker without a definition reports nothing PASS first call reports FIRST and keeps the start values PASS same day keeps the start values PASS the last second of the day is still the same day PASS the first second of the next day reports NEW_DAY PASS an earlier time is ignored PASS a gap of several days is one new day PASS Attach() starts over PASS an object that was never initialized answers with failure values PASS reset times outside 00:00 to 23:59 are refused PASS offsets beyond 14 hours are refused PASS a refused Init() leaves the object unusable PASS SameDay() compares trading days
Two mutation checks follow. In the first, the New York zone gets the EU rule. In the second, the server gets the US rule. In both cases the vectors for the New York close had to report wrong answers, and they did. Each mutation gives 236 wrong answers.
The script then compares the two mutations entry by entry. Both are wrong at the same 60 day starts, with the same number of wrong answers at each one. Neither mutation is wrong at a day start where the other one is right. All 60 day starts close a day in which the US and the EU rule give a different DST state. This comparison covers the vectors of two years and these two mutations only.
The last lines list the days of one year that are not 24 hours long. They are printed so that the Python check can compare them.
PASS mutation: New York with the EU rule, the vectors reported FAIL mutation: 236 wrong answers for New York with the EU rule, the expected result PASS mutation: server with the US rule, the vectors reported FAIL mutation: 236 wrong answers for a server with the US rule, the expected result mutation: day starts with a wrong answer: 60 in both mutations (60 with the same count), 0 only in the first, 0 only in the second mutation: 60 of these 60 day starts end a day in which the US and EU rules disagree TDLEN|0|2025.03.30 00:00:00|2025.03.31 00:00:00|23 TDLEN|0|2025.10.26 00:00:00|2025.10.27 00:00:00|25 TDLEN|1|2025.03.09 00:00:00|2025.03.09 23:00:00|23 TDLEN|1|2025.11.01 23:00:00|2025.11.03 00:00:00|25 TDLEN|2|2025.03.30 01:00:00|2025.03.31 01:00:00|23 TDLEN|2|2025.10.26 01:00:00|2025.10.27 01:00:00|25 TestTradingDay: 47 passed, 0 failed
The next table repeats the TDLEN lines in words. Every time in it is a reading of the server clock, UTC+2 with the EU rule. The definition numbers in the log are 0 for server midnight, 1 for the New York close, and 2 for midnight in Central Europe.
| Definition | Day start, server clock | Day end, server clock | Elapsed hours |
|---|---|---|---|
| Server midnight | Sunday 2025.03.30 00:00 | Monday 2025.03.31 00:00 | 23 |
| Server midnight | Sunday 2025.10.26 00:00 | Monday 2025.10.27 00:00 | 25 |
| 17:00 New York | Sunday 2025.03.09 00:00 | Sunday 2025.03.09 23:00 | 23 |
| 17:00 New York | Saturday 2025.11.01 23:00 | Monday 2025.11.03 00:00 | 25 |
| Midnight Central Europe | Sunday 2025.03.30 01:00 | Monday 2025.03.31 01:00 | 23 |
| Midnight Central Europe | Sunday 2025.10.26 01:00 | Monday 2025.10.27 01:00 | 25 |
On the server I tested, every day with an odd length starts on a Saturday or a Sunday of the server clock. For server midnight and for the New York close, such a day contains no tick, because the market is closed. For midnight in Central Europe, the odd day does contain ticks. That day runs from 01:00 on Sunday to 01:00 on Monday on the server clock, so it holds the first hour of the week. The odd lengths therefore depend on the server and on the definition, and a server with another schedule would give other days.
These tests check my own logic and the date arithmetic on the listed cases. They do not show that the logic is right for every zone and date, and they do not show how the MetaTrader 5 server or the Strategy Tester behaves.
Three years in the Strategy Tester
TradingDayDemo.mq5 tracks three definitions at once and opens a 0.01-lot buy every hour at minute 55. It closes the position 10 minutes later. The purpose is to put deals next to every possible boundary. The EA is not a strategy, and I do not report its profit. It logs every new day of every definition and rebuilds the balance of each finished day from the history. The EA also compares the day start of server midnight with the open of the daily bar, and it writes the deals and the days to CSV files.
//+------------------------------------------------------------------+ //| OnInit | //+------------------------------------------------------------------+ int OnInit() { STdZone server=TdZoneHours(InpServerHours,InpServerDst); for(int i=0; i<DEFS; i++) { if(!g_day[i].InitPreset((ENUM_TD_PRESET)i,server)) return(INIT_FAILED); g_tracker[i].Attach(&g_day[i]); g_prev[i].start=0; g_max_diff[i]=0.0; g_rebuilt[i]=0; PrintFormat("TDCFG|%s|%s|%s",InpTag,g_name[i],g_day[i].Describe()); } g_trade.SetDeviationInPoints(50); return(INIT_SUCCEEDED); }
//+------------------------------------------------------------------+ //| CheckRollover | //| Calls the tracker of one definition. On a new day it logs the | //| day, and it rebuilds the balance of the day that just ended from | //| the deal history to compare it with the balance that was noted. | //+------------------------------------------------------------------+ void CheckRollover(const int i,const datetime now,const double balance,const double equity) { ENUM_TD_EVENT event=g_tracker[i].Update(now,balance,equity); if(event==TD_EVENT_NONE) return; STdDay day=g_tracker[i].Day(); PrintFormat("TDDAY|%s|%s|%s|%d|%d|%I64d|%.2f|%.2f",InpTag,g_name[i],TimeToString(now,TIME_DATE | TIME_SECONDS), (int)day.start,(int)day.end,day.id,balance,equity); if(event==TD_EVENT_NEW_DAY && g_prev[i].start>0) { double rebuilt; if(CDayTracker::BalanceAtStart(g_prev[i].start,g_prev[i].end,balance,rebuilt)) { double diff=MathAbs(rebuilt-g_prev_balance[i]); g_max_diff[i]=MathMax(g_max_diff[i],diff); g_rebuilt[i]++; if(diff>0.005) PrintFormat("TDBAL|%s|%s|%s|noted=%.2f|rebuilt=%.2f",InpTag,g_name[i],TimeToString(g_prev[i].start,TIME_DATE | TIME_SECONDS), g_prev_balance[i],rebuilt); } } if(i==0) { g_d1_total++; if(iTime(_Symbol,PERIOD_D1,0)==day.start) g_d1_equal++; MqlDateTime parts; TimeToStruct(now,parts); if(parts.day<=3 && parts.mon%3==1) LogClocks(); } //--- the first day starts before the first call, so its start balance is not known g_prev[i]=day; if(event==TD_EVENT_FIRST) g_prev[i].start=0; g_prev_balance[i]=g_tracker[i].StartBalance(); }
| Setting | Value |
|---|---|
| Symbol, server | EURUSD, MetaQuotes-Demo |
| Build | 6230 |
| Model | 1-minute OHLC |
| Execution delay | none |
| Deposit, leverage | 10,000 USD, 1:100 |
| Server zone input | UTC+2, EU rule |
| Runs | 2024.01.01 to 2024.12.31, 2025.01.01 to 2025.12.31, 2026.01.01 to 2026.09.30 |
The model is 1-minute OHLC, not real ticks, because only the days and the deals matter. The runs have no execution delay. All logs in this article come from the attached files. I ran each period several times, the last time with the attached code. The lines that the EA printed and the CSV files it wrote are identical in every run of a period, apart from the TDWIN line. Only the attached version prints that line. I searched the three journals for the words failed, error, not enough money, and invalid stops. The only match is the TDORDERS line, and that line reports no failed orders. The EA writes the configuration of the three definitions at the start. The journal then holds one line for every new day.
2025.01.01 00:00:00 TDCFG|y2025|server_midnight|day starts 00:00 UTC+02:00 EU DST, server UTC+02:00 EU DST, repeated reading: first 2025.01.01 00:00:00 TDCFG|y2025|new_york_close|day starts 17:00 UTC-05:00 US DST, server UTC+02:00 EU DST, repeated reading: first 2025.01.01 00:00:00 TDCFG|y2025|central_europe_midnight|day starts 00:00 UTC+01:00 EU DST, server UTC+02:00 EU DST, repeated reading: first
Fig. 4 plots the hour at which each day starts on the server clock through the year of the second run. Server midnight stays at 00:00 and Central Europe at 01:00. The New York close is at 00:00 except in two stretches, where it is at 23:00. In spring a stretch starts with the US change and ends with the EU change. In autumn a stretch starts with the EU change and ends with the US change.
Day start on the server clock through one year
Each value is a new day logged by CDayTracker in the second tester run

Fig. 4. Server midnight is at 00:00, midnight in Central Europe at 01:00, and the 17:00 New York close at 00:00 except for three weeks in spring and one week in autumn when it is at 23:00
The lines below are the journal entries of one New York close week. The day that starts at 23:00 on Monday ends at 23:00 on Tuesday.
2025.03.07 00:00:00 TDDAY|y2025|new_york_close|2025.03.07 00:00:00|1741305600|1741392000|20153|9938.97|9938.43 2025.03.07 01:00:00 TDDAY|y2025|central_europe_midnight|2025.03.07 01:00:00|1741309200|1741395600|20154|9938.67|9938.47 2025.03.10 00:00:00 TDDAY|y2025|server_midnight|2025.03.10 00:00:00|1741564800|1741651200|20157|9935.48|9935.66 2025.03.10 00:00:00 TDDAY|y2025|new_york_close|2025.03.10 00:00:00|1741561200|1741647600|20156|9935.48|9935.66 2025.03.10 00:00:00 TDDAY|y2025|central_europe_midnight|2025.03.10 00:00:00|1741482000|1741568400|20156|9935.48|9935.66 2025.03.10 01:00:00 TDDAY|y2025|central_europe_midnight|2025.03.10 01:00:00|1741568400|1741654800|20157|9935.66|9935.64 2025.03.10 23:00:00 TDDAY|y2025|new_york_close|2025.03.10 23:00:00|1741647600|1741734000|20157|9929.71|9929.87 2025.03.11 00:00:00 TDDAY|y2025|server_midnight|2025.03.11 00:00:00|1741651200|1741737600|20158|9929.68|9929.41 2025.03.11 01:00:00 TDDAY|y2025|central_europe_midnight|2025.03.11 01:00:00|1741654800|1741741200|20158|9929.55|9929.23 2025.03.11 23:00:00 TDDAY|y2025|new_york_close|2025.03.11 23:00:00|1741734000|1741820400|20158|9926.87|9926.85
After the run tag and the definition name, a TDDAY line holds six fields. They are the time of the call, the day start, the day end, the ID, the balance, and the equity. The day start and the day end are server clock timestamps. They are stored as seconds since 1970.01.01, with the server clock reading treated as if it were UTC. The New York line of the Monday shows a start on Sunday at 23:00, because the first tick of the week arrives at 00:00 on Monday.
The results of the three runs are in the next table. The fifth column comes from the Python consistency check described below. It compares every logged start, end, and ID with the clock times that the database gives for the fitted server zone, New York, and Prague. The check does not compare the logged values with the end of the feed. The rebuild counts are the days for which the balance was rebuilt from the history and compared with the balance noted at the day start. The last column shows the largest difference that occurred.
| Run | Days of server midnight | Days of New York close | Days of Central Europe | Starts, ends, or IDs that differ from the clock times | Balance rebuilds, three definitions | Largest rebuild difference |
|---|---|---|---|---|---|---|
| First | 260 | 260 | 313 | 0 | 827 | 0.0000 |
| Second | 258 | 258 | 312 | 0 | 822 | 0.0000 |
| Third | 193 | 194 | 233 | 0 | 614 | 0.0000 |
A tracked day is a day in which at least one tick arrived. Three tracked days hold no deal, so the TDSUM lines show one day fewer with deals than tracked days in those cases. In the first run, a single tick at 00:00 on Christmas Day started a day of server midnight and a day of the New York close, and no deal followed. In the third run, the New York close has one day more than server midnight. The extra day comes from the week that the server clock fit could not explain. On that Friday a tick arrived at 23:00:30, after 17:00 New York, so the resolver had already started the next New York close day. In the tester data no tick followed until Monday, so the position opened at 22:55 closed at 00:00 on Monday, and the new day holds no deal. The New York lines of that week are below.
2026.03.12 23:00:00 TDDAY|y2026|new_york_close|2026.03.12 23:00:00|1773356400|1773442800|20524|9955.05|9954.94 2026.03.13 23:00:30 TDDAY|y2026|new_york_close|2026.03.13 23:00:30|1773442800|1773529200|20525|9954.46|9954.61 2026.03.16 00:00:00 TDDAY|y2026|new_york_close|2026.03.16 00:00:00|1773615600|1773702000|20527|9954.46|9955.75
The definitions differ in how many deals they move to another day. The last lines of the second run show these counts.
2025.12.30 23:59:59 TDSUM|y2025|server_midnight|days_with_deals=258|days_tracked=258|rebuilds=256|max_diff=0.0000 2025.12.30 23:59:59 TDSUM|y2025|new_york_close|days_with_deals=258|days_tracked=258|rebuilds=256|max_diff=0.0000 2025.12.30 23:59:59 TDSUM|y2025|central_europe_midnight|days_with_deals=312|days_tracked=312|rebuilds=310|max_diff=0.0000 2025.12.30 23:59:59 TDMOVED|y2025|server_vs_new_york=32|server_vs_central_europe=504|new_york_vs_central_europe=536|deals=12304 2025.12.30 23:59:59 TDWIN|y2025|seconds_with_deals=12305|wrong_windows=0 2025.12.30 23:59:59 TDD1|y2025|equal=258|total=258 2025.12.30 23:59:59 TDORDERS|y2025|failed=0
In the second run, 32 of 12,304 deals lie between the boundaries of server midnight and the New York close. The 32 deals are eight deals in each of the four weeks in which the two boundaries differ. The EA trades two deals in the hour before midnight on each evening from Monday to Thursday. The Friday session of those weeks ends at 23:00 on the server clock, so Friday adds none. Between server midnight and midnight in Central Europe, 504 deals lie, about two on every trading day. The first and third runs give 32 and 24 for the New York pair. Those counts equal four weeks and three weeks of eight deals. Fig. 5 shows the monthly counts of all three runs.
Some deals fall exactly on a boundary second. A position opened late on Friday closes with the first tick of Monday. That tick often arrives at 00:00:00. That second is the day start of server midnight, and in most weeks also of the New York close. Across the three runs, 54 deals lie exactly on a day start of server midnight and 43 on a day start of the New York close. A day covers its start and not its end, so these deals belong to the Monday. The Python check uses the same rule, and its day counts and nets agree with the EA in all three runs.
The rebuild windows of the demo do not end on such a second, so the balance check does not test the end of a window. The TDWIN line tests both ends of DealsNet() on the whole history of a run. For every second that holds a deal, a window that starts at that second must count the deal, and a window that ends at that second must leave it out. The three runs have 12,397, 12,305, and 9,247 such seconds, the deposit included, and no window gives a wrong sum.
Deals between two day boundaries, by month
Hourly 0.01-lot deals of the three tester runs, counted between the two boundaries of each pair

Fig. 5. The New York close differs from server midnight only in spring and autumn, while midnight in Central Europe sits one hour after server midnight in every month
The TDD1 line compares the day start of the server midnight definition with the open time of the current daily bar. The two agree on every day of all three runs: 260 of 260, 258 of 258, and 193 of 193. The agreement says only that the daily bars of this server start at the resolver's server midnight.
In build 6230, the clock functions behave in the tester as the reference says. I printed all clock functions on the first two or three trading days of every quarter. The lines of the second run are below.
2025.01.02 00:00:30 TDCLOCK|y2025|current=2025.01.02 00:00:30|tradeserver=2025.01.02 00:00:30|gmt=2025.01.02 00:00:30|local=2025.01.02 00:00:30|gmtoffset=0|dst=0 2025.01.03 00:00:00 TDCLOCK|y2025|current=2025.01.03 00:00:00|tradeserver=2025.01.03 00:00:00|gmt=2025.01.03 00:00:00|local=2025.01.03 00:00:00|gmtoffset=0|dst=0 2025.04.01 00:00:00 TDCLOCK|y2025|current=2025.04.01 00:00:00|tradeserver=2025.04.01 00:00:00|gmt=2025.04.01 00:00:00|local=2025.04.01 00:00:00|gmtoffset=0|dst=0 2025.04.02 00:00:00 TDCLOCK|y2025|current=2025.04.02 00:00:00|tradeserver=2025.04.02 00:00:00|gmt=2025.04.02 00:00:00|local=2025.04.02 00:00:00|gmtoffset=0|dst=0 2025.04.03 00:00:00 TDCLOCK|y2025|current=2025.04.03 00:00:00|tradeserver=2025.04.03 00:00:00|gmt=2025.04.03 00:00:00|local=2025.04.03 00:00:00|gmtoffset=0|dst=0 2025.07.01 00:00:00 TDCLOCK|y2025|current=2025.07.01 00:00:00|tradeserver=2025.07.01 00:00:00|gmt=2025.07.01 00:00:00|local=2025.07.01 00:00:00|gmtoffset=0|dst=0 2025.07.02 00:00:00 TDCLOCK|y2025|current=2025.07.02 00:00:00|tradeserver=2025.07.02 00:00:00|gmt=2025.07.02 00:00:00|local=2025.07.02 00:00:00|gmtoffset=0|dst=0 2025.07.03 00:00:00 TDCLOCK|y2025|current=2025.07.03 00:00:00|tradeserver=2025.07.03 00:00:00|gmt=2025.07.03 00:00:00|local=2025.07.03 00:00:00|gmtoffset=0|dst=0 2025.10.01 00:01:00 TDCLOCK|y2025|current=2025.10.01 00:01:00|tradeserver=2025.10.01 00:01:00|gmt=2025.10.01 00:01:00|local=2025.10.01 00:01:00|gmtoffset=0|dst=0 2025.10.02 00:01:00 TDCLOCK|y2025|current=2025.10.02 00:01:00|tradeserver=2025.10.02 00:01:00|gmt=2025.10.02 00:01:00|local=2025.10.02 00:01:00|gmtoffset=0|dst=0 2025.10.03 00:01:00 TDCLOCK|y2025|current=2025.10.03 00:01:00|tradeserver=2025.10.03 00:01:00|gmt=2025.10.03 00:01:00|local=2025.10.03 00:01:00|gmtoffset=0|dst=0
TimeGMT(), TimeTradeServer(), and TimeLocal() all return the server time, and the GMT offset and the DST correction are 0. All 29 lines of the three runs, from winter and summer dates, show the same. In these runs, an EA that needs UTC has to compute UTC from the server zone. The resolver does this conversion. I did not check other builds or servers.
Rechecking the counts with a Python consistency check
The script tradingday_crosscheck.py rebuilds the same answers with Python's zoneinfo module. That module reads the IANA database. The script does not use the MQL5 rules. On Windows it needs the tzdata package. The script has four modes: it checks the fit CSV, the day events in a tester journal, the deals and days CSV files, and the list of odd-length days.
The script makes the following assumptions.
- In the fit mode, New York closes at 17:00 on Fridays, the same assumption that the fit makes. The mode scores every whole-hour zone with no rule, the US rule, or the EU rule against the bar times of the CSV file with its own code. It repeats the method of the MQL5 fit, so it checks that code and not the method.
- The other three modes take the server zone as an input. The default is Europe/Athens, which is UTC+2 with the EU rule and the result of the fit. These modes check the day boundaries for that zone, so they cannot catch a wrong fit.
- The three definitions are server midnight, 17:00 New York, and midnight in Prague.
- The script checks the rules for the zones and years in the files and says nothing about other brokers.
The output for the fit CSV and the odd-length days is below.
fit weeks=248 UTC+2 EU rule hits=246 UTC+2 US rule hits=231 close_utc differences=0 fit weeks in which the two rules disagree=17 EU rule right in 16 US rule right in 1 fit weeks the EU rule does not explain: 2023.07.14 23:00, 2026.03.14 00:00 fit refit in Python: best UTC+2 with EU rule, 246 of 248 weeks runner-up UTC+2 with US rule, 231 weeks
lengths odd days in the journal=6 in the database=6 only in one of them=0
The refit in Python finds the same best zone and the same runner-up as the MQL5 fit, with the same scores. Both use the Friday close at 17:00 New York, so the agreement checks the code of the fit and not that assumption.
For the second run, it recomputes the day starts, ends, and IDs of every logged event, and groups the deals of the CSV file by its own boundaries.
days server_midnight events=258 wrong start=0 wrong end=0 tick outside its day=0 wrong ID=0 days new_york_close events=258 wrong start=0 wrong end=0 tick outside its day=0 wrong ID=0 days central_europe_midnight events=312 wrong start=0 wrong end=0 tick outside its day=0 wrong ID=0 deals server_midnight days with deals=258 (EA 258) days that differ in count or net=0 deals new_york_close days with deals=258 (EA 258) days that differ in count or net=0 deals central_europe_midnight days with deals=312 (EA 312) days that differ in count or net=0 deals between the boundaries of server_midnight and new_york_close: 32 deals between the boundaries of server_midnight and central_europe_midnight: 504 deals between the boundaries of new_york_close and central_europe_midnight: 536 deals in file=12304
The output of the first and third runs has the same form. That output shows 0 starts, ends, and IDs that differ from the clock times, and 0 days that differ in count or net. Its pair counts are 32, 515, and 547 for the first run and 24, 383, and 407 for the third. These counts are equal to the counts of the EA. My first version of the pair counts was not. It ignored the boundary that lies before the first deal, and it counted one deal fewer than the EA for every pair that involves Central Europe. The first deal of each run lies between a day start of server midnight and the start of the Central Europe day one hour later. The EA was therefore right, and the script was wrong. I fixed the script.
Adding the resolver to an EA
The EA needs two decisions: the server zone and the definition. The server zone comes from the fit, or from inputs once it is known. The definition comes from the rule that the EA enforces. The demo above uses the presets, and a rule such as the one quoted in the introduction is the preset TD_CENTRAL_EUROPE_MIDNIGHT. The tracker then gives the start values for the limit.
FitServerClock.mq5 prints the result in the form that the demo takes as inputs, the standard offset in hours and the rule. DealDayReport.mq5 does the same job on the account that the terminal is logged into. It groups the history of the last days by a chosen definition, prints the days with their deals and net result, and counts the deals that move compared with server midnight. The report writes the same CSV format as the demo. By default it fits the server zone itself from the hourly bars of the last five years. I ran it on a MetaQuotes-Demo account with deals on two days.
DealDayReport: best zone UTC+02:00 EU DST, 258 of 261 weeks, runner-up 242, skipped gaps 3 DealDayReport: day starts 17:00 UTC-05:00 US DST, server UTC+02:00 EU DST, repeated reading: first DealDayReport: day 2026.09.10 00:00 to 2026.09.11 00:00, 8 deals, net 494.23 DealDayReport: day 2026.09.11 00:00 to 2026.09.12 00:00, 40 deals, net -5870.00 DealDayReport: 48 deals on 2 days, 0 of them fall between the boundaries of this definition and server midnight DealDayReport: written to MQL5\Files\TradingDay\deal_days.csv
Its fit used a longer history than the one in the server clock fit and found the same zone. None of the 48 deals lies between the two boundaries, so this run does not exercise the count of moved deals. The tester runs above do.
Limitations
The fit and every tester run used one server, MetaQuotes-Demo, build 6230, EURUSD, and the 1-minute OHLC model. The tester results about TimeGMT(), the order of the history, the deal times, and the daily bars hold for that environment only. On another server or build they need a new check. I did not run the code across a clock change on a live account, and a live server could change its clock at another moment than the rule says.
The fit reads the server clock through the trading schedule. Early closes, holidays, missing bars, and special sessions move the last bar of a week, and a few such weeks in one season could look like another rule. Two weeks on the test server stay unexplained. The bars alone cannot show that the fitted zone is right. The live reading checks the offset of one day, not the rule. Before relying on a fit, compare it with a live reading in winter and in summer, or with the server time that the broker documents. The method needs a forex symbol with a Friday close at 17:00 in New York, so it is not meant for symbols that trade around the clock.
The resolver gives clock times. In one of the 17 weeks in which the two rules disagree, the feed stopped one hour after 17:00 New York on the fitted server clock. Another week, outside those 17, closed one hour early in July. A rule that is tied to the broker's actual close or rollover can therefore be one hour off in single weeks. The module does not measure the end of the feed.
The module supports a whole-hour offset with no rule, the US rule, or the EU rule, as they are coded today. The module does not support half-hour or quarter-hour offsets, the southern hemisphere, historical rule changes, or a broker whose clock changes on other dates. The calendar rules are tested from 2015 to 2035, and the day starts around the clock changes of two years. A history of winter weeks only cannot tell the rules apart, and the class reports the tie.
The result for a reset time inside a skipped or a repeated hour is my choice. I have not shown that it matches the rules of FTMO or of any other firm. A reset at 00:00 in Central Europe, as in the FTMO text, never falls into such an hour, because Central Europe changes its clock between 02:00 and 03:00. A server time in the repeated hour of the server clock is read as its first instant. The unit tests cover that rule with values written by hand. The test server had no tick in that hour, so I did not test the case on a server.
The tracker keeps the values of the first call at or after the boundary. For a limit that is measured from the equity at the reset moment, this is a significant limitation, as the CDayTracker section explains. Only the start balance can be rebuilt from the history, not the start equity.
DealsNet() skips credit deals, and no account I used had one. Other deal types that a broker may use for corrections, charges, or bonuses are summed like a deposit. The rebuild therefore depends on how a server writes its history. The deals that fall exactly on a boundary second all came from the first tick of a Monday. I have no deal at a boundary second in the middle of a session.
The counts of deals between boundaries show how much two definitions disagree about one history. They are not a risk measure, and they are defined only for boundaries a few hours apart. The unit tests check my logic and my arithmetic on the listed cases. The Python check takes the fitted zone as its input, so it cannot catch a wrong fit.
What the checks do not coverThe checks do not cover a change of the broker's server settings after the fit. They do not cover a history that the terminal returns out of time order, or a server whose offset the fit cannot express. They leave out the end of the feed, the broker's rollover time, and the rules of any firm that I did not read. They also do not cover the choice of the definition for a given limit. That choice comes from the text of the rule, and the class only applies it.
Conclusion
The module answers one question: which trading day does this server time belong to? It supports a server whose clock has a whole-hour offset and follows no rule, the US rule, or the EU rule, and a reset at any minute of the day in a zone of the same kind. The answers are clock times, not the end of the broker's feed. The unit tests cover seven of these definitions. On MetaQuotes-Demo, the two other definitions of the tester runs differ from server midnight in two ways. In the runs, midnight in Central Europe starts one hour after server midnight on every day. A limit with that reset would therefore put about two deals of my test EA on another day than server midnight does, on every trading day. The New York close and the server midnight are the same instant in all but three or four weeks of each year in the data I used. In those weeks, a limit that resets at the New York close would count the deals of one hour on the wrong day if the EA took the day from the server date.
A reset time inside a skipped or a repeated hour has a defined result, and the fit shows a tie through an equal runner-up score instead of hiding it. The tester runs showed for build 6230 that TimeGMT() returns the server time there and not UTC. In that build, an EA in the tester therefore needs the server zone as an input.
My checks cover one server and one build. If you use the module, run FitServerClock.mq5 on your own broker first. Read the weeks it cannot explain, compare its live reading with the fitted offset in both seasons, and decide from the rule text of your limit which definition to use.
Attached files
| File | Location | Contents |
|---|---|---|
| TdTypes.mqh | MQL5/Include/TradingDay/ | Constants, enumerations, and the STdZone and STdDay structures |
| TdCalendar.mqh | MQL5/Include/TradingDay/ | DST windows, offsets, and conversion between local time and UTC |
| TradingDay.mqh | MQL5/Include/TradingDay/ | CTradingDay |
| ServerClockFit.mqh | MQL5/Include/TradingDay/ | CServerClockFit |
| DayTracker.mqh | MQL5/Include/TradingDay/ | CDayTracker |
| DealDays.mqh | MQL5/Include/TradingDay/ | CDealDays |
| FitServerClock.mq5 | MQL5/Scripts/TradingDay/ | Fits the server zone, writes the weekly CSV file, and prints one live reading of the server clock |
| DealDayReport.mq5 | MQL5/Scripts/TradingDay/ | Groups the account history by a chosen definition |
| TestTradingDay.mq5 | MQL5/Scripts/TradingDay/ | 47 checks, the two mutation checks and their comparison included, and the list of odd-length days |
| TdVectors.mqh | MQL5/Include/TradingDay/ | Reference values from the IANA database, generated by make_vectors.py |
| TradingDayDemo.mq5 | MQL5/Experts/TradingDay/ | Tracks three definitions in the Strategy Tester |
| tradingday_crosscheck.py | MQL5/Files/TradingDay/ | Python consistency check against zoneinfo, with its own refit of the server zone |
| make_vectors.py | MQL5/Files/TradingDay/ | Generates TdVectors.mqh |
| MQL5.zip | Attachment | All files above, with the folder structure of the terminal |
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.