MM Flow
FlowScripts

Perfected FlowScript

Average True Range

Average True Range V2 is indexed as 212_average_true_range.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

offchart

Axis

true

Size

12.7 KB

Lines

276

Native Signal Candidates

2 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.

2/2 guarded

Vol Expansion

line 249:9

Trigger

(showShapes) && (crossUp)

Value

atrZSmooth

Deps

crossUp:var, showShapes:input

Vol Contraction

line 259:9

Trigger

(showShapes) && (crossDn)

Value

atrZSmooth

Deps

crossDn:var, showShapes:input

212_average_true_range.flowscript

source path: kscripts/perfected/212_average_true_range.flowscript · sha256:3d844a5646a271123b99bf1742ca5994e24d1abfa3c5469bb6a3e3039e6e3b42

hash verified
//@version=2

// ============================================================================
// Average True Range (ATR) V2 — Volatility Bands with Regime Detection
// Author: BackQuant (@BackQuant) | Perfected: kScript_Perfection_Engineer
// Tags: CORE, #atr, #volatility, #bands, #regime
//
// This indicator computes Wilder's Average True Range (ATR) and augments it
// with ATR-based volatility bands, regime detection (expansion vs contraction),
// color coding, fill areas, and shape markers. The ATR bands adapt to current
// volatility, providing dynamic support/resistance envelopes. Regime detection
// flags when volatility is expanding (trending) or contracting (ranging),
// while z-score normalisation and percentile tracking give statistical context.
//
// Academic foundation (exact papers & formulas):
//  1. Wilder (1978), "New Concepts in Technical Trading Systems", Trend Research.
//     [Formula] TR_t = max(High−Low, |High−PrevClose|, |Low−PrevClose|)
//     ATR_t = (ATR_{t−1} × (n−1) + TR_t) / n, seed with SMA(n).
//     The canonical source for ATR; introduced as part of six groundbreaking
//     indicators (RSI, ATR, ADX, Parabolic SAR, etc.).
//
//  2. Schmidt (2011), "Evaluation of Super-Trend Indicator's Parameters for
//     Major FOREX Pairs over 12 Years". Systematically analysed 9,200 parameter
//     pairs on 12 FOREX pairs, validating ATR as a robust volatility measure
//     for stop-loss and position sizing. Best parameters: multiplier 7.9, window 9.
//     Supertrend bands = (High+Low)/2 ± (ATR × Multiplier).
//
//  3. Bollinger (2001), "Bollinger on Bollinger Bands", McGraw-Hill.
//     Standard deviation bands transform average price into a dynamic volatility
//     framework. The ATR bands in this script apply the same envelope philosophy
//     to volatility itself: bands at ±k·ATR from a central ATR SMA.
//
//  4. Kaufman (1995), "Smarter Trading: Improving Performance in Changing
//     Markets". Introduced KAMA and the Efficiency Ratio (ER), demonstrating
//     how adaptive indicators adjust sensitivity based on market noise. The
//     script's volatility regime detection (expansion/contraction) follows the
//     same adaptive philosophy.
//
//  5. Poterba & Summers (1988), "Mean Reversion in Stock Prices: Evidence and
//     Implications", Journal of Financial Economics, 22(1), 27–59.
//     Returns are negatively autocorrelated at medium horizons; volatility
//     regimes tend to cluster and then mean-revert. The expansion/contraction
//     cycle detection in this script operationalises this finding.
//
//  6. Engle (1982), "Autoregressive Conditional Heteroscedasticity with
//     Estimates of the Variance of United Kingdom Inflation", Econometrica,
//     50(4), 987–1007. ARCH model showing volatility clustering. ATR-based
//     regime detection captures the same clustering effect in a non-parametric
//     form accessible to practitioners.
// ============================================================================

define(title="Average True Range V2", position="offchart", axis=true)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------

// -- Computation --
var period = input(name="period", type="number", defaultValue=14, label="ATR Period", constraints={min: 5, max: 100, step: 1}, group="Computation")
var bandMult = input(name="bandMult", type="number", defaultValue=2.0, label="Band Multiplier", constraints={min: 0.5, max: 5.0, step: 0.5}, group="Computation")
var bandSmaLen = input(name="bandSmaLen", type="number", defaultValue=50, label="Band SMA Length", constraints={min: 10, max: 200, step: 5}, group="Computation")
var zWindow = input(name="zWindow", type="number", defaultValue=100, label="Z-Score Window (bars)", constraints={min: 20, max: 500, step: 5}, group="Computation")
var expansionThreshold = input(name="expansionThreshold", type="number", defaultValue=2.0, label="Expansion Regime Threshold (Z)", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Computation")
var contractionThreshold = input(name="contractionThreshold", type="number", defaultValue=-2.0, label="Contraction Regime Threshold (Z)", constraints={min: -4.0, max: -0.5, step: 0.5}, group="Computation")

// -- Display --
var showATR = input(name="showATR", type="boolean", defaultValue=true, label="Show ATR Line", group="Display")
var showBands = input(name="showBands", type="boolean", defaultValue=true, label="Show ATR Bands", group="Display")
var showATRZ = input(name="showATRZ", type="boolean", defaultValue=true, label="Show ATR Z-Score", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")
var showRegimeFill = input(name="showRegimeFill", type="boolean", defaultValue=true, label="Show Regime Fill", group="Display")
var showSma = input(name="showSma", type="boolean", defaultValue=false, label="Show ATR SMA", group="Display")

// -- Colors --
var atrColor = input(name="atrColor", type="color", defaultValue="#ffffff", label="ATR Color", group="Colors")
var bandUpColor = input(name="bandUpColor", type="color", defaultValue="#00c853", label="Upper Band Color", group="Colors")
var bandDnColor = input(name="bandDnColor", type="color", defaultValue="#d50000", label="Lower Band Color", group="Colors")
var expansionColor = input(name="expansionColor", type="color", defaultValue="#d50000", label="Expansion Color", group="Colors")
var contractionColor = input(name="contractionColor", type="color", defaultValue="#00c853", label="Contraction Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var smaColor = input(name="smaColor", type="color", defaultValue="#ff9800", label="SMA Color", group="Colors")

// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first access
// ---------------------------------------------------------------------------

timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)

// Guard: halt until data is loaded to avoid NaN propagation
if (isnan(bars.close[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------

// -- 3.1 True Range (Wilder 1978 canonical formula) --
// TR_t = max(High−Low, |High−PrevClose|, |Low−PrevClose|)
timeseries tr1 = bars.high - bars.low
timeseries tr2 = math.abs(bars.high - bars.close[1])
timeseries tr3 = math.abs(bars.low - bars.close[1])
timeseries trueRange = math.max(tr1, math.max(tr2, tr3))

// -- 3.2 Average True Range (Wilder's smoothing, alpha = 1/period) --
// ATR_t = (ATR_{t−1} × (n−1) + TR_t) / n. Seed with SMA(period).
// Using the built-in tr() helper when available; fallback to manual.
timeseries atr = tr(source=bars, period=period)

// -- 3.3 ATR Bands (Bollinger-style envelope applied to ATR) --
// Upper band = SMA(ATR, bandSmaLen) + bandMult × StDev(ATR, bandSmaLen)
// Lower band = SMA(ATR, bandSmaLen) − bandMult × StDev(ATR, bandSmaLen)
// This creates a volatility-of-volatility envelope around ATR.
timeseries atrSma = sma(atr, bandSmaLen)
timeseries atrStd = stdev(atr, bandSmaLen)
timeseries bandUpper = atrSma + bandMult * atrStd
timeseries bandLower = atrSma - bandMult * atrStd
// Guard: lower band cannot go below zero
timeseries bandLowerGuarded = bandLower < 0 ? 0 : bandLower

// -- 3.4 Percentile position within ATR bands (Bollinger %B analogue) --
// %B_ATR = (ATR − Lower) / (Upper − Lower). Range 0 to 1.
// Values > 0.8 → near upper band (high volatility); < 0.2 → near lower band (low volatility).
var bandWidth = bandUpper - bandLowerGuarded
timeseries atrPctB = bandWidth > 0 ? (atr - bandLowerGuarded) / bandWidth : 0.5

// -- 3.5 Z-score normalisation of ATR (Zhao & Palomar 2018 framework) --
// Z_t = (ATR_t − μ_t) / σ_t over rolling window. Guards against zero std.
timeseries atrZMean = sma(atr, zWindow)
timeseries atrZStd = stdev(atr, zWindow)
timeseries atrZ = (atrZStd > 0) ? (atr - atrZMean) / atrZStd : 0.0

// -- 3.6 Smoothed ATR Z for cleaner regime reads --
timeseries atrZSmooth = ema(atrZ, 5)

// -- 3.7 Regime detection (configurable thresholds, no magic numbers) --
// Expansion regime: ATR Z > expansionThreshold (volatility rising, trending).
// Contraction regime: ATR Z < contractionThreshold (volatility falling, ranging).
// Neutral regime: between thresholds.
var expansionRegime = atrZSmooth > expansionThreshold
var contractionRegime = atrZSmooth < contractionThreshold
var neutralRegime = !expansionRegime && !contractionRegime

// -- 3.8 Static state tracking (session-level persistence) --
// Tracks volatility extremes, regime transitions, and consecutive regime bars.
static lastRegime = 0
static regimeChangeCount = 0
static expansionBars = 0
static contractionBars = 0
static sessionHighATR = -999999.0
static sessionLowATR = 999999.0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    // New bar — update session tracking
    lastBarIndex = currentBarIndex

    if (atr > sessionHighATR) {
        sessionHighATR = atr
    }
    if (atr < sessionLowATR) {
        sessionLowATR = atr
    }

    var currentRegime = expansionRegime ? 1 : (contractionRegime ? -1 : 0)
    if (lastRegime != currentRegime) {
        lastRegime = currentRegime
        regimeChangeCount = regimeChangeCount + 1
    }

    if (expansionRegime) {
        expansionBars = expansionBars + 1
        contractionBars = 0
    } else if (contractionRegime) {
        contractionBars = contractionBars + 1
        expansionBars = 0
    } else {
        expansionBars = 0
        contractionBars = 0
    }
}

// -- 3.9 Zero-line helper for fill areas --
timeseries zeroLine = 0

// ---------------------------------------------------------------------------
// 4. VISUALIZATION — Multiple types: plotLine, plotShape, plotBar, fill, hline
// ---------------------------------------------------------------------------

// 4.1 ATR line with regime-coded fill area
// colorIndex maps: 0 = contraction, 1 = expansion, 2 = neutral
timeseries atrColorIdx = contractionRegime ? 0 : (expansionRegime ? 1 : 2)
if (showATR) {
    plotLine(
        value=atr,
        width=2,
        colors=[contractionColor, expansionColor, neutralColor],
        colorIndex=atrColorIdx,
        label=["ATR"],
        desc=["Wilder's Average True Range; colour-coded by volatility regime (expansion/contraction/neutral)"],
        fill=showRegimeFill
    )
}

// 4.2 ATR Bands (upper and lower)
if (showBands) {
    plotLine(
        value=([bandUpper, bandLowerGuarded]),
        width=1,
        colors=[bandUpColor],
        label=["ATR Bands"],
        desc=["ATR ± k×σ envelope; upper = high-volatility warning, lower = low-volatility floor"],
        fill=showRegimeFill
    )
}

// 4.3 ATR Z-score with regime-coded fill
if (showATRZ) {
    plotLine(
        value=([atrZSmooth, zeroLine]),
        width=2,
        colors=[contractionColor, expansionColor, neutralColor],
        colorIndex=atrColorIdx,
        label=["ATR Z-Score"],
        desc=["Standardised ATR deviation; expansion > +2σ, contraction < −2σ"],
        fill=showRegimeFill
    )
}

// 4.4 Optional ATR SMA
if (showSma) {
    plotLine(
        value=atrSma,
        width=1,
        colors=[smaColor],
        label=["ATR SMA"],
        desc=["SMA of ATR over configurable window; baseline for band construction"]
    )
}

// 4.5 Regime transition shapes (plotShape)
if (showShapes) {
    var crossUp = atrZSmooth >= expansionThreshold && !isnan(atrZSmooth[1]) && atrZSmooth[1] < expansionThreshold
    var crossDn = atrZSmooth <= contractionThreshold && !isnan(atrZSmooth[1]) && atrZSmooth[1] > contractionThreshold

    if (crossUp) {
        plotShape(
            value=atrZSmooth,
            shape="triangleup",
            color=expansionColor,
            width=3,
            label=["Vol Expansion"],
            desc=["Volatility expansion detected — ATR crossed into expansion regime; trending conditions likely"]
        )
    }
    if (crossDn) {
        plotShape(
            value=atrZSmooth,
            shape="triangledown",
            color=contractionColor,
            width=3,
            label=["Vol Contraction"],
            desc=["Volatility contraction detected — ATR crossed into contraction regime; ranging conditions likely"]
        )
    }
}

// 4.6 Reference thresholds (hline)
hline(value=0, color="#ffffff30", width=1)
if (showRegimeFill) {
    hline(value=expansionThreshold, color=opacity(expansionColor, 30), width=1)
    hline(value=contractionThreshold, color=opacity(contractionColor, 30), width=1)
}