ta.kc in MQL5: Keltner Channels with an EMA basis

Short answer

MetaTrader 5 has no Keltner indicator. Compute an EMA of the source as the basis and bands at mult times an EMA of the range, both over the same length. The range is averaged with an EMA, not Wilder's ATR, and useTrueRange switches between true range and high - low.

ta.kc(source, length, mult, useTrueRange) returns Keltner Channels as a tuple: an EMA of the source as the middle line, and bands at mult times an EMA of the bar range above and below it. MetaTrader 5 ships no Keltner indicator and no iKeltner function. The equivalent is two EMAs in one loop, one of price and one of the range. Two details decide whether the port matches: the range is averaged with an EMA, not Wilder's ATR, and useTrueRange (default true) switches between the true range and plain high - low.

What ta.kc computes

basis    = ta.ema(source, length)
span     = useTrueRange ? ta.tr : high - low
rangeEma = ta.ema(span, length)
upper    = basis + rangeEma * mult
lower    = basis - rangeEma * mult

Both averages use the same length and the same EMA rule: alpha = 2 / (length + 1), seeded with the first non-na value. Nothing is na for length - 1 bars the way an SMA-based channel is; the lines start on the first bars and their early values depend on where the history begins. The plain ta.tr is na on the first bar of the chart, so with the true range the range EMA starts one bar later, on the second bar. The tuple order is middle, upper, lower. Many "Keltner" indicators published for MetaTrader use an SMA basis or an ATR band instead; those are different channels, not variants of the same number.

The MQL5 equivalent

//@version=6
indicator("Keltner Channels", overlay = true)
len   = input.int(20, "Length")
mult  = input.float(1.5, "Multiplier", step = 0.1)
useTr = input.bool(true, "Use true range")
[basis, upper, lower] = ta.kc(close, len, mult, useTr)
plot(basis, "Basis", color = color.orange)
plot(upper, "Upper", color = color.blue)
plot(lower, "Lower", color = color.blue)

A complete MQL5 indicator. Three plotted buffers carry the tuple, and a calculation buffer carries the range EMA between bars; arrays are oldest-first:

//+------------------------------------------------------------------+
//| ta.kc(source, length, mult, useTrueRange) -> [basis, upper, lower] |
//| basis = EMA(source), band = EMA(true range or high - low) * mult |
//+------------------------------------------------------------------+
#property indicator_chart_window
#property indicator_buffers 4
#property indicator_plots   3
#property indicator_type1   DRAW_LINE
#property indicator_label1  "Basis"
#property indicator_color1  clrOrange
#property indicator_type2   DRAW_LINE
#property indicator_label2  "Upper"
#property indicator_color2  clrDodgerBlue
#property indicator_type3   DRAW_LINE
#property indicator_label3  "Lower"
#property indicator_color3  clrDodgerBlue

input int    InpLength       = 20;   // length
input double InpMult         = 1.5;  // mult
input bool   InpUseTrueRange = true; // useTrueRange: false = high - low

double BasisBuffer[], UpperBuffer[], LowerBuffer[];
double RangeEmaBuffer[];              // EMA of the range, not drawn

int OnInit()
{
   SetIndexBuffer(0, BasisBuffer, INDICATOR_DATA);
   SetIndexBuffer(1, UpperBuffer, INDICATOR_DATA);
   SetIndexBuffer(2, LowerBuffer, INDICATOR_DATA);
   SetIndexBuffer(3, RangeEmaBuffer, INDICATOR_CALCULATIONS);
   for(int p = 0; p < 3; p++)
      PlotIndexSetDouble(p, PLOT_EMPTY_VALUE, EMPTY_VALUE);
   return InpLength > 0 ? INIT_SUCCEEDED : INIT_PARAMETERS_INCORRECT;
}

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 alpha = 2.0 / (InpLength + 1.0);
   int start = prev_calculated > 0 ? prev_calculated - 1 : 0;
   for(int i = start; i < rates_total; i++)
     {
      // basis: ta.ema(source, length), seeded with the first value
      BasisBuffer[i] = (i == 0) ? close[i]
                       : alpha * close[i] + (1.0 - alpha) * BasisBuffer[i - 1];

      // span: ta.tr (na on the first bar) or high - low
      double span;
      if(InpUseTrueRange)
        {
         if(i == 0)
            span = EMPTY_VALUE;
         else
            span = MathMax(high[i] - low[i],
                           MathMax(MathAbs(high[i] - close[i - 1]), MathAbs(low[i] - close[i - 1])));
        }
      else
         span = high[i] - low[i];

      // ta.ema(span, length): a na span keeps the previous EMA; the first valid span seeds it
      const double prevEma = (i > 0) ? RangeEmaBuffer[i - 1] : EMPTY_VALUE;
      if(span == EMPTY_VALUE)
         RangeEmaBuffer[i] = prevEma;
      else if(prevEma == EMPTY_VALUE)
         RangeEmaBuffer[i] = span;
      else
         RangeEmaBuffer[i] = alpha * span + (1.0 - alpha) * prevEma;

      if(RangeEmaBuffer[i] == EMPTY_VALUE)
        {
         UpperBuffer[i] = LowerBuffer[i] = EMPTY_VALUE;
         continue;
        }
      UpperBuffer[i] = BasisBuffer[i] + RangeEmaBuffer[i] * InpMult;
      LowerBuffer[i] = BasisBuffer[i] - RangeEmaBuffer[i] * InpMult;
     }
   return rates_total;
}

For a price source and useTrueRange = false you could take both averages from iMA MODE_EMA handles, one on PRICE_CLOSE and one on the range. There is no applied price for high - low or the true range, though, so the range EMA needs the loop either way.

Where the two differ

TopicPine ScriptMQL5
Native supportta.kcNone; no standard Keltner indicator
Band averageEMA of the range (not ta.atr)Whatever you write; iATR is an SMA of the true range and is a different channel
useTrueRangeDefault true; may be a series boolAn input or a per-bar condition in the loop
SeedingBoth EMAs start at the first non-na valueSame if coded as above; early values depend on the start of history on both platforms
Return valueTuple [basis, upper, lower]Three buffers plus one calculation buffer
Realtime barRecomputed each tick from the previous bar's EMAsSame when both EMAs read [i - 1] and the forming bar is redone

What the Stratlate converter emits

The engine expands the tuple at the call site: __tup0_basis = pine_ema(close, __st0, __pineBar, (int)(len)), the span written per bar into a materialised array (pine_tr(high, low, close, __pineBar) or high - low, chosen per bar when useTrueRange is not a literal, the true range when it is omitted), __tup1_range = pine_ema(<span array>, __st1, …), and the bands as basis ± range * mult. Each EMA has its own state array and seeds with its first non-na value. One small difference: the runtime's pine_tr returns high - low on the very first bar instead of na, so the converted range EMA starts one bar earlier than TradingView's; this only moves the seed, and its weight fades with the EMA. No note is written for it, and the script above converts CLEAN. Compile and backtest the output and compare bars well past the start of the history.

Pitfalls

  • Using iATR for the band. An SMA of the true range is a different width on every bar; channel touches and breakouts move.
  • Using Wilder's RMA for the band. Also a different channel. ta.kc averages the range with an EMA of the same length as the basis.
  • SMA basis. A middle line that lags too much and bands offset from TradingView's are the symptom.
  • Ignoring useTrueRange. With false gaps are ignored and the bands are narrower after gapping sessions; with true they widen on gaps.
  • Integer alpha. 2 / (InpLength + 1) is 0 with an int length; both EMAs freeze at their seeds.

FAQ

Is there a Keltner Channel indicator in MetaTrader 5?

Not among the standard indicators, and there is no iKeltner function. Code Base versions exist but vary in basis and band average, so check them against the formula above before relying on one to match TradingView.

Does ta.kc use ATR?

Not Wilder's ATR. With useTrueRange it averages the true range with an EMA of the given length; without it, the plain high - low range. A channel built on ta.atr or iATR is close but never equal.

Why do the first bars of my Keltner Channel differ from TradingView?

Both averages are EMAs seeded with their first value, and the two platforms' histories begin on different candles. The difference decays as (1 - alpha) to the power of the bar count; compare bars after five to ten times the length.

Convert the whole script

Paste a Pine Script indicator or strategy and get MQL5 with this and every other call mapped, checked against the original on the same bars, and every construct that could not be carried over reported.

Open the converter

Related