Converting request.security() multi-timeframe code
Read a higher timeframe value in MQL5 without repainting, using a timeframe-specific handle and iBarShift.
The Pine version
request.security pulls a value from another timeframe. Writing it with close[1] and lookahead_on is the common non-repainting pattern: you only ever see the completed higher-timeframe bar.
Pine Script
//@version=5
indicator("H4 EMA on lower chart", overlay=true)
h4 = request.security(syminfo.tickerid, "240", ta.ema(close, 50)[1], lookahead=barmerge.lookahead_on)
plot(h4)The MQL5 version
Create the handle with the higher timeframe (PERIOD_H4). For each chart bar, find the matching H4 bar with iBarShift, then read the bar before it to stay non-repainting, matching the [1] in Pine.
MQL5
int hH4;
int OnInit(){
SetIndexBuffer(0, Buf, INDICATOR_DATA);
ArraySetAsSeries(Buf, true);
hH4 = iMA(_Symbol, PERIOD_H4, 50, 0, MODE_EMA, PRICE_CLOSE);
return hH4 == INVALID_HANDLE ? INIT_FAILED : INIT_SUCCEEDED;
}
// inside OnCalculate, with time[] set as series:
for(int i = limit; i >= 0; i--){
int shift = iBarShift(_Symbol, PERIOD_H4, time[i]);
double v[1];
if(shift >= 0 && CopyBuffer(hH4, 0, shift + 1, 1, v) == 1) Buf[i] = v[0];
else Buf[i] = EMPTY_VALUE;
}Things to watch
The higher timeframe history must be downloaded; on the first run CopyBuffer can return -1, so return 0 and let the terminal call you again. In the Strategy Tester use "Every tick based on real ticks" or "1 minute OHLC" so the H4 data is available.