time and timestamp() in MQL5: milliseconds vs datetime
Short answer
MQL5's datetime counts seconds, not Pine's milliseconds. The bar's open time is time[i], its close is time[i] + PeriodSeconds(), and TimeToStruct and StructToTime replace hour, dayofweek and timestamp(). Everything is in the broker's server time zone.
Pine's time is the bar's open time as a UNIX timestamp in milliseconds; hour, minute, dayofweek and friends are fields of that time in the exchange's time zone, and timestamp() builds a millisecond value from calendar parts. MQL5's datetime counts seconds, the bar's open time is time[i] in OnCalculate, the fields come from TimeToStruct into an MqlDateTime, and StructToTime builds a value from parts. Everything is in the broker's server time zone.
What time and timestamp compute
time: open time of the current bar, milliseconds since 1970-01-01 UTC.time_close: the bar's close time, also in ms.hour,minute,second,dayofmonth,month,year,dayofweek,weekofyear: fields oftimein the symbol's exchange time zone. Each also has a function form,hour(t, timezone).dayofweeknumbers Sunday as 1 through Saturday as 7, with named constantsdayofweek.mondayetc.timestamp(year, month, day, hour, minute, second): a millisecond value, interpreted in the exchange time zone unless a time zone string is given first.timenow: the current wall-clock time in ms.
The MQL5 equivalent
The example flags weekday bars between 08:00 and 16:00 and bars after a configurable start date, and shows the open and close of the newest bar. Comparisons are done in seconds on both sides; the Pine millisecond value is printed only to show the factor of 1000.
//@version=6
indicator("time demo")
int startYear = input.int(2024, "Start year")
int startMonth = input.int(3, "Start month")
int startDay = input.int(15, "Start day")
int startStamp = timestamp(startYear, startMonth, startDay, 9, 30)
bool weekday = dayofweek >= dayofweek.monday and dayofweek <= dayofweek.friday
bool london = hour >= 8 and hour < 16
plot(weekday and london ? 1 : 0, "London hours", style=plot.style_histogram)
plot(time >= startStamp ? 1 : 0, "after the start date", style=plot.style_histogram, color=color.orange)
if barstate.islast
label.new(bar_index, 0, "opened " + str.format_time(time, "yyyy-MM-dd HH:mm") + " closes " + str.format_time(time_close, "HH:mm") + " time=" + str.tostring(time))#property indicator_separate_window
#property indicator_buffers 2
#property indicator_plots 2
#property indicator_type1 DRAW_HISTOGRAM
#property indicator_color1 clrDodgerBlue
#property indicator_label1 "London hours"
#property indicator_type2 DRAW_HISTOGRAM
#property indicator_color2 clrOrangeRed
#property indicator_label2 "after the start date"
input int StartYear = 2024;
input int StartMonth = 3;
input int StartDay = 15;
double SessionBuf[];
double AfterBuf[];
datetime startStamp; // Pine: timestamp(StartYear, StartMonth, StartDay, 9, 30)
int OnInit()
{
SetIndexBuffer(0, SessionBuf, INDICATOR_DATA);
SetIndexBuffer(1, AfterBuf, INDICATOR_DATA);
MqlDateTime s;
ZeroMemory(s);
s.year = StartYear; s.mon = StartMonth; s.day = StartDay; s.hour = 9; s.min = 30;
startStamp = StructToTime(s); // seconds, server time zone
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++)
{
// Pine: hour, minute, dayofweek read from `time`; MQL5 reads them
// off the bar's open time with TimeToStruct
MqlDateTime t;
TimeToStruct(time[i], t);
int pineDow = t.day_of_week + 1; // Pine: Sunday = 1, MQL5: Sunday = 0
bool weekday = pineDow >= 2 && pineDow <= 6;
bool london = t.hour >= 8 && t.hour < 16;
SessionBuf[i] = (weekday && london) ? 1.0 : 0.0;
// Pine: time >= timestamp(...) -- both sides in seconds here;
// Pine's time is in milliseconds, so compare like with like
datetime barClose = time[i] + PeriodSeconds(); // Pine: time_close
AfterBuf[i] = (time[i] >= startStamp) ? 1.0 : 0.0;
if(i == rates_total - 1)
Comment("bar opened ", TimeToString(time[i], TIME_DATE | TIME_MINUTES),
" closes ", TimeToString(barClose, TIME_MINUTES),
" Pine time = ", (long)time[i] * 1000, " ms");
}
return rates_total;
}
void OnDeinit(const int reason) { Comment(""); }TimeCurrent() is the server time of the last tick (Pine's timenow in seconds), TimeGMT() the UTC wall clock and TimeTradeServer() the estimated current server time even without ticks.
Where the two differ
| Aspect | Pine | MQL5 |
|---|---|---|
| Unit | milliseconds (int, 64-bit) | seconds (datetime, 64-bit) |
| Time zone of the fields | exchange time zone (syminfo.timezone) | broker server time zone |
| Day of week | Sunday = 1 … Saturday = 7 | day_of_week: Sunday = 0 … Saturday = 6 |
| Bar close time | time_close | time[i] + PeriodSeconds() |
| Build from parts | timestamp(y, mo, d, h, mi) | MqlDateTime + StructToTime, or StringToTime("2024.03.15 09:30") |
| Extract parts | hour, minute, … | TimeToStruct(t, s) then s.hour, s.min, … |
| Time zone argument | hour(time, "UTC") | none; shift by the server offset yourself |
| Session filters | time(timeframe.period, "0930-1600") | compare hour/minute fields by hand |
What the Stratlate converter emits
The engine keeps Pine's millisecond domain: time becomes ((double)(time[bar]) * 1000.0), time_close adds PeriodSeconds() before scaling, and numeric timestamp(...) becomes pine_timestamp_dt(...) * 1000.0, read in server time. hour, minute, dayofweek and the other fields read time[bar] through MQL4-style helpers built on TimeToStruct, with dayofweek shifted by one to Pine's numbering; a supplied Pine timestamp is divided by 1000 first. These are exact apart from the time zone. Two gaps in the current version: the constants dayofweek.monday … dayofweek.sunday are reported as undeclared identifiers (the conversion of this page's script came out PARTIAL for that reason; write the numbers 2 to 6 instead), and str.format_time is reported as an approximation because its layout is dropped, so check any formatted date text in the output.
Pitfalls
- Mixing units: comparing
time[i](seconds) with a Pine-style constant in milliseconds. Symptom: a date condition that is never true, or always true. - Forgetting the Sunday offset:
day_of_week == 1is Monday in MQL5 and Sunday in Pine. - Assuming exchange hours: a session filter written for New York in Pine needs shifting by the difference between the broker's server time and New York, which changes twice a year with daylight saving on either side.
- Storing ms in a 32-bit
int: 1.7e12 overflows. Uselongordouble. - Using the removed MQL4 functions
TimeHour(),TimeDayOfWeek(): they do not exist in MQL5. Symptom: "undeclared identifier" in MetaEditor.
FAQ
Is MQL5 datetime in seconds or milliseconds?
Seconds since 1970-01-01. Pine's time values are milliseconds, so divide a Pine timestamp by 1000 before casting it to datetime and multiply a datetime by 1000 when a Pine-style value is needed.
How do I get the hour of a bar in MQL5?
Call TimeToStruct(time[i], s) with an MqlDateTime s and read s.hour. The hour is in the broker's server time, which is often GMT+2 or GMT+3, not the exchange time Pine uses.
What replaces timestamp(2024, 3, 15, 9, 30) in MQL5?
Fill an MqlDateTime with year, mon, day, hour and min, call StructToTime, and you get a datetime in seconds interpreted as server time. StringToTime("2024.03.15 09:30") does the same from text.
Convert the whole script
Paste a Pine Script indicator or strategy and get MQL5 with this and every other call mapped, checked against the original on the same bars, and every construct that could not be carried over reported.
Open the converter