Pine Script vs MQL5: Differences That Matter for Conversion

Short answer

Pine runs your script once per bar, oldest to newest, and every variable becomes a series with its own history, so you never write the bar loop. MQL5 makes you write the loop and manage history yourself, and six differences decide whether a conversion gives the same numbers.

Pine Script and MQL5 both describe indicators and trading rules, but they run on very different machines. This guide is for traders and developers who know one of the two languages and need to move code to the other: it covers the six differences that decide whether a conversion gives the same numbers, with small examples of each.

1. Execution model: per-bar script vs event handlers

A Pine script is a program that TradingView runs once for every bar, oldest to newest. Every line executes on every bar, and each variable automatically becomes a series with its own history. You never write the bar loop.

MQL5 is event-driven. An indicator implements OnInit() (setup) and OnCalculate() (called on every new tick), and an Expert Advisor implements OnTick(). Inside OnCalculate() you write the loop over bars yourself, and you use prev_calculated to skip bars that were already computed on an earlier call. The same indicator in both languages:

//@version=6
indicator("Close vs SMA %")
length = input.int(20, "Length", minval = 1)
basis  = ta.sma(close, length)
pct    = 100 * (close - basis) / basis
plot(pct, "Distance %", color.teal)
hline(0)
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_plots   1
#property indicator_label1  "Distance %"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrTeal
#property indicator_level1  0.0

input int InpLength = 20; // Length

double DistBuf[];

int OnInit()
{
   if(InpLength < 1)
      return INIT_PARAMETERS_INCORRECT;
   SetIndexBuffer(0, DistBuf, 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[])
{
   // Index 0 is the OLDEST bar here (MQL5 default, not series-indexed).
   int start = (prev_calculated > 0) ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
   {
      DistBuf[i] = EMPTY_VALUE;              // Pine: na
      if(i < InpLength - 1)
         continue;                           // ta.sma is na during warm-up
      double sum = 0.0;
      for(int k = 0; k < InpLength; k++)
         sum += close[i - k];                // close[i - k] is Pine's close[k]
      double basis = sum / InpLength;
      if(basis != 0.0)                       // Pine's x / 0 is na, MQL's is an error
         DistBuf[i] = 100.0 * (close[i] - basis) / basis;
   }
   return rates_total;
}

On the live bar the two platforms also differ. A Pine indicator re-executes the realtime bar on every tick, and before each re-run it rolls its variables back to the values they had when the bar opened (only varip escapes this). MQL5 has no such rollback: OnCalculate() recomputes the last bar on each tick, but any global or static variable you change there changes once per tick, not once per bar. Code generated by Stratlate's converter saves each bar's starting state and restores it before every re-run of the live bar, which reproduces TradingView's model; in hand-written code you must design for it.

2. Bar indexing and history

In Pine, close[1] is always the previous bar. In MQL5 it depends on the array. The price arrays passed to OnCalculate() are not series-indexed by default: index 0 is the oldest bar and rates_total - 1 the newest. Inside a loop over i, Pine's close[k] is therefore close[i - k]. Calling ArraySetAsSeries(close, true) flips the array so that 0 is the newest bar, and functions such as iClose(_Symbol, _Period, shift) always use series order (shift 0 is the current bar). Mixing the two conventions in one file is the most common source of mirrored or shifted output.

Your own variables have no history at all in MQL5. If the Pine code reads a computed value from an earlier bar, store that value in a buffer:

r = ta.rsi(close, 14)
change = r - r[1]          // history of a computed value: free
// Keep r in a buffer (INDICATOR_CALCULATIONS if it is not drawn);
// a local variable would forget last bar's value.
ChangeBuf[i] = (i > 0 && RsiBuf[i] != EMPTY_VALUE && RsiBuf[i - 1] != EMPTY_VALUE)
             ? RsiBuf[i] - RsiBuf[i - 1]
             : EMPTY_VALUE;

3. Missing values: na vs EMPTY_VALUE

Pine has a real "no value" called na. It propagates through arithmetic, every comparison with it is false, nz(x) replaces it with zero, and a plot simply skips it. Division by zero also gives na.

MQL5 has none of this. The usual stand-in, EMPTY_VALUE, is just DBL_MAX, an ordinary large number: adding to it produces garbage silently, and nothing marks it as missing except the plot setting PLOT_EMPTY_VALUE, which only tells the terminal not to draw it. Integer or floating-point division by zero is a critical runtime error that stops the indicator. So every place where Pine relies on na needs an explicit check in MQL5, as the basis != 0.0 guard above shows. Stratlate's generated code represents na internally as a NaN, which propagates like Pine's, routes any division whose divisor could be zero through a helper that returns na instead of stopping, and sets EMPTY_VALUE as each plot's empty value.

4. Types, state and arithmetic

Pine infers types and adds qualifiers (const, input, simple, series) that decide where a value may be used; for example ta.ema() needs a length that does not change from bar to bar. MQL5 is statically typed like C++: int, long, double, datetime, color, string, with no qualifier system.

Two consequences matter in practice. First, in Pine v6 7 / 2 is 3.5; in MQL5, dividing two integers truncates to 3, so write 7.0 / 2 or cast. Second, Pine's var (initialise once, carry forward) maps to a global or static variable only on closed bars. Because of the live-bar behaviour above, it is safer to derive the value from the previous bar's stored value:

var int ups = 0
if close > close[1]
    ups += 1
// A global "ups++" would add 1 on every TICK of the live bar.
// Derive the value from the previous bar's stored value instead,
// so recomputing bar i overwrites rather than accumulates.
UpsBuf[i] = (i > 0 ? UpsBuf[i - 1] : 0.0)
          + ((i > 0 && close[i] > close[i - 1]) ? 1.0 : 0.0);

5. Built-in indicators and inputs

Pine's ta.sma(), ta.rsi() and the rest return a value on the current bar. MQL5's built-ins such as iMA() and iRSI() return a handle; you create it once in OnInit() and read values with CopyBuffer(), after checking BarsCalculated(). Warm-up and seeding are not guaranteed to match TradingView bar for bar, so for an exact match many conversions compute the formula directly, as the SMA loop above does.

Inputs map closely: input.int(20, "Length") becomes input int InpLength = 20; // Length, where the trailing comment is the label shown in the Inputs tab. Unlike Pine, an MQL5 input is a constant at run time; assigning to it is a compile error. options = [...] lists map best to an enum used as the input's type.

6. Output and trading

Each plot() becomes an indicator buffer declared with #property indicator_buffers, indicator_plots and per-plot indicator_typeN/indicator_colorN. A colour that changes per bar needs a DRAW_COLOR_LINE plot with an extra colour-index buffer. line.new() and label.new() become chart objects created with ObjectCreate(). Some Pine features have no exact MetaTrader equivalent: an indicator in a separate window cannot recolour the main chart's candles, so a per-bar barcolor() or bgcolor() is an approximation.

Strategies differ most. A Pine strategy() runs inside TradingView's broker emulator: by default it evaluates on bar close and fills market orders at the next bar's open, with quantities in contracts, cash or percent of equity. An MQL5 Expert Advisor sends real orders from OnTick(), on every tick, in lots, and must handle the account type (netting keeps one position per symbol; hedging allows several). Stratlate converts a strategy() to an Expert Advisor that trades through the standard CTrade class; the strategy's plots are dropped because an EA has no indicator buffers, and the report says so.

Pitfalls

  • Reading close[i + 1] as the previous bar in MQL5. With default (non-series) arrays that is the next bar. Symptom: the line leads price, or "array out of range" on the newest bar.
  • Accumulating in a global on the live bar. Symptom: counters and running sums drift upward during the session and jump back after a chart refresh.
  • Treating EMPTY_VALUE as na in arithmetic. Symptom: values around 1.8e308, or a plot that shoots off the scale.
  • Integer division. Symptom: a smoothing factor such as 2 / (length + 1) evaluates to 0 and the line goes flat.
  • Using iMA() as if it returned a price. Symptom: a "value" equal to a small integer (the handle number).
  • Testing a strategy conversion only on a demo chart. Run it in the MT5 Strategy Tester and compare its trade list with TradingView's before going live.

FAQ

Is Pine Script easier than MQL5?

For indicators, usually yes: Pine handles the bar loop, history and missing values for you. MQL5 is a general-purpose C++-like language, so you write that machinery yourself but gain full control over orders, files, timers and multiple symbols.

Can every Pine Script be converted to MQL5?

Most indicator logic can, because MQL5 is the more general language. Some TradingView features have only approximate equivalents, such as recolouring main-chart candles from a separate-window indicator or the broker emulator's exact fill rules, so a converted script should be compiled, compared on the same data and backtested.

Why do my converted values differ from TradingView?

The usual causes are array direction (series vs non-series indexing), different warm-up or seeding of moving averages, missing-value handling, and different price data from your broker's feed. Compare on the same symbol, timeframe and bars before changing the logic.

Convert a Pine Script to MQL5

Paste a TradingView indicator or strategy and get MQL5 (or MQL4) source, with every construct that was approximated or could not be converted listed in the report.

Open the converter

Related guides