Perfected FlowScript
VWAP Z-Score & Exhaustion (TV - Algopint - Merge)
VWAP Z-Score & Exhaustion — Perfected Edition is indexed as 181_vwap_z_score_exhaustion.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
14.6 KB
Lines
471
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Fade Short
line 382:9
Trigger
(showExhaustion) && (fadeShortSig)
Value
zSmooth
Deps
fadeShortSig:var, showExhaustion:input
Fade Long
line 392:9
Trigger
(showExhaustion) && (fadeLongSig)
Value
zSmooth
Deps
fadeLongSig:var, showExhaustion:input
Extreme High
line 406:9
Trigger
(showExtreme) && (extremeHighSig)
Value
zSmooth
Deps
extremeHighSig:var, showExtreme:input
Extreme Low
line 416:9
Trigger
(showExtreme) && (extremeLowSig)
Value
zSmooth
Deps
extremeLowSig:var, showExtreme:input
181_vwap_z_score_exhaustion.flowscript
source path: kscripts/perfected/181_vwap_z_score_exhaustion.flowscript · sha256:bf5df2a1ad90144da3d110b4858df417f3065465c8640fe5b6ff65f3e375ee75
//@version=2
// Source: kiyotaka.ai/hub/kscript (original) — Perfected by kScript_Perfection_Engineer
// ============================================================================
// VWAP Z-Score & Exhaustion [Perfected Edition]
// Author: E (@Edward) — Perfected by kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, #VWAP, #Z-Score, #exhaustion, #meanreversion, #volume
//
// Production-quality rolling VWAP Z-Score oscillator with volume exhaustion
// detection, intrabar delta proxy, and comprehensive fill/shape/visualization
// suite. Color-coded by regime, fills between Z-Score and zero, shape markers
// for extreme deviations and exhaustion events, and a summary table on the
// last bar. Uses static variables for reliable stateful signal tracking.
//
// Research papers underpinning this design:
// - Berkowitz, Logue & Noser (1988), "The Total Cost of Transactions on the
// NYSE": foundational VWAP formula VWAP = Σ(Price_i × Volume_i) / ΣVolume_i
// as institutional benchmark.
// - NinjaTrader (2026), "Z-Score Futures Trading Strategy": z = (Price - VWAP)
// / σ; ~95% of values within ±2σ, making extreme deviations fade candidates.
// - Easley, López de Prado & O'Hara (2012), "Bulk Classification of Trading
// Activity": BVC probabilistic volume classification; intrabar delta proxy
// based on close position within bar range.
// - Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
// Supply and Demand": liquidity memory model explains why volume exhaustion
// (current vol < SMA) signals move fatigue and follow-through failure.
// - Poterba & Summers (1988), "Mean Reversion in Stock Prices": negative
// autocorrelation at medium horizons supports mean-reversion at extremes.
// ============================================================================
define(
title="VWAP Z-Score & Exhaustion — Perfected Edition",
position="offchart",
axis=true
)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// ---------------------------------------------------------------------------
// --- VWAP Settings ---
var rvLen = input(
name="rvLen",
type="number",
defaultValue=14,
label="VWAP Lookback",
constraints={min: 5, max: 200, step: 1},
group="VWAP Settings"
)
var zLen = input(
name="zLen",
type="number",
defaultValue=50,
label="Z-Score Window",
constraints={min: 10, max: 500, step: 1},
group="VWAP Settings"
)
// --- Exhaustion Thresholds ---
var upperThresh = input(
name="upperThresh",
type="number",
defaultValue=2.5,
label="Upper Threshold (σ)",
constraints={min: 1.0, max: 5.0, step: 0.1},
group="Exhaustion"
)
var lowerThresh = input(
name="lowerThresh",
type="number",
defaultValue=-2.5,
label="Lower Threshold (σ)",
constraints={min: -5.0, max: -1.0, step: 0.1},
group="Exhaustion"
)
var extremeUpper = input(
name="extremeUpper",
type="number",
defaultValue=3.5,
label="Extreme Upper (σ)",
constraints={min: 2.0, max: 6.0, step: 0.1},
group="Exhaustion"
)
var extremeLower = input(
name="extremeLower",
type="number",
defaultValue=-3.5,
label="Extreme Lower (σ)",
constraints={min: -6.0, max: -2.0, step: 0.1},
group="Exhaustion"
)
// --- Volume ---
var smaLen = input(
name="smaLen",
type="number",
defaultValue=20,
label="Volume SMA Length",
constraints={min: 5, max: 100, step: 1},
group="Volume"
)
var smoothLen = input(
name="smoothLen",
type="number",
defaultValue=3,
label="Output Smoothing",
constraints={min: 1, max: 20, step: 1},
group="Volume"
)
// --- Display ---
var showZLine = input(
name="showZLine",
type="boolean",
defaultValue=true,
label="Show Z-Score Line",
group="Display"
)
var showFill = input(
name="showFill",
type="boolean",
defaultValue=true,
label="Show Z-Score Fill",
group="Display"
)
var showVwap = input(
name="showVwap",
type="boolean",
defaultValue=false,
label="Show VWAP Line (on chart)",
group="Display"
)
var showExhaustion = input(
name="showExhaustion",
type="boolean",
defaultValue=true,
label="Show Exhaustion Shapes",
group="Display"
)
var showExtreme = input(
name="showExtreme",
type="boolean",
defaultValue=true,
label="Show Extreme Deviation Shapes",
group="Display"
)
var showHist = input(
name="showHist",
type="boolean",
defaultValue=true,
label="Show Z Momentum Histogram",
group="Display"
)
var markerSize = input(
name="markerSize",
type="number",
defaultValue=2,
label="Shape Size",
constraints={min: 1, max: 4, step: 1},
group="Display"
)
// --- Colors ---
var bullColor = input(
name="bullColor",
type="color",
defaultValue="#26a69a",
label="Bull Color (negative z = below VWAP)",
group="Colors"
)
var bearColor = input(
name="bearColor",
type="color",
defaultValue="#ef5350",
label="Bear Color (positive z = above VWAP)",
group="Colors"
)
var fadeShortColor = input(
name="fadeShortColor",
type="color",
defaultValue="#ff1744",
label="Fade Short Color",
group="Colors"
)
var fadeLongColor = input(
name="fadeLongColor",
type="color",
defaultValue="#00e676",
label="Fade Long Color",
group="Colors"
)
var nodeColor = input(
name="nodeColor",
type="color",
defaultValue="#ffa726",
label="Exhaustion Node 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
timeseries volume = price.volume
if (isnan(close[0]) || isnan(high[0]) || isnan(low[0]) || isnan(volume[0])) {
return
}
// ---------------------------------------------------------------------------
// 3. ROLLING VWAP & VOLUME-WEIGHTED STD DEV
// ---------------------------------------------------------------------------
// VWAP = Σ(Price × Volume) / Σ(Volume) over rolling window
// Use HLC3 as price source for volume weighting (typical price)
timeseries typ = (high + low + close) / 3
timeseries pv = typ * volume
timeseries cumPV = sum(pv, rvLen)
timeseries cumV = sum(volume, rvLen)
timeseries vwap = cumV > 0 ? cumPV / cumV : typ
// Volume-weighted variance = Σ(V × (P - VWAP)²) / Σ(V)
timeseries devSq = (typ - vwap) * (typ - vwap) * volume
timeseries sumSqDev = sum(devSq, rvLen)
timeseries variance = cumV > 0 ? sumSqDev / cumV : 0
timeseries vwStd = math.sqrt(math.max(variance, 0))
// ---------------------------------------------------------------------------
// 4. Z-SCORE CALCULATION
// ---------------------------------------------------------------------------
// z = (Close - VWAP) / σ; EMA-smoothed for cleaner signal
timeseries zRaw = (close - vwap) / math.max(vwStd, 0.0001)
timeseries zSmooth = ema(zRaw, smoothLen)
// Z momentum histogram (rate of change in z-score)
timeseries zMomentum = zSmooth - zSmooth[1]
// ---------------------------------------------------------------------------
// 5. VOLUME EXHAUSTION
// ---------------------------------------------------------------------------
// Volume exhausted = current volume below its SMA (liquidity drying up)
timeseries volSMA = sma(volume, smaLen)
var volExhausted = volume < volSMA
// ---------------------------------------------------------------------------
// 6. INTRABAR DELTA PROXY
// ---------------------------------------------------------------------------
// Per BVC (Easley et al. 2012): allocate volume based on close position
// within bar range. Close near high = more buyer-initiated; near low =
// more seller-initiated.
timeseries rng = math.max(high - low, 0.0001)
timeseries closePos = (close - low) / rng
timeseries delta = (closePos - 0.5) * volume * 2.0
// Delta SMA for cleaner signal
timeseries deltaSMA = sma(delta, smaLen)
// ---------------------------------------------------------------------------
// 7. REGIME DETECTION
// ---------------------------------------------------------------------------
// Z-score regime: above/below VWAP, extreme thresholds
var zAbove = zSmooth > 0
var zExtremeHigh = zSmooth >= extremeUpper
var zExtremeLow = zSmooth <= extremeLower
var zOverbought = zSmooth >= upperThresh
var zOversold = zSmooth <= lowerThresh
// ---------------------------------------------------------------------------
// 8. EXHAUSTION SIGNALS (static for reliable one-shot detection)
// ---------------------------------------------------------------------------
// Fade Short: z > upper, vol exhausted, delta negative (sellers in control)
// Fade Long: z < lower, vol exhausted, delta positive (buyers in control)
static lastFadeShort = -1
static lastFadeLong = -1
var fadeShortSig = false
var fadeLongSig = false
// One-shot: only fire once per exhaustion event (bar-based debounce)
if (!isLiveUpdate) {
fadeShortSig = zSmooth > upperThresh && volExhausted && deltaSMA < 0
if (fadeShortSig) {
if (lastFadeShort == barIndex) {
fadeShortSig = false
} else {
lastFadeShort = barIndex
}
}
fadeLongSig = zSmooth < lowerThresh && volExhausted && deltaSMA > 0
if (fadeLongSig) {
if (lastFadeLong == barIndex) {
fadeLongSig = false
} else {
lastFadeLong = barIndex
}
}
}
// Extreme deviation signals (one-shot)
static lastExtremeHigh = -1
static lastExtremeLow = -1
var extremeHighSig = false
var extremeLowSig = false
if (!isLiveUpdate) {
extremeHighSig = zSmooth >= extremeUpper
if (extremeHighSig) {
if (lastExtremeHigh == barIndex) {
extremeHighSig = false
} else {
lastExtremeHigh = barIndex
}
}
extremeLowSig = zSmooth <= extremeLower
if (extremeLowSig) {
if (lastExtremeLow == barIndex) {
extremeLowSig = false
} else {
lastExtremeLow = barIndex
}
}
}
// ---------------------------------------------------------------------------
// 9. PLOTTING
// ---------------------------------------------------------------------------
// --- Z-Score Line (regime-colored) ---
if (showZLine) {
plotLine(
value=zSmooth,
colors=[bearColor, bullColor],
colorIndex=zAbove ? 0 : 1,
width=2,
label=["VWAP Z"],
desc=["Rolling VWAP Z-Score (EMA-smoothed)"]
)
}
// --- Z-Score Fill (to zero line) ---
if (showFill) {
plotLine(
value=[0, zSmooth],
colors=[opacity(bearColor, 15), opacity(bullColor, 15)],
colorIndex=zAbove ? 0 : 1,
fill=true,
width=1,
label=["Z Fill"],
desc=["Fill between Z-Score and zero (regime-colored)"]
)
}
// --- Z Momentum Histogram ---
if (showHist) {
var histBull = zMomentum >= 0
plotBar(
value=zMomentum,
colors=[opacity(bullColor, 50), opacity(bearColor, 50)],
colorIndex=histBull ? 0 : 1,
width=1,
label=["Z Momentum"],
desc=["Rate of change in Z-Score (momentum histogram)"]
)
}
// --- Reference Lines ---
hline(value=0, color=transparency("#ffffff", 85), width=1)
hline(value=upperThresh, color=transparency(bearColor, 60), width=1)
hline(value=lowerThresh, color=transparency(bullColor, 60), width=1)
hline(value=extremeUpper, color=transparency(fadeShortColor, 70), width=1, style="dashed")
hline(value=extremeLower, color=transparency(fadeLongColor, 70), width=1, style="dashed")
// --- Exhaustion Shape Markers ---
if (showExhaustion) {
if (fadeShortSig) {
plotShape(
value=zSmooth,
shape="triangledown",
colorIndex=fadeShortColor,
width=markerSize,
label=["Fade Short"],
desc=["Z > " + upperThresh + " + vol exhausted + negative delta: potential short fade"]
)
}
if (fadeLongSig) {
plotShape(
value=zSmooth,
shape="triangleup",
colorIndex=fadeLongColor,
width=markerSize,
label=["Fade Long"],
desc=["Z < " + lowerThresh + " + vol exhausted + positive delta: potential long fade"]
)
}
}
// --- Extreme Deviation Shape Markers ---
if (showExtreme) {
if (extremeHighSig) {
plotShape(
value=zSmooth,
shape="xcross",
colorIndex=nodeColor,
width=markerSize,
label=["Extreme High"],
desc=["Z-Score reached extreme upper bound (>= " + extremeUpper + "σ)"]
)
}
if (extremeLowSig) {
plotShape(
value=zSmooth,
shape="xcross",
colorIndex=nodeColor,
width=markerSize,
label=["Extreme Low"],
desc=["Z-Score reached extreme lower bound (<= " + extremeLower + "σ)"]
)
}
}
// --- On-Chart VWAP (optional, for fill between price and VWAP) ---
if (showVwap) {
plotLine(
value=vwap,
colors=["#42a5f5"],
width=1,
label=["VWAP"],
desc=["Rolling volume-weighted average price"]
)
}
// ---------------------------------------------------------------------------
// 10. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
var regimeText = zExtremeHigh ? "EXTREME OVERBOUGHT" : (zExtremeLow ? "EXTREME OVERSOLD" : (zOverbought ? "OVERBOUGHT" : (zOversold ? "OVERSOLD" : (zAbove ? "ABOVE VWAP" : "BELOW VWAP"))))
var regimeTextColor = zExtremeHigh ? fadeShortColor : (zExtremeLow ? fadeLongColor : (zAbove ? bearColor : bullColor))
var volStatus = volExhausted ? "EXHAUSTED" : "ACTIVE"
var volColor = volExhausted ? nodeColor : "#9e9e9e"
var deltaStatus = deltaSMA > 0 ? "NET BUYERS" : (deltaSMA < 0 ? "NET SELLERS" : "BALANCED")
var deltaColor = deltaSMA > 0 ? bullColor : (deltaSMA < 0 ? bearColor : "#9e9e9e")
plotTable(
data=[
["VWAP Z-Score — Perfected", regimeText],
["Z-Score", zSmooth[0]],
["VWAP", vwap[0]],
["Volume", volStatus],
["Delta", deltaStatus],
["Z Momentum", zMomentum[0]]
],
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
)
}