Pine Script → MQL5 cheat sheet
Short answer
The Pine Script built-ins and their MQL5 equivalents on one page: 89 functions from ta.sma and ta.rsi to strategy.entry and request.security, each linked to a full explanation. Each row names the closest MQL5 equivalent of a Pine Script v6 built-in. "Closest" is doing work in that sentence: the linked page explains where the two differ and shows the code that actually matches TradingView's values.
Each row names the closest MQL5 equivalent of a Pine Script v6 built-in. "Closest" is doing work in that sentence: the linked page explains where the two differ and shows the code that actually matches TradingView's values. For the other direction see the MQL5 → Pine Script cheat sheet.
Averages and volatility (ta.*)
| Pine Script v6 | MQL5 equivalent |
|---|---|
[basis, upper, lower] = ta.bb(source, length, mult) | iBands(..., length, 0, mult, price): buffer 0 basis, 1 upper, 2 lower |
[basis, upper, lower] = ta.kc(source, length, mult, useTrueRange) | No native; EMA(src) +/- mult * EMA(true range or high - low), same length |
ta.alma(source, length, offset, sigma) | No native; Gaussian weights exp(-(j-m)^2/(2s^2)), m = offset*(len-1), s = len/sigma |
ta.atr(length) | NOT iATR (SMA of TR); Wilder RMA of true range, SMA-seeded, first bar TR = high - low |
ta.bbw(source, length, mult) | No native; 2 * mult * stdev / sma, or (upper - lower) / base from iBands |
ta.ema(source, length) | iMA(..., MODE_EMA, price) or alpha = 2/(len+1) recursion seeded with the first value |
ta.hma(source, length) | No native; wma(2*wma(src, len/2) - wma(src, len), round(sqrt(len))) via a buffer |
ta.linreg(source, length, offset) | No native; least-squares fit over len bars; intercept + slope * (len - 1 - offset) |
ta.rma(source, length) | iMA(..., MODE_SMMA, price); alpha = 1/len, SMA-seeded; feeds ta.rsi and ta.atr |
ta.sma(source, length) | iMA(..., MODE_SMA, price) for a price source; otherwise sum of last length values / length |
ta.stdev(source, length, biased) | iStdDev(..., MODE_SMA, price) for biased = true (population); divide by len - 1 for false |
ta.tr(handle_na) | max(high-low, |high-close[i-1]|, |low-close[i-1]|); first bar na or high-low |
ta.vwma(source, length) | No native; sum(src * vol) / sum(vol) over length bars, tick or real volume |
ta.wma(source, length) | iMA(..., MODE_LWMA, price) or sum(src[k] * (len - k)) / (len * (len + 1) / 2) |
Language, values and time
| Pine Script v6 | MQL5 equivalent |
|---|---|
bar_index, last_bar_index | the loop index i (oldest-first) and rates_total - 1; start the loop at prev_calculated - 1 |
barstate.isconfirmed, islast, isrealtime, isfirst, isnew | i < rates_total-1; i == rates_total-1; prev_calculated > 0; i == 0; time[] changed |
color.new(color, transp), color.rgb(r, g, b, transp) | C'r,g,b' or a clr constant; blend transparency with the chart background |
fixnan(x) | buf[i] = isNaN(x) ? buf[i-1] : x, with the carry read from the previous bar's slot |
hl2, hlc3, ohlc4, hlcc4 | PRICE_MEDIAN, PRICE_TYPICAL, none (compute (o+h+l+c)/4), PRICE_WEIGHTED |
math.abs, max, min, round, floor, ceil, pow, sqrt, log, exp, sign, sum, avg | MathAbs/MathMax/MathRound/…; sign, round(x, n), sum(x, len) written by hand |
na, na(x) | a quiet NaN tested with !MathIsValidNumber(x); EMPTY_VALUE only in plot buffers |
nz(x), nz(x, replacement) | MathIsValidNumber(x) ? x : replacement (default 0); guard EMPTY_VALUE separately |
request.security(symbol, timeframe, expression) | iBarShift(sym, tf, time[i]) + 1, then iClose/iHigh or CopyBuffer from a native handle |
str.tostring(x, format), str.format(fmt, ...) | DoubleToString(x, digits), IntegerToString(n), StringFormat("%.2f %d %s", ...) |
syminfo.mintick, syminfo.pointvalue, syminfo.tickerid, syminfo.currency | SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE / _VALUE), _Point, _Symbol |
time, time_close, timestamp(), hour, minute, dayofweek | time[i] (datetime, seconds), time[i] + PeriodSeconds(), StructToTime, TimeToStruct |
timeframe.period, timeframe.in_seconds(), timeframe.multiplier, timeframe.change() | _Period (ENUM_TIMEFRAMES), PeriodSeconds(tf), a calendar comparison on time[] |
var x = …, varip x = … | var: previous bar's buffer slot (rolled back per tick); varip: static, reset on new bar |
x[n] (close[1], mySeries[2]) | x[i-n] on oldest-first arrays with i-n >= 0; own series need a buffer |
Oscillators and trend (ta.*)
| Pine Script v6 | MQL5 equivalent |
|---|---|
ta.cci(source, length) | iCCI with the matching PRICE_* constant; same formula, 0 instead of na on a flat window |
ta.cmo(series, length) | Sum of up and down changes over len bars by hand; MT5 has no iCMO |
ta.dmi(diLength, adxSmoothing) | Wilder-smoothed +DM, -DM, TR by hand; iADXWilder close (one period); iADX differs |
ta.macd(source, fast, slow, signal) | Two EMAs and an EMA signal line by hand; iMACD's signal line is an SMA |
ta.mfi(source, length) | iMFI(sym, tf, len, VOLUME_TICK|VOLUME_REAL) for hlc3; by hand for other sources |
ta.mom(source, length) | price[i] - price[i - length]; iMomentum is price / price[length] * 100, a different number |
ta.obv | iOBV(sym, tf, VOLUME_TICK|VOLUME_REAL); same rule, different start, so compare slopes |
ta.roc(source, length) | 100 * (price[i] - price[i - len]) / price[i - len]; no iROC exists in MT5 |
ta.rsi(source, length) | iRSI for price sources; hand-written Wilder RSI for computed sources |
ta.sar(start, inc, max) | iSAR(sym, tf, step, max) only when start == inc; otherwise Wilder's SAR by hand |
ta.stoch(source, high, low, length) | Raw %K by hand (highest/lowest window); iStochastic slows it by summing, not SMA |
ta.supertrend(factor, atrPeriod) | hl2 +/- factor * Wilder ATR with ratcheting bands, by hand; no iSuperTrend |
ta.tsi(source, short_length, long_length) | EMA(EMA(change, long), short) / EMA(EMA(|change|, long), short), range -1..1 |
ta.vwap(source) | Running sum(src * volume) / sum(volume), reset each session; no iVWAP in MT5 |
ta.wpr(length) | iWPR(sym, tf, len); same formula, previous value instead of na on a flat window |
Plots, drawings, inputs and alerts
| Pine Script v6 | MQL5 equivalent |
|---|---|
alert(message, freq) | Alert()/SendNotification() with a bar-time guard; per_bar_close tests bar rates_total-2 |
alertcondition(condition, title, message) | No direct equivalent: Alert()/SendNotification() in OnCalculate on the closed bar, once |
box.new(left, top, right, bottom, border_color, border_width, bgcolor, extend) | ObjectCreate(0, name, OBJ_RECTANGLE, 0, t1, top, t2, bottom); OBJPROP_FILL, OBJPROP_WIDTH |
hline(price, title, color, linestyle, linewidth); fill(a, b, color) | hline → #property indicator_levelN (subwindow); fill → DRAW_FILLING plot over two buffers |
input.int(defval, title, minval, maxval, step, tooltip, group, inline) | input int/double/bool Name = default; // title; range checks in OnInit; input group |
input.source(defval, title, tooltip, inline, group) | input ENUM_APPLIED_PRICE (compute the price per bar), or price[] of short-form OnCalculate |
input.string(defval, title, options=[...]) | enum E { A, B, C }; input E InpX = B; // members labelled by trailing comments |
input.timeframe(defval, title, options) | input ENUM_TIMEFRAMES InpTf = PERIOD_CURRENT; "" (chart timeframe) is PERIOD_CURRENT |
label.new(x, y, text, xloc, yloc, color, style, textcolor, size) | OBJ_TEXT at (time, price) + OBJPROP_TEXT/COLOR/ANCHOR; ObjectDelete by name |
line.new(x1, y1, x2, y2, xloc, extend, color, style, width) | ObjectCreate(0, name, OBJ_TREND, 0, t1, p1, t2, p2); extend → OBJPROP_RAY_RIGHT/RAY_LEFT |
plot(series, title, color, linewidth, style, offset, display) | One double buffer per plot; #property indicator_typeN/colorN/widthN; PLOT_SHIFT for offset |
plotcandle(open, high, low, close, title, color, wickcolor, bordercolor) | DRAW_CANDLES over 4 buffers O,H,L,C, +1 colour-index buffer; plotbar → DRAW_BARS |
plotchar(series, title, char, location, color, offset, text, size) | DRAW_ARROW with a Wingdings code for char; text= becomes OBJ_TEXT per signal bar |
plotshape(series, title, style, location, color, offset, text, size) | DRAW_ARROW buffer: value = high/low where true, EMPTY_VALUE elsewhere; PLOT_ARROW glyph |
table.new(position, columns, rows); table.cell(t, col, row, text, text_color, bgcolor) | No native table: OBJ_LABEL (+OBJ_RECTANGLE_LABEL) per cell, corner from position |
Series utilities (ta.*)
| Pine Script v6 | MQL5 equivalent |
|---|---|
ta.barssince(condition) | Last[i] = cond ? i : Last[i-1]; result i - Last[i]; EMPTY_VALUE while never true |
ta.change(source, length = 1) | src[i] - src[i-len] on oldest-first arrays; EMPTY_VALUE for i < len; bool: a != a[i-1] |
ta.cross(source1, source2) | crossover || crossunder: (d0 > 0 && d1 <= 0) || (d0 < 0 && d1 >= 0) with d = a - b |
ta.crossover(source1, source2) | a[i] > b[i] && a[i-1] <= b[i-1] on oldest-first arrays; false on any missing value |
ta.crossunder(source1, source2) | a[i] < b[i] && a[i-1] >= b[i-1]; in an EA on series arrays: a[1] < b[1] && a[2] >= b[2] |
ta.cum(source) | Cum[i] = (i == 0 ? 0 : Cum[i-1]) + src[i] in a buffer; depends on chart history length |
ta.highest(source, length) / ta.highest(length) | high[ArrayMaximum(high, i-len+1, len)] on oldest-first arrays; EMPTY_VALUE for i < len-1 |
ta.highestbars(source, length) / ta.highestbars(length) | (index of window max) - i on oldest-first arrays, 0..-(len-1); na until the window is full |
ta.lowest(source, length) / ta.lowest(length) | src[ArrayMinimum(src, i-len+1, len)] on oldest-first arrays; EMPTY_VALUE for i < len-1 |
ta.lowestbars(source, length) / ta.lowestbars(length) | (index of window min) - i on oldest-first arrays, 0..-(len-1); na until window is full |
ta.percentrank(source, length) | 100 * count(src[i-k] <= src[i], k = 1..len) / len; EMPTY_VALUE while i < len |
ta.pivothigh(source, leftbars, rightbars) / ta.pivothigh(leftbars, rightbars) | src[i-right] if no left bar is higher and no right bar as high; returned right bars late |
ta.pivotlow(source, leftbars, rightbars) / ta.pivotlow(leftbars, rightbars) | src[i-right] if no left bar is lower and no right bar as low; returned right bars late |
ta.rising(source, length), ta.falling(source, length) | src[i] > src[i-k] for every k in 1..len (strict); falling mirrors it; false on na |
ta.valuewhen(condition, source, occurrence) | scan k = i..0 over a cond buffer, skip `occurrence` hits, return src[k]; else EMPTY_VALUE |
Strategies (strategy.*)
| Pine Script v6 | MQL5 equivalent |
|---|---|
strategy(calc_on_every_tick, process_orders_on_close) | new-bar gate in OnTick reading shift 1; every tick on shift 0 for calc_on_every_tick |
strategy(commission_type, commission_value, slippage) | no code equivalent: symbol commission and tester delays; model Pine's costs in OnTester |
strategy(default_qty_type = strategy.fixed | strategy.cash | strategy.percent_of_equity, default_qty_value) | lots = money / (price / tick size × tick value), floored to SYMBOL_VOLUME_STEP |
strategy(pyramiding = N) | count own positions per direction (hedging) or an entry counter (netting) before Buy/Sell |
strategy(title, overlay, initial_capital, default_qty_type, default_qty_value, pyramiding, commission_value, slippage, calc_on_every_tick, process_orders_on_close) | inputs for lots, pyramiding and deviation; capital and commission are tester settings |
strategy.cancel(id) / strategy.cancel_all() | CTrade.OrderDelete on pending orders whose comment is the id; positions are untouched |
strategy.close(id, comment, qty, qty_percent) / strategy.close_all() | PositionClose(ticket) on positions whose comment is the id; partial → PositionClosePartial |
strategy.entry(id, direction, qty, limit, stop, comment) | close opposite positions, then CTrade.Buy/Sell; limit/stop → pending order; id → comment |
strategy.equity / strategy.netprofit / strategy.openprofit / strategy.initial_capital | AccountInfoDouble(ACCOUNT_EQUITY / ACCOUNT_PROFIT); netprofit = balance − starting balance |
strategy.exit(id, from_entry, profit, limit, loss, stop, trail_points, trail_offset) | PositionModify SL/TP; ticks → open price ± n × tick size; trailing stop coded per tick |
strategy.opentrades / strategy.closedtrades and their .entry_price(n), .profit(n), .size(n) | PositionsTotal + PositionGet*; HistorySelect + DEAL_ENTRY_OUT deals for closed trades |
strategy.order(id, direction, qty, limit, stop, comment) | CTrade.Buy/Sell with no reversal logic; netting nets it, hedging needs a partial close |
strategy.position_avg_price | POSITION_PRICE_OPEN; volume-weighted mean over positions on hedging accounts |
strategy.position_size | Σ POSITION_VOLUME, + for POSITION_TYPE_BUY, − for SELL, over this EA's positions (lots) |
strategy.risk.max_drawdown / max_intraday_loss / max_position_size / allow_entry_in | hand-written guards in OnTick over equity, deal history and net lots; not converted |
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