input.timeframe in MQL5: ENUM_TIMEFRAMES and PERIOD_CURRENT

Short answer

Use an input of type ENUM_TIMEFRAMES, which MetaTrader shows as a drop-down of its 21 standard timeframes plus current. Pine's empty string, the chart's timeframe, is PERIOD_CURRENT, and the value goes straight into iClose, iBarShift, CopyRates or an indicator handle.

input.timeframe() gives the user a timeframe picker, almost always to feed request.security(). MQL5's counterpart is an input of type ENUM_TIMEFRAMES: MetaTrader shows a drop-down of its 21 standard timeframes plus "current", and the value goes straight into iClose, iBarShift, CopyRates or an indicator handle such as iMA(_Symbol, InpTf, ...). Pine's empty string, which means "the chart's timeframe", is PERIOD_CURRENT.

What input.timeframe() computes

input.timeframe(defval, title, options, tooltip, inline, group, confirm, display, active) returns an input string in Pine's timeframe notation: "1" to "1440" are minutes, "60" is one hour, "240" four hours, "D" or "1D" a day, "W" a week, "M" a month, and multiples such as "3D", "2W" or seconds like "30S" are allowed. The empty string "" stands for the chart's own timeframe, and request.security treats it that way. Because the value is a string, scripts also pass it to timeframe.in_seconds() or compare it with timeframe.period. options restricts the picker to a list.

The MQL5 equivalent

The Pine version reads the previous completed close of a user-chosen timeframe, using the close[1] plus lookahead_on form that does not repaint.

//@version=6
indicator("TF demo", overlay=true)
tf = input.timeframe("", "Timeframe")
prevClose = request.security(syminfo.tickerid, tf, close[1], lookahead=barmerge.lookahead_on)
plot(prevClose, "Prev HTF close", linewidth=2)

In MQL5 the input is an ENUM_TIMEFRAMES. iBarShift finds the higher-timeframe bar that contains each chart bar and shift + 1 is the last completed one, the same value Pine's close[1] with lookahead gives. OnInit refuses a timeframe below the chart's, because one chart bar would then contain several bars of the requested timeframe and "the bar containing this bar" no longer exists.

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_label1  "Prev HTF close"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue
#property indicator_width1  2

// input.timeframe("") -> PERIOD_CURRENT, which means "the chart's timeframe"
input ENUM_TIMEFRAMES InpTf = PERIOD_CURRENT;   // Timeframe

double BufHtf[];

int OnInit()
{
   if(PeriodSeconds(InpTf) < PeriodSeconds(_Period))
     {
      Print("Pick a timeframe at or above the chart's");
      return INIT_PARAMETERS_INCORRECT;
     }
   SetIndexBuffer(0, BufHtf, 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[])
{
   ENUM_TIMEFRAMES tf = InpTf == PERIOD_CURRENT ? _Period : InpTf;
   int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
     {
      int shift = iBarShift(_Symbol, tf, time[i]);   // the HTF bar containing this bar
      // close[1] with lookahead_on: the last COMPLETED higher-timeframe bar
      double c = shift < 0 ? 0.0 : iClose(_Symbol, tf, shift + 1);
      BufHtf[i] = c > 0.0 ? c : EMPTY_VALUE;          // 0 means that history is not loaded yet
     }
   return rates_total;
}
Pine stringENUM_TIMEFRAMES
"" (chart)PERIOD_CURRENT (resolve with _Period when you need the real value)
"1", "5", "15", "30"PERIOD_M1, PERIOD_M5, PERIOD_M15, PERIOD_M30
"60", "240", "720"PERIOD_H1, PERIOD_H4, PERIOD_H12
"D", "W", "M"PERIOD_D1, PERIOD_W1, PERIOD_MN1
"45", "3D", "2W", "30S"none: MetaTrader has no custom multiples and no seconds timeframes

Where the two differ

TopicPine ScriptMQL5
TypeString in timeframe notationEnum; PeriodSeconds(tf) gives its length
Chart timeframe""PERIOD_CURRENT, which is 0; compare against _Period only after resolving it
Available valuesAny number of minutes, days, weeks, months, seconds21 fixed timeframes from M1 to MN1
Lower timeframe than the chartAllowed with request.security_lower_tfReadable with CopyRates, but you aggregate yourself
Session alignmentExchange sessionBroker server day; daily bars can open at a different hour
HistoryFetched with the chartLoaded on demand; iClose can return 0 until it is, so check and retry

What the Stratlate converter emits

The converter keeps the Pine notation: input.timeframe("", ...) becomes input string tf = ""; and every use is resolved at run time by the runtime helper pine_tf_period(tf), which maps "" and "0" to PERIOD_CURRENT, "D"/"1D", "W" and "M" to D1, W1 and MN1, and the minute counts MetaTrader has (1 to 30, 60, 120, 180, 240, 360, 480, 720) to their periods. Any other string, such as "45" or "3D", falls back to PERIOD_CURRENT without a message, so type the timeframe in Pine notation and stick to the values MetaTrader supports. The request.security read it feeds is reported as an approximation (PM292) because TradingView aligns higher-timeframe bars to the exchange session and MetaTrader to the broker's server day; the example above converts as APPROXIMATED for that reason. Compile it and compare a few bars at session boundaries.

Pitfalls

  • Comparing InpTf with _Period while it is still PERIOD_CURRENT. The test is false on every chart; resolve the input first as the example does.
  • Reading iClose(_Symbol, tf, shift) instead of shift + 1. On history that is the higher-timeframe bar's final close, a value the chart bar could not have known, so a backtest built on it looks better than live trading.
  • Treating a 0 from iClose as a price. The higher-timeframe history is not loaded yet; write EMPTY_VALUE and let the next call fill it.
  • Typing "4H" into a converted string input. Pine notation is minutes, so four hours is "240"; the unknown string falls back to the chart timeframe.
  • Expecting daily values to match TradingView on a broker whose server day starts at a different hour. The daily bar itself is different; compare on a symbol whose sessions agree before suspecting the code.

FAQ

How do I show a timeframe picker limited to a few choices?

Declare your own enum whose members are assigned the periods, for example enum ENUM_HTF { HTF_H1 = PERIOD_H1, HTF_H4 = PERIOD_H4, HTF_D1 = PERIOD_D1 };, and cast the input to ENUM_TIMEFRAMES where it is used. This is the MQL5 form of input.timeframe(..., options=[...]).

What does timeframe.in_seconds(tf) become?

PeriodSeconds(tf), which also resolves PERIOD_CURRENT to the chart's period. For minutes, hours, days and weeks the two agree exactly; for a month both platforms use a fixed nominal length, so check the value before using it in arithmetic.

Can an MQL5 indicator use a 3-day or 45-minute timeframe?

Not as a timeframe. You can build such bars yourself from CopyRates on D1 or M15 by grouping three bars at a time, but nothing in the platform supplies them, and the converter does not do this aggregation.

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

Related