Perfected FlowScript
Keltner Channel
Keltner Channel — Perfected Edition is indexed as 272_keltner_channel.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
13.4 KB
Lines
354
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Breakout
line 278:9
Trigger
(showShapes) && (breakOut)
Value
upper
Deps
breakOut:var, showShapes:input
Breakdown
line 289:9
Trigger
(showShapes) && (breakDown)
Value
lower
Deps
breakDown:var, showShapes:input
Regime Change
line 300:9
Trigger
(showShapes) && (regimeChange)
Value
basis
Deps
regimeChange:var, showShapes:input
Squeeze
line 313:5
Trigger
(showSqueeze && isSqueeze && squeezeBars <= 3)
Value
basis
Deps
isSqueeze:timeseries, showSqueeze:input, squeezeBars:static
272_keltner_channel.flowscript
source path: kscripts/perfected/272_keltner_channel.flowscript · sha256:0c47d705e635b2f2984a2c980d72cc371bdbbccf6b854d11b60acc6e9059dd7d
//@version=2
// ============================================================================
// Keltner Channel — Perfected Edition
// Author: T (@Tuto) | Enhanced by kScript_Perfection_Engineer
// Index: 272
// Tags: CORE, #keltner, #channels, #atr, #envelope, #regime, #breakout, #squeeze
//
// Production-grade volatility-adaptive envelope using EMA basis with bands at
// ±(ATR × multiplier). Surfaces regime detection (price above/below channels),
// squeeze detection (band contraction vs historical width), color-coded fills,
// shape alerts for channel breaks and squeeze events, and comprehensive
// state tracking via static variables.
//
// Academic foundations (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.
//
// 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 Channel — 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
// -----------------------------------------------------------------------------
// True Range = max(H−L, |H−C[1]|, |L−C[1]|)
// ATR = RMA(TR, atrLen) — Wilder smoothing
timeseries prevClose = isnan(close[1]) ? close : close[1]
timeseries tr1 = high - low
timeseries tr2 = math.abs(high - prevClose)
timeseries tr3 = math.abs(low - prevClose)
timeseries trueRange = math.max(tr1, math.max(tr2, tr3))
timeseries atr = rma(trueRange, 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)
// -----------------------------------------------------------------------------
// Squeeze occurs when band width is near its lookback minimum, indicating
// volatility compression that often precedes expansion.
timeseries lowestBandWidth = lowest(source=bandWidth, period=squeezeLookback)
timeseries isSqueeze = enableSqueeze && (bandWidth <= lowestBandWidth * (1 + squeezeThreshold))
// -----------------------------------------------------------------------------
// 6. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
static bullBars = 0
static bearBars = 0
static neutralBars = 0
static squeezeBars = 0
static prevRegime = 0 // 0=neutral, 1=bull, -1=bear
var regimeChange = false
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
}
if (!isLiveUpdate) {
var currRegime = regimeBull ? 1 : (regimeBear ? -1 : 0)
if (prevRegime != 0 && currRegime != prevRegime) {
regimeChange = true
}
prevRegime = currRegime
}
// -----------------------------------------------------------------------------
// 7. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Breakout / breakdown events (price crosses the band boundary)
var breakOut = regimeBull && close[1] <= upper[1]
var breakDown = regimeBear && close[1] >= lower[1]
// -----------------------------------------------------------------------------
// 8. VISUALIZATION
// -----------------------------------------------------------------------------
// 8.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: EMA + ATR × " + mult, "Lower Keltner band: EMA − ATR × " + mult]
)
}
// 8.2 Regime fill (price vs channels) — color the entire band interior 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"]
)
}
// 8.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]
)
}
// 8.4 Middle (basis) line
if (showMiddle) {
plotLine(
value=basis,
width=2,
colors=[basisColor],
label=["Basis EMA"],
desc=["EMA basis (middle line) — " + emaLen + " periods"]
)
}
// 8.5 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.6 Breakout shapes (channel breaks)
if (showShapes) {
// Breakout above upper
if (breakOut) {
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 (breakDown) {
plotShape(
value=lower,
shape="triangledown",
colorIndex=bearColor,
width=3,
label=["Breakdown"],
desc=["Price broke below lower Keltner band — bearish breakdown / trend acceleration"]
)
}
// Regime change shape
if (regimeChange) {
plotShape(
value=basis,
shape="xcross",
colorIndex=regimeColor,
width=2,
label=["Regime Change"],
desc=["Price regime changed relative to Keltner channels"]
)
}
}
// 8.7 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"]
)
}
// -----------------------------------------------------------------------------
// 9. 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 Channel — Perfected", regimeText],
["Basis EMA", basis[0]],
["Upper Band", upper[0]],
["Lower Band", lower[0]],
["ATR", atr[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
)
}