Perfected FlowScript
Keltner Channels
Keltner Channels — Perfected Edition is indexed as 184_keltner_channels.flowscript. The exact FlowScript is viewable here; chart observe and trading automation use the current mmflow chart/recipe signal proxy until FlowScript v2 transpilation is available.
This exact FlowScript uses the v2 source dialect. It is viewable and connected to the chart/automation proxy, but direct editor execution needs the FlowScript v2 transpiler.
Dialect
flowscript-v2
Compatibility
flowscript-v2-needs-transpile
Position
onchart
Axis
false
Size
12.0 KB
Lines
314
Native Signal Candidates
3 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Breakout
line 239:9
Trigger
(showShapes) && (regimeBull && close[1] <= upper[1])
Value
upper
Deps
close:timeseries, regimeBull:var, showShapes:input, upper:timeseries
Breakdown
line 250:9
Trigger
(showShapes) && (regimeBear && close[1] >= lower[1])
Value
lower
Deps
close:timeseries, lower:timeseries, regimeBear:var, showShapes:input
Squeeze
line 263:5
Trigger
(showSqueeze && isSqueeze && squeezeBars <= 3)
Value
basis
Deps
isSqueeze:timeseries, showSqueeze:input, squeezeBars:static
184_keltner_channels.flowscript
source path: kscripts/perfected/184_keltner_channels.flowscript · sha256:6eec88ad228d4bea21a02fbd8c584c4df101714f590c470a11d7ba0737d12575
//@version=2
// ============================================================================
// Keltner Channels — Perfected Edition
// Author: BackQuant (@BackQuant) | Perfected: kScript_Perfection_Engineer
// Tags: CORE, #keltner, #channels, #atr, #envelope, #regime, #breakout
//
// Volatility-adaptive envelope using EMA basis with bands at ±(ATR × multiplier).
// Surfaces regime detection (price above/below channels), squeeze detection
// (band contraction), color-coded fills, and shape alerts for channel breaks.
//
// Academic foundation (exact papers & formulas):
// 1. Keltner (1960), "How to Make Money in Commodities".
// Original 10-day MA of (H+L+C)/3 with bands from 10-day EMA of (High − Low).
// One of the earliest volatility-based channel systems.
//
// 2. Wilder (1978), "New Concepts in Technical Trading Systems".
// ATR = SMA(True Range, n); True Range = max(H−L, |H−Cₚᵣᵢₒᵣ|, |L−Cₚᵣᵢₒᵣ|).
// The modern Keltner uses Wilder ATR for band width.
// DOI: implied by canonical reference
//
// 3. Leung & Chong (2003), "An Empirical Comparison of Moving Average
// Envelopes and Bollinger Bands".
// ATR-based bands produce smoother channel widths than SD-based bands,
// supporting Keltner's utility in trending regimes.
//
// 4. Rahman (2024), "Optimising Supertrend Parameters using Bayesian
// Optimisation for Maximising Profit".
// Validates ATR-based trend indicators (Supertrend is ATR-band derived)
// remain effective with proper parameter optimization.
//
// 5. Murphy (1999), "Technical Analysis of the Financial Markets".
// Channel breakouts as trend-continuation signals: price closing outside
// an envelope often signals acceleration rather than reversal.
// ============================================================================
define(title="Keltner Channels — Perfected Edition", position="onchart", axis=false)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// -- Channel Settings --
var src = input(name="src", type="select", defaultValue="close", label="Source",
options=["close","hl2","hlc3","ohlc4"], group="Channel Settings")
var emaLen = input(name="emaLen", type="number", defaultValue=20, label="EMA Length",
constraints={min: 5, max: 100, step: 1}, group="Channel Settings")
var atrLen = input(name="atrLen", type="number", defaultValue=14, label="ATR Length",
constraints={min: 5, max: 50, step: 1}, group="Channel Settings")
var mult = input(name="mult", type="number", defaultValue=2.0, label="ATR Multiplier",
constraints={min: 0.5, max: 5.0, step: 0.5}, group="Channel Settings")
// -- Squeeze Detection --
var enableSqueeze = input(name="enableSqueeze", type="boolean", defaultValue=true,
label="Enable Squeeze Detection", group="Squeeze Detection")
var squeezeLookback = input(name="squeezeLookback", type="number", defaultValue=20,
label="Squeeze Lookback", constraints={min: 10, max: 100, step: 5}, group="Squeeze Detection")
var squeezeThreshold = input(name="squeezeThreshold", type="number", defaultValue=0.25,
label="Squeeze Threshold %", constraints={min: 0.1, max: 0.5, step: 0.05}, group="Squeeze Detection")
// -- Display --
var showBands = input(name="showBands", type="boolean", defaultValue=true,
label="Show Bands", group="Display")
var showFill = input(name="showFill", type="boolean", defaultValue=true,
label="Show Band Fill", group="Display")
var showMiddle = input(name="showMiddle", type="boolean", defaultValue=true,
label="Show Middle Line", group="Display")
var showRegime = input(name="showRegime", type="boolean", defaultValue=true,
label="Show Regime Fill", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true,
label="Show Break Shapes", group="Display")
var showSqueeze = input(name="showSqueeze", type="boolean", defaultValue=true,
label="Show Squeeze Shapes", group="Display")
// -- Colors --
var basisColor = input(name="basisColor", type="color", defaultValue="#ffa726",
label="Basis Color", group="Colors")
var upperColor = input(name="upperColor", type="color", defaultValue="#26a69a",
label="Upper Band Color", group="Colors")
var lowerColor = input(name="lowerColor", type="color", defaultValue="#ef5350",
label="Lower Band Color", group="Colors")
var bullColor = input(name="bullColor", type="color", defaultValue="#00c853",
label="Bull Regime Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#d50000",
label="Bear Regime Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c",
label="Neutral Color", group="Colors")
// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------
timeseries price = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = price.close
timeseries high = price.high
timeseries low = price.low
if (isnan(close[0]) || isnan(high[0]) || isnan(low[0])) {
return
}
// Source selector
timeseries source = (src == "close") ? close
: (src == "hl2") ? (high + low) / 2.0
: (src == "hlc3") ? (high + low + close) / 3.0
: (high + low + close + price.open) / 4.0
// ---------------------------------------------------------------------------
// 3. ATR (Wilder) & EMA BASIS
// ---------------------------------------------------------------------------
timeseries tr = math.max(high - low,
math.max(math.abs(high - close[1]), math.abs(low - close[1])))
timeseries atr = rma(tr, atrLen)
timeseries basis = ema(source, emaLen)
// Bands
timeseries upper = basis + atr * mult
timeseries lower = basis - atr * mult
// Band width for squeeze detection
timeseries bandWidth = upper - lower
timeseries bandWidthPct = (bandWidth / math.max(basis, 0.0001)) * 100
// ---------------------------------------------------------------------------
// 4. REGIME DETECTION
// ---------------------------------------------------------------------------
// Price relative to channels:
// Breakout above upper = bullish regime
// Breakdown below lower = bearish regime
// Between bands = neutral / mean-reversion regime
var regimeBull = close > upper
var regimeBear = close < lower
var regimeNeutral = !regimeBull && !regimeBear
// Regime color
timeseries regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
// ---------------------------------------------------------------------------
// 5. SQUEEZE DETECTION (band contraction)
// ---------------------------------------------------------------------------
timeseries lowestBandWidth = lowest(source=bandWidth, period=squeezeLookback)
timeseries isSqueeze = enableSqueeze && (bandWidth <= lowestBandWidth * (1 + squeezeThreshold))
// ---------------------------------------------------------------------------
// 6. STATIC STATE TRACKING — Consecutive bars in regime
// ---------------------------------------------------------------------------
static bullBars = 0
static bearBars = 0
static neutralBars = 0
static squeezeBars = 0
if (regimeBull) {
bullBars = bullBars + 1
bearBars = 0
neutralBars = 0
} else if (regimeBear) {
bearBars = bearBars + 1
bullBars = 0
neutralBars = 0
} else {
neutralBars = neutralBars + 1
bullBars = 0
bearBars = 0
}
if (isSqueeze) {
squeezeBars = squeezeBars + 1
} else {
squeezeBars = 0
}
// ---------------------------------------------------------------------------
// 7. VISUALIZATION
// ---------------------------------------------------------------------------
// 7.1 Band fill (between upper and lower)
if (showBands && showFill) {
plotLine(
value=[upper, lower],
width=1,
colors=[transparency(upperColor, 80), transparency(lowerColor, 80)],
colorIndex=0,
fill=true,
label=["Upper", "Lower"],
desc=["Upper Keltner band", "Lower Keltner band"]
)
}
// 7.2 Regime fill (price vs channels) — color the entire band by regime
timeseries regimeFillTop = regimeBull ? upper : (regimeBear ? lower : basis)
timeseries regimeFillBot = regimeBull ? lower : (regimeBear ? upper : lower)
if (showRegime) {
var regColorIdx = regimeBull ? 0 : (regimeBear ? 1 : 2)
plotLine(
value=[regimeFillTop, regimeFillBot],
width=1,
colors=[transparency(bullColor, 30), transparency(bearColor, 30), transparency(neutralColor, 20)],
colorIndex=regColorIdx,
fill=true,
label=["Regime Fill"],
desc=["Channel interior colored by price regime: green = breakout above, red = breakdown below, grey = within bands"]
)
}
// 7.3 Upper / Lower band lines
if (showBands) {
plotLine(
value=upper,
width=2,
colors=[upperColor],
label=["Upper Band"],
desc=["Upper Keltner band: EMA + ATR × " + mult]
)
plotLine(
value=lower,
width=2,
colors=[lowerColor],
label=["Lower Band"],
desc=["Lower Keltner band: EMA − ATR × " + mult]
)
}
// 7.4 Middle (basis) line
if (showMiddle) {
plotLine(
value=basis,
width=2,
colors=[basisColor],
label=["Basis EMA"],
desc=["EMA basis (middle line) — " + emaLen + " periods"]
)
}
// 7.5 Breakout shapes (channel breaks)
if (showShapes) {
// Breakout above upper
if (regimeBull && close[1] <= upper[1]) {
plotShape(
value=upper,
shape="triangleup",
colorIndex=bullColor,
width=3,
label=["Breakout"],
desc=["Price broke above upper Keltner band — bullish breakout / trend acceleration"]
)
}
// Breakdown below lower
if (regimeBear && close[1] >= lower[1]) {
plotShape(
value=lower,
shape="triangledown",
colorIndex=bearColor,
width=3,
label=["Breakdown"],
desc=["Price broke below lower Keltner band — bearish breakdown / trend acceleration"]
)
}
}
// 7.6 Squeeze shapes (band contraction — often precedes expansion)
if (showSqueeze && isSqueeze && squeezeBars <= 3) {
plotShape(
value=basis,
shape="circle",
colorIndex="#ffeb3b",
width=2,
label=["Squeeze"],
desc=["Band width contracted to " + squeezeLookback + "-bar minimum + " + (squeezeThreshold * 100) + "% — volatility compression, expansion likely"]
)
}
// 7.7 Basis color coding by regime (optional visual emphasis)
if (showMiddle) {
plotLine(
value=basis,
width=1,
colors=[regimeColor],
label=["Basis (Regime)"],
desc=["EMA basis colored by current regime"]
)
}
// ---------------------------------------------------------------------------
// 8. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regimeBull ? "BREAKOUT (BULL)" : (regimeBear ? "BREAKDOWN (BEAR)" : "NEUTRAL (MEAN-REVERSION)")
var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
plotTable(
data=[
["Keltner Channels — Perfected", regimeText],
["Basis EMA", basis[0]],
["Upper Band", upper[0]],
["Lower Band", lower[0]],
["Band Width %", bandWidthPct[0]],
["Squeeze?", isSqueeze ? "YES (" + squeezeBars + " bars)" : "NO"],
["Consec Regime", bullBars > 0 ? bullBars : (bearBars > 0 ? bearBars : neutralBars)]
],
position="top_right",
headerRow=true,
headerColumn=true,
textColor="#e2e8f0",
headerTextColor="#ffffff",
backgroundColor=transparency("#0f172a", 40),
headerBackgroundColor=transparency("#1e293b", 40),
borderColor=transparency("#334155", 40),
borderWidth=1,
fontSize=10,
cellPadding=4
)
}