Skip to Content
While25SDK docs
ExamplesIndicators

Keltner channel: an average with a band of average true ranges

An exponential average of the close, with an upper and a lower line a multiple of the average true range away, the space between them shaded. It draws on the price itself, and the breakout strategy in `strategies/keltner_breakout.py` reads the same numbers from its own bars.

An exponential average of the close, with an upper and a lower line a multiple of the average true range away, the space between them shaded. It draws on the price itself, and the breakout strategy in strategies/keltner_breakout.py reads the same numbers from its own bars.

Shows: Indicator, overlay=True, three Plots, Fill, a warmup callable of the params, while25.bars, self.times, pure helpers a strategy can import.

View on GitHub

indicators/keltner_channel.py
"""Keltner channel: an average with a band of average true ranges

An exponential average of the close, with an upper and a lower line a
multiple of the average true range away, the space between them shaded. It
draws on the price itself, and the breakout strategy in
`strategies/keltner_breakout.py` reads the same numbers from its own bars.

Shows: Indicator, overlay=True, three Plots, Fill, a warmup callable of the params, while25.bars, self.times, pure helpers a strategy can import.
"""
import while25
from while25 import Fill, Indicator, Plot
from while25.inputs import Float, Int


def ema(values, n):
    """Exponential average, seeded with the mean of the first n values;
    None before that."""
    out = [None] * len(values)
    if n < 1 or len(values) < n:
        return out
    k = 2 / (n + 1)
    out[n - 1] = prev = sum(values[:n]) / n
    for i in range(n, len(values)):
        prev = values[i] * k + prev * (1 - k)
        out[i] = prev
    return out


def true_range(bars):
    """Each bar's true range; the first bar has no previous close, so its
    range is high minus low."""
    out = []
    for i, b in enumerate(bars):
        if i == 0:
            out.append(b["high"] - b["low"])
        else:
            c = bars[i - 1]["close"]
            out.append(max(b["high"] - b["low"], abs(b["high"] - c), abs(b["low"] - c)))
    return out


def keltner(bars, length, atr_length, mult):
    """(basis, upper, lower) lists, one value per bar, None while warming up."""
    basis = ema([b["close"] for b in bars], length)
    atr = ema(true_range(bars), atr_length)
    upper = [None if m is None or a is None else m + mult * a for m, a in zip(basis, atr)]
    lower = [None if m is None or a is None else m - mult * a for m, a in zip(basis, atr)]
    return basis, upper, lower


class KeltnerChannel(Indicator):
    id = "keltner_channel"
    label = "Keltner channel"
    overlay = True

    inputs = [Int("length", default=20, minimum=2, maximum=500),
              Int("atr_length", default=10, minimum=2, maximum=500),
              Float("mult", default=2.0, minimum=0.1, maximum=10.0, step=0.1)]

    plots = [Plot("basis", color="#E8A817", width=2),
             Plot("upper", color="#8A8279", style="dashed"),
             Plot("lower", color="#8A8279", style="dashed")]
    fills = [Fill("upper", "lower", color="#E8A817", opacity=0.06)]

    warmup = lambda params: max(int(params.get("length", 20)),     # noqa: E731
                                int(params.get("atr_length", 10)))

    def compute(self, ctx):
        p = while25.params
        rows = while25.bars
        basis, upper, lower = keltner(rows, p["length"], p["atr_length"], p["mult"])
        self.times = [int(r["time"]) for r in rows]
        return {"basis": basis, "upper": upper, "lower": lower}