Pine time and timestamp() in MQL5: time zones and units

Short answer

Two differences cause almost all time bugs: the unit and the clock. Pine's time is milliseconds in UTC and its calendar functions use the exchange's time zone; MQL5's datetime is in seconds and server time. Session filters have no built-in MQL5 equivalent.

Time code converts with no compile errors and still fails quietly: a session filter that is three hours off, a date filter that never triggers, a weekday test that skips Mondays. Two differences cause almost all of it, the unit and the clock. This guide covers both and maps Pine's time functions to MQL5, including session filters, which have no built-in MQL5 equivalent.

Units and clocks

Pine: time is the bar's open time as a UNIX timestamp in milliseconds, always in UTC. Calendar functions such as hour, dayofweek and timestamp() work in the exchange's time zone (syminfo.timezone) unless you pass another one.

MQL5: datetime is a 64-bit count of seconds since 1970-01-01, with no time zone attached. Bar times in time[], iTime() and CopyTime() are on the broker's server clock, which is often UTC+2 in winter and UTC+3 in summer but varies by broker.

So a Pine time value equals the MT5 bar time minus the server's UTC offset, times 1000. The milliseconds also need a wide type: a current Pine timestamp is about 1.7 × 1012, far beyond the 2,147,483,647 an MQL int can hold. Use long, or double, which represents whole numbers exactly up to 253.

PineMQL5Notes
timetime[i]Seconds, server clock
time_closetime[i] + PeriodSeconds()For regular bars
timenowTimeCurrent()Time of the last server tick
hour, minuteTimeToStruct(t, dt); dt.hour, dt.minMQL5 has no TimeHour(); that is MQL4
dayofweekdt.day_of_week + 1Pine counts Sunday as 1, MQL5 as 0
timestamp(2024, 3, 1, 9, 30)D'2024.03.01 09:30'Or StructToTime / StringToTime
input.time()input datetimeEntered on the server clock
datetime barTime = time[i];                      // seconds, broker server time
MqlDateTime dt;
TimeToStruct(barTime, dt);
int pineHour = dt.hour;                          // Pine: hour (but see time zones)
int pineDow  = dt.day_of_week + 1;               // Pine: dayofweek, Sunday = 1
datetime barClose = barTime + PeriodSeconds();   // Pine: time_close, regular bars
datetime t1 = D'2024.03.01 09:30';               // Pine: timestamp(2024, 3, 1, 9, 30)
datetime t2 = StringToTime("2024.03.01 09:30");  // same value, from a string

Dates and timestamp()

timestamp(2024, 1, 1, 0, 0) means midnight in the exchange's time zone; timestamp("UTC", 2024, 1, 1, 0, 0) means midnight UTC. In MQL5, D'2024.01.01 00:00' is just a number, and when you compare it with time[i] it means midnight on the server clock. For a date filter that is usually close enough; for anything at a specific hour, it is not.

//@version=6
indicator("From date", overlay = true)
fromTime = input.time(timestamp(2024, 1, 1, 0, 0), "From")
inRange  = time >= fromTime
plot(inRange ? close : na, "Close since start date")
input datetime InpFrom = D'2024.01.01 00:00';   // midnight on the SERVER clock
// ... inside the OnCalculate loop:
bool inRange = time[i] >= InpFrom;               // both in seconds, both server time

Getting the server's UTC offset

On a live chart, the difference between TimeTradeServer() and TimeGMT() gives the current offset in seconds:

long serverOffset = (long)(TimeTradeServer() - TimeGMT());  // seconds; live chart only
long pineMs = ((long)time[i] - serverOffset) * 1000;        // Pine-style UTC milliseconds

Two limits apply. The value is the offset now; bars from before a daylight saving change had a different one. And in the Strategy Tester, TimeGMT() returns the simulated server time, so the computed offset is zero. When the offset matters, make it an input and check it once against a candle whose UTC time you know.

Session filters: time() with a session string

Pine's time(timeframe.period, "0930-1600", "America/New_York") returns na for bars outside the session, which makes it a compact session test. MQL5 has no equivalent, so you shift the bar time into the exchange's clock and compare minutes after midnight:

//@version=6
indicator("Session high", overlay = true)
inSession = not na(time(timeframe.period, "0930-1600", "America/New_York"))
var float sessHigh = na
if inSession
    sessHigh := inSession[1] ? math.max(sessHigh, high) : high
plot(inSession ? sessHigh : na, "Session high", style = plot.style_linebr)
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrGold
#property indicator_label1  "Session high"

input int InpExchangeMinusServerHours = -7; // Exchange time minus server time (hours)
input int InpSessionStart = 9 * 60 + 30;    // Session start, minutes after midnight (exchange)
input int InpSessionEnd   = 16 * 60;        // Session end, minutes after midnight (exchange)

double HighBuf[];

bool InSession(const datetime serverTime)
{
   MqlDateTime t;
   TimeToStruct(serverTime + InpExchangeMinusServerHours * 3600, t);
   const int minutes = t.hour * 60 + t.min;
   return minutes >= InpSessionStart && minutes < InpSessionEnd;
}

int OnInit()
{
   SetIndexBuffer(0, HighBuf, INDICATOR_DATA);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   return INIT_SUCCEEDED;
}

int OnCalculate(const int rates_total, const int prev_calculated,
                const datetime &time[], const double &open[],
                const double &high[], const double &low[],
                const double &close[], const long &tick_volume[],
                const long &volume[], const int &spread[])
{
   int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
     {
      const bool inNow  = InSession(time[i]);
      const bool inPrev = (i > 0) && InSession(time[i - 1]);
      if(!inNow)
         HighBuf[i] = EMPTY_VALUE;                         // gap, like plot.style_linebr
      else if(!inPrev)
         HighBuf[i] = high[i];                             // first bar of the session
      else
         HighBuf[i] = MathMax(HighBuf[i - 1], high[i]);    // running session high
     }
   return rates_total;
}

The offset input is the exchange time minus the server time. Many brokers move their server clock on the US daylight saving schedule, which keeps the difference to New York constant (minus 7 hours for a UTC+2/UTC+3 server); others follow the European schedule, and then the difference changes by an hour for a few weeks in March and in October/November. Check a session open in both seasons before trusting the filter.

What Stratlate's converter does

The Pine to MQL5 converter keeps time, time_close and timestamp() values in milliseconds as double, since a 32-bit MQL int overflows on them. time is the MT5 bar time times 1000, so it is on the broker's server clock rather than UTC. hour, dayofweek and the other calendar functions read the MT5 bar time, and a timestamp passed to them is divided by 1000 first; dayofweek is shifted to Pine's Sunday-is-1 numbering. timestamp(y, m, d, h, mi), including the "UTC" / "GMT" form, is built from its calendar parts on that same server clock, and timenow becomes TimeCurrent(). Date strings such as timestamp("01 Jan 2024 00:00 +0000") are parsed into their calendar parts the same way. timestamp() with any other time zone argument and time() with a session argument are reported as not converted; add a session test like the one above. Compile and backtest the output, and check session boundaries against TradingView.

Pitfalls

  • Milliseconds in an int. The value wraps to a meaningless number; MetaEditor warns about possible loss of data on an implicit long to int conversion, and an explicit cast silences the warning without fixing anything.
  • Seconds compared with milliseconds. A Pine-style constant compared with time[i] makes a date filter always true or always false.
  • Weekday off by one. dayofweek == dayofweek.monday is 2 in Pine and 1 in MqlDateTime; without the + 1, a Monday filter fires on Tuesdays.
  • Server time treated as exchange time. Session filters and hour-of-day rules shift by the zone difference, typically several hours.
  • Daily bars. MT5 D1 bars start at server midnight; TradingView's daily bars follow the exchange session. Daily highs, lows and closes can differ, and so does anything built on them.
  • Daylight saving. A fixed offset is wrong for a few weeks a year when the broker and the exchange change clocks on different dates.
  • Tester offset. TimeTradeServer() - TimeGMT() is zero in the Strategy Tester.

FAQ

Why is Pine's time 1000 times larger than MQL5's datetime?

Pine counts milliseconds since 1970 in UTC, and MQL5's datetime counts seconds. Divide a Pine time by 1000 to get seconds, and remember that MetaTrader bar times are on the broker's server clock, not UTC.

What is the MQL5 equivalent of hour in Pine Script?

Convert the bar time with TimeToStruct and read the hour field. MQL5 has no TimeHour function; that is MQL4. The hour you get is in broker server time, while Pine's hour is in the exchange time zone unless you pass a timezone.

How do I get the broker's offset from UTC in MQL5?

TimeTradeServer() - TimeGMT() gives the current offset in seconds on a live chart. It does not tell you the offset for past dates across a daylight saving change, and in the Strategy Tester it is zero, so use an input when the result matters.

Convert time logic without the unit bugs

Stratlate keeps Pine time values in milliseconds, maps calendar functions to MT5 bar time and reports the session filters it cannot convert. Compile and backtest the result before you trade on it.

Open the converter

Related guides