MM Flow
FlowScripts

Perfected FlowScript

ATR

ATR Pro — Perfected Edition is indexed as 361_atr.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

19.5 KB

Lines

608

Native Signal Candidates

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

5/5 guarded

Expansion Start

line 520:9

Trigger

(showShapes) && (expansionStart)

Value

atrRaw

Deps

expansionStart:var, showShapes:input

Contraction Start

line 530:9

Trigger

(showShapes) && (contractionStart)

Value

atrRaw

Deps

contractionStart:var, showShapes:input

ATR Cross Up

line 540:9

Trigger

(showShapes) && (atrCrossUp)

Value

atrRaw

Deps

atrCrossUp:var, showShapes:input

ATR Cross Down

line 550:9

Trigger

(showShapes) && (atrCrossDn)

Value

atrRaw

Deps

atrCrossDn:var, showShapes:input

Extreme Vol

line 560:9

Trigger

(showShapes) && (extremeVol)

Value

atrRaw

Deps

extremeVol:var, showShapes:input

361_atr.flowscript

source path: kscripts/perfected/361_atr.flowscript · sha256:f364fc5dfac43c38fc3c5a4ee2178599d1a7f52e4f1e8c443afc8d1552e136b6

hash verified
//@version=2
// ============================================================================
// ATR Pro — Perfected Edition
// Author: C (@CMNDRFrakha) | Enhanced by kScript Perfection Engineer
// Tags: CORE, #atr, #volatility, #bands, #regime, #expansion, #contraction
//
// Production-quality academically-grounded volatility analysis suite.
// Implements Wilder's canonical ATR with full ATR-based Keltner bands,
// multi-timescale regime detection (expansion / contraction / neutral),
// color-coded volatility states, band fills, shape markers, and
// session-level static tracking.
//
// Research papers underpinning this design:
//  1. Wilder (1978), "New Concepts in Technical Trading Systems": canonical
//     ATR publication. TR = max(H−L, |H−Cₚᵣᵢₒᵣ|, |L−Cₚᵣᵢₒᵣ|); ATR is the
//     RMA of TR with alpha = 1/period. Original smoothing period = 14.
//  2. Keltner (1960) / Raschke (1980s): Keltner Channels = MA ± k × ATR.
//     ATR-based bands produce smoother, more predictable channel widths than
//     σ-based Bollinger Bands. Modern refinement: 20-period EMA ± 2×ATR.
//  3. Leung & Chong (2003), "An Empirical Comparison of Moving Average
//     Envelopes and Bollinger Bands": ATR-based envelopes outperform fixed
//     envelopes at capturing abrupt price fluctuations; ATR bands are a
//     valid alternative to σ-based bands.
//  4. Abdul Rahman (2024), "Optimising Supertrend Parameters using Bayesian
//     Optimisation": validated ATR's central role in volatility-based systems.
//     Best Supertrend parameters: multiplier 7.9, window 9 across 9,200
//     parameter pairs on 12 major FOREX pairs.
//  5. Bollinger (2001), "Bollinger on Bollinger Bands": the "Squeeze" concept
//     — when short-term volatility exceeds long-term baseline, the market is
//     in expansion; the inverse signals compression. Underpins the dual-ATR
//     expansion/contraction regime model.
//  6. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
//     Supply and Demand": liquidity-memory framework. Volatility expansion
//     follows temporary liquidity depletion; ratio of short-term to long-term
//     volatility captures this digestion process.
// ============================================================================

define(
    title="ATR Pro — Perfected Edition",
    position="offchart",
    axis=true
)

// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------

// --- ATR Core Settings ---
var atrLen = input(
    name="atrLen",
    type="number",
    defaultValue=14,
    label="ATR Length (Wilder Period)",
    constraints={min: 2, max: 100, step: 1},
    group="ATR Core"
)
var smoothType = input(
    name="smoothType",
    type="select",
    defaultValue="Wilder RMA",
    label="Smoothing Type",
    options=["Wilder RMA", "SMA", "EMA"],
    group="ATR Core"
)
var shortAtrLen = input(
    name="shortAtrLen",
    type="number",
    defaultValue=9,
    label="Short ATR Length (Regime)",
    constraints={min: 2, max: 50, step: 1},
    group="ATR Core"
)
var longAtrLen = input(
    name="longAtrLen",
    type="number",
    defaultValue=38,
    label="Long ATR Length (Regime)",
    constraints={min: 5, max: 200, step: 1},
    group="ATR Core"
)

// --- ATR Bands (Keltner-style) ---
var bandMult = input(
    name="bandMult",
    type="number",
    defaultValue=2.0,
    label="Band Multiplier (× ATR)",
    constraints={min: 0.5, max: 10.0, step: 0.5},
    group="ATR Bands"
)
var bandBasisLen = input(
    name="bandBasisLen",
    type="number",
    defaultValue=20,
    label="Band Basis EMA Length",
    constraints={min: 5, max: 100, step: 1},
    group="ATR Bands"
)
var showBands = input(
    name="showBands",
    type="boolean",
    defaultValue=true,
    label="Show ATR Bands",
    group="ATR Bands"
)
var showBandFill = input(
    name="showBandFill",
    type="boolean",
    defaultValue=true,
    label="Show Band Fill",
    group="ATR Bands"
)

// --- Thresholds & Regime ---
var expansionThresh = input(
    name="expansionThresh",
    type="number",
    defaultValue=1.25,
    label="Expansion Threshold (Short/Long Ratio)",
    constraints={min: 1.0, max: 3.0, step: 0.05},
    group="Thresholds"
)
var contractionThresh = input(
    name="contractionThresh",
    type="number",
    defaultValue=0.75,
    label="Contraction Threshold (Short/Long Ratio)",
    constraints={min: 0.1, max: 0.95, step: 0.05},
    group="Thresholds"
)
var extremeThresh = input(
    name="extremeThresh",
    type="number",
    defaultValue=2.0,
    label="Extreme Volatility Threshold (× ATR)",
    constraints={min: 1.0, max: 5.0, step: 0.25},
    group="Thresholds"
)

// --- Display ---
var showAtrLine = input(
    name="showAtrLine",
    type="boolean",
    defaultValue=true,
    label="Show Primary ATR Line",
    group="Display"
)
var showShortLong = input(
    name="showShortLong",
    type="boolean",
    defaultValue=true,
    label="Show Short & Long ATR Lines",
    group="Display"
)
var showAtrRatio = input(
    name="showAtrRatio",
    type="boolean",
    defaultValue=true,
    label="Show ATR Ratio (Expansion/Contraction)",
    group="Display"
)
var showAtrHistogram = input(
    name="showAtrHistogram",
    type="boolean",
    defaultValue=true,
    label="Show ATR Momentum Histogram",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Regime Shapes",
    group="Display"
)
var showTrBars = input(
    name="showTrBars",
    type="boolean",
    defaultValue=false,
    label="Show True Range Histogram",
    group="Display"
)

// --- Colors ---
var atrColor = input(
    name="atrColor",
    type="color",
    defaultValue="#ff9800",
    label="ATR Line Color",
    group="Colors"
)
var expansionColor = input(
    name="expansionColor",
    type="color",
    defaultValue="#ef5350",
    label="Expansion Color",
    group="Colors"
)
var contractionColor = input(
    name="contractionColor",
    type="color",
    defaultValue="#26a69a",
    label="Contraction Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)
var bandColor = input(
    name="bandColor",
    type="color",
    defaultValue="#00bcd4",
    label="Band Line Color",
    group="Colors"
)
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bull / Low Vol Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bear / High Vol Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close

if (isnan(px[0])) {
    return
}

// -----------------------------------------------------------------------------
// 3. TRUE RANGE — canonical Wilder (1978) definition
// -----------------------------------------------------------------------------
// TR = max(High − Low, |High − Previous Close|, |Low − Previous Close|)
// True Range accounts for gap moves that simple High−Low misses.

timeseries prevClose = bars.close[1]
timeseries tr = math.max(
    bars.high - bars.low,
    math.max(
        math.abs(bars.high - prevClose),
        math.abs(bars.low - prevClose)
    )
)

// -----------------------------------------------------------------------------
// 4. ATR COMPUTATION — multi-variant with Wilder canonical
// -----------------------------------------------------------------------------
// Wilder RMA: alpha = 1/period. Slower, smoother response than EMA (alpha = 2/(N+1)).
// Per Wilder (1978): ATR = (Prior_ATR × (n−1) + Current_TR) / n.

timeseries atrRaw = 0.0
if (smoothType == "Wilder RMA") {
    atrRaw = rma(source=tr, period=atrLen)
} else if (smoothType == "SMA") {
    atrRaw = sma(source=tr, period=atrLen)
} else {
    atrRaw = ema(source=tr, period=atrLen)
}

// Short and long ATR for regime detection (Bollinger 2001 squeeze concept)
timeseries atrShort = rma(source=tr, period=shortAtrLen)
timeseries atrLong  = rma(source=tr, period=longAtrLen)

// ATR as a percentage of price (normalized volatility)
timeseries atrPct = bars.close > 0 ? (atrRaw / bars.close) * 100.0 : 0.0

// -----------------------------------------------------------------------------
// 5. ATR BANDS — Keltner-style (Keltner 1960 / Raschke 1980s)
// -----------------------------------------------------------------------------
// Upper Band = Basis + (ATR × Multiplier)
// Lower Band = Basis − (ATR × Multiplier)
// Basis = EMA of close (default 20, modern Keltner convention)

timeseries bandBasis = ema(source=bars.close, period=bandBasisLen)
timeseries bandHalf = atrRaw * bandMult
timeseries upperBand = bandBasis + bandHalf
timeseries lowerBand = bandBasis - bandHalf

// Percent B of ATR bands (analogous to Bollinger %B, but ATR-based)
// %B = (Price − LowerBand) / (UpperBand − LowerBand) ∈ [0, 1]
var bandWidth = upperBand - lowerBand
timeseries bandPctB = bandWidth > 0 ? (bars.close - lowerBand) / bandWidth : 0.5

// -----------------------------------------------------------------------------
// 6. REGIME DETECTION — Expansion / Contraction / Neutral
// -----------------------------------------------------------------------------
// Per Bollinger (2001) squeeze concept and Bouchaud et al. (2009) liquidity memory:
// Short ATR vs Long ATR ratio identifies volatility regime shifts.
// Expansion: short-term vol exceeds long-term baseline (liquidity depletion).
// Contraction: short-term vol below baseline (liquidity accumulation / digestion).

timeseries atrRatio = atrLong > 0 ? atrShort / atrLong : 1.0

var regimeExpansion = atrRatio > expansionThresh
var regimeContraction = atrRatio < contractionThresh
var regimeNeutral = !regimeExpansion && !regimeContraction

var regimeColor = regimeExpansion
    ? expansionColor
    : (regimeContraction ? contractionColor : neutralColor)

// ATR momentum: difference between short and long ATR
timeseries atrMomentum = atrShort - atrLong

// -----------------------------------------------------------------------------
// 7. EXTREME & ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Extreme volatility: current TR exceeds ATR × extreme threshold (outlier bar)
var extremeVol = tr > atrRaw * extremeThresh

// ATR crossing above/below its own long-term average (volatility trend shift)
timeseries atrAvg = sma(source=atrRaw, period=longAtrLen)
var atrCrossUp = atrRaw > atrAvg && atrRaw[1] <= atrAvg[1]
var atrCrossDn = atrRaw < atrAvg && atrRaw[1] >= atrAvg[1]

// Regime transition events
var expansionStart = regimeExpansion && !regimeExpansion[1]
var contractionStart = regimeContraction && !regimeContraction[1]

// Upper/lower band breach (price relative to ATR bands)
var priceAboveUpper = bars.close > upperBand && bars.close[1] <= upperBand[1]
var priceBelowLower = bars.close < lowerBand && bars.close[1] >= lowerBand[1]

// -----------------------------------------------------------------------------
// 8. STATIC STATE TRACKING (Session-level persistence)
// -----------------------------------------------------------------------------
// Tracks session extremes, regime transitions, and extreme-event counts.

static sessionHighAtr = -999999.0
static sessionLowAtr = 999999.0
static sessionHighTr = -999999.0
static expansionCount = 0
static contractionCount = 0
static lastRegime = 0    // 0=neutral, 1=expansion, -1=contraction
static lastBarIndex = 0
static extremeVolCount = 0

var currentBarIndex = bar_index[0]

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

    if (atrRaw[0] > sessionHighAtr) {
        sessionHighAtr = atrRaw[0]
    }
    if (atrRaw[0] < sessionLowAtr) {
        sessionLowAtr = atrRaw[0]
    }
    if (tr[0] > sessionHighTr) {
        sessionHighTr = tr[0]
    }

    var currentRegime = regimeExpansion ? 1 : (regimeContraction ? -1 : 0)
    if (lastRegime != currentRegime) {
        lastRegime = currentRegime
    }

    if (regimeExpansion) {
        expansionCount = expansionCount + 1
    }
    if (regimeContraction) {
        contractionCount = contractionCount + 1
    }
    if (extremeVol) {
        extremeVolCount = extremeVolCount + 1
    }
}

// -----------------------------------------------------------------------------
// 9. PLOTTING
// -----------------------------------------------------------------------------

// --- Zero line (for ratio and momentum panels)
if (showAtrRatio || showAtrHistogram) {
    hline(value=0, color="#ffffff30", width=1)
}

// --- Expansion / Contraction threshold lines for ratio panel
if (showAtrRatio) {
    hline(value=expansionThresh, color=transparency(expansionColor, 60), width=1)
    hline(value=contractionThresh, color=transparency(contractionColor, 60), width=1)
    hline(value=1.0, color="#ffffff40", width=1)
}

// --- Primary ATR Line (regime-colored) ---
if (showAtrLine) {
    plotLine(
        value=atrRaw,
        width=2,
        colors=[regimeColor],
        label=["ATR Pro"],
        desc=["ATR (" + smoothType + " " + atrLen + ") — regime-colored volatility measure"]
    )
}

// --- Short & Long ATR Lines (with fill) ---
if (showShortLong) {
    var shortAboveLong = atrShort > atrLong
    plotLine(
        value=[atrShort, atrLong],
        width=1,
        colors=[transparency(expansionColor, 30), transparency(contractionColor, 30)],
        colorIndex=shortAboveLong ? 0 : 1,
        fill=true,
        label=["ATR Short", "ATR Long"],
        desc=["Short ATR (" + shortAtrLen + ") vs Long ATR (" + longAtrLen + ") — expansion/contraction fill"]
    )

    plotLine(
        value=atrShort,
        width=2,
        colors=[expansionColor],
        label=["ATR Short"],
        desc=["Short-term ATR (" + shortAtrLen + ") — fast volatility response"]
    )
    plotLine(
        value=atrLong,
        width=2,
        colors=[contractionColor],
        label=["ATR Long"],
        desc=["Long-term ATR (" + longAtrLen + ") — baseline volatility"]
    )
}

// --- ATR Ratio (Expansion/Contraction line) ---
if (showAtrRatio) {
    plotLine(
        value=atrRatio,
        width=2,
        colors=[regimeColor],
        label=["ATR Ratio"],
        desc=["Short/Long ATR ratio — expansion (>" + expansionThresh + ") / contraction (<" + contractionThresh + ")"]
    )
}

// --- ATR Momentum Histogram ---
if (showAtrHistogram) {
    var histBull = atrMomentum >= 0
    plotBar(
        value=atrMomentum,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["ATR Momentum"],
        desc=["ATR momentum: Short ATR minus Long ATR — volatility acceleration/deceleration"]
    )
}

// --- True Range Histogram (optional, per-candle volatility) ---
if (showTrBars) {
    var trBull = tr >= atrRaw
    plotBar(
        value=tr,
        colors=[transparency(bullColor, 40), transparency(bearColor, 40)],
        colorIndex=trBull ? 1 : 0,
        width=1,
        label=["True Range"],
        desc=["Per-candle True Range (Wilder 1978) — raw volatility before smoothing"]
    )
}

// --- ATR Bands (Keltner-style) on chart (if position permits, shown as offchart reference) ---
if (showBands) {
    plotLine(
        value=upperBand,
        width=1,
        colors=[transparency(bandColor, 50)],
        label=["Upper Band"],
        desc=["ATR Upper Band: Basis + (ATR × " + bandMult + ") — Keltner-style"]
    )
    plotLine(
        value=lowerBand,
        width=1,
        colors=[transparency(bandColor, 50)],
        label=["Lower Band"],
        desc=["ATR Lower Band: Basis − (ATR × " + bandMult + ") — Keltner-style"]
    )
    plotLine(
        value=bandBasis,
        width=1,
        colors=[transparency(bandColor, 80)],
        label=["Band Basis"],
        desc=["ATR Band Basis (EMA " + bandBasisLen + ") — Keltner centerline"]
    )
}

// --- Band Fill (between upper and lower bands) ---
if (showBandFill && showBands) {
    var bandWide = bandWidth > (atrRaw * bandMult * 0.5)
    plotLine(
        value=[upperBand, lowerBand],
        width=1,
        colors=[transparency(expansionColor, 10), transparency(contractionColor, 10)],
        colorIndex=bandWide ? 0 : 1,
        fill=true,
        label=["Upper Band", "Lower Band"],
        desc=["ATR Band fill — width indicates volatility envelope"]
    )
}

// --- Regime Transition Shapes ---
if (showShapes) {
    if (expansionStart) {
        plotShape(
            value=atrRaw,
            shape="triangledown",
            colorIndex=expansionColor,
            width=3,
            label=["Expansion Start"],
            desc=["Volatility expansion regime started — short ATR exceeds long ATR by >" + expansionThresh]
        )
    }
    if (contractionStart) {
        plotShape(
            value=atrRaw,
            shape="triangleup",
            colorIndex=contractionColor,
            width=3,
            label=["Contraction Start"],
            desc=["Volatility contraction regime started — short ATR falls below long ATR by <" + contractionThresh]
        )
    }
    if (atrCrossUp) {
        plotShape(
            value=atrRaw,
            shape="circle",
            colorIndex=bullColor,
            width=2,
            label=["ATR Cross Up"],
            desc=["ATR crossed above its long-term average — volatility increasing"]
        )
    }
    if (atrCrossDn) {
        plotShape(
            value=atrRaw,
            shape="circle",
            colorIndex=bearColor,
            width=2,
            label=["ATR Cross Down"],
            desc=["ATR crossed below its long-term average — volatility decreasing"]
        )
    }
    if (extremeVol) {
        plotShape(
            value=atrRaw,
            shape="diamond",
            colorIndex=expansionColor,
            width=4,
            label=["Extreme Vol"],
            desc=["Extreme volatility bar — TR exceeds ATR × " + extremeThresh]
        )
    }
}

// -----------------------------------------------------------------------------
// 10. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeExpansion
        ? "EXPANSION"
        : (regimeContraction ? "CONTRACTION" : "NEUTRAL")
    var regimeTextColor = regimeExpansion
        ? expansionColor
        : (regimeContraction ? contractionColor : neutralColor)

    plotTable(
        data=[
            ["ATR Pro — Perfected", regimeText],
            ["ATR (" + smoothType + " " + atrLen + ")", atrRaw[0]],
            ["ATR Short (" + shortAtrLen + ")", atrShort[0]],
            ["ATR Long (" + longAtrLen + ")", atrLong[0]],
            ["ATR Ratio", atrRatio[0]],
            ["ATR % of Price", atrPct[0]],
            ["Band %B", bandPctB[0]],
            ["Session High ATR", sessionHighAtr],
            ["Session Low ATR", sessionLowAtr],
            ["Extreme Vol Count", extremeVolCount]
        ],
        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
    )
}