Keltner Channel: TradingView (Pine Script) to MT5 (MQL5)

Short answer

Keltner is an EMA of the close with bands a multiple of the average range above and below. Compute the EMA, true range and Wilder average by hand in MQL5: iMA seeds its EMA differently from ta.ema, and iATR is a simple average of true range, not Wilder's.

A Keltner Channel is an exponential moving average of the close with bands placed a multiple of the average range above and below it. TradingView's version offers a choice of range measure; the MQL5 port below keeps that choice and computes the same EMA, true range and Wilder average by hand, because MetaTrader's iMA seeds its EMA differently from Pine's ta.ema (so early bars differ), and its iATR is a simple average of the true range rather than Wilder's, so it differs from ta.atr on every bar.

How the Keltner Channel is calculated

Defaults: EMA length 20, multiplier 2, range length 10.

  • Basis = EMA(close, 20). Pine's ta.ema starts at the first close and then applies alpha = 2 / (length + 1).
  • Width, one of three: ta.atr(10) (true range smoothed with Wilder's RMA, seeded with an SMA of the first 10 true ranges); an EMA of the true range; or an EMA of high - low.
  • Upper / Lower = Basis ± 2 × Width.

True range is max(high - low, |high - close[1]|, |low - close[1]|); on the very first bar, where there is no previous close, ta.tr(true) uses high - low. The distinction between ATR and an EMA of true range is not cosmetic: Wilder's RMA uses alpha = 1/n while the EMA uses 2/(n+1), so with the same length the EMA variant reacts almost twice as fast and the bands are visibly more nervous.

Compared with Bollinger Bands, which use a simple moving average and a multiple of the standard deviation, Keltner bands are smoother and do not contract as sharply in quiet markets. That is why the two are combined in squeeze indicators: Bollinger inside Keltner means volatility has compressed.

Pine Script v6 version

An original script. The width is selected with a string input so all three variants can be compared on one chart by changing a setting.

//@version=6
indicator("Keltner Channel", shorttitle="KC", overlay=true)

length   = input.int(20, "EMA length", minval=1)
mult     = input.float(2.0, "Multiplier", minval=0.1, step=0.1)
atrLen   = input.int(10, "Range length", minval=1)
bandMode = input.string("ATR", "Band width", options=["ATR", "EMA of true range", "EMA of high-low"])

basis = ta.ema(close, length)
width = bandMode == "ATR" ? ta.atr(atrLen) :
        bandMode == "EMA of true range" ? ta.ema(ta.tr(true), atrLen) :
        ta.ema(high - low, atrLen)

upper = basis + mult * width
lower = basis - mult * width

plot(basis, "Basis", color=color.blue)
pUp = plot(upper, "Upper", color=color.teal)
pLo = plot(lower, "Lower", color=color.teal)
fill(pUp, pLo, color=color.new(color.teal, 92), title="Channel")

MQL5 version

Five buffers: three drawn, two for calculation (the raw range and its smoothed value). The string option becomes an enum input, which MetaTrader shows as a drop-down. All smoothing is written out so the seeding matches Pine: the EMA starts at the first value, and the ATR branch starts with a simple average at bar InpRange - 1 and switches to the Wilder recurrence from the next bar on.

//+------------------------------------------------------------------+
//| Keltner Channel: EMA basis +/- Multiplier * smoothed range        |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 5
#property indicator_plots   3
#property indicator_label1  "Basis"
#property indicator_type1   DRAW_LINE
#property indicator_color1  clrDodgerBlue
#property indicator_label2  "Upper"
#property indicator_type2   DRAW_LINE
#property indicator_color2  clrTeal
#property indicator_label3  "Lower"
#property indicator_type3   DRAW_LINE
#property indicator_color3  clrTeal

enum ENUM_KC_WIDTH
  {
   KC_ATR       = 0,  // ATR (Wilder)
   KC_EMA_TR    = 1,  // EMA of true range
   KC_EMA_RANGE = 2   // EMA of high-low
  };

input int           InpLength = 20;      // EMA length
input double        InpMult   = 2.0;     // Multiplier
input int           InpRange  = 10;      // Range length
input ENUM_KC_WIDTH InpWidth  = KC_ATR;  // Band width

double BasisBuf[], UpperBuf[], LowerBuf[];
double RangeBuf[], WidthBuf[];           // raw range and its smoothed value

int OnInit()
  {
   if(InpLength < 1 || InpRange < 1 || InpMult <= 0.0)
      return INIT_PARAMETERS_INCORRECT;
   SetIndexBuffer(0, BasisBuf, INDICATOR_DATA);
   SetIndexBuffer(1, UpperBuf, INDICATOR_DATA);
   SetIndexBuffer(2, LowerBuf, INDICATOR_DATA);
   SetIndexBuffer(3, RangeBuf, INDICATOR_CALCULATIONS);
   SetIndexBuffer(4, WidthBuf, INDICATOR_CALCULATIONS);
   // Pine's ta.ema is defined from bar 0; ta.atr is na for the first Range-1 bars.
   int bandBegin = (InpWidth == KC_ATR) ? InpRange - 1 : 0;
   PlotIndexSetInteger(1, PLOT_DRAW_BEGIN, bandBegin);
   PlotIndexSetInteger(2, PLOT_DRAW_BEGIN, bandBegin);
   for(int p = 0; p < 3; p++)
      PlotIndexSetDouble(p, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   IndicatorSetString(INDICATOR_SHORTNAME, "KC(" + IntegerToString(InpLength) + ","
                      + DoubleToString(InpMult, 1) + "," + IntegerToString(InpRange) + ")");
   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[])
  {
   const double aBasis = 2.0 / (InpLength + 1.0);
   const double aRange = 2.0 / (InpRange + 1.0);
   int start = (prev_calculated > 0) ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
     {
      // Basis: EMA seeded with the first close, exactly as ta.ema does.
      BasisBuf[i] = (i == 0) ? close[i] : aBasis * close[i] + (1.0 - aBasis) * BasisBuf[i - 1];

      // Raw range for this bar. ta.tr(true) uses high-low on the first bar.
      if(InpWidth == KC_EMA_RANGE || i == 0)
         RangeBuf[i] = high[i] - low[i];
      else
         RangeBuf[i] = MathMax(high[i] - low[i],
                               MathMax(MathAbs(high[i] - close[i - 1]),
                                       MathAbs(low[i]  - close[i - 1])));

      // Smoothed range.
      if(InpWidth == KC_ATR)
        {
         // Wilder RMA, seeded with the SMA of the first Range true ranges (ta.atr / ta.rma).
         if(i < InpRange - 1)
            WidthBuf[i] = EMPTY_VALUE;
         else if(i == InpRange - 1)
           {
            double sum = 0.0;
            for(int k = 0; k < InpRange; k++)
               sum += RangeBuf[i - k];
            WidthBuf[i] = sum / InpRange;
           }
         else
            WidthBuf[i] = (WidthBuf[i - 1] * (InpRange - 1) + RangeBuf[i]) / InpRange;
        }
      else
         WidthBuf[i] = (i == 0) ? RangeBuf[i] : aRange * RangeBuf[i] + (1.0 - aRange) * WidthBuf[i - 1];

      if(WidthBuf[i] == EMPTY_VALUE)
        {
         UpperBuf[i] = EMPTY_VALUE;
         LowerBuf[i] = EMPTY_VALUE;
        }
      else
        {
         UpperBuf[i] = BasisBuf[i] + InpMult * WidthBuf[i];
         LowerBuf[i] = BasisBuf[i] - InpMult * WidthBuf[i];
        }
     }
   return rates_total;
  }

The EMPTY_VALUE sentinel plays the role of na: the width buffer holds it until the ATR has enough bars, and the band buffers copy it so nothing is drawn. The basis has no warm-up because ta.ema has none either.

Differences you will see on the chart

TradingViewMetaTrader 5 (this port)
Basis on the first barsDefined from bar 0; converges towards the "true" EMA over roughly 3 × length barsIdentical, because the port seeds with the first close like ta.ema. Using iMA(..., MODE_EMA) instead would differ on early bars
ATR widthna for the first 9 bars, SMA seed on bar 10EMPTY_VALUE for the first 9 bars, SMA seed on bar 10. The terminal's own ATR is not a drop-in: the ATR.mq5 source shipped in Indicators\Examples sets the first bar's true range to 0, produces its first value one bar later, and then averages the true range with a plain moving average rather than Wilder's recurrence
Values after warm-up—Match to floating-point precision on closed bars; both recurrences are evaluated in the same order
Fill between bandsfill()Not included; add a DRAW_FILLING plot if you want it
Realtime barRecomputed on every tickBar rates_total - 1 recomputed on every tick, reading BasisBuf[i-1] which is already final

If your TradingView chart has less history than your MT5 chart (or the other way round), the EMA and the Wilder average start from different first bars and the two basis lines differ slightly until they converge. This is a property of recursive averages, not a bug in either program; see moving averages in Pine vs MQL5.

Using it in MetaTrader 5

Save as Keltner.mq5 under MQL5\Indicators, compile with F7 in MetaEditor, and attach from the Navigator. The Band width input is a drop-down with the three variants. From an EA, iCustom(_Symbol, _Period, "Keltner", 20, 2.0, 10, 0) creates the handle (the last argument is the enum value, 0 for ATR), and buffers 0, 1 and 2 are Basis, Upper and Lower. Buffers 3 and 4 are calculation buffers and can also be read with CopyBuffer, which is a cheap way to get the ATR with Pine seeding into an EA.

What the Stratlate converter emits

The Pine version above converts CLEAN. ta.ema(close, length) becomes a stateful runtime call, pine_ema, that carries the previous bar's value in a hidden buffer and seeds with the first value; ta.atr becomes pine_atr_c, which stores the true range in one buffer and the Wilder average, seeded with an SMA, in another. Because the three range measures sit on the branches of a ternary, each call is reached only on the bars where its branch is selected, and the engine gives each one its own per-call history (the _c/_step forms with a pine_cpos counter) rather than sharing one buffer. input.string with options= becomes an enum input with one member per option, and fill() becomes a DRAW_FILLING plot. The notes are informational only: minval/step on inputs are dropped. The output is verified bar by bar against the original on the same data; compile it and compare on your own symbol before trading on it.

Pitfalls

  • Replacing the basis with iMA(_Symbol, _Period, 20, 0, MODE_EMA, PRICE_CLOSE). The values converge, but the first hundred or so bars differ from TradingView and a backtest that starts there sees different signals.
  • Using iATR for the width and expecting a match with ta.atr. The bundled ATR.mq5 source averages the true range with a simple moving average and starts one bar later than Pine, whereas ta.atr is Wilder's recurrence seeded with an SMA. The two never line up bar for bar; the hand-written buffer above is the safe choice.
  • Choosing "EMA of true range" in one platform and "ATR" in the other. Same length, different alpha: the bands are about twice as responsive and the channel looks wrong even though both programs are correct.
  • Forgetting PLOT_DRAW_BEGIN for the bands. The terminal draws a line from EMPTY_VALUE at the first bars unless PLOT_EMPTY_VALUE is set, which this version does, or draw-begin skips them.
  • Letting the multiplier be 0 or negative. Pine refuses via minval; MQL5 has no such attribute, so the check lives in OnInit and returns INIT_PARAMETERS_INCORRECT.

FAQ

Does MetaTrader 5 have a built-in Keltner Channel?

No. Envelopes (a percentage band around a moving average) ship with the terminal, Keltner does not. The indicator above is the complete replacement; it uses no includes and compiles as is.

Which width setting should I pick to match a TradingView chart?

Open the settings of the Keltner Channel on that chart and read its band style, band length and basis type, then set the same here. An average true range corresponds to the ATR option; a range smoothed with an exponential average corresponds to one of the two EMA options. If the chart smooths with Wilder's average or a simple average instead, change the smoothing line in the MQL5 version to match, since the band style alone does not determine the values.

Why do my Keltner bands in MT5 differ from TradingView only at the left edge of the chart?

Because both the EMA and the Wilder average are recursive and start from the first bar each platform has. If the two charts begin at different dates, the averages start from different values and converge over a few hundred bars. Load the same history range, or compare only bars well after the start.

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