Welcome Forex EA downloads & MT4/MT5 auto-trading resources — EAs, Gold EAs, quant tools and real-world automation.
Sign In Sign Up

TimeServerDaylightSavings - MetaTrader 5 Script - MT4/MT5 Resources

author EAcpu | 3 reads | 0 comments |

TimeServerDaylightSavings - script for MetaTrader 5

This script introduces the function timeServerDaylightSavingTime() which is missing from the built-in, it only provides the timeDaylightSavingTime() for the local computer. Additionally, the attached header mqh file also includes some other useful server-bound time-related functions, in particular allowing you to find out whether your broker typically uses DST switches.

All of this is based on empirical analysis of the broker's quote history. The whole idea is described in the algorithmic trading book in the section about Daylight Saving Time (Daylight Saving Time). In a nutshell, the method analyzes weekly opening hours statistics and infers the broker’s GMT offset. The two different maxima in the offset statistics, if they map to adjacent times, most likely correspond to standard ("winter") and daylight saving ("summer") time.

This script is actually a refined and expanded version of the script from the book. Specifically, releases from October 2024 include an important bug fix: the opening time for weekly trading is detected by the US market, which itself is affected by US time zone daylight saving time switches (EST, UTC-5, Standard Winter Time <--> EDT, UTC-4, daylight saving time), which is why it is important to remove the impact of US daylight saving time to get a continuous natural time flow throughout the year - this is what is done in the fix. All credit goes to Amrali .

TimeServerDaylightSavings - script for MetaTrader 5

Note that in the Northern and Southern Hemispheres, time zone adjustments are in opposite directions: in the Northern Hemisphere, "spring" (March or April) adds 1 hour and "fall" (October or November) subtracts 1 hour, while in the Southern Hemisphere it is the opposite (because all seasons are swapped).

Due to the specific nature of the analysis, it is recommended to run the symbol of the most liquid FX symbol (usually EURUSD).

This is the API:

 // Server time zone and DST current information
Structure server time zone // Analysis based on one week's opening time history {
Integer offset GMT; // Time zone offset (in seconds) of the week relative to UTC/GMT Integer offset for daylight saving time; // DST correction in seconds (contained in offsetGMT according to MQL5) Boolean value for daylight saving time support; // Detection of DST changes in quotes }; // Estimated server time zone and DST mode server time zone based on H1 quote history TimeServerZone(
const datetime servicetime = 0 , // By default, the current time, but a time in the past can be specified const integer threshold = threshold,
Constant double search year = 0.0 , // By default, all available bars, otherwise 3 years seems to be enough Constant string symbol = invalid ) // By default, the symbol of the current chart

// Estimated server time DST mode correction (in seconds)
integer time server daylight saving time ( const datetime servicetime = 0 ,
const integer threshold = threshold, const double lookup year = 0.0 , const string sign = invalid ); // Estimated server time zone offset in seconds
Integer time server GMT offset history ( const datetime servicetime = 0 ,
constant integer threshold = threshold, constant double search year = 0.0 , constant string symbol = invalid ); // Estimate whether the server has DST enabled (true/false)
boolean time server daylight saving time supported ( const datetimeservicetime = 0 ,
constant integer threshold = threshold, constant double search year = 0.0 , constant string sign = invalid ); // Simulation of the TimeGMTOffset() function of the trading server, difference in seconds
Integer time server GMTOffset(); // TimeGMT() - TimeTradeServer()

The functions TimeServerDaylightSavings() , TimeServerGMTOffsetHistory() , and TimeServerDaylightSavingsSupported() are just wrappers for TimeServerZone() , so if you need more than one trait, it's better to use the latter trait and read the value from the ServerTimeZone structure.

All these functions take the server time as the first parameter for which you want to get the corresponding feature (current or past). If the server time is left at 0 (default), results for the current moment are returned.

The second parameter threshold allows you to adjust the sensitivity of the algorithm. By default it is 52/4, which is one quarter of the statistics needed to make decisions (to detect time zones without possible interference from weeks before and after holidays). On the other hand, this setting prevents prompt detection of temporary time zone changes if your broker decides to do so at some point. You may want to set the threshold to 0 so that the algorithm detects any changes as quickly as possible.

Function TimeServerGMTOffset() does not use historical analysis, but calculates the offset directly through MQL5 functions (such as TimeGMT() - TimeTradeServer() ).

Please note that this function uses the same offset representation as the MQL5 built-in function TimeGMTOffset() function, i.e. a positive time zone (e.g. GMT+3) is represented by a negative offset (e.g. -10800) and vice versa. This notation is used by some other programming languages, such as JavaScript, but there are also other languages ​​that use positive offsets to represent positive time zones and negative offsets to represent negative time zones. Double check your algorithm.

The test script outputs all acquired data to the log, for example:

 1 ~ built-in function ~ timelocal () = 2024.10 . 05 00:39:01 / good time current () = 2024.10 . 05 00:38:59 / Good Time Trading Server () = 2024.10 . 05 00:39:01 / Good time GMT () = 2024.10 . 04 21:39:01 / ok time GMT Offset () = - 10800 / ok time DST () = 0 / ok 2 ~ addition of built-in functions ~
Time server GMTOffset()=- 10800 / OK 3 ~ Use DST to estimate server TZ based on the historical opening time of the week ~
TimeServerDaylightSavings()=- 3600 / OK [Offset GMT] [Offset DST] [Support DST]
[ 0 ] - 10800 - 3600 true

In this case, it is detected that the server is currently in DST mode, but the local computer is not.

Keep in mind that the system clocks of your local computer and server will often show slightly different times (seconds or even minutes), even if they are in the same time zone. Also note that the built-in TimeTradeServer() function returns a synthetic datetime : this is the server's time, with hourly precision, but it inherits the fraction of an hour from the local clock. This was done in MQL5 to simplify conversions between time zones - time local() , time GMT() also returned in "local format", and the trade server time.

You can enable verbose printing of data analyzed by a preprocessor directive:

 #define PRINT_DST_DETAILS

It should be placed before the code, including:

 #include "timeserverDST.mqh"

The following is an example of the details in the log:

Get 20023 H1 Bar, ~ Chapter 834 Day Weekly Opening Hours Statistics: 30 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 83 54 0 Time zone changes (UTC±X weeks before/after start):
            [Start of week] [Before] [DSTb] [After] [DSTa]
[ 0 ] 2021.07 . 25 00:00:00 - 2147483648 Error - 1 Error [ 1 ] 2021.11 . 08 00:00:00 0True0False [ 2 ] 2022.03 . 14 00:00:00 0 false 0 true [ 3 ] 2022.11 . 07 00:00:00 0True0False [ 4 ] 2023.03 . 13 00:00:00 0 false 0 true [ 5 ] 2023.11 . 06 00:00:00 0True0False [ 6 ] 2024.03 . 11 00 : 00 : 00 0 wrong 2 wrong
3 Different time zones detected in quotes, 1 Daylight Savings Candidate Server Time Offset: UTC+ 2 STD TimeServerDaylightSavings()=- 3600 / ok

Please feel free to run this script in your environment and post the resulting logs in the discussion.

2024.10.10 - Bugfix: US DST switch (interfering with business hours statistics) has been removed from the timeline before main analysis.

2024.10.27 - Added server time of interest and minimum weekly statistics threshold as arguments to all functions; timeserverGMTOffsetEmpiric() was renamed to timeserverGMToffsetHistory() .

2024.10.29 - Minor bugfix to incorporate requested time into lookup cycle.

2024.10.30 - Fixed daylight saving time in TimeZoneChange array; lookups are now performed from the srvtime parameter if specified.

2024.11.01 - Added automatic adjustment of calculations when applied to precious metals, which can provide more reliable results during periods when the US DST and EU DST schedules are out of sync.

2024.11.04 - Improve the online detection of daylight saving time switch on/off.

2024.11.07 - Added caching of time zone/DST changes for batch requests of indicator or economic event backtest history.

2024.11.08 - Optimizing cache performance through small code refactoring.

2024.11.16 - 1 hour adjustment to amrali derived timestamps from metal.

2024.11.17 - Refactors and fixes by amrali: Eliminated cache rebuild for online requests during weekends, added 48-hour lookahead to detect TZ changes during weekends (possible DST transitions), Sunday 00:00 used as time zone boundary (instead of first of the week).

2024.11.20 - Default threshold changed to 1 (a balance between timely detection of time zone changes and elimination of false positives for non-standard weeks (e.g. after holidays)); Added a new set of time formatting functions, including time zone offset and DST (see TimeZoneFmt.mqh); other minor improvements.


Attachment download

📎 prtf.mqh (1.49 KB)

📎 mqlerror.mqh (8.53 KB)

📎 datetime.mqh (2.56 KB)

📎 timeserverdst.mqh (15.66 KB)

📎 timezonefmt.mqh (3.35 KB)

📎 timezoneshistory.mq5 (4.56 KB)

Source: MQL5 #52557

Verification code Refresh