Pine Script ↔ MQL5 reference
One page per construct: what it does on its own platform, the closest equivalent on the other, where the two differ (seeding, missing values, indexing, timing), and what the Stratlate engine emits for it. Every complete MQL5 program on these pages compiles in MetaEditor 5 and every Pine example parses as Pine Script v6.
Looking for the whole table at once? See the Pine Script → MQL5 cheat sheet and the MQL5 → Pine Script cheat sheet. For longer explanations, the guides cover each topic end to end.
Pine Script → MQL5
Averages and volatility (ta.*)
[basis, upper, lower] = ta.bb(source, length, mult)— ta.bb in MQL5: iBands, the multiplier and the tuple
ta.bb(source, length, mult) returns basis, upper and lower. In MQL5 use iBands buffers 0, 1 and 2, or an SMA plus and minus mult times the population stdev.[basis, upper, lower] = ta.kc(source, length, mult, useTrueRange)— ta.kc in MQL5: Keltner Channels with an EMA basis
ta.kc(source, length, mult, useTrueRange) has no MQL5 built-in. Basis is an EMA of the source; bands add mult times an EMA of true range or high - low.ta.alma(source, length, offset, sigma)— ta.alma in MQL5: Gaussian weights, offset and sigma
ta.alma(source, length, offset, sigma) has no native MQL5 equivalent. Build it with Gaussian weights centred at offset * (length - 1) with width length / sigma.ta.atr(length)— ta.atr in MQL5: why iATR differs and the exact Wilder ATR
ta.atr(length) is a Wilder RMA of true range, SMA-seeded. MQL5 iATR is an SMA of true range, so it differs on every bar. Here is the exact MQL5 port.ta.bbw(source, length, mult)— ta.bbw in MQL5: Bollinger Band Width without a built-in
ta.bbw(source, length, mult) is (upper - lower) / basis, which equals 2 * mult * stdev / sma. MQL5 has no built-in: compute it in a loop or from iBands buffers.ta.ema(source, length)— ta.ema in MQL5: iMA MODE_EMA, seeding and the first bars
ta.ema(source, length) in MQL5 is iMA MODE_EMA or alpha * src + (1 - alpha) * prev with alpha = 2 / (length + 1), seeded with the first source value.ta.hma(source, length)— ta.hma in MQL5: Hull average from three weighted MAs
ta.hma(source, length) has no native MQL5 function. Build it as wma(2 * wma(src, length / 2) - wma(src, length), round(sqrt(length))) with a calculation buffer.ta.linreg(source, length, offset)— ta.linreg in MQL5: least-squares line endpoint with offset
ta.linreg(source, length, offset) has no MQL5 function. Fit a least-squares line to the last length values and read intercept + slope * (length - 1 - offset).ta.rma(source, length)— ta.rma in MQL5: Wilder smoothing, iMA MODE_SMMA, SMA seed
ta.rma(source, length) in MQL5 is iMA MODE_SMMA: Wilder smoothing with alpha = 1 / length, seeded with the SMA of the first length values, na before that.ta.sma(source, length)— ta.sma in MQL5: iMA MODE_SMA or a windowed mean
ta.sma(source, length) in MQL5 is iMA with MODE_SMA for a price source, or the sum of the last length values divided by length. Covers na, indexing and seeding.ta.stdev(source, length, biased)— ta.stdev in MQL5: iStdDev and the biased flag
ta.stdev(source, length) with the default biased = true is the population stdev and equals iStdDev with MODE_SMA. biased = false divides by length - 1.ta.tr(handle_na)— ta.tr in MQL5: true range, handle_na and the first bar
ta.tr in MQL5 is max(high - low, abs(high - close[1]), abs(low - close[1])). ta.tr(true) uses high - low on the first bar; bare ta.tr is na there.ta.vwma(source, length)— ta.vwma in MQL5: no native, sum(src*vol)/sum(vol)
ta.vwma(source, length) has no iMA mode in MQL5. Compute sum(source * volume) / sum(volume) over the last length bars and choose tick or real volume first.ta.wma(source, length)— ta.wma in MQL5: iMA MODE_LWMA and the weight order
ta.wma(source, length) in MQL5 is iMA with MODE_LWMA: linear weights with the newest bar weighted length and the oldest 1, divided by length * (length + 1) / 2.
Language, values and time
bar_index, last_bar_index— bar_index in MQL5: rates_total, prev_calculated and the loop
Pine's bar_index and last_bar_index in MQL5: the loop index i and rates_total - 1, what prev_calculated means, and where the loop must start on each call.barstate.isconfirmed, islast, isrealtime, isfirst, isnew— barstate in MQL5: isconfirmed, islast, isrealtime, isnew
Pine's barstate.isconfirmed, islast, isrealtime, isfirst and isnew in MQL5: expressions over rates_total and prev_calculated, plus the new-bar test an EA needs.color.new(color, transp), color.rgb(r, g, b, transp)— color.new and color.rgb in MQL5: colours without transparency
Pine color.new and color.rgb in MQL5: C'r,g,b' literals and clr constants, and why transparency has to be blended into the colour for plots and objects.fixnan(x)— fixnan in MQL5: carrying the last valid value forward
Pine's fixnan(x) in MQL5: keep the previous bar's value when the current one is NaN, store the carry in a buffer slot so the forming bar recalculates safely.hl2, hlc3, ohlc4, hlcc4— hl2, hlc3, ohlc4 in MQL5: applied prices and the ohlc4 gap
Pine's hl2, hlc3, ohlc4 and hlcc4 in MQL5: PRICE_MEDIAN, PRICE_TYPICAL and PRICE_WEIGHTED, why ohlc4 has no applied price, and how to compute each by hand.math.abs, max, min, round, floor, ceil, pow, sqrt, log, exp, sign, sum, avg— math.* in MQL5: MathAbs, MathRound, math.sum and math.sign
Pine math functions in MQL5: MathAbs, MathMax, MathRound and friends, plus those with no direct twin: math.sign, math.round with precision, windowed math.sum.na, na(x)— na in MQL5: NaN, EMPTY_VALUE and MathIsValidNumber
Pine's na value and na() test in MQL5: use a quiet NaN tested with MathIsValidNumber, write EMPTY_VALUE to plot buffers, and never compare with ==.nz(x), nz(x, replacement)— nz in MQL5: replacing na with zero or a default value
Pine nz(x) and nz(x, replacement) in MQL5: a two-line function on MathIsValidNumber, where it belongs in a recurrence, and why EMPTY_VALUE needs its own check.request.security(symbol, timeframe, expression)— request.security in MQL5: iBarShift, iClose and lookahead
Pine's request.security in MQL5 in short: align each chart bar with iBarShift, read iClose or a native handle, and add 1 to the shift for lookahead_off.str.tostring(x, format), str.format(fmt, ...)— str.tostring in MQL5: DoubleToString and StringFormat
Pine str.tostring and str.format in MQL5: DoubleToString with explicit digits, IntegerToString, and StringFormat with printf codes instead of {0} patterns.syminfo.mintick, syminfo.pointvalue, syminfo.tickerid, syminfo.currency— syminfo.mintick in MQL5: SYMBOL_POINT vs tick size and value
Pine's syminfo.mintick, pointvalue, tickerid and currency in MQL5: SymbolInfoDouble with SYMBOL_TRADE_TICK_SIZE, SYMBOL_POINT and TICK_VALUE, and _Symbol.time, time_close, timestamp(), hour, minute, dayofweek— time and timestamp() in MQL5: milliseconds vs datetime
Pine time, timestamp(), hour and dayofweek in MQL5: datetime counts seconds, TimeToStruct gives the fields, Sunday is 0, and the clock is server time.timeframe.period, timeframe.in_seconds(), timeframe.multiplier, timeframe.change()— timeframe.period in MQL5: ENUM_TIMEFRAMES and PeriodSeconds
Pine timeframe.period, in_seconds, multiplier and change in MQL5: _Period is an enum, not minutes; PeriodSeconds gives seconds, a calendar test gives change.var x = …, varip x = …— var and varip in MQL5: persistent state and tick rollback
Pine var and varip in MQL5: keep a var value in a per-bar buffer so the forming bar can be recomputed, make a varip value a static reset on each new bar.x[n] (close[1], mySeries[2])— close[1] in MQL5: the history operator and array offsets
Pine's x[n] history operator in MQL5: OnCalculate arrays are oldest-first, so close[1] is close[i-1]; what ArraySetAsSeries changes, and how to bound the index.
Oscillators and trend (ta.*)
ta.cci(source, length)— ta.cci in MQL5: iCCI, mean deviation and the 0.015 constant
ta.cci and MetaTrader's iCCI share the formula: price minus its SMA over 0.015 times the mean absolute deviation. iCCI fits price sources; others need code.ta.cmo(series, length)— ta.cmo in MQL5: Chande Momentum Oscillator by hand
MetaTrader 5 has no built-in Chande Momentum Oscillator. ta.cmo is 100 times up moves minus down moves over their sum; here is a complete MQL5 version.ta.dmi(diLength, adxSmoothing)— ta.dmi in MQL5: iADX vs iADXWilder and the DI smoothing
ta.dmi returns +DI, -DI and ADX with Wilder smoothing. iADXWilder is the close match, iADX smooths with EMAs and differs. Exact MQL5 code with both lengths.ta.macd(source, fast, slow, signal)— ta.macd in MQL5: why iMACD's signal line does not match
ta.macd returns MACD, signal and histogram with an EMA signal line; MetaTrader's iMACD smooths the signal with an SMA, so write the EMA version yourself.ta.mfi(source, length)— ta.mfi in MQL5: iMFI, tick volume and the one-bar offset
ta.mfi maps to iMFI with the typical price, but MetaTrader's tick volume is not TradingView's volume and the first value lands one bar later. Full MQL5 code.ta.mom(source, length)— ta.mom in MQL5: not iMomentum, which returns a ratio
ta.mom(src, len) is src minus src len bars ago; MetaTrader's iMomentum is src divided by the old value times 100. Use a subtraction, shown in full MQL5.ta.obv— ta.obv in MQL5: iOBV, tick volume and the starting value
ta.obv is a running total of volume signed by the close change; iOBV computes the same with tick or real volume. Absolute levels never match, only slopes.ta.roc(source, length)— ta.roc in MQL5: percentage change with no built-in iROC
ta.roc(src, len) is 100 times the change over len bars divided by the old value. MT5 has no iROC; write the division yourself, as shown in a complete indicator.ta.rsi(source, length)— ta.rsi in MQL5: iRSI vs an RSI that matches TradingView
ta.rsi and MetaTrader's iRSI both use Wilder smoothing seeded with a simple average, so they agree after warm-up; iRSI is limited to applied prices.ta.sar(start, inc, max)— ta.sar in MQL5: iSAR arguments, seeding and the live bar
ta.sar takes start, increment and maximum; iSAR takes only step and maximum, so it matches only when start equals increment. Full Parabolic SAR in MQL5.ta.stoch(source, high, low, length)— ta.stoch in MQL5: raw %K vs iStochastic's slowing and %D
ta.stoch returns the unsmoothed %K; MetaTrader's iStochastic adds slowing and %D and averages the ratio differently. Here is the exact MQL5 match.ta.supertrend(factor, atrPeriod)— ta.supertrend in MQL5: bands, ATR and the direction sign
MT5 has no built-in SuperTrend. ta.supertrend returns the line and a direction where -1 means uptrend. A complete MQL5 version that matches it bar for bar.ta.tsi(source, short_length, long_length)— ta.tsi in MQL5: True Strength Index with double EMAs
MT5 has no iTSI. ta.tsi double-smooths the one-bar change and its absolute value with EMAs, long length first, and returns -1..1. Complete MQL5 code inside.ta.vwap(source)— ta.vwap in MQL5: session VWAP without a built-in iVWAP
MetaTrader 5 has no iVWAP. ta.vwap sums price times volume from the session start; in MQL5 you reset two running sums at a session boundary you choose.ta.wpr(length)— ta.wpr in MQL5: iWPR and the Williams %R formula
ta.wpr(length) and MetaTrader's iWPR compute the same Williams %R from the bar high, low and close; only the flat-window case differs. Full MQL5 code.
Plots, drawings, inputs and alerts
alert(message, freq)— alert() in MQL5: once per bar and once per bar close
Pine's alert() maps to Alert() in MQL5 with a bar-time guard: freq_once_per_bar tests the forming bar, freq_once_per_bar_close the closed bar. EA OnTick too.alertcondition(condition, title, message)— alertcondition() in MQL5: Alert() on a confirmed bar, once
MQL5 has no alertcondition(). Call Alert() or SendNotification() from OnCalculate on the closed bar, with a once-per-bar guard and no alerts on history.box.new(left, top, right, bottom, border_color, border_width, bgcolor, extend)— box.new() in MQL5: OBJ_RECTANGLE, fill colour and border width
Pine's box.new() is an OBJ_RECTANGLE in MQL5: two time/price corners, OBJPROP_FILL for bgcolor, OBJPROP_WIDTH for the border. One colour only; compiled example.hline(price, title, color, linestyle, linewidth); fill(a, b, color)— hline() and fill() in MQL5: indicator levels and DRAW_FILLING
Pine's hline() is #property indicator_levelN in an MQL5 subwindow; fill() between two plots is a DRAW_FILLING plot with two buffers. Compiled RSI example.input.int(defval, title, minval, maxval, step, tooltip, group, inline)— input.int, input.float, input.bool in MQL5: input variables
Pine's input.int/float/bool become MQL5 input variables. minval and maxval are not enforced by MetaTrader, so check them in OnInit; group maps to input group.input.source(defval, title, tooltip, inline, group)— input.source in MQL5: ENUM_APPLIED_PRICE and Apply to
Pine's input.source becomes an ENUM_APPLIED_PRICE input in MQL5, or the Apply to tab of a short-form OnCalculate. Why PRICE_WEIGHTED is hlcc4, not ohlc4.input.string(defval, title, options=[...])— input.string options in MQL5: enum inputs for drop-downs
A Pine input.string with options=[...] becomes an MQL5 enum input: one member per option, labelled by its comment. How to compare it and keep the label text.input.timeframe(defval, title, options)— input.timeframe in MQL5: ENUM_TIMEFRAMES and PERIOD_CURRENT
Pine's input.timeframe becomes an ENUM_TIMEFRAMES input in MQL5; the empty string meaning the chart timeframe is PERIOD_CURRENT. Compiled HTF example.label.new(x, y, text, xloc, yloc, color, style, textcolor, size)— label.new() in MQL5: OBJ_TEXT, anchors, limits and deletion
Pine's label.new() becomes an OBJ_TEXT chart object in MQL5 (OBJ_LABEL for screen-anchored text). Naming, anchors, the max_labels_count ring and cleanup.line.new(x1, y1, x2, y2, xloc, extend, color, style, width)— line.new() in MQL5: OBJ_TREND, rays and time coordinates
Pine's line.new() maps to an OBJ_TREND object in MQL5. extend.right becomes OBJPROP_RAY_RIGHT, bar indexes become times, and styles map to STYLE_*. Compiled.plot(series, title, color, linewidth, style, offset, display)— plot() in MQL5: indicator buffers, draw types and offsets
Pine's plot() maps to an MQL5 indicator buffer plus #property indicator_type/color/width. Style, offset and display equivalents, with a compiled example.plotcandle(open, high, low, close, title, color, wickcolor, bordercolor)— plotcandle() and plotbar() in MQL5: DRAW_CANDLES, 4 buffers
Pine's plotcandle() and plotbar() map to DRAW_CANDLES and DRAW_BARS over four buffers in open, high, low, close order; a fifth buffer colours each bar.plotchar(series, title, char, location, color, offset, text, size)— plotchar() in MQL5: Wingdings glyphs and text on signal bars
Pine's plotchar() is a DRAW_ARROW plot in MQL5 with a Wingdings code instead of a Unicode char; the text argument needs OBJ_TEXT objects. Compiled example.plotshape(series, title, style, location, color, offset, text, size)— plotshape() in MQL5: DRAW_ARROW markers and Wingdings codes
Pine's plotshape() becomes a DRAW_ARROW buffer in MQL5: PLOT_ARROW picks the Wingdings glyph, the buffer holds high or low, PLOT_ARROW_SHIFT places it.table.new(position, columns, rows); table.cell(t, col, row, text, text_color, bgcolor)— table.new() in MQL5: a grid of OBJ_LABEL objects per corner
MQL5 has no table object. Pine's table.new() and table.cell() become OBJ_LABEL and OBJ_RECTANGLE_LABEL objects anchored to a chart corner with OBJPROP_CORNER.
Series utilities (ta.*)
ta.barssince(condition)— ta.barssince in MQL5: a stateful counter that survives ticks
ta.barssince(cond) counts bars since the condition was last true and is na until it has been true once. Build it in MQL5 as per-bar state, not a static counter.ta.change(source, length = 1)— ta.change in MQL5: src - src[len], bool form and first bars
ta.change(src, len) is src minus its value len bars ago, na until that bar exists; on a bool it means changed. The MQL5 difference, guard and index order.ta.cross(source1, source2)— ta.cross in MQL5: either-direction cross as a sign change
ta.cross(a, b) is true when a crosses b in either direction. In MQL5 it is a sign change of a - b between two bars, with the strict and non-strict sides kept.ta.crossover(source1, source2)— ta.crossover in MQL5: the exact two-bar test, with na handling
ta.crossover(a, b) is true when a is above b on this bar and was not above it on the previous bar. The MQL5 test, the index direction and the na rules.ta.crossunder(source1, source2)— ta.crossunder in MQL5: closed-bar test in an Expert Advisor
ta.crossunder(a, b) is true when a is below b now and was not below it one bar earlier. How to test it on closed bars in an MQL5 EA with series indexing.ta.cum(source)— ta.cum in MQL5: a running total seeded on the first bar
ta.cum(src) is the running total of src from the first bar of the chart. In MQL5: Cum[i] = Cum[i-1] + src[i], seeded on bar 0, with na treated as zero.ta.highest(source, length) / ta.highest(length)— ta.highest in MQL5: ArrayMaximum, iHighest and the window edge
ta.highest(src, len) is the maximum of the last len values including the current bar, na until the window is full. MQL5 forms with ArrayMaximum and iHighest.ta.highestbars(source, length) / ta.highestbars(length)— ta.highestbars in MQL5: the negative offset of the window high
ta.highestbars(src, len) returns the offset of the highest value in the window, 0 for the current bar and negative for earlier bars. Window scan and na in MQL5.ta.lowest(source, length) / ta.lowest(length)— ta.lowest in MQL5: ArrayMinimum, iLowest and the one-arg form
ta.lowest(src, len) is the smallest of the last len values including the current bar; ta.lowest(len) reads low. MQL5 with ArrayMinimum, iLowest and a na guard.ta.lowestbars(source, length) / ta.lowestbars(length)— ta.lowestbars in MQL5: offset of the window low, bars since
ta.lowestbars(src, len) gives the offset of the lowest value in the window: 0 now, negative for earlier bars. The MQL5 scan, the sign in series order, and na.ta.percentrank(source, length)— ta.percentrank in MQL5: share of previous values at or below
ta.percentrank(src, len) is the percentage of the previous len values less than or equal to the current one; the current bar is excluded. The MQL5 loop.ta.pivothigh(source, leftbars, rightbars) / ta.pivothigh(leftbars, rightbars)— ta.pivothigh in MQL5: confirmed right bars late, vs iFractals
ta.pivothigh(left, right) returns a swing high right bars after it happened, na otherwise. The offset, the tie rule, MQL5 code and how iFractals compares.ta.pivotlow(source, leftbars, rightbars) / ta.pivotlow(leftbars, rightbars)— ta.pivotlow in MQL5: the delayed swing low and its offset
ta.pivotlow(left, right) returns a swing low on the bar that confirms it, right bars later, na elsewhere. MQL5 code that keeps it on the pivot bar; iFractals.ta.rising(source, length), ta.falling(source, length)— ta.rising and ta.falling in MQL5: strict test over length bars
ta.rising(src, len) is true when the current value exceeds each of the previous len values; ta.falling is the mirror. The exact rule, na handling and MQL5 loop.ta.valuewhen(condition, source, occurrence)— ta.valuewhen in MQL5: backward scan with an occurrence index
ta.valuewhen(cond, src, n) returns src at the (n+1)-th most recent bar where cond was true, the current bar included. The MQL5 backward scan and its state.
Strategies (strategy.*)
strategy(calc_on_every_tick, process_orders_on_close)— calc_on_every_tick in MQL5: bar-close vs tick evaluation
Pine runs a strategy at bar close and fills at the next open. An EA does this with a new-bar gate in OnTick reading shift 1; calc_on_every_tick reads shift 0.strategy(commission_type, commission_value, slippage)— Commission and slippage in MQL5: tester and broker settings
Pine's commission_value and slippage cannot be set in MQL5 code. MT5 takes commission from the symbol and slippage from real fills; model costs in OnTester.strategy(default_qty_type = strategy.fixed | strategy.cash | strategy.percent_of_equity, default_qty_value)— default_qty_type in MQL5: fixed, cash and percent as lots
Pine sizes orders in contracts, cash or percent of equity; MT5 needs lots. Convert via tick value and size, floor to the lot step, skip tiny orders.strategy(pyramiding = N)— pyramiding in MQL5: limiting stacked entries in an EA
strategy(pyramiding = N) caps entries per direction. In MQL5 count the EA's positions on hedging accounts, or keep an entry counter on netting accounts.strategy(title, overlay, initial_capital, default_qty_type, default_qty_value, pyramiding, commission_value, slippage, calc_on_every_tick, process_orders_on_close)— strategy() in MQL5: declaration arguments as EA inputs
Where each strategy() argument goes in an MQL5 EA: default_qty_value, pyramiding and slippage become inputs; initial_capital and commission are tester settings.strategy.cancel(id) / strategy.cancel_all()— strategy.cancel in MQL5: OrderDelete for pending orders
strategy.cancel(id) and cancel_all remove resting orders, not positions. In MQL5: CTrade.OrderDelete over OrdersTotal, filtered by symbol, magic and comment.strategy.close(id, comment, qty, qty_percent) / strategy.close_all()— strategy.close in MQL5: PositionClose by entry id
strategy.close(id) is CTrade.PositionClose on the position whose comment is the id; qty_percent is PositionClosePartial; close_all loops over all positions.strategy.entry(id, direction, qty, limit, stop, comment)— strategy.entry in MQL5: CTrade Buy/Sell with Pine's reversal
strategy.entry maps to CTrade.Buy or Sell after closing any opposite position; the id becomes the order comment; limit or stop entries become pending orders.strategy.equity / strategy.netprofit / strategy.openprofit / strategy.initial_capital— strategy.equity and netprofit in MQL5: account values
strategy.equity is ACCOUNT_EQUITY, openprofit is ACCOUNT_PROFIT, netprofit is the balance change since start; MT5 reports in the deposit currency.strategy.exit(id, from_entry, profit, limit, loss, stop, trail_points, trail_offset)— strategy.exit in MQL5: stop, limit, ticks and trailing exits
strategy.exit stop= and limit= become the position's SL and TP via PositionModify; loss= and profit= are ticks from the fill price; trail_* needs per-tick code.strategy.opentrades / strategy.closedtrades and their .entry_price(n), .profit(n), .size(n)— strategy.opentrades and closedtrades in MQL5
strategy.opentrades counts open trades, closedtrades finished ones. In MQL5 loop PositionsTotal for open trades and the closing deals of HistoryDealsTotal.strategy.order(id, direction, qty, limit, stop, comment)— strategy.order in MQL5: an order that adds, never reverses
strategy.order adds its quantity to the net position with no reversal rules. In MQL5: a plain CTrade.Buy or Sell on netting accounts; hedging needs extra code.strategy.position_avg_price— strategy.position_avg_price in MQL5: POSITION_PRICE_OPEN
strategy.position_avg_price is the volume-weighted entry price. In MQL5 read POSITION_PRICE_OPEN on a netting account, or average it over hedged positions.strategy.position_size— strategy.position_size in MQL5: signed volume from positions
strategy.position_size is positive long, negative short, zero flat. In MQL5 sum POSITION_VOLUME signed by POSITION_TYPE over the EA's positions, in lots.strategy.risk.max_drawdown / max_intraday_loss / max_position_size / allow_entry_in— strategy.risk in MQL5: drawdown and daily loss guards
strategy.risk.max_drawdown, max_intraday_loss and other risk rules have no MQL5 equivalent; code guards in OnTick. The converter reports them unsupported.
MQL5 → Pine Script
Indicator functions
CopyBuffer(handle, buffer_num, start_pos, count, buffer[])— CopyBuffer in Pine Script: the value is just the series
CopyBuffer copies indicator values from a handle into an array; in Pine Script the indicator call is the series, and start_pos becomes the history offset [n].iADX(symbol, period, adx_period) / iADXWilder(symbol, period, adx_period)— iADX in Pine Script: ta.dmi matches iADXWilder, not iADX
MetaTrader's iADX smooths with an EMA seeded at zero and only iADXWilder uses Wilder's method, so ta.dmi ports iADXWilder; iADX needs a hand-written EMA.iATR(symbol, period, ma_period)— iATR in Pine Script: ta.sma(ta.tr, n), not ta.atr
MetaTrader's iATR is a simple average of true range, so its exact Pine Script port is ta.sma(ta.tr(false), n); ta.atr uses Wilder smoothing and differs.iBands(symbol, period, bands_period, bands_shift, deviation, applied_price)— iBands in Pine Script: ta.bb with deviation as the multiplier
iBands(symbol, period, n, shift, deviation, price) is ta.bb(source, n, deviation) in Pine Script; the three buffers map to the tuple, the shift to offset.iCCI(symbol, period, ma_period, applied_price)— iCCI in Pine Script: ta.cci with the applied price as source
iCCI(symbol, period, n, applied_price) is ta.cci(source, n) in Pine Script; both use the 0.015 constant and mean absolute deviation, so the values match.iCustom(symbol, period, name, inputs...)— iCustom in Pine Script: no equivalent, so inline the logic
Pine Script cannot call another indicator the way iCustom does. Port the called indicator's logic, import it from a library, or read its plot with input.source.iIchimoku(symbol, period, tenkan_sen, kijun_sen, senkou_span_b)— iIchimoku in Pine Script: five buffers and the displacement
iIchimoku's five buffers are midpoints of ta.highest and ta.lowest in Pine Script; the cloud and Chikou shift is the Kijun period, applied with plot offset.iMA(symbol, period, ma_period, ma_shift, ma_method, applied_price)— iMA in Pine Script: ta.sma, ta.ema, ta.rma or ta.wma by mode
iMA maps to ta.sma, ta.ema, ta.rma or ta.wma depending on ma_method; ma_shift becomes plot offset and applied_price becomes the source argument.iMACD(symbol, period, fast_ema, slow_ema, signal_period, applied_price)— iMACD in Pine Script: the signal line is an SMA, not ta.macd
MetaTrader's iMACD smooths the signal line with a simple average, so the exact Pine Script port is ta.ema minus ta.ema and ta.sma(macd, signal), not ta.macd.iMFI(symbol, period, ma_period, applied_volume)— iMFI in Pine Script: ta.mfi(hlc3, n) and the volume feed
iMFI(symbol, period, n, applied_volume) is ta.mfi(hlc3, n) in Pine Script: same typical-price money flow over n bars; differences come from the volume feed.iMomentum(symbol, period, mom_period, applied_price)— iMomentum in Pine Script: a ratio times 100, not ta.mom
MetaTrader's iMomentum is price / price n bars ago × 100 and oscillates around 100; Pine's ta.mom is a difference around 0. Port it as src / src[n] * 100.iOBV(symbol, period, applied_volume)— iOBV in Pine Script: ta.obv and the first-bar offset
iOBV is ta.obv in Pine Script: both add volume on up closes and subtract it on down closes. MetaTrader starts at the first bar's volume, so levels differ.iRSI(symbol, period, ma_period, applied_price)— iRSI in Pine Script: ta.rsi is the same Wilder RSI
iRSI(symbol, period, n, applied_price) is ta.rsi(source, n) in Pine Script: both use Wilder smoothing seeded with a simple average, so values match.iSAR(symbol, period, step, maximum)— iSAR in Pine Script: ta.sar(step, step, maximum)
MetaTrader's iSAR(symbol, period, step, maximum) is ta.sar(step, step, maximum) in Pine Script: step is both start and increment; only the first trend differs.iStochastic(symbol, period, Kperiod, Dperiod, slowing, ma_method, price_field)— iStochastic in Pine Script: slowing is not ta.sma of ta.stoch
iStochastic's %K smooths numerator and denominator separately over the slowing period; the exact Pine Script port uses math.sum, and %D is ta.sma of that %K.
Program structure and trading
Alert(...), SendNotification(msg), PlaySound(file), SendMail(subject, body)— Alert and SendNotification in Pine Script: alert()
Alert, SendNotification and PlaySound all become alert() or alertcondition() in Pine; the channel is set in the alert dialog. Frequency and closed bars.ArraySetAsSeries(array[], true) then array[shift]— ArraySetAsSeries in Pine Script: index direction and []
ArraySetAsSeries flips an MQL5 array to newest-first. Pine series are always newest-first: close[1] is one bar back. Index rules, out-of-range, loops.Buf[i] = EMPTY_VALUE; PlotIndexSetDouble(n, PLOT_EMPTY_VALUE, v); PLOT_DRAW_BEGIN— EMPTY_VALUE in Pine Script: na and gaps in plots
EMPTY_VALUE, PLOT_EMPTY_VALUE and PLOT_DRAW_BEGIN all become na in Pine Script. How gaps, warm-up bars and arrow buffers translate, and which tests break.CopyRates(symbol, tf, start, count, MqlRates &rates[]); rates[i].close— CopyRates and MqlRates in Pine Script: OHLCV built-ins
CopyRates fills an MqlRates array; in Pine the fields are the built-in series open, high, low, close, volume and time. Index mapping and tick_volume vs volume.iClose(symbol, timeframe, shift), iHigh, iLow, iOpen, iVolume, iTime— iClose, iHigh, iLow, iTime in Pine Script: close[shift]
iClose(sym, tf, shift) is close[shift] on the chart timeframe and request.security for another timeframe or symbol. Shift alignment, iTime units, iBarShift.input int X = 14; // Title sinput, enum inputs, input group "Name"— input, sinput and enum inputs in Pine Script: input.*()
MQL5 input, sinput, enum inputs and input group map to input.int, input.float, input.bool, input.enum or input.string with options, group= and display.none.int OnCalculate(rates_total, prev_calculated, time[], open[], ...)— OnCalculate in Pine Script: the bar loop becomes one line
OnCalculate, rates_total and prev_calculated have no Pine Script counterpart: Pine runs the script once per bar. What happens to the loop and the guards.int OnInit() { SetIndexBuffer(...); handle = iMA(...); IndicatorSetString(...); }— OnInit in Pine Script: handles, buffers and properties
OnInit work (indicator handles, SetIndexBuffer, IndicatorSetString, input checks) becomes the indicator() or strategy() declaration and input.* calls in Pine.ObjectCreate(chart, name, OBJ_TREND / OBJ_RECTANGLE / OBJ_TEXT / OBJ_HLINE, sub, t1, p1, ...)— ObjectCreate in Pine Script: line.new, box.new, label.new
OBJ_TREND, OBJ_RECTANGLE, OBJ_TEXT and OBJ_HLINE map to line.new, box.new, label.new and extended lines. Handles instead of names, and the 500-object limit.PositionSelect(symbol); PositionGetDouble(POSITION_PRICE_OPEN / VOLUME / PROFIT / SL)— PositionSelect in Pine Script: strategy.position_size
PositionSelect and PositionGetDouble map to strategy.position_size, position_avg_price, openprofit and opentrades.*. No equivalent for SL, TP, magic.SetIndexBuffer(index, array[], INDICATOR_DATA) + #property indicator_typeN/colorN— SetIndexBuffer in Pine Script: buffers become plot() calls
SetIndexBuffer, #property indicator_type/color and PlotIndexSetInteger map to one plot() call with style and color arguments; EMPTY_VALUE becomes na.SymbolInfoDouble(sym, SYMBOL_POINT / TRADE_TICK_SIZE / TRADE_TICK_VALUE / VOLUME_MIN)— SymbolInfoDouble in Pine Script: syminfo.mintick, pointvalue
SYMBOL_POINT and TICK_SIZE map to syminfo.mintick, TICK_VALUE to pointvalue times mintick, VOLUME_MIN to syminfo.mincontract. Pine has no lot step or Bid/Ask.TimeCurrent(), TimeToStruct(t, MqlDateTime &dt), dt.hour, dt.day_of_week, iTime()— TimeCurrent and TimeToStruct in Pine Script: time, hour()
TimeCurrent, TimeToStruct and iTime map to time, timenow, hour() and dayofweek() in Pine. Seconds vs milliseconds, broker server time vs exchange time zone.trade.Buy(lots, sym, price, sl, tp) / OrderSend(MqlTradeRequest, MqlTradeResult)— CTrade and OrderSend in Pine Script: strategy.entry/exit
CTrade.Buy/Sell, PositionClose and OrderSend with MqlTradeRequest map to strategy.entry, strategy.exit with stop/limit prices and strategy.close. Lots vs qty.void OnTick() with an iTime(...,0) new-bar gate— OnTick in Pine Script: per-bar strategy evaluation
OnTick runs on every tick; a Pine strategy runs once per bar close. How the new-bar gate, shift 1, barstate.isconfirmed and calc_on_every_tick line up.