Local Time Zone and Local Session Time - MetaTrader 5 Library | MT5 EA Download - MetaTrader 5 Resources








Hello traders.
This library has all the functionality to get the current local time for a specific or all Forex markets. You can convert local time between time zones to your broker's server time. You can also place trades within a specific session by setting the session start and end time for each session individually. The library will handle the different time offsets and daylight saving time changes of brokers and these markets. This relieves you of the burden of reinventing the wheel every time you write an Expert Advisor or technical indicator that has to deal with time zones and local session times.
A time zone is defined as a standard time based on the geographic representation of that location. In other words, a time zone refers to the local time in a specific region based on the Earth's rotation. It is defined in UTC (Coordinated Universal Time), the standard for coordinating time in various regions of the world.
For example - New York time is 5 hours behind Greenwich Mean Time, expressed as UTC-5 or UTC-4 depending on daylight. Sydney time is 10 hours ahead of Greenwich Mean Time and is expressed as UTC+10 or UTC+11 depending on daylight (summer or winter). The terms UTC and GMT are often used interchangeably to refer to offsets, so UTC+2 and often GMT+2 have the same meaning.
If the time zone is east of GMT, the UTC offset is positive; if the time zone is west of GMT, the UTC offset is negative.
//+------------------------------------------------------------------+ //|Time zone identifier | //+------------------------------------------------------------------+ Enum ENUM_ZONE_ID { ZONE_ID_SYDNEY, // Sydney ZONE_ID_TOKYO, // Tokyo ZONE_ID_FRANKFURT, // Frankfurt ZONE_ID_LONDON, // London ZONE_ID_NEWYORK, // New York ZONE_ID_UTC, // UTC ZONE_ID_LOCAL, // Local ZONE_ID_BROKER, // Broker ZONE_ID_CUSTOM // Custom };
//+------------------------------------------------------------------+ //| CTimeZoneInfo class. | //|Purpose: Class obtains the specified local time| | //| Location and time zone information, time | //| Changes for the current year. | //| | //|Offset notation used in the library: | //| Please note that the library indicates positive time | //| Positive offset zone and negative time zone | //| By negative offset. | //| In contrast, MQL5's built-in TimeGMTOffset() | //| function represents positive time zone, such as GMT+3, | //| Negative offset, such as -10800, or vice versa. | //+------------------------------------------------------------------+ Class C Time Zone Information { Public : CTimeZoneInfo( ENUM_ZONE_ID placeId, date time pLocalTime = TIME_NOW ); ~CTimeZoneInfo( blank ); string name ( blank ); // Return time zone name string to string ( boolean seconds = true , boolean zname = true ); // Return local time string boolean formatted with TZ/DST offset and tzname refresh time ( blank ); // Refresh the current local time and fill in the time zone information boolean set local time ( datetime pLocalTime = TIME_NOW); // Sets the local time at this location to the specified time date time local ( blank ); // Returns the local time date time in the time zone UTC ( blank ); // Returns the UTC time (same for all time zones) as an integer time GMT offset ( blank ); // Positive for a positive time zone (e.g., GMT+3), negative otherwise. (includes daylight saving time) integer time daylight saving time ( blank ); // Returns the DST correction (in seconds) for the set local time time zone. Date and time ConvertLocalTime( ENUM_ZONE_ID Destination Id ); // Convert the local time of this time zone to the local time of other time zones Boolean value Get the daylight switching time ( date time &dst_start, date time &dst_end); // Get the start and end time date and time of daylight saving time of the current year Get the daylight next switch ( blank ); // Get the local time of the next daylight saving time switch blank Print object ( blank ); //--- Static methods that do not require object creation. Stationary Date Time GetCurrentTimeForPlace ( ENUM_ZONE_ID LocationId ); // Get the current local time in the specified time zone Stationary String Place Format Time ( DateTimeTime , ENUM_ZONE_ID LocationId, Boolean Seconds = True , Boolean Name = True ); Stationary date and time convert time to location ( date time and time, ENUM_ZONE_ID location Id, ENUM_ZONE_ID destination Id); Stationary integer time GMT offset (ENUM_ZONE_ID location ID, date time time = TIME_NOW); // returnThe total tz offset (UTC+DST) of the time zone relative to GMT for the given local time is the integer time daylight saving time at rest (ENUM_ZONE_ID place ID, date time time = TIME_NOW); // Returns the daylight saving time correction (in seconds) for the time zone given local time at rest Boolean IsDaylightSavingTime (ENUM_ZONE_ID placeId, date time time = TIME_NOW); // Check whether the specified time belongs to daylight saving time . The Boolean value of the stationary GetDaylightSwitchTimes (ENUM_ZONE_ID placeId, integer my year, datetime &dst_start, datetime &dst_end); the stationary Boolean value of GetDaylightSwitchDeltas(ENUM_ZONE_ID placeId, integer my year, integer &delta_start, integer &delta_end); static boolean set custom time zone ( thin name, integer baseGMT offset = 0 , // Defines a time zone not found in the library. ENUM_ZONE_ID dstSchedule = ZONE_ID_UTC); static boolean set custom time zone using GoldSymbol ( boolean enable= True ); // Set option to use golden symbols to estimate server TZ/DST };
//+------------------------------------------------------------------+ //| CSessionHours class. | //|Purpose: Class to access local trading hours| //| Specify the location. | //| Derived from class CTimeZoneInfo. | //|Note: The default session time is set to 8:00 AM to 5:00 PM | //| The local time of the new CSessionHours object. | //+------------------------------------------------------------------+ class CSessionHours: public C time zone information { public : CSessionHours( ENUM_ZONE_ID placeId ); ~CSessionHours( blank ); //--- Method to access local session time Boolean value refresh time ( blank ); // Refresh the current local time and the current day's session time Boolean value Set local time ( date time p local time); //--- Methods to override the default local session time boolean start local time( integer hours , integer p minutes); // Set the local session start time using start hours and minutes boolean end local time( integer hours , integer p minutes); // Set the local session end time using end hours and minutes //--- Methods to access the local session time datetime start localtime( blank ); datetime end local time( blank ); boolean Check local session ( blank ); // Check if the local trading session is currently active. integer seconds remaining session ( blank ); // The remaining time (in seconds) until the local session is closed for the day. //--- Static methods that do not require object creation. Still date and time Foreign exchange closing time ( blank ); // Broker time when the foreign exchange market is closed this week. static integer Number of Forex seconds remaining ( blank ); // Time remaining in seconds for the Forex market closing this week. };
Note that the library says time zone Positive offset, negative time zone and negative offset.
This is contrary to MQL5's built-in TimeGMTOffset() function, which represents a positive time zone (eg GMT+3) with a negative offset (eg -10800) and vice versa.
By default, the library will search for and load the XAUUSD symbol to estimate the server's time zone offset. During periods when the US DST and EU DST schedules are out of sync (March and late October), XAUUSD can provide more reliable results (especially for brokers following the EU DST schedule). Alternatively, if your broker follows the US DST schedule, or has no schedule at all, then using chart symbols will work too. Call CTimeZoneInfo::SetUsingGoldSymbol() with "false" to use the current chart's symbol instead of XAUUSD.
To determine a broker's Daylight Saving Time (DST) schedule, you can use this script https://www.mql5.com/en/code/48650
//+------------------------------------------------------------------+ //|Set the option to use the XAUUSD (gold) symbol to estimate | //|Determine the server's TZ/DST by analyzing H1 quote history. | //| TRUE: Search and load gold symbols (default behavior). | //| FALSE: Use the symbol of the current chart. | //+------------------------------------------------------------------+ void CTimeZoneInfo::SetUsingGoldSymbol( const boolean enabled= true );
notes :
As a side effect of XAUUSD starting one hour after Forex trading, the daylight saving time switch will happen an hour later (only in the strategy tester, not in normal mode).
During testing in the strategy tester, timeGMT() always equal to time trading server() Simulate server time.
The TimeZoneInfo library estimates the correct time for a time zone based on "real" GMT by analyzing H1 quote history, rather than based on the time returned by calling the built-in TimeGMT function.
If the XAUUSD symbol is used to estimate the TZ/DST of the server, the dst switch will occur after one hour in the strategy tester.
this refreshtime() Method will update the time zone for the current local time. Let's look at an example to show how to get the current time.
Print ( "\n========== Get the current time in the time zone ===========" ); CTimeZoneInfo tz(ZONE_ID_TOKYO); tz.RefreshTime(); // Fill in the current time zone information and print ( "Name(): " , tz.Name()); print ( "TimeLocal():" , here.TimeLocal ()); print ( "ToString():" , tz.ToString());
Output :
// ========== Get the current time in the time zone ========== // Name() : Tokyo // TimeLocal() : 2024.02.28 19:58:50 // ToString() : Wednesday, February 28, 2024 19:58:50 GMT+9 [Tokyo]
Do you need more information?
print ("\n========== More information about time zones==========="); CTimeZoneInfo tz(ZONE_ID_NEWYORK); tz.RefreshTime(); Print ("Name() : ", tz.Name()); print ("TimeUTC() : ", tz.TimeUTC()); print (" timelocal ():", hereby.timelocal ()); print (" TimeGMTOffset ():", hereby. TimeGMTOffset ()); print (" TimeDaylight Saving Time (): ", here. Time Daylight Saving Time ()); Print ("ToString() : ", tz.ToString()); Date and time target start, target end; tz.GetDaylightSwitchTimes(dst_start, dst_end); print ("dst_start : ", dst_start); print ("dst_end : ", dst_end); Print ("GetDaylightNextSwitch() : ", tz.GetDaylightNextSwitch());
Output:
// ========== More information about time zones ========== // Name() : New York // TimeUTC() : 2024.03.17 16:50:38 // TimeLocal() : 2024.03.17 12:50:38 // TimeGMTOffset() : -14400 // TimeDaylightSavings() : 3600 // ToString() : Sunday, 17 March 2024 12:50:38 GMT-4 [New York] (Daylight Savings Time) // dst_start : 2024.03.10 02:00:00 // dst_end : 2024.11.03 02:00:00 // Get DaylightNextSwitch() : 2024.11.03 02:00:00
notes:
- The time UTC() method returns UTC time, which is equivalent to GMT time.
- The timelocal() method returns the local time for that time zone (which may change by calling the refreshtime or setlocaltime methods).
- The timeGMTOffset() method returns the current difference (in seconds) between local time and GMT time for this time zone, taking into account switches to winter or summer time. The offset returned includes the DST adjustment for the current time zone. If the time zone is east of (earlier than) GMT, the GMT offset is positive; if the time zone is west of (later than) GMT, the GMT offset is negative.
-timeDaylightSaving() method returns the daylight saving time (DST) adjustment in seconds if the area has switched to daylight saving time in a region where DST is in effect. Returns 0 if the time zone has been switched to winter (standard) time (or if the time zone does not support DST). The dst adjustment is already part of TimeGMTOffset.
The CTimeZoneInfo class includes the Set Custom Time Zone method, which you can use to configure the built-in custom time zone. Later, a custom time zone can be used via the ZONE_ID_CUSTOM identifier. Let's look at an example that shows how to configure a built-in custom time zone to specify a name, an offset from Greenwich Mean Time (GMT), and a daylight saving time identifier.
Print ( "\n========== Configure built-in custom time zone ==========" ); string name = "custom+3" ; // Custom time zone name integer Base GMT offset = 10800 ; // Custom time zone's base GMT offset in seconds ENUM_ZONE_ID daylightRuleId = ZONE_ID_LONDON; // Custom time zone's DST schedule boolean success = CTimeZoneInfo::SetCustomTimeZone(name, baseGMTOffset, daylightRuleId); print ( "Parameter 'name':" , name); print ( "Parameter 'baseGMTOffset':" , base GMT offset); Print ( "Parameter 'daylightRuleId':" , enumeration to string (daylight rule ID)); print ( "SetCustomTimeZone() returned: " , success);
Output:
// ========== Configure built-in custom time zone ========== // Parameter 'name' : Custom+3 // Parameter "baseGMTOffset": 10800 // Parameter "daylightRuleId": ZONE_ID_LONDON // SetCustomTimeZone() returns: true
Let's see an example to show how to get the current local time for all time zones.
Print ( "\n========== Get the current time in all time zones ===========" ); for (ENUM_ZONE_ID ID= 0 ; id <= MAX_ZONE_ID; id++) { CTimeZoneInfo tz(id); tz.RefreshTime(); Print format ( "%-12s: %s | %s" , tz.Name(), string time (tz. time local ()), tz.ToString()); }
Output:
// ========== Get the current time for all time zones ========== // Sydney : 2024.02.28 21:58 | Wednesday, February 28, 2024 21:58:50 GMT+11 [Sydney] (Daylight Saving Time) // Tokyo : 2024.02.28 19:58 | Wednesday, February 28, 2024 19:58:50 GMT+9 [Tokyo] // Frankfurt : 2024.02.28 11:58 | Wednesday, February 28, 2024 11:58:50 GMT+1 [Frankfurt] // London : 2024.02.28 10:58 | Wednesday, February 28, 2024 10:58:50 GMT+0 [London] // New York : 2024.02.28 05:58 | Wednesday, February 28, 2024 05:58:50 GMT-5 [New York] // UTC : 2024.02.28 10:58 | Wednesday, February 28, 2024 10:58:50 GMT+0 [UTC] // Home : 2024.02.28 12:58 | Wednesday, February 28, 2024 12:58:50 GMT+2 [Home] // FXOpen-MT5 : 2024.02.28 12:58 | Wednesday, February 28, 2024 12:58:50 GMT+2 [FXOpen-MT5]
This can be done in other ways using the static method GetCurrentPlaceTime () . Also, please note that there is another static method formattimeaslocation () that can be used to format pure mql datetime variables into strings (Similar to string time ) but contains the weekday, date, time, time zone name, and offset. These static methods do not require object creation to call them.
print ( "\n========== GetCurrentTimeForPlace() ============" ); for (ENUM_ZONE_ID ID = 0 ; id <= MAX_ZONE_ID; id++) { DateTimeTime = CTimeZoneInfo::GetCurrentTimeForPlace(id); Print format ( "Time: %s | %s" , string time (time), CTimeZoneInfo::FormatTimeForPlace(time, id)); }
Output :
// ========== GetCurrentTimeForPlace() ========== // Time: 2024.02.28 21:58 | Wednesday, February 28, 2024 21:58:50 GMT+11 [Sydney] (Daylight Saving Time) // Time: 2024.02.28 19:58 | February 28, 2024 Wednesday 2024.02.28 19:58:50 GMT+9 [Tokyo] // Time: 2024.02.28 11:58 | Wednesday 28 February 2024 11:58:50 GMT+1 [Frankfurt] // Time: 2024.02.28 10:58 | Wednesday 28 February 2024 10:58:50 GMT+0 [London] // Time : 2024.02.28 05:58 | Wednesday, February 28, 2024 05:58:50 GMT-5 [New York] // Time : 2024.02.28 10:58 | Wednesday, February 28, 2024 10:58:50 GMT+0 [UTC] // Time : 2024.02.28 12:58 | Wednesday, February 28, 2024 12:58:50 GMT+2 [Home] // Time: 2024.02.28 12:58 | Wednesday, February 28, 2024 12:58:50 GMT+2 [FXOpen-MT5]
this set local time() method will set Specify local time . Let's look at an example to show how to set the local time for a time zone.
Print ( "\n========== Set the local time of the time zone ===========" ); CTimeZoneInfo tz(ZONE_ID_NEWYORK); if (tz.set local time ( D'2021.07.15 09:31' )) Print format ( "%-12s: %s | %s" , tz.Name(), string time (tz. time local ()), tz.ToString()); if (tz.set local time ( D'2022.01.23 17:04' )) Print format ( "%-12s: %s | %s" , tz.Name(), string time (tz. time local ()), tz.ToString()); if (tz.set local time ( D'2023.03.12 02:21' )) Print format ( "%-12s: %s | %s" , tz.Name(), string time (tz. time local ()), tz.ToString());