TimeCurrent and TimeToStruct in Pine Script: time, hour()
Short answer
The bar's open time is time and the current time is timenow, both in milliseconds since 1970 UTC. MqlDateTime fields become functions: dt.hour is hour(time, tz) and dt.day_of_week is dayofweek(time, tz) - 1. Get the time zone argument right.
TimeCurrent() returns the broker server's time of the last received tick, iTime() and the time[] array give bar open times, and TimeToStruct(t, dt) splits a datetime into an MqlDateTime with year, mon, day, hour, min, sec, day_of_week and day_of_year. In Pine Script the bar's open time is time, the current wall-clock time is timenow, both in milliseconds since 1970 UTC, and the struct fields are functions: dt.hour becomes hour(time, tz), dt.day_of_week becomes dayofweek(time, tz) - 1. The time zone argument is the part people get wrong.
What TimeCurrent and TimeToStruct compute
An MQL5 datetime is a count of seconds since 1970 in the broker's server clock. There is no time zone attached; a server set to GMT+2 (common for brokers that align daily bars with the New York close, moving to GMT+3 in northern summer) simply writes its local time into the number. TimeToStruct therefore returns server-clock fields. day_of_week runs 0 (Sunday) to 6 (Saturday), mon 1 to 12. TimeCurrent() is the time of the most recent quote on any symbol in Market Watch; in an indicator's history loop it is the same value for every bar, so per-bar code must use time[i]. TimeGMT() and TimeLocal() give UTC and the PC's clock.
A Pine time value is a real UTC instant in milliseconds. Calendar functions convert it to a time zone on demand: hour(t, "GMT+2"), minute(t, tz), dayofweek(t, tz), dayofmonth, month, year. Without the second argument they use syminfo.timezone, the exchange's zone of the chart's data feed. The variables hour, dayofweek and so on without parentheses are the same for the current bar in the exchange zone. timenow is the current time; time_close is the bar's close time.
The Pine Script equivalent
An indicator that draws the close only during a weekday session defined in server hours, and shows the current server time on the chart.
//@version=6
indicator("Session close", overlay = true)
startHour = input.int(9, "Session start hour")
endHour = input.int(17, "Session end hour (exclusive)")
tz = input.string("GMT+2", "Clock to use (broker server time is often GMT+2/+3)")
// time is the bar open in milliseconds UTC. hour()/dayofweek() convert it to the given
// time zone; without the second argument they use the exchange's (syminfo.timezone).
h = hour(time, tz)
dow = dayofweek(time, tz) // 1 = Sunday ... 7 = Saturday in Pine
weekday = dow >= dayofweek.monday and dow <= dayofweek.friday
inHours = h >= startHour and h < endHour
plot(weekday and inHours ? close : na, "Session close", color = color.rgb(0, 191, 255),
linewidth = 2, style = plot.style_linebr)
// TimeCurrent(): the latest known time is timenow (ms), updated on realtime ticks.
if barstate.islast
label.new(bar_index, high, "Now: " + str.format_time(timenow, "yyyy.MM.dd HH:mm:ss", tz))#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrDeepSkyBlue
#property indicator_width1 2
#property indicator_label1 "Session close"
input int InpStartHour = 9; // Session start hour (server time)
input int InpEndHour = 17; // Session end hour (server time, exclusive)
double SessBuffer[];
int OnInit()
{
SetIndexBuffer(0, SessBuffer, 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[])
{
MqlDateTime dt;
int start = (prev_calculated == 0) ? 0 : prev_calculated - 1;
for(int i = start; i < rates_total; i++)
{
TimeToStruct(time[i], dt); // bar open time, broker server clock
bool weekday = dt.day_of_week >= 1 && dt.day_of_week <= 5; // 0 = Sunday
bool inHours = dt.hour >= InpStartHour && dt.hour < InpEndHour;
SessBuffer[i] = (weekday && inHours) ? close[i] : EMPTY_VALUE;
}
// TimeCurrent() is the time of the last tick received, not of bar i.
Comment("Server time: ", TimeToString(TimeCurrent(), TIME_DATE | TIME_SECONDS));
return(rates_total);
}| MQL5 | Pine |
|---|---|
time[i], iTime(_Symbol, _Period, n) | time[n] (ms) |
TimeCurrent() | timenow for the clock, or time_close for the bar being evaluated |
TimeGMT() | timenow (already UTC) |
dt.hour, dt.min, dt.sec | hour(t, tz), minute(t, tz), second(t, tz) |
dt.day_of_week (0 = Sunday) | dayofweek(t, tz) - 1, or compare with dayofweek.monday etc. (1 = Sunday) |
dt.day, dt.mon, dt.year | dayofmonth(t, tz), month(t, tz), year(t, tz) |
StructToTime(dt) | timestamp(tz, year, month, day, hour, minute) |
TimeToString(t) | str.format_time(t, "yyyy.MM.dd HH:mm", tz) |
t + 3600 | t + 3600 * 1000 |
Where the two differ
Units. Seconds against milliseconds. Every constant duration (PeriodSeconds(), 86400) must be multiplied by 1000, and every comparison between an MQL-style value and time must convert one side.
Clock. An MQL5 session filter "9 to 17" means server hours. In Pine, hour(time) is exchange hours, which for TradingView forex feeds is usually New York or UTC depending on the source. Pass the broker's offset explicitly ("GMT+2"), and remember that a broker switching between GMT+2 and GMT+3 needs a DST-aware zone; many brokers follow New York daylight saving, so "America/New_York" with hours shifted by 7 matches them all year.
Day numbering. MQL5 day_of_week 0 is Sunday; Pine's dayofweek 1 is Sunday. Off-by-one here turns a "no Friday trading" rule into "no Saturday trading", which silently does nothing.
Current time on history. timenow on historical bars is the time the script ran, not the bar's time; use time or time_close for logic and timenow only for display or realtime checks.
What the Stratlate converter emits
The MQL5 to Pine engine keeps datetime values in seconds, as MQL5 does: TimeCurrent(), TimeLocal() and TimeGMT() become (time / 1000), iTime(…, n) becomes (time[n] / 1000), and in an EA the clock is moved to time_close / 1000 because a strategy evaluates at the bar's close. MqlDateTime is modelled as the bound timestamp: TimeToStruct(t, dt) becomes dt := t and field reads become calendar functions on dt * 1000, so dt.hour is hour(…) and dt.day_of_week is dayofweek(…) - 1 (PineCatalog TimeToStruct, PineExprRenderer). These calls use the chart's exchange time zone, not the broker's server clock, so a session filter written in server hours needs its time zone set by hand. In the program above the struct is declared before the loop and the filter came out as expected; with MqlDateTime dt; declared inside the loop body the field reads were reported as unresolved identifiers and the conditions were emitted as false, so move the declaration out of the loop before converting. TimeToString goes through the runtime helper f_format_time. Compile the output and compare it on the same bars.
Pitfalls
- Calling
hour(time)for a rule written in broker hours. Symptom: the session is shifted by the difference between the feed's exchange zone and the server clock, typically 2 to 7 hours. - Converting
TimeCurrent()inside a history loop totimenow. On every historical bar it returns the same present time, so time filters are all true or all false on history. - Forgetting the -1 on
dayofweek. Use the named constantsdayofweek.monday…dayofweek.sundayto avoid the question altogether. - Adding seconds to
time.time + 3600is 3.6 seconds later in Pine. - Building
timestamp()without a time zone. It then uses the exchange zone; give it the same zone you use forhour().
FAQ
How do I get the broker server time in Pine?
Pine has no broker. Use timenow or time and format it in the broker's zone: str.format_time(timenow, "HH:mm", "GMT+2"). If the broker follows New York daylight saving, a fixed offset is wrong for part of the year.
What is the Pine equivalent of PeriodSeconds()?
timeframe.in_seconds(), which returns seconds for the chart timeframe (or one passed as a string). Multiply by 1000 before comparing it with time.
How do I detect a new day like comparing dt.day between bars?
timeframe.change("D") is true on the first bar of each new daily session. For a day boundary in a specific time zone, compare dayofmonth(time, tz) with dayofmonth(time[1], tz).
Convert the whole program
Paste an MQL4 or MQL5 indicator or Expert Advisor and get Pine Script v6 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