Implementing a Zone-Aware Rollover Window Gate in MQL5
Contents
- Introduction
- Architecture
- The spread spike on the test server
- CTradeWindows
- CSpreadProfile
- Scripts, files, and the windows file
- Unit tests
- Tester runs
- Python consistency check
- Using the gate in your EA
- Limitations
- What the checks do not cover
- Conclusion
- Attached files
Introduction
At 17:00 in New York the forex day rolls over, and the spread of many symbols widens for a while. On the test server, in the learning period of this article, the typical spread of EURUSD rose from a baseline of 2.5 points to 54.3 points at 17:02 New York. The learner marks a run of 87 minutes, from 16:33 to 17:59, in which the typical spread is at least three times the baseline. An EA that sends an order in that run pays the wide spread at entry. A stop loss close to the market can also be hit by the spread alone.
A common answer is a time filter in server time with a start hour and an end hour as inputs. The filter blocks entries between the two hours. The filter covers the rollover only while the server clock keeps the same distance to the New York clock. On the server I tested, that distance changes during the year.
I model that server as UTC+2 with the European DST rule, and New York follows the US rule. The two rules change the clocks on different Sundays. In the weeks between those Sundays, 17:00 in New York is 23:00 on the server clock and not 00:00. A filter that blocks the hour after server midnight then covers the wrong hour. The IANA time zone database gives the size of the effect under that model. Consider a window fixed in server time at the position that the New York window has in a normal week. In 2025 and 2026, that fixed window misses 48 of the 626 New York windows from Sunday to Friday.
The module is built around two include files. TradeWindows.mqh defines the CTradeWindows class. CTradeWindows holds a list of daily windows in which entries are not allowed. Each window starts at a clock time in a chosen zone, such as 16:28 in New York, so it follows that zone through its clock changes. The second file, SpreadProfile.mqh, defines the CSpreadProfile class. CSpreadProfile measures the typical spread of each minute of the day on the clock of a zone. The class turns the minutes that stand out into windows. The windows can be saved to a file and loaded by an EA.
Both classes use the zone and DST code of my Trading Day article. I copied the two files of that code unchanged into the attached archive, so this article does not depend on a separate download.
The checks fall into two groups. The first group checks my code. It includes 113 unit checks, a list of window intervals from the IANA database, a mutation test, and a Python consistency check. The Python check rebuilds the bins, the windows, and the gate verdicts with a second implementation. These checks show that the arithmetic matches a second implementation under the same zone model. They do not show that the broker follows that model. The second group looks at the server's data. It includes spread profiles of three periods and Strategy Tester runs that use windows learned before the test period.
The numbers come from one server, one terminal build, and EURUSD in the tester. The server is MetaQuotes-Demo, and the build is 6230. Five more symbols appear only in the learned profiles, without tester runs. Other brokers differ, and that is the reason the window is learned from ticks and not typed in.
The closest published work is the article Adaptive Spread Monitoring and Order Gating in MQL5. It gates orders with a rolling histogram of recent spreads. Its own Limitations section notes that the rolling window forgets observations by tick count, with no regard for the time of day. My profile keeps the spread by minute of the day on the clock of a zone. The gate can therefore block a window before the first wide tick arrives, and the window follows that zone through its DST changes.
Architecture
The core module consists of four include files, TdTypes.mqh and TdCalendar.mqh for zones, TradeWindows.mqh for the window list, and SpreadProfile.mqh for the profile. The archive also holds one 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 rollover window gate
From tick history to a learned window and to the gate inside an EA

Fig. 1. CSpreadProfile and FindSpikes turn tick history into learned windows. AppendTo and the windows file carry the windows to CTradeWindows, and an EA asks that class before every entry
Every time that the classes accept or return is a server time, the reading of the server clock that TimeCurrent() and the tick history use. Inside, the classes convert it to UTC, and then to the clock of the window's zone. The server zone is an input of both classes. Neither class tries to find it.
The server zone is an assumption of this article, and every file and test below depends on it. I took UTC+2 with the EU rule from the clock fit of the Trading Day article. That fit uses the hour of the last bar before each weekend. That hour is itself tied to the New York close. One check here does not depend on the spread. At the time of the script runs, the time of a fresh EURUSD tick minus the computer's UTC clock gave +3 hours, and the model gives +3 hours for that date. This confirms the offset at a single moment, not the dates on which the server changes its clock.
The two zone files also exist in the archive of the Trading Day article, so a program should include only one copy of the two files.
The spread spike on the test server
I measured the spike with SpreadByMinute.mq5, which the scripts section describes. The script reads the ticks of a period, keeps the spread of every tick in points, and fills a CSpreadProfile. The profile bins the ticks by minute of the day on the clock of a zone. The next table names the periods. The learning period ends before the test period starts, so the Strategy Tester runs below are a forward test.
| Period | Server dates | Use |
|---|---|---|
| Learning period | 2025.11.03 to 2026.01.30 | The windows files of the tester runs |
| Disagreement weeks | 2026.03.09 to 2026.03.27 | The weeks in which the US and EU clocks disagree |
| Test period | 2026.02.02 to 2026.03.31 | Strategy Tester runs |
| Later period | 2026.04.06 to 2026.06.30 | Whether the learned window changed after the test period |
I ran the script twice on the learning period, once on the New York clock and once on the server clock.
SPREADMIN symbol=EURUSD clock=NY server_days_with_ticks=63 clock_days_spanned=90 clock_days_with_data=78 SPREADMIN stored=5135058 ignored=0 baseline=2.452 SPREADMIN server offset now: measured=+3 h model=+3 h tick_age=22 s SPREADMIN spikes=1 factor=3.00 SPREADMIN spike 1 start=16:33 length=87 peak=54.250 at=17:02 SPREADMIN windows added=1 saved=yes SPREADMIN window spike: 16:28 UTC-05:00 US DST for 97 min, Sun-Fri, learned
The first line has three day counts. The learning period has 63 server days with ticks, the weekdays without the two holidays. On the New York clock, the profile spans 90 calendar days, weekends included, and 78 of those days hold ticks. The difference comes from the Sunday evening session. On the New York clock that session is a day of its own, 13 times in the period. The evenings of the two holidays account for the other two days. On the server clock, the evening session belongs to Monday, so the server profile has 63 days with ticks.
The profile on the New York clock found one run, from 16:33 for 87 minutes, with a peak of 54.3 points at 17:02 against a baseline of 2.5 points. The window that the script derives from the run starts 5 minutes earlier and lasts 97 minutes. Fig. 2 shows the profile around that run.
Typical spread of EURUSD by minute on the New York clock
Learning period, with the baseline, the threshold, and the learned window

Fig. 2. The typical spread of EURUSD is near 2.5 points until about 16:30 on the New York clock, rises to 54 points in the first minutes after 17:00, and falls back by 18:00, and the learned window covers 16:28 to 18:05
The same ticks binned on the server clock give the same run, shifted to 23:33. In the learning period the US and EU clocks agree, so a window typed in server time would be right there. The disagreement weeks are different. I ran the script on the 15 weekdays of those weeks, once per clock.
SPREADMIN symbol=EURUSD clock=server server_days_with_ticks=15 clock_days_spanned=19 clock_days_with_data=15 SPREADMIN stored=2323628 ignored=0 baseline=3.043 SPREADMIN server offset now: measured=+3 h model=+3 h tick_age=22 s SPREADMIN spikes=1 factor=3.00 SPREADMIN spike 1 start=23:00 length=60 peak=33.172 at=23:02 SPREADMIN windows added=1 saved=yes SPREADMIN window spike: 22:55 UTC+02:00 EU DST for 70 min, Sun-Fri, learned
On the New York clock, the run is still at 17:00 for 60 minutes. On the server clock, it moves to 23:00. The peak in these weeks is 33.2 points at 17:02 New York. On the server clock, the peak is at 23:02. Fig. 3 draws both server clock profiles.
These profiles agree with the zone model. They do not test it. The profile on the New York clock depends on the model, because the model converts every tick time. Reading the spike as "17:00 in New York" also assumes the cause that the model is meant to show. So the model stays an assumption, and the tests, the files, and the tester comparison all rest on it.
Typical spread of EURUSD by minute on the server clock
Learning period, in which the US and EU clocks agree, and the disagreement weeks

Fig. 3. On the server clock, the spread spike starts near 23:30 in the learning period and at 23:00 in the disagreement weeks. The window learned in the learning period covers only part of the second spike
The next table collects the runs on all periods. The learned run is not the same in every period. In the learning period it starts at 16:33 and lasts 87 minutes. In the three later periods it starts at 17:00 and lasts 60 minutes. The baseline of the learning period, 2.5 points, is the lowest of the four. A lower baseline gives a lower threshold, and more of the quiet build-up before 17:00 crosses it. The CSpreadProfile section shows how much the run depends on the factor in that period.
| Period | Clock | Days with ticks | Baseline, points | Run | Peak, points |
|---|---|---|---|---|---|
| Learning period | New York | 63 | 2.45 | 16:33 for 87 minutes | 54.3 |
| Learning period | server | 63 | 2.45 | 23:33 for 87 minutes | 54.3 |
| Disagreement weeks | New York | 15 | 3.04 | 17:00 for 60 minutes | 33.2 |
| Disagreement weeks | server | 15 | 3.04 | 23:00 for 60 minutes | 33.2 |
| Test period | New York | 43 | 2.77 | 17:00 for 60 minutes | 28.1 |
| Later period | New York | 62 | 3.05 | 17:00 for 60 minutes | 40.5 |
| Later period | server | 62 | 3.05 | 00:00 for 60 minutes | 40.5 |
The learner is not tied to EURUSD. I ran it on five more symbols with the same learning period, the same clock, and the same settings. The next table lists the runs, and Fig. 4 draws the padded windows. These five symbols have no tester runs.
| Symbol | Baseline, points | Runs on the New York clock | Peak, points |
|---|---|---|---|
| EURUSD | 2.45 | 16:33 for 87 minutes | 54.3 |
| GBPUSD | 4.00 | 16:00 for 121 minutes | 151.8 |
| USDJPY | 4.00 | 16:55 for 66 minutes | 112.3 |
| XAUUSD | 16.27 | none | none |
| AUS200 | 19.63 | 00:30 for 40 minutes | 96.0 |
| JPN225 | 8.58 | 18:00 for one minute | 29.2 |
Learned windows of six symbols on the New York clock
Learning period, factor 3, padding of 5 minutes on both sides

Fig. 4. The learned windows of EURUSD, GBPUSD, and USDJPY lie around 17:00 on the New York clock with different starts and lengths. AUS200 has a window after midnight, JPN225 a short one at 17:55, and XAUUSD has none
Three currency pairs have a run around 17:00 New York. GBPUSD has a run of 121 minutes that starts at 16:00, and USDJPY has a run of 66 minutes from 16:55. XAUUSD has no run at a factor of 3 in this period. AUS200 has a run at 00:30, and JPN225 has a run of one minute at 18:00. I did not investigate why gold and the two indices behave this way. The runs show that the position and the length of a window differ by symbol. One pair of hour inputs shared by these six symbols would fit the three currency pairs only loosely and the other three not at all.
My first version of the learner collected Monday to Friday on the New York clock. In my first tester run, the first attempts of the test period fell on Sunday evening in New York, each with a spread of 27 points, and both gates answered open. The weekly open has its own wide hour. I changed the default day mask to Sunday to Friday. This mask covers the days on which a 17:00 clock time in New York occurs while the market is open. The windows files, the IANA lists of the unit tests, and the tester runs all use that mask.
CTradeWindows
A window repeats every day. A window has a label, a zone, a start on the clock of that zone, a length, and a day mask. The label may not contain a comma, because the file format uses commas. Bit d of the day mask selects the weekday on which the window starts, with Sunday as bit 0. A window that starts at 23:55 on Monday and lasts 25 minutes also blocks the first 20 minutes of Tuesday.
//+------------------------------------------------------------------+ //| A blocked interval that repeats every day on the clock of a zone | //| It starts start_sec seconds after local midnight and lasts | //| length_sec elapsed seconds. Bit d of day_mask selects the local | //| weekday on which the window starts, with Sunday as bit 0. | //+------------------------------------------------------------------+ struct SRgWindow { string label; // short name without commas, used in logs and files STdZone zone; // zone whose clock gives the start time int start_sec; // seconds after local midnight, 0 to 86399 int length_sec; // elapsed seconds, 60 to 86400 int day_mask; // weekdays on which the window starts ENUM_RG_SOURCE source; // fixed or learned };
The central method is ActiveAt. The method takes a UTC instant and answers whether the instant lies inside one window. A window may run past midnight of its zone, so the method checks two days, the local date of the instant and the day before. For each day, it converts the start reading to UTC with TdLocalToUtc and adds the length in seconds. This conversion is the part that handles clock changes. A start reading in the skipped hour, such as 02:30 in New York on the March day, lands one hour later. A start reading in the repeated hour takes the first instant.
//+------------------------------------------------------------------+ //| CTradeWindows::ActiveAt | //| True when the UTC instant lies inside the window. The window of | //| the local date of the instant and the window of the day before | //| are checked, because a window may run past midnight. The start | //| of each is a clock reading of the zone, so a reading that is | //| skipped or repeated by a clock change is resolved by TdCalendar. | //+------------------------------------------------------------------+ bool CTradeWindows::ActiveAt(const SRgWindow &w,const datetime utc,datetime &end_utc) const { datetime date=TdDate(TdUtcToLocal(w.zone,utc)); for(int k=0; k<2; k++) { datetime day=date-k*TD_DAY; if((w.day_mask&(1<<TdDayOfWeek(day)))==0) continue; ENUM_TD_LOCAL kind; datetime from=TdLocalToUtc(w.zone,day+w.start_sec,TD_FOLD_FIRST,kind); datetime to=from+w.length_sec; if(utc>=from && utc<to) { end_utc=to; return(true); } } return(false); }
IsBlocked converts the server time to UTC and calls ActiveAt for every window. A window includes its first second and excludes its last second. When windows overlap, the verdict names the window that ends last, because the caller wants to know how long to wait. When two windows end at the same second, the one that was added first wins.
//+------------------------------------------------------------------+ //| CTradeWindows::IsBlocked | //| True when a trade at the server time falls inside a window. A | //| window includes its first second and excludes its last. When | //| windows overlap, the verdict names the one that ends last, | //| which is the time a caller has to wait for. A tie goes to the | //| window that was added first. | //+------------------------------------------------------------------+ bool CTradeWindows::IsBlocked(const datetime server_time,SRgVerdict &verdict) const { verdict.blocked=false; verdict.index=-1; verdict.until=0; verdict.label=""; if(!m_ready || server_time<=0) return(false); datetime utc=ServerToUtc(server_time); datetime best=0; for(int i=0; i<ArraySize(m_list); i++) { datetime end_utc; if(!ActiveAt(m_list[i],utc,end_utc)) continue; if(end_utc>best) { best=end_utc; verdict.index=i; } } if(verdict.index<0) return(false); verdict.blocked=true; verdict.until=UtcToServer(best); verdict.label=m_list[verdict.index].label; return(true); }
NextOpen answers the other question, when trading may start again. It walks from the end of one window to the end of the next, so windows that touch each other count as one. The walk stops after 512 steps, which is eight days of 64 windows that touch each other. A return value of 0 means that no open time was found within that guard. The same value comes back when the windows block every moment of a week.
//+------------------------------------------------------------------+ //| CTradeWindows::NextOpen | //| First server time at or after the given time that is outside | //| every window. Windows that touch each other count as one. The | //| search gives up after RG_OPEN_STEPS steps and returns 0, which | //| also happens when the windows block every moment of a week. | //+------------------------------------------------------------------+ datetime CTradeWindows::NextOpen(const datetime server_time) const { datetime t=server_time; for(int step=0; step<RG_OPEN_STEPS; step++) { SRgVerdict v; if(!IsBlocked(t,v)) return(m_ready ? t : 0); t=v.until; } return(0); }
An EA that holds a position for a planned time has a second question. It should not enter when the exit would fall inside a window. SecondsToNextWindow gives the elapsed time until the next window starts, whether or not a window is active now.
//+------------------------------------------------------------------+ //| CTradeWindows::SecondsToNextWindow | //| Elapsed seconds until the next window starts, whether or not a | //| window is active now. Returns -1 when the list is empty. | //+------------------------------------------------------------------+ int CTradeWindows::SecondsToNextWindow(const datetime server_time) const { if(!m_ready || server_time<=0) return(-1); datetime utc=ServerToUtc(server_time); datetime best=0; for(int i=0; i<ArraySize(m_list); i++) { datetime from=NextStartUtc(m_list[i],utc); if(from>0 && (best==0 || from<best)) best=from; } return(best==0 ? -1 : (int)(best-utc)); }
AddAround builds a window from an anchor time and two margins. The anchor 17:00 in New York with 10 minutes before and 15 minutes after gives a window that starts at 16:50 and lasts 25 minutes. The day mask names the weekdays of the anchor. When the margin moves the start before midnight, RgShiftMask moves the mask back by one day. An anchor at 00:05 from Monday to Friday with 10 minutes before therefore gives a window that starts at 23:55 from Sunday to Thursday. My first version kept the mask unchanged, so that window started on the wrong days.
//+------------------------------------------------------------------+ //| RgShiftMask | //| Moves every weekday of a day mask the given number of days back, | //| so that Monday becomes Sunday and Sunday becomes Saturday for 1. | //+------------------------------------------------------------------+ int RgShiftMask(const int mask,const int days_back) { int out=0; int k=((days_back%7)+7)%7; for(int d=0; d<7; d++) if((mask&(1<<d))!=0) out|=1<<((d-k+7)%7); return(out); }
//+------------------------------------------------------------------+ //| CTradeWindows::AddAround | //| Adds a window around an anchor time, for example 10 minutes | //| before and 15 minutes after 17:00. The day mask selects the | //| weekdays of the anchor. When the margin moves the start before | //| midnight, the mask moves back by the same number of days. | //+------------------------------------------------------------------+ bool CTradeWindows::AddAround(const string label,const STdZone &zone,const int hour,const int minute, const int minutes_before,const int minutes_after,const int day_mask) { if(minutes_before<0 || minutes_after<0) return(false); int start=hour*60+minute-minutes_before; int days_back=0; while(start<0) { start+=RG_DAY_MINUTES; days_back++; } return(Add(label,zone,start/60,start%60,minutes_before+minutes_after,RgShiftMask(day_mask,days_back))); }
The list holds at most 64 windows. Add and AddAround return false, and add nothing, for a value that is out of range or for a full list. A refused call leaves the list unchanged.
CSpreadProfile
The profile stores two numbers per day and minute, the sum of the tick spreads and the number of ticks. A tick is binned by the minute of its server time on the clock of the profile's zone. The date on that clock decides the day. Ticks of days that are not in the day mask are ignored, and so are ticks of a date before the first stored date.
//+------------------------------------------------------------------+ //| CSpreadProfile::Add | //| Stores the spread of one tick, in points. Samples must arrive in | //| time order by calendar day. A sample on a weekday that is not in | //| the mask, on a date before the first stored date, or with a | //| negative or zero spread is ignored and the call returns false. | //+------------------------------------------------------------------+ bool CSpreadProfile::Add(const datetime server_time,const double spread) { if(!m_ready || server_time<=0 || spread<=0.0) { m_ignored++; return(false); } long key=(long)server_time/RG_MINUTE; if(key!=m_key) { m_key=key; ENUM_TD_LOCAL kind; datetime local=TdUtcToLocal(m_clock,TdLocalToUtc(m_server,server_time,TD_FOLD_FIRST,kind)); datetime date=TdDate(local); m_minute=(int)(((long)local%TD_DAY)/RG_MINUTE); m_use=((m_day_mask&(1<<TdDayOfWeek(date)))!=0); if(m_use) { if(m_days==0) m_first=date; long idx=((long)date-(long)m_first)/TD_DAY; m_use=(idx>=0 && idx<SP_MAX_DAYS); m_day=(int)idx; } } if(!m_use) { m_ignored++; return(false); } if(m_day>=m_days) { int old=m_days*RG_DAY_MINUTES; int now=(m_day+1)*RG_DAY_MINUTES; ArrayResize(m_sum,now); ArrayResize(m_cnt,now); for(int i=old; i<now; i++) { m_sum[i]=0.0; m_cnt[i]=0; } m_days=m_day+1; } m_sum[m_day*RG_DAY_MINUTES+m_minute]+=spread; m_cnt[m_day*RG_DAY_MINUTES+m_minute]++; m_stored++; return(true); }
The typical spread of a minute is the median over all days of the daily mean of that minute. I chose the median of means on purpose. A news release or a thin evening on one day changes the mean of one cell and leaves the median of 63 days where it was. The unit tests include a day on which every minute has a spread of 1,000 points, and the learned run does not change. A minute without any tick on a day adds nothing to the median for that day. In a thin market, the typical spread of a minute therefore comes from the days on which that minute had ticks.
//+------------------------------------------------------------------+ //| CSpreadProfile::MinuteMedian | //| Median over all days of the daily mean spread of one minute. | //| days_used is the number of days that have a sample in it. | //+------------------------------------------------------------------+ double CSpreadProfile::MinuteMedian(const int minute,int &days_used) const { days_used=0; if(minute<0 || minute>=RG_DAY_MINUTES) return(0.0); double v[]; ArrayResize(v,m_days); for(int d=0; d<m_days; d++) { int i=d*RG_DAY_MINUTES+minute; if(m_cnt[i]>0) v[days_used++]=m_sum[i]/m_cnt[i]; } if(days_used==0) return(0.0); ArrayResize(v,days_used); ArraySort(v); return((v[(days_used-1)/2]+v[days_used/2])/2.0); }
FindSpikes works in four steps. First it computes the baseline, the median of the typical spread over all minutes that have at least min_days days. FindSpikes returns -1 when fewer than 720 minutes qualify, because a baseline from half a day is not reliable. Second, it flags every minute with a typical spread of at least factor times the baseline. Third, it closes gaps of up to merge_gap minutes between flagged minutes, going around midnight. Fourth, it collects the runs, starting the walk at a minute that is not flagged, so that no run is cut at the start of the day.
//+------------------------------------------------------------------+ //| CSpreadProfile::FindSpikes | //| Runs of minutes whose typical spread is at least factor times | //| the baseline. A minute with fewer than min_days days is never | //| flagged. Runs separated by merge_gap minutes or fewer are | //| joined, and a run may cross midnight of the profile clock. | //| Returns the number of runs, or -1 when there is no baseline. | //+------------------------------------------------------------------+ int CSpreadProfile::FindSpikes(const double factor,const int min_days,const int merge_gap, SRgSpike &spikes[]) const { ArrayResize(spikes,0); double base=Baseline(min_days); if(base<=0.0) return(-1); double med[]; bool flag[]; ArrayResize(med,RG_DAY_MINUTES); ArrayResize(flag,RG_DAY_MINUTES); for(int m=0; m<RG_DAY_MINUTES; m++) { int used; med[m]=MinuteMedian(m,used); flag[m]=(used>=min_days && med[m]>=factor*base); } //--- fill the short gaps between flagged minutes, going around midnight bool filled[]; ArrayCopy(filled,flag); for(int m=0; m<RG_DAY_MINUTES; m++) { if(!flag[m]) continue; for(int g=1; g<=merge_gap+1; g++) { int next=(m+g)%RG_DAY_MINUTES; if(flag[next]) { for(int k=1; k<g; k++) filled[(m+k)%RG_DAY_MINUTES]=true; break; } } } //--- start walking at a minute that is not flagged, so no run is cut at index 0 int start=-1; for(int m=0; m<RG_DAY_MINUTES; m++) if(!filled[m]) { start=m; break; } if(start<0) { ArrayResize(spikes,1); spikes[0].start_min=0; spikes[0].length_min=RG_DAY_MINUTES; spikes[0].peak=0.0; spikes[0].peak_min=0; for(int m=0; m<RG_DAY_MINUTES; m++) if(med[m]>spikes[0].peak) { spikes[0].peak=med[m]; spikes[0].peak_min=m; } return(1); } int n=0; int i=1; while(i<=RG_DAY_MINUTES) { int m=(start+i)%RG_DAY_MINUTES; if(!filled[m]) { i++; continue; } int first=m; double peak=0.0; int peak_min=m; int len=0; while(i<=RG_DAY_MINUTES && filled[(start+i)%RG_DAY_MINUTES]) { int mm=(start+i)%RG_DAY_MINUTES; if(med[mm]>peak) { peak=med[mm]; peak_min=mm; } len++; i++; } ArrayResize(spikes,n+1); spikes[n].start_min=first; spikes[n].length_min=len; spikes[n].peak=peak; spikes[n].peak_min=peak_min; n++; } return(n); }
The factor, the minimum number of days, the merge gap, and the padding are my choices. They are not derived from the data. The Python check rebuilds the runs for other factors from the cells file of each symbol. The next table shows the padded windows for four factors in the learning period.
| Symbol | Factor 1.5 | Factor 2 | Factor 3 | Factor 5 |
|---|---|---|---|---|
| EURUSD | 15:55 for 131 minutes | 15:55 for 130 minutes | 16:28 for 97 minutes | 16:52 for 73 minutes |
| GBPUSD | 15:55 for 131 minutes | 15:55 for 131 minutes | 15:55 for 131 minutes | 15:55 for 130 minutes |
| USDJPY | 16:50 for 85 minutes | 16:50 for 76 minutes | 16:50 for 76 minutes | 16:56 for 70 minutes |
| XAUUSD | 15:55 for 70 minutes, and 17:55 for 15 minutes | 16:25 for 40 minutes, and 17:55 for 14 minutes | none | none |
| AUS200 | 00:25 for 51 minutes | 00:25 for 50 minutes | 00:25 for 50 minutes | none |
| JPN225 | 17:55 for 23 minutes | 17:55 for 17 minutes | 17:55 for 11 minutes | none |
The factor matters more than I expected. On EURUSD, the start of the window moves by 57 minutes between the factors 1.5 and 5. Fig. 2 shows the reason. From 16:00 the typical spread steps up to about 6 points, and from about 16:30 it stays between 8 and 10 points. Both steps lie between two and four times the baseline, so the factor decides whether the build-up before 17:00 belongs to the window. GBPUSD keeps the same window for all four factors. USDJPY moves by six minutes at most. XAUUSD, AUS200, and JPN225 lose their windows at the higher factors. I would choose the factor per symbol, at a value where the window stops moving.
The profile also pools the weekdays. The Sunday open, the Friday close, and the days in the middle of the week can have different spread patterns, and one median per minute hides that. The weekdays command of the Python check splits the cells of the learning period by weekday. It judges every weekday against the threshold of all days, 7.36 points.
WEEKDAYS baseline_of_all_days=2.4517 threshold=7.3552 WEEKDAYS Sun days=13 minutes_with_data=420 runs=17:01+60 peak 105.0 WEEKDAYS Mon days=13 minutes_with_data=1440 runs=16:55+65 peak 51.5 WEEKDAYS Tue days=13 minutes_with_data=1440 runs=16:47+73 peak 47.5 WEEKDAYS Wed days=13 minutes_with_data=1440 runs=16:00+120 peak 30.5 WEEKDAYS Thu days=13 minutes_with_data=1440 runs=16:00+120 peak 60.7 WEEKDAYS Fri days=13 minutes_with_data=1020 runs=16:33+1 peak 7.4; 16:44+15 peak 13.3
The weekdays differ. Sunday has the highest peak, 105 points, because the weekly open falls on the rollover minute. Monday and Tuesday have runs that start at 16:55 and 16:47. Wednesday and Thursday have runs from 16:00 for 120 minutes, so in that period the hour before the rollover was also wide on those two days. Friday has data only until 17:00, when the market closes, and its two short runs end there. I did not investigate the reason for the hour before the rollover on Wednesday and Thursday. One window for all days covers the union only partly: the pooled run starts at 16:33, after the start of the Wednesday and Thursday runs. A learner with one window per weekday would follow these patterns more closely, and I did not build one.
AppendTo turns the runs into learned windows on the clock of the profile. The method adds padding before and after each run. The first wide tick of a day can arrive a little before the median shows it, and the end of the run is not sharp on every day. The padding is 5 minutes on both sides in this article. The day mask names the weekdays on which the runs start. A start that the padding moves before midnight wraps to the evening of the day before, and the mask moves back one day with it.
//+------------------------------------------------------------------+ //| CSpreadProfile::AppendTo | //| Adds each run as a learned window on the profile clock, with | //| padding before and after it. The labels are the given text and | //| the run number. The day mask selects the weekdays on which the | //| runs start. When the padding moves a start before midnight, the | //| mask moves back one day with it. Returns the windows added. | //+------------------------------------------------------------------+ int CSpreadProfile::AppendTo(CTradeWindows &list,const string label,const SRgSpike &spikes[], const int pad_before,const int pad_after,const int day_mask) const { int added=0; if(pad_before<0 || pad_after<0) return(0); for(int i=0; i<ArraySize(spikes); i++) { int start=spikes[i].start_min-pad_before; int days_back=0; while(start<0) { start+=RG_DAY_MINUTES; days_back++; } int len=MathMin(RG_DAY_MINUTES,spikes[i].length_min+pad_before+pad_after); string name=(ArraySize(spikes)>1 ? StringFormat("%s%d",label,i+1) : label); if(list.Add(name,m_clock,start/60,start%60,len,RgShiftMask(day_mask,days_back),RG_LEARNED)) added++; } return(added); }
That shift matters for a run at 00:00 on the server clock. In the later period, the server clock run starts at 00:00, the padded window at 23:55, and the window file names the days Sunday to Thursday and Saturday. The New York windows of this article start at 16:28 and 16:55, so the padding does not move them past midnight.
Scripts, files, and the windows file
SpreadByMinute.mq5 is the script that I used to measure the spike. The next table lists its inputs. My first run found no ticks at all. The script now waits up to 90 seconds for the terminal to connect, and it retries a weekday without ticks for up to 20 seconds.
| Input | Meaning | Value used |
|---|---|---|
| InpSymbol | Symbol of the profile | EURUSD, and five more listed above |
| InpFrom, InpDays | First server day and number of server days | per period, see the periods table above |
| InpServerStd | Standard offset of the server clock, in hours | 2 |
| InpClock | Clock of the profile, New York or server | per run |
| InpFactor | Spike threshold, times the baseline | 3 |
| InpDayMask | Weekdays of the profile clock to collect | 63, Sunday to Friday |
| InpMinDays | Days a minute needs to be judged | 10 |
| InpMergeGap | Longest quiet gap, in minutes, that still joins two spike runs | 5 |
| InpPadBefore, InpPadAfter | Minutes added before and after a spike | 5 and 5 |
| InpLabel | Label of the learned windows | spike |
| InpProfileCsv, InpCellsCsv, InpWindowsCsv | Names of the three output files, empty for none | per run |
The script can also write three files. The first holds the typical spread of the 1,440 minutes. The second holds the mean and the tick count of every day and minute for the Python check. The third is the windows file. The methods Save and Load move windows between the script and an EA. The windows file is a CSV with a header, and Load finds the columns by name.
label,std_offset_sec,dst,start_min,length_min,day_mask,source spike,-18000,1,988,97,63,1
The columns hold the label, the standard offset of the zone in seconds, the DST rule as a number, the start and the length in minutes, the day mask, and the source. In this file, -18000 with rule 1 corresponds to New York, and the mask 63 stands for Sunday to Friday. A zone is stored as an offset and a rule, not as an IANA name, so the file can only hold the zones that the calendar code knows. Load fails the whole call, and leaves the old list unchanged, when a column is missing or duplicated. The call also fails when a field is not an integer, when a row has the wrong number of fields, or when a value is out of range. The error text names the line. A window that an EA silently skipped because of a typo in the file would be the worst outcome here, and the unit tests cover each of these cases. A file with valid values that are wrong, such as a start at 15:00 typed by hand, loads without an error. The demo EA prints every window it loaded, so such a file can be seen in the journal. However, no check catches such a file.
Unit tests
TestTradeWindows.mq5 prints one PASS or FAIL line per check. The checks fall into 10 groups, shown in the next table.
| Group | Checks | What it covers |
|---|---|---|
| validation | 22 | Range checks of Add, the limit of 64 windows, Remove, and Clear |
| midnight | eight | A window across midnight, NextOpen, and the repeated hour of the server clock |
| day mask | five | A window that starts on one weekday and runs into the next |
| overlap | 11 | The window that is named, ties, touching windows, 64 windows in a row, and the NextOpen guard |
| around | 12 | AddAround arithmetic, the shift of the day mask, RgShiftMask, and the text of Describe |
| seconds to next | six | SecondsToNextWindow with and without an active window |
| file | 16 | Save, Load, the column order, and nine kinds of bad file |
| IANA vectors | five | Five lists of window intervals from the database, two of them the windows of the files |
| mutant | two | The server clock window against the New York intervals |
| profile | 26 | Baseline, runs, gaps, midnight, padding, the mask shift of AppendTo, the median, and the counters |
The five IANA checks require clarification. The script make_vectors.py writes RgVectors.mqh from the IANA database through Python's zoneinfo. For five window definitions, the file lists the start and the end of every window in 2025 and 2026 as server clock readings. Two definitions are the windows of the two files of the Strategy Tester runs, 16:28 in New York and 23:28 on the server clock, each for 97 minutes from Sunday to Friday. Two more start at 01:30 and at 02:30 in New York, inside the repeated hour and the skipped hour of that clock. For each interval, the test checks four points.
- The first second of the interval is blocked, and the reported wait runs to the end of the interval.
- The second before the start is open.
- The last second of the interval is blocked.
- The end second is open, since an interval does not include its end.
The test also checks that NextOpen of the start returns the end.
//+------------------------------------------------------------------+ //| CheckList | //| Checks one list of window intervals from make_vectors.py. Each | //| interval must start blocked, end open, report its end as the | //| wait, and be open one second before the start. Returns the | //| number of intervals with at least one wrong answer. | //+------------------------------------------------------------------+ int CheckList(const CTradeWindows &list,const datetime &v[]) { int bad=0; for(int i=0; i+1<ArraySize(v); i+=2) { SRgVerdict verdict; bool ok=list.IsBlocked(v[i],verdict) && verdict.until==v[i+1]; ok=ok && !list.IsBlocked(v[i]-1); ok=ok && list.IsBlocked(v[i+1]-1); ok=ok && !list.IsBlocked(v[i+1]); ok=ok && list.NextOpen(v[i])==v[i+1]; if(!ok) { bad++; if(bad<=3) PrintFormat("RGVEC wrong interval %s to %s",TimeToString(v[i],TIME_DATE|TIME_SECONDS), TimeToString(v[i+1],TIME_DATE|TIME_SECONDS)); } } return(bad); }
RGVEC NY_ROLLOVER intervals=626 wrong=0 PASS IANA vectors: New York 16:28 for 97 minutes, Sunday to Friday, the window of ny_windows.csv RGVEC NY_ACROSS_MIDNIGHT intervals=626 wrong=0 PASS IANA vectors: New York 23:50 for 20 minutes, across New York midnight RGVEC SRV_ACROSS_MIDNIGHT intervals=626 wrong=0 PASS IANA vectors: server clock 23:28 for 97 minutes, the window of server_windows.csv RGVEC NY_REPEATED_HOUR intervals=730 wrong=0 PASS IANA vectors: New York 01:30 for 60 minutes, including the repeated hour RGVEC NY_SKIPPED_HOUR intervals=730 wrong=0 PASS IANA vectors: New York 02:30 for 60 minutes, including the skipped hour
NY_ROLLOVER windows 626 left out 0 NY_ACROSS_MIDNIGHT windows 626 left out 0 SRV_ACROSS_MIDNIGHT windows 626 left out 0 NY_REPEATED_HOUR windows 730 left out 0 NY_SKIPPED_HOUR windows 730 left out 0 NY_ROLLOVER windows with a server start other than 23:28: 48
These checks compare my DST rules with the database. They do not compare my code with the broker. The server in the vectors is Europe/Athens, the zone model of this article. A start or an end inside the skipped or repeated hour of that server would have been left out, and the generator prints the number of left-out intervals. The number was zero for all five lists.
The mutation test makes the fixed server window fail on purpose. The test uses the window of the server clock file, 23:28 for 97 minutes. That time equals 16:28 in New York when the US and EU clocks agree. The test expects the window to miss the New York intervals on the days when the clocks disagree, and it reports FAIL for exactly those intervals.
//+------------------------------------------------------------------+ //| TestMutant | //| The window of server_windows.csv, fixed on the server clock at | //| the time that New York 16:28 has in a normal week. The test | //| expects it to miss the New York intervals on the days when the | //| US and EU clocks disagree, Sunday to Friday, and on no others. | //+------------------------------------------------------------------+ void TestMutant(void) { CTradeWindows fixed; Fresh(fixed); fixed.Add("fixed server window",Server(),23,28,97,RG_TRADING_DAYS); int total=ArraySize(V_NY_ROLLOVER)/2; int missed=0; for(int i=0; i+1<ArraySize(V_NY_ROLLOVER); i+=2) { SRgVerdict v; bool covers=fixed.IsBlocked(V_NY_ROLLOVER[i],v) && v.until==V_NY_ROLLOVER[i+1]; if(!covers) missed++; } PrintFormat("RGMUT fixed server window misses %d of %d New York intervals",missed,total); Check(missed>0 && missed<total,"mutant: a fixed server window fails on some intervals and not on all"); Check(missed==48,"mutant: it fails on 48 intervals, the days on which the US and EU clocks disagree"); }
RGMUT fixed server window misses 48 of 626 New York intervals PASS mutant: a fixed server window fails on some intervals and not on all PASS mutant: it fails on 48 intervals, the days on which the US and EU clocks disagree
The test that expected a failure found 48 failing intervals out of 626. The generator counts the same 48 in Python, as the windows of the same list whose server start is not 23:28. The 48 intervals are the days, Sunday to Friday, on which the US and EU clocks disagree, and the count equals the 48 of the Introduction.
One of my own checks was wrong at first. I expected the profile on the server clock and the profile on the New York clock to store the same number of samples. They differ, because the server profile drops the Saturday readings that follow the Friday rollover. The check now states that difference.
The unit tests check my logic and my arithmetic for the listed cases. They say nothing about a broker's server or about what the spread does there.
Tester runs
WindowGateDemo.mq5 is a small Expert Advisor that exists to compare gates on the same entry attempts. Every 15 minutes on the server clock, it makes one attempt to buy 0.01 lot and holds the position for 12 minutes. It loads two windows files, one learned on the New York clock and one learned on the server clock. Both files come from the learning period, which ends before the test period. Both windows have the same length, 97 minutes.
For every attempt, the EA asks both gates and logs both answers. The answer is open, in, or clear. In means the entry itself is inside a window. Clear means the planned exit, 12 minutes later, would fall inside a window.
//+------------------------------------------------------------------+ //| Verdict | //| Gate answer for an entry now and an exit after the hold time. | //| Returns "in" inside a window, "clear" when the exit would fall | //| in a window, and "open" otherwise. | //+------------------------------------------------------------------+ string Verdict(const CTradeWindows &gate,const datetime now) { if(gate.IsBlocked(now)) return("in"); if(InpKeepClear) { int wait=gate.SecondsToNextWindow(now); if(wait>=0 && wait<InpHoldMinutes*60) return("clear"); } return("open"); }
The input InpMode decides what the EA does with the answers. In the first mode, it trades every attempt and only logs. In the second, it skips an attempt that the New York gate blocks. In the third, it skips an attempt that the server clock gate blocks. Because the first mode trades every attempt, the log of that run shows what each gate would have said about the same attempts. I compare the gates on those attempts within one run, because separate runs would add differences that the gates do not cause. The EA counts only its own position, found by symbol and magic number, so a position of another symbol or EA does not stop an attempt.
//+------------------------------------------------------------------+ //| OwnPosition | //| Ticket of the open position of this EA on this symbol, 0 when | //| there is none. Positions of other symbols or other EAs do not | //| count. | //+------------------------------------------------------------------+ ulong OwnPosition(void) { for(int i=PositionsTotal()-1; i>=0; i--) { ulong ticket=PositionGetTicket(i); if(ticket==0) continue; if(PositionGetString(POSITION_SYMBOL)==_Symbol && PositionGetInteger(POSITION_MAGIC)==InpMagic) return(ticket); } return(0); }
//+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { MqlTick tick; if(!SymbolInfoTick(_Symbol,tick)) return; datetime now=tick.time; ulong own=OwnPosition(); //--- a position without a close time (entry result unknown) gets one from its open time if(own>0 && g_close_at==0) g_close_at=(datetime)PositionGetInteger(POSITION_TIME)+InpHoldMinutes*60; if(own==0) g_close_at=0; if(g_close_at>0 && now>=g_close_at && own>0) { bool sent=g_trade.PositionClose(own); uint code=g_trade.ResultRetcode(); if(sent && code==TRADE_RETCODE_DONE && OwnPosition()==0) { g_closed++; g_close_at=0; own=0; } else { g_close_fail++; if(g_close_fail<=20) PrintFormat("RGFAIL close retcode=%u",code); own=OwnPosition(); } } if(g_next==0) g_next=NextGrid(now); if(now<g_next) return; g_next=NextGrid(now); if(tick.bid<=0 || tick.ask<=tick.bid || own>0) return; g_attempts++; double spread=(tick.ask-tick.bid)/_Point; string ny=Verdict(g_ny,now); string sv=Verdict(g_srv,now); if(ny=="in") g_ny_in++; if(ny=="clear") g_ny_clear++; if(sv=="in") g_srv_in++; if(sv=="clear") g_srv_clear++; bool skip=(InpMode==GATE_NEW_YORK && ny!="open") || (InpMode==GATE_SERVER && sv!="open"); PrintFormat("RGATE n=%d t=%s spread=%.1f ny=%s server=%s action=%s",g_attempts, TimeToString(now,TIME_DATE|TIME_SECONDS),spread,ny,sv,skip ? "skip" : "trade"); if(skip) return; bool sent=g_trade.Buy(InpLots,_Symbol); uint code=g_trade.ResultRetcode(); ulong deal=g_trade.ResultDeal(); //--- an entry counts only when the server executed it and the position exists if(sent && (code==TRADE_RETCODE_DONE || code==TRADE_RETCODE_DONE_PARTIAL) && deal>0 && OwnPosition()>0) { g_traded++; g_close_at=now+InpHoldMinutes*60; PrintFormat("RGDEAL n=%d deal=%I64u retcode=%u",g_attempts,deal,code); } else { g_entry_fail++; PrintFormat("RGFAIL buy n=%d retcode=%u deal=%I64u",g_attempts,code,deal); } }
The next table shows the setup.
| Setting | Value |
|---|---|
| Symbol and period | EURUSD, H1 |
| Model | Every tick based on real ticks |
| Execution | No delay |
| Dates | 2026.02.02 to 2026.04.01 |
| Deposit | 10,000 USD, leverage 1:100 |
| Inputs | InpAttemptMinutes 15, InpHoldMinutes 12, InpLots 0.01, InpKeepClear true, InpServerStd 2, InpMagic 25237 |
| Windows files | Learning period, 2025.11.03 to 2026.01.30, New York clock and server clock |
The logs of all runs hold 3,896 attempts. A run with no delay on real ticks has no randomness. I ran the first mode three times, and the attempt lines of the three logs are identical.
A true return from Buy() or PositionClose() does not mean that the trade server executed the request. After Buy(), the EA checks ResultRetcode(), the deal ticket, and its own open position. Only then does it count the entry and set the close time. After PositionClose(), the EA resets the close time only when the retcode is TRADE_RETCODE_DONE and the position no longer exists. Failed requests are logged as RGFAIL lines and counted in the RGSUM summary line. In all five runs, every entry attempt was executed and every close was confirmed. The logs hold no RGFAIL line. The executed entries in the next table therefore equal the entry attempts.
Each gate skipped 280 attempts, and every skipped attempt was inside a window. No attempt was skipped for its exit. The last attempt before a window comes 13 minutes before the window starts, one minute more than the hold time.
An entry is wide when its spread is at least 7.36 points. This threshold is three times the baseline of the learning profile, the same factor and baseline that FindSpikes used. FindSpikes applies the threshold to the typical spread of a minute. The tester comparison applies the threshold to the spread of one tick. The next table shows what remained in the three runs.
| Run | Executed entries | Wide entries | Mean spread at entry, points |
|---|---|---|---|
| Every attempt traded | 3,896 | 268 | 4.15 |
| New York gate | 3,616 | 91 | 3.22 |
| Server clock gate | 3,616 | 111 | 3.31 |
On the days on which the US and EU clocks agree, both gates block the same instants, and they gave the same counts. Of 168 wide attempts, 41 got through. On the days on which the clocks disagree, the New York gate let 50 of 100 wide attempts through, and the server clock gate let 70 of 100 through. The Python consistency check below counts the wide attempts in the hour from 17:00 to 17:59 in New York. The server clock gate let 19 of those through, and the New York gate let none through. The server window still caught part of the rollover in those weeks. Its padded start at 23:28 overlaps the second half of the hour that starts at 23:00 on the server clock, as Fig. 3 shows.
Fig. 5 shows where the server gate fails. It counts the wide attempts that each gate let through per week.
Wide attempts that each gate let through, by week
Run that traded every attempt, EURUSD, test period

Fig. 5. The two gates let the same wide attempts through in the weeks in which the US and EU clocks agree, and in the three weeks in which they disagree the server clock gate lets more through
Fig. 6 shows the effect on the entries of the three runs. The numbers are the mean spread at entry, split by whether the US and EU clocks agreed on that day. The mean spread at entry is a cost per entry and not a trading result, and I do not report profits.
Mean spread at entry for the three tester runs
Days on which the US and EU clocks agree, and days on which they disagree

Fig. 6. On days on which the clocks agree both gates lower the mean spread at entry by the same amount, and on days on which they disagree the New York gate lowers it more than the server clock gate
This comparison shows the cost of one fixed server window that was learned while the US and EU clocks agreed. The comparison does not show that the other server time approaches are worse. A server window shifted by the US rule is the New York window expressed in server time. A server window relearned every week would follow the change with a delay of its learning period. I did not test either.
The gates do not remove every wide entry. The New York gate left 91 wide entries, and none of those entries is in the hour from 17:00 to 17:59. The most frequent New York hours of those 91 attempts are 08:00 with 12, 00:00 with eight, and 14:00 with seven. I did not check what happened in those hours. The gate is a rollover gate, and it does not know about any other cause of a wide spread.
Python consistency check
The script rollover_crosscheck.py has four commands. The script uses the standard library. On Windows, zoneinfo also requires the tzdata package. The script is a second implementation of the same rules, shares no code with the MQL5 implementation, and takes its zones from the IANA database. The script uses the same server zone model as the MQL5 code. A match shows that the two implementations agree on the given data. A match does not show that the rules or the zone model describe what the broker does.
The first command, bin, reads a tick export from ExportTicks.mq5. The command bins the ticks by minute with zoneinfo and compares the result with the day-by-minute means that SpreadByMinute.mq5 wrote for the same dates. Only the dates that the export covers completely are compared.
BIN clock=server complete_dates=2026-03-10,2026-03-11 BIN cells_compared=2880 missing_in_cells=0 extra_in_cells=0 BIN mean_differences_over_1e-5=0 count_differences=0 worst_mean_difference=0.00000050
The block above is the March export on the server clock. The other three combinations of export and clock give the same result. The two March dates have 2,880 cells. The two December dates have 2,877 cells on the New York clock and 2,878 on the server clock, because a few minutes of those dates had no tick. In all four runs, no cell was missing on either side, and no tick count differed. No mean differed by more than 1e-5, the precision of the cells file, and the worst difference was 5e-7. The March export covers days on which the US and EU clocks disagree, and the December export covers days on which they agree.
The second command, profile, rebuilds the typical spread of every minute, the baseline, the runs, and the padded windows from the cells file. It compares them with the profile file and the windows file of the script, the day mask included.
PROFILE minutes_with_data=1440 baseline=2.4517 worst_median_difference=0.000050 PROFILE run start=16:33 length=87 peak=54.250 at=17:02 PROFILE windows_expected=['16:28+97 mask 63'] windows_in_file=['16:28+97 mask 63'] match=True
The spread spike section lists seven EURUSD profile runs. The same command matched six of them, the windows and their day masks included. The seventh run, the test period on the New York clock, was not checked. That run only shows whether the window moves, and it wrote no cells file for the command to rebuild from. In the later period on the server clock, the expected mask is 95, Sunday to Thursday and Saturday, and the file holds 95.
The third command, weekdays, gave the weekday table of the CSpreadProfile section. The fourth command, gate, reads a tester log. The command recomputes the answer of both gates for every attempt from the windows files and compares the result with the answer that the EA logged. The window test in Python is a short function of its own.
def inside(win, utc): local_date = utc.astimezone(win["zone"]).date() for k in (0, 1): day = local_date - dt.timedelta(days=k) if not has_day(win, day): continue start = window_start_utc(win, day) if start <= utc < start + dt.timedelta(minutes=win["length"]): return True return False
GATE attempts=3896 median_spread=3.00 wide_from=7.36 (3.0 times the learning baseline 2.452) GATE verdicts_differing_from_EA: new_york=0 server=0 GATE clocks=agree gate=new_york attempts=2554 wide=168 wide_let_through=41 blocked=188 blocked_not_wide=61 GATE clocks=agree gate=server attempts=2554 wide=168 wide_let_through=41 blocked=188 blocked_not_wide=61 GATE clocks=disagree gate=new_york attempts=1342 wide=100 wide_let_through=50 blocked=92 blocked_not_wide=42 GATE clocks=disagree gate=server attempts=1342 wide=100 wide_let_through=70 blocked=92 blocked_not_wide=62 GATE gate=new_york wide_let_through=91, of which in the New York hour 17:00 to 17:59: 0 GATE gate=new_york most frequent New York hours of the wide attempts let through: 08:00 (12), 00:00 (8), 14:00 (7), 09:00 (6), 11:00 (6) GATE gate=server wide_let_through=111, of which in the New York hour 17:00 to 17:59: 19 GATE gate=server most frequent New York hours of the wide attempts let through: 17:00 (19), 08:00 (12), 00:00 (8), 14:00 (7), 09:00 (6) GATE entry_attempts=3896 executed_entries=3896 not_executed=0 GATE executed=3896 mean_spread_at_entry=4.15 median=3.00 wide_entries=268
The verdicts match on all attempts for both gates, including the attempts that the answer clear covers. The same script also gives the counts that the results table and Fig. 5 use, so those numbers do not come from the EA's own counters. The script counts an entry as executed only when the log has an RGDEAL line for that attempt.
Using the gate in your EA
The steps are the same for each symbol that I tried. Run SpreadByMinute.mq5 on the symbol, on the New York clock, with your broker's server offset. Compare the run it prints with Fig. 2, and try two or three factors, because the CSpreadProfile section shows that the window can move with the factor. Copy the windows file next to the EA, or list it with a tester_file property for the Strategy Tester. Load the file in OnInit, print the windows, and ask the gate before every entry.
//+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { STdZone srv=TdZoneHours(InpServerStd,TD_DST_EU); string err; g_ny.Init(srv); g_srv.Init(srv); if(!g_ny.Load(InpNyFile,err)) { PrintFormat("RGDEMO cannot load %s: %s",InpNyFile,err); return(INIT_FAILED); } if(!g_srv.Load(InpServerFile,err)) { PrintFormat("RGDEMO cannot load %s: %s",InpServerFile,err); return(INIT_FAILED); } for(int i=0; i<g_ny.Count(); i++) PrintFormat("RGDEMO ny window %s",g_ny.Describe(i)); for(int i=0; i<g_srv.Count(); i++) PrintFormat("RGDEMO server window %s",g_srv.Describe(i)); g_trade.SetExpertMagicNumber(InpMagic); g_trade.SetDeviationInPoints(100); g_trade.SetTypeFillingBySymbol(_Symbol); PrintFormat("RGDEMO mode=%d attempt=%d hold=%d keep_clear=%s",(int)InpMode,InpAttemptMinutes,InpHoldMinutes, InpKeepClear ? "yes" : "no"); return(INIT_SUCCEEDED); }
The entry check in the demo is the Verdict function shown with the tester runs. An EA that does not use a planned hold time can call IsBlocked alone. In the tester runs, the EA loaded its files through tester_file properties, and the tester found them there.
The server offset is an input. A wrong offset moves every learned window by the same amount, so check it before you trust a file. The Trading Day article has a fit that finds the offset from hourly bars. A window learned on the New York clock needs no change when the broker moves its clock, because the window is a New York clock time. The window can still change with the season, as the spike measurements show, so relearn it from recent weeks and compare the result with the saved file.
Limitations
The numbers come from one server, MetaQuotes-Demo, in one terminal build. The tester runs use EURUSD only. The five other symbols appear only in profiles. I do not know how a live broker behaves, and I did not run the learner on any other broker. The conclusions of this article hold for that server, that build, and those periods.
The server zone, UTC+2 with the EU rule, is an assumption. The profiles agree with it, and the offset at one moment matches it. Neither shows the dates on which the server changes its clock.
The spread is the bid and ask difference of ticks in the history. A real order may fill at another price, and the tester ran with no execution delay. The runs measure the spread at the moment of an attempt. They do not measure slippage, requotes, rejections, profit, or drawdown. A lower mean spread at entry is a lower entry cost and says nothing about the quality of a trading system.
The result of FindSpikes depends on the factor, the minimum number of days, the merge gap, and the padding. The CSpreadProfile section shows the effect of the factor on six symbols in the learning period. I did not vary the other settings, and I did not run the factor check on other brokers.
The tester labels an attempt as wide when its spread is at least three times the baseline of the learning profile. FindSpikes uses the same factor of three. However, FindSpikes applies the factor to the typical spread of a minute, the median of daily means, while the tester applies the factor to the spread of one tick. The two uses share the number, not the statistic. A different threshold changes the tester counts.
The windows file is static. The spike measurements show that the learned window changed on this server. The window from the learning period starts at 16:28 and lasts 97 minutes. The window from the later period starts at 16:55 and lasts 70 minutes. A file therefore needs to be relearned, and the gate does not notice when its file is stale. I did not measure how fast a file loses its fit or what a stale file costs.
The profile pools the weekdays. The CSpreadProfile section shows that the runs differ by weekday, and one window per mask cannot follow that.
The tester comparison covers one fixed server window learned while the US and EU clocks agreed. A server window that is relearned often, or shifted by the US rule, was not tested. A server window shifted by the US rule is the New York window expressed in server time.
The calendar supports whole-hour offsets with no rule, the US rule, or the EU rule, as coded today. The calendar does not support the southern hemisphere, half-hour offsets, or historical rule changes. The windows file stores a zone as an offset and a rule, not as an IANA zone name.
A window is a daily clock time. A window does not know about holidays, early closes, or special sessions.
The gate only blocks entries and does not manage stop losses, pending orders, or positions already open when a window starts. A stop that is triggered inside a window still fills at the wide spread.
Windows have a resolution of one minute. A server reading in the repeated hour of a server clock with DST is read as the first instant, because a time alone cannot tell the two apart. When a broker stamps a tick in the second pass of that hour, the conversion is one hour off for that hour. The list holds 64 windows, and NextOpen gives up after 512 steps.
What the checks do not cover
The checks do not cover a change in the broker's behavior after the later period, other brokers, or other symbols in the tester. They do not cover news spikes, and the New York gate does not block those either. The New York gate let 91 wide entries through outside the rollover window, so the module is a rollover gate and not a general spread filter. The checks do not cover the execution quality of real orders, live running, or a server whose offset is not known. They do not catch a windows file with valid values that are wrong. The Python check shares the server zone with the MQL5 implementation, and so it cannot show that this zone is right.
Conclusion
CTradeWindows keeps a list of daily windows on the clocks of their zones, and it answers whether a server time is inside one, when trading may start again, and how long until the next window. CSpreadProfile finds the windows for a symbol from tick spreads. On the test server, the peak of the EURUSD run fell at 17:01 or 17:02 New York in all four periods, while the start and the length of the run changed with the season. In a forward test, a fixed server clock window learned while the US and EU clocks agreed let 19 wide attempts through in the New York rollover hour of the disagreement weeks, and the New York window let none through. Both results rest on the zone model of the server, on one server, and on one symbol in the tester.
My checks cover one server, one build, and EURUSD in the tester. If you use the module, run SpreadByMinute.mq5 on your own broker first, set the server offset, try more than one factor, and decide from your strategy whether the padding and the gate rule fit it.
Attached files
| File | Location | Contents |
|---|---|---|
| TdTypes.mqh | MQL5/Include/RolloverGate/ | Constants, enumerations, and the STdZone structure, copied unchanged from the Trading Day article |
| TdCalendar.mqh | MQL5/Include/RolloverGate/ | DST windows, offsets, and conversion between local time and UTC, copied unchanged from the Trading Day article |
| TradeWindows.mqh | MQL5/Include/RolloverGate/ | CTradeWindows, with the window structure, the verdict, and the file format |
| SpreadProfile.mqh | MQL5/Include/RolloverGate/ | CSpreadProfile and the run structure |
| RgVectors.mqh | MQL5/Include/RolloverGate/ | Window intervals from the IANA database, generated by make_vectors.py |
| SpreadByMinute.mq5 | MQL5/Scripts/RolloverGate/ | Builds a profile from ticks, finds the runs, and writes the windows file |
| ExportTicks.mq5 | MQL5/Scripts/RolloverGate/ | Writes ticks of chosen days to a CSV file for the Python check |
| TestTradeWindows.mq5 | MQL5/Scripts/RolloverGate/ | 113 checks, including the IANA vectors and the mutation test |
| WindowGateDemo.mq5 | MQL5/Experts/RolloverGate/ | Compares the two gates on the same entry attempts in the Strategy Tester |
| rollover_crosscheck.py | MQL5/Files/RolloverGate/ | Python consistency check for the bins, the profile, the weekdays, and the gate verdicts |
| make_vectors.py | MQL5/Files/RolloverGate/ | Generates RgVectors.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.