ATR Trailing Stop: TradingView (Pine Script) to MT5 (MQL5)

Short answer

The stop follows price at keyValue × ATR, moves only toward price while price stays on one side, and flips when a bar closes through it. Written with the same recurrence, the Pine Script v6 and MQL5 versions give the same line and the same buy and sell flips after the ATR warm-up.

An ATR trailing stop is a line that follows price at a distance of keyValue × ATR, moves only toward price while price stays on one side, and jumps to the other side when a bar closes through it. Scripts of this shape are often called "UT Bot" style. The version below, written from scratch in Pine Script v6 and in MQL5, gives the same line and the same buy/sell flips after the ATR warm-up.

How the ATR trailing stop is calculated

Inputs: keyValue (default 1.0, the ATR multiple), atrLen (default 10) and a source src (default close). Each bar:

  • loss = keyValue × ATR(atrLen), with Wilder's ATR: true range averaged by ta.rma, seeded with a simple average of the first atrLen true ranges.
  • prev = nz(trail[1]), the previous line, or 0 on the first bars.
  • If src and src[1] are both above prev: trail = max(prev, src - loss). The stop rises or holds; it never falls while price stays above it.
  • If both are below prev: trail = min(prev, src + loss).
  • Otherwise price has just crossed the line: trail = src > prev ? src - loss : src + loss, placing the line on the new side.
  • side = src > trail ? 1 : -1. A buy marker appears when side turns from -1 to 1, a sell marker when it turns from 1 to -1.

Because prev is 0 before the line exists, the first bar with an ATR value sees src > 0 and starts the line below price. The direction on that bar is treated as undefined so that it does not produce a false buy marker.

Pine Script v6 version

trail is a var so that its previous value survives into the next bar; nz() turns the first na into 0, which is the behaviour the recurrence relies on.

//@version=6
indicator("ATR trailing stop", "ATR TS", overlay = true)

keyValue = input.float(1.0, "Key value (ATR multiple)", minval = 0.1, step = 0.1)
atrLen   = input.int(10, "ATR length", minval = 1)
src      = input.source(close, "Source")

float loss = keyValue * ta.atr(atrLen)

// The line trails price: it ratchets toward price while price stays on one
// side, and jumps to the other side of price after a close through it.
var float trail = na
float prev = nz(trail[1])
bool aboveBoth = src > prev and src[1] > prev
bool belowBoth = src < prev and src[1] < prev
trail := aboveBoth ? math.max(prev, src - loss) :
         belowBoth ? math.min(prev, src + loss) :
         src > prev ? src - loss : src + loss

int side = na(trail) ? na : (src > trail ? 1 : -1)
bool buy  = side == 1 and side[1] == -1
bool sell = side == -1 and side[1] == 1

plot(trail, "Trailing stop", side == 1 ? color.green : color.red, 2)
plotshape(buy, "Buy", shape.labelup, location.belowbar, color.green, text = "Buy", textcolor = color.white, size = size.small)
plotshape(sell, "Sell", shape.labeldown, location.abovebar, color.red, text = "Sell", textcolor = color.white, size = size.small)
alertcondition(buy, "ATR stop buy", "Price crossed above the ATR trailing stop")
alertcondition(sell, "ATR stop sell", "Price crossed below the ATR trailing stop")

During the ATR warm-up loss is na, so math.max(prev, src - loss) is na and the line is not drawn; side is explicitly na on those bars so the first real bar is not a "flip".

MQL5 version

The MQL5 indicator carries the line, the ATR and the side in per-bar buffers. prev is read from Trail[i - 1] with 0 substituted for EMPTY_VALUE, which is the literal translation of nz(trail[1]). The line is a DRAW_COLOR_LINE (green while price is above, red below) and the flips are two DRAW_ARROW buffers.

//+------------------------------------------------------------------+
//| ATRTrailingStop_TV.mq5 - ATR trailing stop with buy/sell flips   |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 8
#property indicator_plots   3
#property indicator_label1  "Trailing stop"
#property indicator_type1   DRAW_COLOR_LINE
#property indicator_color1  clrGreen, clrRed
#property indicator_width1  2
#property indicator_label2  "Buy"
#property indicator_type2   DRAW_ARROW
#property indicator_color2  clrGreen
#property indicator_width2  2
#property indicator_label3  "Sell"
#property indicator_type3   DRAW_ARROW
#property indicator_color3  clrRed
#property indicator_width3  2

input double             InpKey    = 1.0;         // Key value (ATR multiple)
input int                InpAtrLen = 10;          // ATR length
input ENUM_APPLIED_PRICE InpPrice  = PRICE_CLOSE; // Source

double Trail[], TrailColor[], BuyArrow[], SellArrow[];   // drawn
double Src[], Tr[], Atr[], Side[];                       // per-bar state

int OnInit()
{
   if(InpAtrLen < 1 || InpKey <= 0.0)
      return INIT_PARAMETERS_INCORRECT;
   SetIndexBuffer(0, Trail,      INDICATOR_DATA);
   SetIndexBuffer(1, TrailColor, INDICATOR_COLOR_INDEX);
   SetIndexBuffer(2, BuyArrow,   INDICATOR_DATA);
   SetIndexBuffer(3, SellArrow,  INDICATOR_DATA);
   SetIndexBuffer(4, Src,  INDICATOR_CALCULATIONS);
   SetIndexBuffer(5, Tr,   INDICATOR_CALCULATIONS);
   SetIndexBuffer(6, Atr,  INDICATOR_CALCULATIONS);
   SetIndexBuffer(7, Side, INDICATOR_CALCULATIONS);
   PlotIndexSetDouble(0, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetDouble(1, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetDouble(2, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   PlotIndexSetInteger(1, PLOT_ARROW, 233);
   PlotIndexSetInteger(2, PLOT_ARROW, 234);
   IndicatorSetString(INDICATOR_SHORTNAME, "ATR stop(" + DoubleToString(InpKey, 1) + "," + (string)InpAtrLen + ")");
   return INIT_SUCCEEDED;
}

double Price(const int i, const double &open[], const double &high[],
             const double &low[], const double &close[])
{
   switch(InpPrice)
   {
      case PRICE_OPEN:     return open[i];
      case PRICE_HIGH:     return high[i];
      case PRICE_LOW:      return low[i];
      case PRICE_MEDIAN:   return (high[i] + low[i]) / 2.0;
      case PRICE_TYPICAL:  return (high[i] + low[i] + close[i]) / 3.0;
      case PRICE_WEIGHTED: return (high[i] + low[i] + 2.0 * close[i]) / 4.0;
      default:             return close[i];
   }
}

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[])
{
   int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
   {
      Src[i] = Price(i, open, high, low, close);

      // Wilder ATR seeded with a simple average, as ta.atr does
      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;

      BuyArrow[i] = EMPTY_VALUE; SellArrow[i] = EMPTY_VALUE;
      if(Atr[i] == EMPTY_VALUE)
      {
         Trail[i] = EMPTY_VALUE; TrailColor[i] = 1; Side[i] = 0;
         continue;
      }

      double loss = InpKey * Atr[i];
      double prev = (i > 0 && Trail[i - 1] != EMPTY_VALUE) ? Trail[i - 1] : 0.0;   // nz(trail[1])
      double src  = Src[i];
      double src1 = (i > 0) ? Src[i - 1] : src;

      if(src > prev && src1 > prev)       Trail[i] = MathMax(prev, src - loss);   // ratchet up
      else if(src < prev && src1 < prev)  Trail[i] = MathMin(prev, src + loss);   // ratchet down
      else                                Trail[i] = (src > prev) ? src - loss : src + loss;   // flip

      Side[i] = (src > Trail[i]) ? 1 : -1;
      TrailColor[i] = (Side[i] == 1) ? 0 : 1;
      if(i > 0 && Side[i] == 1 && Side[i - 1] == -1)  BuyArrow[i]  = low[i];
      if(i > 0 && Side[i] == -1 && Side[i - 1] == 1)  SellArrow[i] = high[i];
   }
   return rates_total;
}

Side[i] is 0 on warm-up bars, so the first bar with a line cannot trigger an arrow, matching the Pine na. Everything else reads bar i - 1 only, which keeps the realtime bar recomputation idempotent.

Differences you will see on the chart

TopicTradingViewMetaTrader 5
Warm-upNo line for the first atrLen - 1 bars.Same bars are EMPTY_VALUE.
Early valuesThe ATR seed depends on which bars each platform loaded first, and the trailing line is path dependent: a slightly different ATR can delay or advance one flip, after which the two lines run on different sides until the next flip. Compare recent bars; after the seed decays (a few hundred bars for atrLen = 10) flips coincide.
Markersplotshape labels with text "Buy"/"Sell".Arrow buffers (Wingdings 233/234) at the bar's low/high; add text objects if you need the words.
Realtime barThe line and a possible flip change with every tick until the bar closes.Same; the arrow on the open bar can disappear before close in both.
SourceAny series via input.source.Applied price enum; an external series needs its own buffer.

Closed bars do not repaint on either platform.

What the Stratlate converter does with this script

Converted with the Stratlate engine, the Pine script above is graded CLEAN. ta.atr becomes pine_atr_hlc (true range with Wilder smoothing seeded by a simple average); the var float trail becomes a per-bar array read through pine_hist, with nz emitted as pine_nz; input.source becomes an ENUM_APPLIED_PRICE input evaluated with pine_source; the coloured plot becomes a DRAW_COLOR_LINE; and each plotshape becomes a DRAW_ARROW buffer with its "Buy"/"Sell" text drawn as a chart text object by pine_shape_text. alertcondition is kept as pine_alertcond, which raises an MT5 alert once per bar on the live bar. Informational notes (PM221) say that step and minval have no MQL input field. Compile and backtest the result before trading it.

Using it in MetaTrader 5

  1. Save as ATRTrailingStop_TV.mq5 in MQL5\Indicators, compile (F7, no warnings), attach to a chart and set Key value and ATR length to the TradingView values.
  2. In an EA, iCustom(_Symbol, _Period, "ATRTrailingStop_TV", InpKey, InpAtrLen, PRICE_CLOSE). Buffer 2 is the buy arrow, buffer 3 the sell arrow; buffer 7 (Side) is 1 or -1 and is the simplest way to know which side of the line the market is on. Read bar 1 (the last closed bar) rather than bar 0 to avoid acting on a flip that is cancelled before the close.
  3. For a stop-loss, the line value on the last closed bar is a natural level: CopyBuffer(handle, 0, 1, 1, value) and place the stop there.
  4. Alerts: inside the loop, when i == rates_total - 1 and BuyArrow[i] != EMPTY_VALUE, call Alert(), guarded by the bar time so it fires once.

Pitfalls

  • Replacing nz(trail[1]) with the current price. The 0 matters: it makes the line start on the correct side on the first bar. Substituting src moves the first flip and the error propagates.
  • Keeping trail in a scalar. A static double updated on each tick ratchets several times per bar on the live candle. Use a buffer indexed by bar and recompute from Trail[i - 1].
  • Taking the ATR from iATR. MetaTrader's standard ATR does not smooth the true range the way ta.rma does, so the distance to price differs and flips shift. Compute it as shown.
  • Comparing src with the current line to detect the flip. The flip test in the recurrence uses prev; the side uses the new line. Swapping them produces a line that sits on the wrong side for one bar after each flip.
  • Acting on bar 0. The line on the open bar moves with every tick, and a buy arrow can appear and vanish. EAs should read the last closed bar.

FAQ

Is this the same as the "UT Bot" indicator?

It uses the same trailing-stop recurrence that UT Bot style scripts are built on: key value times ATR, a line that ratchets toward price, and a flip when price closes through it. The code here is written independently and omits extras such as a Heikin Ashi source or an EMA cross filter; add those on top if your script has them.

Why do the buy and sell markers differ from TradingView on the first part of the chart?

The line is path dependent: each value is built from the previous one. A small difference in the ATR seed on the first bars changes one early flip, and from there the two lines are on different sides until the next unambiguous cross. Compare the recent part of the chart.

Can I use the line value as a stop-loss in an EA?

Yes. Read buffer 0 on the last closed bar with CopyBuffer and use it as the stop level; the line only moves in your favour while the trade is open, which is what a trailing stop should do.

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