request.security and Multi-Timeframe Logic in MQL5
Short answer
request.security hides three decisions that MQL5 makes you write out: which higher-timeframe bar each chart bar sees, whether that bar may still be forming, and how the indicator's history is built. Which value Pine returns depends on lookahead.
Multi-timeframe scripts are among the most common Pine scripts and the most often mis-converted. request.security hides three decisions (which higher-timeframe bar each chart bar sees, whether that bar may still be forming, and how the indicator's history is built) that MQL5 makes you write out. This guide shows each one for developers converting MTF indicators and strategies.
What request.security returns on each bar
For every bar of your chart, Pine evaluates the expression on the requested timeframe and hands back one value. Which value depends on lookahead:
- Default,
barmerge.lookahead_off: on historical bars, the higher-timeframe value only appears once that higher-timeframe bar has closed. On the realtime bar, the still-forming value is returned and changes until the bar closes, which is the classic repaint. expr[1]withbarmerge.lookahead_on: the last completed higher-timeframe bar, on historical and realtime bars alike. This is the form TradingView documents for non-repainting output, and the easiest to reproduce exactly.exprwithlookahead_on(no[1]): the higher-timeframe bar that contains the chart bar, including its final close, on history. That leaks future data into a backtest.
//@version=6
indicator("HTF EMA, no repaint", overlay = true)
len = input.int(20, "EMA length")
tf = input.timeframe("D", "Higher timeframe")
htfEma = request.security(syminfo.tickerid, tf, ta.ema(close, len)[1], lookahead = barmerge.lookahead_on)
plot(htfEma, "HTF EMA", color.orange)The MQL5 version: one higher-timeframe bar per chart bar
MQL5 indicators compute their whole history in OnCalculate, so for each chart bar you need the index of its higher-timeframe bar. iBarShift(symbol, tf, time[i]) returns the bar containing that time (the forming one, from that bar's point of view); adding 1 gives the last completed one, which is exactly expr[1] with lookahead on. Recursive indicators such as an EMA need the higher timeframe's own full history, so instead of recomputing them you create the indicator on that timeframe with a handle:
#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots 1
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrOrange
#property indicator_label1 "HTF EMA"
input int InpLen = 20; // EMA length
input ENUM_TIMEFRAMES InpTf = PERIOD_D1; // Higher timeframe
double Buf[];
int hEma = INVALID_HANDLE;
int OnInit()
{
if(PeriodSeconds(InpTf) <= PeriodSeconds(_Period))
return INIT_PARAMETERS_INCORRECT;
SetIndexBuffer(0, Buf, INDICATOR_DATA);
PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
hEma = iMA(_Symbol, InpTf, InpLen, 0, MODE_EMA, PRICE_CLOSE);
return hEma == INVALID_HANDLE ? INIT_FAILED : 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[])
{
// the higher-timeframe series may still be loading: try again next tick
if(BarsCalculated(hEma) <= 0)
return 0;
const int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
for(int i = start; i < rates_total; i++) // time[] is oldest-first here
{
Buf[i] = EMPTY_VALUE;
const int htf = iBarShift(_Symbol, InpTf, time[i], false);
if(htf < 0)
continue;
double v[1];
// htf = the higher-timeframe bar containing this bar (still forming);
// htf + 1 = the last COMPLETED one: no repainting
if(CopyBuffer(hEma, 0, htf + 1, 1, v) == 1)
Buf[i] = v[0];
}
return rates_total;
}Notes on the code: time[] in OnCalculate is indexed oldest-first unless you call ArraySetAsSeries, while iBarShift and CopyBuffer count shifts from the newest bar. Returning 0 while BarsCalculated is not ready makes the terminal call again with prev_calculated = 0, so the full history is rebuilt once the higher timeframe has loaded. For long histories, copying the whole higher-timeframe buffer once and indexing it is faster than one CopyBuffer per chart bar.
Timeframe strings
Pine timeframes are strings; MT5 has a fixed ENUM_TIMEFRAMES list.
| Pine Script v6 | MQL5 | Notes |
|---|---|---|
"1", "5", "15", "30" | PERIOD_M1 … PERIOD_M30 | Minutes. MT5 also has M2–M6, M10, M12, M20. |
"60", "240" | PERIOD_H1, PERIOD_H4 | H2, H3, H6, H8 and H12 exist too. |
"D", "W", "M" | PERIOD_D1, PERIOD_W1, PERIOD_MN1 | Also spelled "1D", "1W", "1M". |
"45", "3D", "2W" | none | Not an MT5 timeframe: build those bars yourself from a lower timeframe. |
input.timeframe("D") | input ENUM_TIMEFRAMES InpTf = PERIOD_D1; | The user picks from MT5's list. |
Prices, tuples and other symbols
A bare price needs no handle: iClose, iHigh, iLow, iOpen and iTime return a value directly in MQL5. A tuple request becomes several reads at the same index:
[pdh, pdl] = request.security(syminfo.tickerid, "D", [high[1], low[1]], lookahead = barmerge.lookahead_on)const int d = iBarShift(_Symbol, PERIOD_D1, time[i], false); // once per chart bar
const double pdh = (d < 0) ? EMPTY_VALUE : iHigh(_Symbol, PERIOD_D1, d + 1);
const double pdl = (d < 0) ? EMPTY_VALUE : iLow(_Symbol, PERIOD_D1, d + 1);For another symbol, the name is the broker's, not TradingView's (OANDA:XAUUSD may be XAUUSD, GOLD or XAUUSD.m), and it must be selected so its history is available:
// Pine: request.security("OANDA:XAUUSD", "60", close[1], lookahead = barmerge.lookahead_on)
// OnInit: make sure the broker's symbol (name may differ: "XAUUSD", "GOLD", "XAUUSD.m")
// is in Market Watch so its history is available
SymbolSelect("XAUUSD", true);
// OnCalculate, for chart bar i (arrays oldest-first):
const int g = iBarShift("XAUUSD", PERIOD_H1, time[i], false);
const double goldPrevClose = (g < 0) ? EMPTY_VALUE : iClose("XAUUSD", PERIOD_H1, g + 1);request.security_lower_tf, which returns an array of lower-timeframe values per bar, has no one-call equivalent; it is a loop over CopyRates for the chart bar's time range.
What Stratlate does with request.security
Stratlate aligns every higher-timeframe read to each chart bar with iBarShift on that bar's time. For the default lookahead_off, and for expr[1] with lookahead on, it reads the last completed higher-timeframe bar, so the result does not repaint. Prices are read with the i* series functions, ta.sma and ta.wma of a price are rebuilt from that window of higher-timeframe bars, native indicators such as ta.ema or ta.rsi get a handle created in OnInit, and a value the script computes itself is read by running the indicator on the other timeframe or symbol. Every higher-timeframe read is reported as an approximation because of the session-boundary difference described below; a lookahead_on read gets an extra note that the original also repaints on the realtime bar, and request.security_lower_tf is reported as not converted. Compile and backtest the result before relying on it.
Pitfalls
- Using shift 0 or 1 without iBarShift.
iClose(_Symbol, PERIOD_D1, 1)is yesterday as of now, so the same value is drawn across all of history. Symptom: a flat line. - Forgetting the +1. Reading the containing bar gives the day's final close to every intraday bar of that day. Symptom: a backtest that looks too good.
- Session boundaries. TradingView cuts daily bars at its feed's session; your broker cuts them at server midnight and may add Sunday bars. Symptom: daily values that differ near the open.
- EMA warm-up. The MT5 handle and Pine start their EMA at different points of history, so early values differ and converge later. Compare only after a few times the length.
- History not loaded. In the first call after attaching,
iBarShiftcan return -1 andCopyBufferfail. Symptom: gaps that disappear on refresh. Handle it and recalculate. - Timeframe lower than the chart. The alignment above assumes a higher timeframe; the example refuses anything else in
OnInit.
FAQ
What is the MQL5 equivalent of request.security?
There is no single function. For prices use iClose, iHigh and the other series functions on the other timeframe or symbol; for indicators create a handle with that timeframe, such as iMA or iRSI, and read it with CopyBuffer. In an indicator, map each chart bar to its higher-timeframe bar with iBarShift.
How do I avoid repainting when converting request.security?
Read the last completed higher-timeframe bar: in Pine, an expression with [1] and lookahead set to barmerge.lookahead_on; in MQL5, the iBarShift result plus one. That value never changes once the chart bar has closed.
Why are my daily values different from TradingView on some bars?
Daily and weekly bars are cut at different times. TradingView follows the exchange session of its data feed, MetaTrader the broker's server day. Some brokers also produce short Sunday bars. Compare your broker's D1 bars with TradingView's before suspecting the code.
Convert your multi-timeframe script
Paste a Pine indicator or strategy that uses request.security and get MQL5 that aligns each higher-timeframe read to its own chart bar.
Open the converter