Supertrend: TradingView (Pine Script) to MT5 (MQL5)

Short answer

Supertrend is an ATR band below price in an uptrend and above it in a downtrend, switching sides when a bar closes through it. Written with the same recurrence, Pine v6 and MQL5 match bar for bar after the ATR warm-up, provided MQL5 computes Wilder's ATR itself instead of calling iATR.

Supertrend draws one line: an ATR band below price in an uptrend and above price in a downtrend, switching sides when a bar closes through it. The same recurrence written in Pine Script v6 and in MQL5 gives the same line bar for bar once the ATR has warmed up, provided the MQL5 side computes Wilder's ATR itself instead of calling iATR.

How Supertrend is calculated

With atrLen (default 10) and a multiplier mult (default 3), every bar computes two raw bands around the bar's midpoint hl2 = (high + low) / 2:

  • upRaw = hl2 + mult * ATR(atrLen) and dnRaw = hl2 - mult * ATR(atrLen).
  • Ratchet. The upper band may only move down and the lower band only up, until the previous bar's close has crossed the band: upBand = (upRaw < upBand[1] or close[1] > upBand[1]) ? upRaw : upBand[1], and symmetrically for dnBand with the comparisons reversed.
  • Direction. While the trend is bearish (dir = 1) the indicator watches the upper band and flips to bullish (dir = -1) when close > upBand. While bullish it watches the lower band and flips to bearish when close < dnBand. On the first bar that has an ATR value the direction is forced to 1.
  • The plotted value is upBand when dir = 1 and dnBand when dir = -1.

The ATR is Wilder's: the true range max(high - low, |high - close[1]|, |low - close[1]|) averaged with ta.rma, which seeds with a simple average of the first atrLen true ranges and then applies atr = (atr[1] * (atrLen - 1) + tr) / atrLen. The sign convention (1 = bearish, -1 = bullish) is the one TradingView's ta.supertrend returns, so a script that uses the built-in can be compared directly against the written-out version.

Pine Script v6 version

The recurrence is spelled out instead of calling ta.supertrend, so every line has a one-to-one counterpart in the MQL5 code below. The bands self-reference through upBand[1], which is why they are declared before being reassigned with :=.

//@version=6
indicator("Supertrend, written out", "ST", overlay = true)

atrLen = input.int(10, "ATR length", minval = 1)
mult   = input.float(3.0, "ATR multiplier", minval = 0.1, step = 0.1)

float atr   = ta.atr(atrLen)
float upRaw = hl2 + mult * atr
float dnRaw = hl2 - mult * atr

// A band may only tighten. It resets to the raw value once the previous
// close has moved through it.
float upBand = upRaw
float dnBand = dnRaw
upBand := na(upBand[1]) or upRaw < upBand[1] or close[1] > upBand[1] ? upRaw : upBand[1]
dnBand := na(dnBand[1]) or dnRaw > dnBand[1] or close[1] < dnBand[1] ? dnRaw : dnBand[1]

// 1 = price under the upper band (bearish), -1 = price over the lower band
// (bullish). Same sign convention as ta.supertrend.
var int dir = 1
if na(atr[1])
    dir := 1
else if dir[1] == 1
    dir := close > upBand ? -1 : 1
else
    dir := close < dnBand ? 1 : -1

float st = dir == 1 ? upBand : dnBand
bool flipUp   = dir == -1 and dir[1] == 1
bool flipDown = dir == 1 and dir[1] == -1

plot(dir == 1 ? st : na, "Bearish", color.red, 2, plot.style_linebr)
plot(dir == -1 ? st : na, "Bullish", color.green, 2, plot.style_linebr)
plotshape(flipUp, "Flip up", shape.triangleup, location.belowbar, color.green, size = size.small)
plotshape(flipDown, "Flip down", shape.triangledown, location.abovebar, color.red, size = size.small)
alertcondition(flipUp, "Supertrend bullish", "Supertrend flipped up")
alertcondition(flipDown, "Supertrend bearish", "Supertrend flipped down")

The na(upBand[1]) test covers the first bar with an ATR, where the history is empty. TradingView's reference writes the same thing with nz(upBand[1]), which turns the missing value into 0 and lets close[1] > 0 pick the raw band; the result is identical.

MQL5 version

The MQL5 indicator keeps its state in per-bar calculation buffers (Upper, Lower, Dir, Atr, Tr) rather than in static variables. Every bar reads only bar i - 1, so recomputing the current bar on each tick cannot double-apply the ratchet. The arrays are left oldest-first, the default in OnCalculate, so i - 1 is the previous bar exactly like Pine's [1].

//+------------------------------------------------------------------+
//| Supertrend_TV.mq5 - Supertrend with the same values as Pine      |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 9
#property indicator_plots   4
#property indicator_label1  "Bearish"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrRed
#property indicator_width1  2
#property indicator_label2  "Bullish"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrGreen
#property indicator_width2  2
#property indicator_label3  "Flip up"
#property indicator_type3   DRAW_ARROW
#property indicator_color3  clrGreen
#property indicator_label4  "Flip down"
#property indicator_type4   DRAW_ARROW
#property indicator_color4  clrRed

input int    InpAtrLen = 10;   // ATR length
input double InpMult   = 3.0;  // ATR multiplier

double BearBuf[], BullBuf[], UpArrow[], DnArrow[];   // drawn
double Atr[], Tr[], Upper[], Lower[], Dir[];         // per-bar state

int OnInit()
{
   if(InpAtrLen < 1 || InpMult <= 0.0)
      return INIT_PARAMETERS_INCORRECT;
   SetIndexBuffer(0, BearBuf, INDICATOR_DATA);
   SetIndexBuffer(1, BullBuf, INDICATOR_DATA);
   SetIndexBuffer(2, UpArrow, INDICATOR_DATA);
   SetIndexBuffer(3, DnArrow, INDICATOR_DATA);
   SetIndexBuffer(4, Atr,   INDICATOR_CALCULATIONS);
   SetIndexBuffer(5, Tr,    INDICATOR_CALCULATIONS);
   SetIndexBuffer(6, Upper, INDICATOR_CALCULATIONS);
   SetIndexBuffer(7, Lower, INDICATOR_CALCULATIONS);
   SetIndexBuffer(8, Dir,   INDICATOR_CALCULATIONS);
   for(int p = 0; p < 4; p++)
      PlotIndexSetDouble(p, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetInteger(2, PLOT_ARROW, 233);   // up arrow
   PlotIndexSetInteger(3, PLOT_ARROW, 234);   // down arrow
   IndicatorSetString(INDICATOR_SHORTNAME, "Supertrend(" + (string)InpAtrLen + "," + DoubleToString(InpMult, 1) + ")");
   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[])
{
   // Arrays are oldest-first: index 0 is the oldest bar, rates_total-1 the
   // current one. Recomputing the current bar on every tick is safe because
   // each bar only reads bar i-1.
   int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
   {
      // True range, then Wilder's average seeded with a simple mean (ta.atr)
      Tr[i] = (i == 0) ? high[i] - low[i]
            : MathMax(high[i] - low[i], MathMax(MathAbs(high[i] - close[i - 1]), MathAbs(low[i] - close[i - 1])));
      if(i < InpAtrLen - 1)
         Atr[i] = EMPTY_VALUE;
      else if(i == InpAtrLen - 1)
      {
         double sum = 0.0;
         for(int k = 0; k < InpAtrLen; k++) sum += Tr[i - k];
         Atr[i] = sum / InpAtrLen;
      }
      else
         Atr[i] = (Atr[i - 1] * (InpAtrLen - 1) + Tr[i]) / InpAtrLen;

      BearBuf[i] = EMPTY_VALUE; BullBuf[i] = EMPTY_VALUE;
      UpArrow[i] = EMPTY_VALUE; DnArrow[i] = EMPTY_VALUE;
      if(Atr[i] == EMPTY_VALUE)
      {
         Upper[i] = EMPTY_VALUE; Lower[i] = EMPTY_VALUE; Dir[i] = 1;
         continue;
      }

      double mid   = (high[i] + low[i]) / 2.0;             // hl2
      double upRaw = mid + InpMult * Atr[i];
      double dnRaw = mid - InpMult * Atr[i];
      bool havePrev = (i > 0 && Upper[i - 1] != EMPTY_VALUE); // Pine: not na(atr[1])

      // A band may only tighten until the previous close moves through it
      Upper[i] = (!havePrev || upRaw < Upper[i - 1] || close[i - 1] > Upper[i - 1]) ? upRaw : Upper[i - 1];
      Lower[i] = (!havePrev || dnRaw > Lower[i - 1] || close[i - 1] < Lower[i - 1]) ? dnRaw : Lower[i - 1];

      // 1 = bearish (upper band active), -1 = bullish (lower band active)
      if(!havePrev)              Dir[i] = 1;
      else if(Dir[i - 1] == 1)   Dir[i] = (close[i] > Upper[i]) ? -1 : 1;
      else                       Dir[i] = (close[i] < Lower[i]) ? 1 : -1;

      if(Dir[i] == 1) BearBuf[i] = Upper[i]; else BullBuf[i] = Lower[i];
      if(havePrev && Dir[i] == -1 && Dir[i - 1] == 1) UpArrow[i] = low[i];
      if(havePrev && Dir[i] == 1 && Dir[i - 1] == -1) DnArrow[i] = high[i];
   }
   return rates_total;
}

Four drawn buffers stand in for the two Pine plots and two plotshape calls: a bearish line, a bullish line and two arrow buffers (Wingdings 233 and 234) placed at the bar's low or high. EMPTY_VALUE in a DRAW_LINE buffer leaves a gap, which gives the same look as plot.style_linebr with na.

Differences you will see on the chart

TopicTradingViewMetaTrader 5
Warm-upBars 0 to atrLen - 2 are na; the line starts on bar atrLen - 1 with direction 1.Same bars are EMPTY_VALUE; the first drawn value is the upper band on bar atrLen - 1.
History depthThe ATR seed depends on the first bars of the loaded history.Same, but MT5 loads a different number of bars (Max bars in chart). Early values differ until the seed has decayed; after roughly 5 to 10 times atrLen the lines agree. Because the direction state depends on the past, a seed difference that changes one early flip can shift later flips too, so compare recent bars.
ColourTwo plots in red and green.Two line buffers with their own indicator_color; no colour buffer is needed.
Realtime barRecalculated on each tick; a flip can appear and vanish before the bar closes.Identical behaviour: prev_calculated - 1 recomputes the current bar on each tick.
Alertsalertcondition appears in the alert dialog.Not built in; add Alert() on Dir[rates_total-1] != Dir[rates_total-2] or read the arrow buffers from an EA.

Neither version repaints closed bars: once a bar is finished, its bands and direction depend only on data up to that bar.

What the Stratlate converter does with this script

Converted with the Stratlate engine, the Pine script above is graded CLEAN. ta.atr becomes the runtime helper pine_atr_hlc (true range plus Wilder smoothing seeded with a simple average), the self-referencing bands and the var int dir become per-bar arrays read through pine_hist, the two plots become DRAW_LINE buffers with their colours set in OnInit, and the plotshape calls become DRAW_ARROW buffers. The report carries informational notes (PM221) that input options such as step have no MQL input equivalent. A script that calls ta.supertrend(factor, atrPeriod) instead is mapped to the runtime helpers pine_supertrend and pine_supertrend_dir, which implement the same recurrence. Either way, compile the output and backtest it against the TradingView chart before trading it.

Using it in MetaTrader 5

  1. Save the MQL5 code as Supertrend_TV.mq5 under MQL5\Indicators, open it in MetaEditor and press F7. It compiles without warnings.
  2. Drag it onto a chart from the Navigator. Set ATR length and ATR multiplier to the values used on TradingView (10 and 3 by default).
  3. To trade it from an Expert Advisor, create the handle with iCustom(_Symbol, _Period, "Supertrend_TV", InpAtrLen, InpMult) and read buffer 2 (flip up) and 3 (flip down); a value other than EMPTY_VALUE on the last closed bar is a signal.
  4. For a chart alert, add if(i == rates_total - 1 && UpArrow[i] != EMPTY_VALUE) Alert("Supertrend flipped up") inside the loop; wrap it in a check on the bar time so the alert fires once per bar.

Pitfalls

  • Using iATR for the band width. MetaTrader's standard ATR smooths the true range differently from ta.rma, so the bands and every flip timing drift from TradingView. Compute the true range and the Wilder recursion yourself, as above.
  • Comparing against the current band. The ratchet compares the previous close with the previous band (close[1] vs upBand[1]), but the flip compares the current close with the current band. Mixing the two produces a line that flips one bar early or late.
  • Storing state in static variables. A static double upper updated on each tick applies the ratchet several times per bar on the realtime bar, so the line creeps. Use a calculation buffer indexed by bar.
  • Calling ArraySetAsSeries on the price arrays and then still writing i - 1 for the previous bar. After the flip, the previous bar is i + 1; the loop must be rewritten, not just the indexing.
  • Judging the port by the first bars. The two platforms seed the ATR from different first bars, so the first hundred bars differ by design. Compare recent bars.

FAQ

Why does the MQL5 Supertrend flip on a different bar than TradingView near the start of the chart?

The ATR seed is the simple average of the first ten true ranges in whatever history each platform loaded, and a different seed moves the bands slightly. If the price closes within that difference of a band, one platform flips and the other does not, and the direction state then diverges until the next unambiguous flip. On recent bars both versions agree.

Can I use ta.supertrend instead of writing the recurrence out?

Yes. ta.supertrend(mult, atrLen) returns the same two values as st and dir above with the same sign convention. Writing it out matters only when porting by hand, because MQL5 has no built-in Supertrend and the spelled-out version maps line by line.

Does MetaTrader draw the gap between the red and green segments like plot.style_linebr?

Yes. A DRAW_LINE buffer does not connect across EMPTY_VALUE, so setting the inactive buffer to EMPTY_VALUE on each bar leaves the same break between the two colours that TradingView shows.

Convert your own version

Have a variant of this indicator, or any other TradingView script? Paste it and get MQL5 that is checked against the original on the same price history, with every construct that could not be carried over reported.

Open the converter

Related