Perfected FlowScript
Liquidity-Adjusted ATR/Vol Forecast
Liquidity-Adjusted ATR/Vol Forecast [LAF] is indexed as 213_liquidity_adjusted_atr_vol_forecast.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.9 KB
Lines
329
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Band Expanding
line 283:5
Trigger
(showShapes && bandExpanding)
Value
bandUpper
Deps
bandExpanding:var, showShapes:input
Band Squeeze
line 293:5
Trigger
(showShapes && bandSqueezing)
Value
bandLower
Deps
bandSqueezing:var, showShapes:input
Upper Band Touch
line 303:5
Trigger
(showShapes && touchUpper)
Value
bandUpper
Deps
showShapes:input, touchUpper:var
Lower Band Touch
line 313:5
Trigger
(showShapes && touchLower)
Value
bandLower
Deps
showShapes:input, touchLower:var
213_liquidity_adjusted_atr_vol_forecast.flowscript
source path: kscripts/perfected/213_liquidity_adjusted_atr_vol_forecast.flowscript · sha256:c62b9a0cada80dd839af5bfdfcc49463a88aa7e03601faddb5e2ab55a68d9c24
//@version=2
// Source: kiyotaka.ai/hub/kscript (original) — Perfected by kScript_Perfection_Engineer
// ============================================================================
// Liquidity-Adjusted ATR Volatility Forecast [LAF] — Perfected
// Author: D — Perfected by kScript_Perfection_Engineer
// Tags: ADVANCED, #atr, #volatility, #liquidity, #forecast, #zscore, #orderbook
//
// Predicts next-bar volatility by combining traditional ATR with real-time
// orderbook depth analysis. Liquidity-adjusted bands expand when the book is
// thin (higher adverse-selection cost) and contract when depth is abundant.
// A volatility forecast via EMA of ATR, z-score normalisation, and regime
// detection provide a complete statistical framework.
//
// Research papers underpinning this design:
// 1. Wilder (1978), *New Concepts in Technical Trading Systems*: Original
// ATR formula — ATR = SMA(TR, N), where TR = max(H−L, |H−C₁|, |L−C₁|).
// 2. Amihud & Mendelson (1986), "Asset Pricing and the Bid-Ask Spread":
// Spread as proxy for illiquidity; expected returns increase with spread.
// [Formula] LiquidityCost ∝ Spread / MidPrice
// 3. Kyle (1985), "Continuous Auctions and Insider Trading":
// Three dimensions of liquidity — tightness, depth, resiliency.
// λ (price-impact coefficient) inversely proportional to depth.
// [Formula] p_t = p_{t−1} + λ·OFI_t + noise
// 4. Paddrik, Hayes, Scherer & Beling (2014), "Effects of Limit Order Book
// Information Level on Market Stability Metrics": OBWA (Order Book
// Weighted Average Spread) using first 10 depth levels; deeper book
// information improves stability assessment.
// 5. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events":
// OFI_t = Δq_t^b·I_{Δq_t^b>0} − Δq_t^a·I_{Δq_t^a>0}; price impact slope
// inversely proportional to market depth.
// 6. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint":
// Z-score event triggers: z_t = (x_t − μ) / σ; entry thresholds at ±d·σ.
// ============================================================================
define(
title="Liquidity-Adjusted ATR/Vol Forecast [LAF]",
position="onchart",
axis=false
)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// -- ATR Group --
var atrPeriod = input(name="atrPeriod", type="number", defaultValue=14, label="ATR Period", constraints={min: 5, max: 50, step: 1}, group="ATR")
var atrMult = input(name="atrMult", type="number", defaultValue=1.5, label="Band Multiplier (x ATR)", constraints={min: 0.5, max: 5.0, step: 0.1}, group="ATR")
var forecastLen = input(name="forecastLen", type="number", defaultValue=14, label="Vol Forecast EMA Length", constraints={min: 5, max: 50, step: 1}, group="ATR")
// -- Liquidity Group --
var depth1 = input(name="depth1", type="number", defaultValue=0.5, label="Depth 1 (%)", constraints={min: 0.1, max: 5.0, step: 0.1}, group="Liquidity")
var depth2 = input(name="depth2", type="number", defaultValue=1.0, label="Depth 2 (%)", constraints={min: 0.1, max: 10.0, step: 0.1}, group="Liquidity")
var depth3 = input(name="depth3", type="number", defaultValue=2.0, label="Depth 3 (%)", constraints={min: 0.1, max: 20.0, step: 0.1}, group="Liquidity")
var liqLookback = input(name="liqLookback", type="number", defaultValue=50, label="Liquidity MA Lookback", constraints={min: 10, max: 200, step: 5}, group="Liquidity")
var useOrderbook = input(name="useOrderbook", type="boolean", defaultValue=true, label="Use Orderbook Depth", group="Liquidity")
// -- Z-Score Group --
var zLookback = input(name="zLookback", type="number", defaultValue=50, label="Z-Score Window", constraints={min: 20, max: 200, step: 5}, group="Z-Score")
var zThreshold = input(name="zThreshold", type="number", defaultValue=2.0, label="Z-Score Regime Threshold", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Z-Score")
// -- Display Group --
var showBands = input(name="showBands", type="boolean", defaultValue=true, label="Show Liquidity-Adjusted Bands", group="Display")
var showForecast = input(name="showForecast", type="boolean", defaultValue=true, label="Show Vol Forecast", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show ATR Z-Score", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shape Alerts", group="Display")
var lineWidth = input(name="lineWidth", type="number", defaultValue=2, label="Line Width", constraints={min: 1, max: 4, step: 1}, group="Display")
var shapeSize = input(name="shapeSize", type="number", defaultValue=2, label="Shape Size", constraints={min: 1, max: 4, step: 1}, group="Display")
// -- Colors Group --
var bandColor = input(name="bandColor", type="color", defaultValue="#00bcd4", label="Band Color", group="Colors")
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Bullish Regime Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Bearish Regime Color", group="Colors")
var forecastColor = input(name="forecastColor", type="color", defaultValue="#ff9800", label="Vol Forecast Color", group="Colors")
var zHighColor = input(name="zHighColor", type="color", defaultValue="#d50000", label="High Z-Score Color", group="Colors")
var zLowColor = input(name="zLowColor", type="color", defaultValue="#00c853", label="Low Z-Score Color", group="Colors")
// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first access
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = bars.close
timeseries high = bars.high
timeseries low = bars.low
timeseries t = bars.time
// Orderbook depth (if available)
timeseries obi = source("orderbook_imbalance", currentSymbol, currentExchange)
// Guard: halt until OHLCV has loaded
if (isnan(t[0]) || isnan(close[0]) || isnan(high[0]) || isnan(low[0])) {
return
}
// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------
// -- 3.1 ATR computation (Wilder 1978) --
// TR = max(H − L, |H − C₁|, |L − C₁|)
timeseries tr = true_range(source=bars, period=atrPeriod)
timeseries atr = atr(source=bars, period=atrPeriod)
// -- 3.2 Liquidity proxy: volume within near-price range --
// Range-normalised volume as a liquidity proxy; when range is tight relative
// to volume, liquidity is thick. When range is wide relative to volume, thin.
timeseries range = high - low
timeseries vol = bars.volume
timeseries liq1 = vol * (depth1 / 100.0)
timeseries liq2 = vol * (depth2 / 100.0)
timeseries liq3 = vol * (depth3 / 100.0)
timeseries liqAvg = (liq1 + liq2 + liq3) / 3
// If orderbook imbalance is available, blend it into the liquidity signal
// Orderbook imbalance near ±1 indicates extreme directional commitment
// which reduces effective liquidity on the passive side.
timeseries obiAbs = isnum(obi) ? math.abs(obi) : 0
timeseries liqBlend = obiAbs > 0.5 ? liqAvg * (1.0 - obiAbs * 0.3) : liqAvg
timeseries liqMA = sma(source=liqBlend, period=liqLookback)
// Adjustment factor: 1.0 when liquidity = MA, > 1 when thin (high vol expected),
// < 1 when thick (low vol expected). Guard against zero division.
timeseries adj = liqMA > 0 ? liqMA / math.max(liqBlend, 1e-9) : 1.0
// -- 3.3 Liquidity-adjusted ATR bands --
timeseries adjATR = atr * atrMult * adj
timeseries bandUpper = close + adjATR
timeseries bandLower = close - adjATR
timeseries midUpper = close + adjATR * 0.5
timeseries midLower = close - adjATR * 0.5
// -- 3.4 Volatility forecast (EMA of ATR) --
// Forecast next-bar volatility using an EMA of the ATR series. This is a
// simple but effective predictive filter — see Kaufman (1995) for EMA-based
// volatility forecasting in adaptive systems.
timeseries volForecast = ema(source=atr, period=forecastLen)
timeseries forecastUpper = close + volForecast * atrMult
timeseries forecastLower = close - volForecast * atrMult
// -- 3.5 Z-score normalisation of ATR --
// Z_t = (ATR_t − μ_t) / σ_t, where μ = SMA(ATR, W), σ = StDev(ATR, W).
// Guards: if σ == 0 we emit 0 to prevent division-by-zero crashes.
timeseries atrMean = sma(source=atr, period=zLookback)
timeseries atrStd = stdev(source=atr, period=zLookback)
timeseries atrZ = (atrStd > 0) ? (atr - atrMean) / atrStd : 0
// -- 3.6 Regime detection --
// High Z → vol is expanding above normal (potential breakout / squeeze)
// Low Z → vol is contracting below normal (potential consolidation / pinch)
// Mid Z → normal volatility regime
var isHighVol = atrZ > zThreshold
var isLowVol = atrZ < -zThreshold
var isNormalVol = !isHighVol && !isLowVol
// Regime colour index: 0 = high vol (bearish for mean-reversion), 1 = low vol
// (bullish for breakout), 2 = normal
var regimeIdx = isHighVol ? 0 : (isLowVol ? 1 : 2)
// -- 3.7 Band squeeze / expansion detection (shape alerts) --
// Band expansion: adjATR exceeds its own EMA by a significant margin
// Band squeeze: adjATR falls below its own EMA by a significant margin
timeseries adjATR_MA = ema(source=adjATR, period=liqLookback)
var bandExpanding = adjATR > adjATR_MA * 1.2
var bandSqueezing = adjATR < adjATR_MA * 0.8
// -- 3.8 Static tracking for volatility forecast state --
// Tracks consecutive bars in each regime for context-aware alerting.
static lastRegime = 0
static highVolBars = 0
static lowVolBars = 0
static normalVolBars = 0
if (isHighVol) {
highVolBars = highVolBars + 1
lowVolBars = 0
normalVolBars = 0
lastRegime = 1
} else if (isLowVol) {
lowVolBars = lowVolBars + 1
highVolBars = 0
normalVolBars = 0
lastRegime = -1
} else {
normalVolBars = normalVolBars + 1
highVolBars = 0
lowVolBars = 0
lastRegime = 0
}
// -- 3.9 Touch detection --
var touchUpper = high >= bandUpper && low <= bandUpper
var touchLower = high >= bandLower && low <= bandLower
var touchForecastUpper = high >= forecastUpper && low <= forecastUpper
var touchForecastLower = high >= forecastLower && low <= forecastLower
// ---------------------------------------------------------------------------
// 4. VISUALIZATION
// ---------------------------------------------------------------------------
// 4.1 Liquidity-adjusted bands (plotLine, regime-coloured fill)
if (showBands) {
plotLine(
value=([bandLower, bandUpper]),
width=1,
colors=[opacity(bearColor, 12), opacity(bullColor, 12), opacity("#78909c", 10)],
colorIndex=regimeIdx,
fill=true,
label=["LAF Band Fill"],
desc=["Liquidity-adjusted ATR band fill (regime-coloured)"]
)
plotLine(
value=bandUpper,
width=lineWidth,
colors=[bandColor],
label=["LAF Upper"],
desc=["Liquidity-adjusted upper band: close + ATR × mult × adj"]
)
plotLine(
value=bandLower,
width=lineWidth,
colors=[bandColor],
label=["LAF Lower"],
desc=["Liquidity-adjusted lower band: close − ATR × mult × adj"]
)
plotLine(
value=midUpper,
width=1,
colors=[opacity(bandColor, 40)],
label=["LAF Mid Upper"],
desc=["50% mid upper band"]
)
plotLine(
value=midLower,
width=1,
colors=[opacity(bandColor, 40)],
label=["LAF Mid Lower"],
desc=["50% mid lower band"]
)
}
// 4.2 Volatility forecast (plotLine)
if (showForecast) {
plotLine(
value=forecastUpper,
width=1,
colors=[forecastColor],
label=["Vol Forecast Upper"],
desc=["EMA-based next-bar volatility forecast upper band"]
)
plotLine(
value=forecastLower,
width=1,
colors=[forecastColor],
label=["Vol Forecast Lower"],
desc=["EMA-based next-bar volatility forecast lower band"]
)
plotLine(
value=([forecastLower, forecastUpper]),
width=1,
colors=[opacity(forecastColor, 10)],
fill=true,
label=["Forecast Fill"],
desc=["Volatility forecast band fill"]
)
}
// 4.3 ATR Z-Score (plotLine, colour-coded by regime)
if (showZScore) {
plotLine(
value=atrZ,
width=2,
colors=[zHighColor, zLowColor, "#78909c"],
colorIndex=regimeIdx,
label=["ATR Z-Score"],
desc=["Z-score of ATR: (ATR − μ) / σ; > threshold = expanding, < −threshold = contracting"]
)
}
// 4.4 Shape markers for extreme events
if (showShapes && bandExpanding) {
plotShape(
value=bandUpper,
shape="triangledown",
colorIndex=bearColor,
width=shapeSize,
label=["Band Expanding"],
desc=["Liquidity-adjusted bands expanding; high volatility regime detected"]
)
}
if (showShapes && bandSqueezing) {
plotShape(
value=bandLower,
shape="triangleup",
colorIndex=bullColor,
width=shapeSize,
label=["Band Squeeze"],
desc=["Liquidity-adjusted bands squeezing; low volatility / potential breakout imminent"]
)
}
if (showShapes && touchUpper) {
plotShape(
value=bandUpper,
shape="triangledown",
colorIndex=bandColor,
width=shapeSize,
label=["Upper Band Touch"],
desc=["Price touched liquidity-adjusted upper band"]
)
}
if (showShapes && touchLower) {
plotShape(
value=bandLower,
shape="triangleup",
colorIndex=bandColor,
width=shapeSize,
label=["Lower Band Touch"],
desc=["Price touched liquidity-adjusted lower band"]
)
}
// 4.5 Reference hlines
hline(value=0, color="#ffffff30", width=1)
if (showZScore) {
hline(value=zThreshold, color="#ffffff20", width=1)
hline(value=-zThreshold, color="#ffffff20", width=1)
}