Perfected FlowScript
True Range Histogram
True Range Histogram Pro — Perfected Edition is indexed as 343_true_range_histogram.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
13.7 KB
Lines
449
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Extreme Spike
line 371:9
Trigger
(showShapes) && (spikeAlert)
Value
tr
Deps
showShapes:input, spikeAlert:var
Compression
line 381:9
Trigger
(showShapes) && (compressionAlert)
Value
tr
Deps
compressionAlert:var, showShapes:input
Expansion
line 391:9
Trigger
(showShapes) && (expansionAlert)
Value
tr
Deps
expansionAlert:var, showShapes:input
ATR Break
line 401:9
Trigger
(showShapes) && (atrBreakUp)
Value
tr
Deps
atrBreakUp:var, showShapes:input
343_true_range_histogram.flowscript
source path: kscripts/perfected/343_true_range_histogram.flowscript · sha256:39d3066323e5d08eb642eb03d0ab0fd45d14e64b75de8d41e35b6db18df9a409
//@version=2
// ============================================================================
// True Range Histogram Pro — Perfected Edition
// Author: S (@Shea777x) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #atr, #true-range, #volatility, #histogram, #regime
//
// Production-quality volatility analysis indicator displaying per-candle True
// Range as a colour-coded histogram with ATR overlay, ATR-based normalised
// histogram, volatility regime detection, dynamic thresholds, extreme-spike
// shape alerts, and cumulative statistics via static state tracking.
//
// Research papers underpinning this design:
// 1. Wilder (1978), "New Concepts in Technical Trading Systems": canonical
// introduction of True Range and ATR. TR = max(High−Low, |High−Closeₚᵣᵢₒᵣ|,
// |Low−Closeₚᵣᵢₒᵣ|); ATR = SMA(TR, N). Original smoothing period = 14.
// 2. Leung & Chong (2003), "An Empirical Comparison of Moving Average
// Envelopes and Bollinger Bands": standard-deviation-based bands outperform
// fixed envelopes; per-candle TR is the raw input to both ATR and stdev.
// 3. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
// Supply and Demand": liquidity memory explains volatility clustering. TR
// spikes flag liquidity depletion and regime shifts.
// 4. Yang Xu et al. (2021), "Price Volatility Characteristics...": ARIMA-GJR-
// GARCH decomposition validates that unexpected volatility shocks (TR
// spikes) carry more predictive information than expected volatility.
// 5. Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the Basis
// and Open Interest in Futures Contracts": volatility regimes are linked to
// information flow; extreme TR episodes predict subsequent range expansion.
// ============================================================================
define(
title="True Range Histogram Pro — Perfected Edition",
position="offchart",
axis=true
)
// ----------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ----------------------------------------------------------------------------
// --- True Range ---
var trLookback = input(
name="trLookback",
type="number",
defaultValue=1,
label="TR Lookback (bars)",
constraints={min: 1, max: 10, step: 1},
group="True Range"
)
// --- ATR ---
var atrLen = input(
name="atrLen",
type="number",
defaultValue=14,
label="ATR Length",
constraints={min: 2, max: 50, step: 1},
group="ATR"
)
var atrSmooth = input(
name="atrSmooth",
type="number",
defaultValue=3,
label="ATR EMA Smooth",
constraints={min: 1, max: 20, step: 1},
group="ATR"
)
// --- Volatility Regime ---
var regimeLookback = input(
name="regimeLookback",
type="number",
defaultValue=20,
label="Regime Lookback",
constraints={min: 5, max: 100, step: 1},
group="Volatility Regime"
)
var lowMult = input(
name="lowMult",
type="number",
defaultValue=0.5,
label="Low Volatility Multiplier (× ATR)",
constraints={min: 0.1, max: 1.0, step: 0.1},
group="Volatility Regime"
)
var highMult = input(
name="highMult",
type="number",
defaultValue=1.5,
label="High Volatility Multiplier (× ATR)",
constraints={min: 1.0, max: 3.0, step: 0.1},
group="Volatility Regime"
)
var extremeMult = input(
name="extremeMult",
type="number",
defaultValue=2.5,
label="Extreme Volatility Multiplier (× ATR)",
constraints={min: 2.0, max: 5.0, step: 0.1},
group="Volatility Regime"
)
// --- Display ---
var showTrHist = input(
name="showTrHist",
type="boolean",
defaultValue=true,
label="Show TR Histogram",
group="Display"
)
var showAtrLine = input(
name="showAtrLine",
type="boolean",
defaultValue=true,
label="Show ATR Line",
group="Display"
)
var showNormHist = input(
name="showNormHist",
type="boolean",
defaultValue=true,
label="Show Normalised TR Histogram",
group="Display"
)
var showRegimeFill = input(
name="showRegimeFill",
type="boolean",
defaultValue=true,
label="Show Regime Fill Areas",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Spike Shapes",
group="Display"
)
var showPercentile = input(
name="showPercentile",
type="boolean",
defaultValue=true,
label="Show TR Percentile Line",
group="Display"
)
// --- Colors ---
var lowVolColor = input(
name="lowVolColor",
type="color",
defaultValue="#42a5f5",
label="Low Volatility Color",
group="Colors"
)
var normalVolColor = input(
name="normalVolColor",
type="color",
defaultValue="#78909c",
label="Normal Volatility Color",
group="Colors"
)
var highVolColor = input(
name="highVolColor",
type="color",
defaultValue="#ffa726",
label="High Volatility Color",
group="Colors"
)
var extremeVolColor = input(
name="extremeVolColor",
type="color",
defaultValue="#ef5350",
label="Extreme Volatility Color",
group="Colors"
)
var atrColor = input(
name="atrColor",
type="color",
defaultValue="#ffffff",
label="ATR Line Color",
group="Colors"
)
// ----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ----------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
if (isnan(px[0]) || isnan(bars.high[0]) || isnan(bars.low[0])) {
return
}
// ----------------------------------------------------------------------------
// 3. COMPUTATION
// ----------------------------------------------------------------------------
// -- 3.1 True Range --
timeseries prevClose = px[1]
timeseries tr = math.max(
bars.high - bars.low,
math.max(
math.abs(bars.high - prevClose),
math.abs(bars.low - prevClose)
)
)
// -- 3.2 ATR (smoothed) --
timeseries atrRaw = rma(source=tr, period=atrLen)
timeseries atr = ema(source=atrRaw, period=atrSmooth)
// -- 3.3 Normalised TR (TR as a multiple of ATR) --
timeseries trNorm = (atr > 0) ? tr / atr : 1
// -- 3.4 TR Percentile (rolling rank within lookback) --
// Approximate percentile via counting bars below current TR
timeseries trPercentile = 50.0
// Use a simplified proxy: how many stdevs is TR from mean?
timeseries trMean = sma(source=tr, period=regimeLookback)
timeseries trStd = stdev(source=tr, period=regimeLookback)
timeseries trZ = (trStd > 0) ? (tr - trMean) / trStd : 0
timeseries trPercentileProxy = 50 + (trZ * 15)
timeseries trPercentileClamped = math.min(100, math.max(0, trPercentileProxy))
// -- 3.5 Volatility Regime Detection --
timeseries lowThreshold = atr * lowMult
timeseries highThreshold = atr * highMult
timeseries extremeThreshold = atr * extremeMult
var regimeLow = tr < lowThreshold
var regimeHigh = tr > highThreshold
var regimeExtreme = tr > extremeThreshold
var regimeNormal = !regimeLow && !regimeHigh
// Regime colour index: 0=low, 1=normal, 2=high, 3=extreme
var regimeIdx = regimeExtreme ? 3 : (regimeHigh ? 2 : (regimeLow ? 0 : 1))
// -- 3.6 Candle Direction --
var isBull = px[0] > px[1]
var isBear = px[0] < px[1]
// ----------------------------------------------------------------------------
// 4. STATIC STATE TRACKING
// ----------------------------------------------------------------------------
static totalBars = 0
static lowVolBars = 0
static highVolBars = 0
static extremeVolBars = 0
static spikeCount = 0
static prevRegime = -1
static regimeChanges = 0
static maxTR = 0.0
static minTR = 0.0
static avgTR = 0.0
static cumTR = 0.0
if (!isLiveUpdate) {
totalBars = totalBars + 1
cumTR = cumTR + tr[0]
avgTR = (totalBars > 0) ? cumTR / totalBars : 0
if (tr[0] > maxTR) { maxTR = tr[0] }
if (minTR == 0 || tr[0] < minTR) { minTR = tr[0] }
if (regimeLow) { lowVolBars = lowVolBars + 1 }
if (regimeHigh) { highVolBars = highVolBars + 1 }
if (regimeExtreme) { extremeVolBars = extremeVolBars + 1 }
if (regimeExtreme || (regimeHigh && isBull)) { spikeCount = spikeCount + 1 }
var currentRegime = regimeIdx
if (prevRegime >= 0 && currentRegime != prevRegime) {
regimeChanges = regimeChanges + 1
}
prevRegime = currentRegime
}
// ----------------------------------------------------------------------------
// 5. ALERT CONDITIONS
// ----------------------------------------------------------------------------
var spikeAlert = regimeExtreme && !regimeExtreme[1]
var compressionAlert = regimeLow && !regimeLow[1]
var expansionAlert = regimeHigh && !regimeHigh[1]
var atrBreakUp = tr > (atr * 2) && tr[1] <= (atr[1] * 2)
var atrBreakDown = tr < (atr * 0.3) && tr[1] >= (atr[1] * 0.3)
// ----------------------------------------------------------------------------
// 6. VISUALIZATION
// ----------------------------------------------------------------------------
// --- Zero line ---
hline(value=0, color="#ffffff20", width=1)
// --- TR Histogram (regime-coloured) ---
if (showTrHist) {
plotBar(
value=tr,
colors=[
transparency(lowVolColor, 30),
transparency(normalVolColor, 30),
transparency(highVolColor, 30),
transparency(extremeVolColor, 30)
],
colorIndex=regimeIdx,
width=1,
label=["True Range"],
desc=["Per-candle True Range coloured by volatility regime"]
)
}
// --- ATR Line ---
if (showAtrLine) {
plotLine(
value=atr,
width=2,
colors=[atrColor],
label=["ATR"],
desc=["Average True Range (smoothed) — volatility baseline"]
)
}
// --- Regime Threshold Lines ---
if (showRegimeFill) {
hline(value=highThreshold[0], color=transparency(highVolColor, 50), width=1)
hline(value=lowThreshold[0], color=transparency(lowVolColor, 50), width=1)
}
// --- ATR Fill (TR vs ATR ribbon) ---
if (showRegimeFill) {
var trAboveAtr = tr > atr
plotLine(
value=[tr, atr],
width=1,
colors=[transparency(highVolColor, 20), transparency(lowVolColor, 20)],
colorIndex=trAboveAtr ? 0 : 1,
fill=true,
label=["TR", "ATR"],
desc=["Fill between True Range and ATR baseline"]
)
}
// --- Normalised TR Histogram (TR / ATR) ---
if (showNormHist) {
var normBull = trNorm >= 1
plotBar(
value=trNorm - 1,
colors=[transparency(highVolColor, 50), transparency(lowVolColor, 50)],
colorIndex=normBull ? 0 : 1,
width=1,
label=["TR/ATR Ratio"],
desc=["Normalised TR: deviation from ATR baseline (centred at 0)"]
)
}
// --- TR Percentile Line ---
if (showPercentile) {
plotLine(
value=trPercentileClamped,
width=1,
colors=["#7c4dff"],
label=["TR Percentile"],
desc=["Approximate TR percentile within rolling lookback (0-100)"]
)
hline(value=50, color="#ffffff15", width=1)
hline(value=80, color=transparency(extremeVolColor, 40), width=1)
hline(value=20, color=transparency(lowVolColor, 40), width=1)
}
// --- Spike Shapes ---
if (showShapes) {
if (spikeAlert) {
plotShape(
value=tr,
shape="triangledown",
colorIndex=extremeVolColor,
width=3,
label=["Extreme Spike"],
desc=["True Range spiked into extreme volatility regime (> " + extremeMult + "× ATR)"]
)
}
if (compressionAlert) {
plotShape(
value=tr,
shape="triangleup",
colorIndex=lowVolColor,
width=2,
label=["Compression"],
desc=["True Range compressed into low-volatility regime (< " + lowMult + "× ATR)"]
)
}
if (expansionAlert) {
plotShape(
value=tr,
shape="xcross",
colorIndex=highVolColor,
width=2,
label=["Expansion"],
desc=["True Range expanded into high-volatility regime (> " + highMult + "× ATR)"]
)
}
if (atrBreakUp) {
plotShape(
value=tr,
shape="arrowdown",
colorIndex=extremeVolColor,
width=1,
label=["ATR Break"],
desc=["TR broke 2× ATR — potential volatility breakout"]
)
}
}
// ----------------------------------------------------------------------------
// 7. REGIME TABLE (last bar only)
// ----------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regimeExtreme ? "EXTREME" : (regimeHigh ? "HIGH" : (regimeLow ? "LOW" : "NORMAL"))
var regimeTextColor = regimeExtreme ? extremeVolColor : (regimeHigh ? highVolColor : (regimeLow ? lowVolColor : normalVolColor))
var lowPct = (totalBars > 0) ? (lowVolBars / totalBars) * 100 : 0
var highPct = (totalBars > 0) ? (highVolBars / totalBars) * 100 : 0
var extremePct = (totalBars > 0) ? (extremeVolBars / totalBars) * 100 : 0
plotTable(
data=[
["TR Histogram Pro", regimeText],
["TR", tr[0]],
["ATR", atr[0]],
["TR/ATR", trNorm[0]],
["TR Percentile", trPercentileClamped[0]],
["Low Vol %", lowPct],
["High Vol %", highPct],
["Extreme Vol %", extremePct],
["Max TR", maxTR],
["Avg TR", avgTR],
["Regime Changes", regimeChanges]
],
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
)
}