Perfected FlowScript
SCF VWAP Divergence
SCF VWAP Divergence [Perfected] is indexed as 086_scf_vwap_divergence.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
17.2 KB
Lines
440
Native Signal Candidates
8 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
VWAP Cross Up
line 357:5
Trigger
(showVwapCross && vwapCrossUp)
Value
dev
Deps
showVwapCross:input, vwapCrossUp:var
VWAP Cross Down
line 367:5
Trigger
(showVwapCross && vwapCrossDown)
Value
dev
Deps
showVwapCross:input, vwapCrossDown:var
Band 2 Upper Touch
line 379:5
Trigger
(showBandTouch && touchBand2Up)
Value
dev
Deps
showBandTouch:input, touchBand2Up:var
Band 2 Lower Touch
line 389:5
Trigger
(showBandTouch && touchBand2Dn)
Value
dev
Deps
showBandTouch:input, touchBand2Dn:var
Band 3 Upper Touch
line 399:5
Trigger
(showBandTouch && touchBand3Up)
Value
dev
Deps
showBandTouch:input, touchBand3Up:var
Band 3 Lower Touch
line 409:5
Trigger
(showBandTouch && touchBand3Dn)
Value
dev
Deps
showBandTouch:input, touchBand3Dn:var
Extreme Short Z
line 421:5
Trigger
(showExtreme && extremeZUp)
Value
devZ
Deps
extremeZUp:var, showExtreme:input
Extreme Long Z
line 431:5
Trigger
(showExtreme && extremeZDn)
Value
devZ
Deps
extremeZDn:var, showExtreme:input
086_scf_vwap_divergence.flowscript
source path: kscripts/perfected/086_scf_vwap_divergence.flowscript · sha256:9455395389c72eb5610b36fec5b6ec27a34df0048a34b8ffff521d264795881a
//@version=2
// Source: kiyotaka.ai/hub/kscript (original) — Perfected by kScript_Perfection_Engineer
// ============================================================================
// SCF VWAP Divergence — Anchored VWAP with Standard Deviation Bands [Perfected]
// Author: SoulzBTC (@SoulzBTC) — Perfected by kScript_Perfection_Engineer
// Tags: CORE, #vwap, #anchoredvwap, #divergence, #stddev, #zscore, #meanreversion
//
// Detects statistical deviation between price and anchored volume-weighted
// average price (VWAP) with proper daily anchoring, volume-weighted standard
// deviation bands, z-score normalization, and regime-coded visual cues.
//
// FORMULA FOUNDATION:
// 1. Anchored VWAP: VWAP = Σ(Price_i × Volume_i) / ΣVolume_i, reset daily
// per Berkowitz, Logue & Noser (1988) and Shannon (2021).
// 2. Volume-Weighted Standard Deviation: σ = √[Σ(Vᵢ·(Pᵢ−VWAP)²)/ΣVᵢ]
// per StudyRaid (2026); ~68.2% within ±1σ, ~95.4% within ±2σ.
// 3. VWAP Z-Score: z = (Price − VWAP) / σ, per NinjaTrader (2026);
// signals statistical rarity and mean-reversion potential at ±2σ.
// 4. Deviation EMA: smoothed price−VWAP for trend direction of divergence.
//
// RESEARCH BASIS:
// • Berkowitz, Logue & Noser (1988), "The Total Cost of Transactions on the
// NYSE": foundational VWAP as institutional benchmark.
// • Madhavan (2002), "VWAP Strategies": when VWAP is a sensible benchmark.
// • McCulloch & Kazakov (2007), "Optimal VWAP Trading Strategy": optimal
// volume-front-loading for better-than-VWAP execution.
// • Shannon (2021), "Maximum Trading Gains with the Anchored VWAP":
// AVWAP reveals institutional fair value; anchor quality decays 60–90 days.
// • StudyRaid (2026), "Standard Deviation Bands in VWAP": volume-weighted
// σ transforms VWAP into a dynamic volatility framework.
// • Harris (1986), "A Transaction Data Study of Weekly and Intradaily
// Patterns in Stock Returns": intraday seasonality supports session
// anchoring and daily reset conventions.
// ============================================================================
define(
title="SCF VWAP Divergence [Perfected]",
position="offchart",
axis=true
)
// ---------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ---------------------------------------------------------------------------
// --- Anchor Group ---
var anchorMode = input(name="anchorMode", type="select", defaultValue="Daily", label="Anchor Mode", options=["Daily", "4h", "8h", "12h", "Weekly", "Rolling 50 Bars", "Rolling 200 Bars"], group="Anchor")
var tzOffsetH = input(name="tzOffsetH", type="number", defaultValue=0, label="Timezone Offset (hours from UTC)", constraints={min: -12, max: 14, step: 1}, group="Anchor")
// --- Bands Group ---
var band1Mult = input(name="band1Mult", type="number", defaultValue=1.0, label="Band 1 Multiplier (σ)", constraints={min: 0.1, max: 5.0, step: 0.1}, group="Bands")
var band2Mult = input(name="band2Mult", type="number", defaultValue=2.0, label="Band 2 Multiplier (σ)", constraints={min: 0.1, max: 5.0, step: 0.1}, group="Bands")
var band3Mult = input(name="band3Mult", type="number", defaultValue=3.0, label="Band 3 Multiplier (σ)", constraints={min: 0.1, max: 5.0, step: 0.1}, group="Bands")
var showBand1 = input(name="showBand1", type="boolean", defaultValue=true, label="Show Band 1", group="Bands")
var showBand2 = input(name="showBand2", type="boolean", defaultValue=true, label="Show Band 2", group="Bands")
var showBand3 = input(name="showBand3", type="boolean", defaultValue=false, label="Show Band 3", group="Bands")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Deviation Fill", group="Bands")
// --- Z-Score Group ---
var zScoreWindow = input(name="zScoreWindow", type="number", defaultValue=20, label="Z-Score Lookback Window", constraints={min: 5, max: 100, step: 1}, group="Z-Score")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Z-Score")
var zThreshold = input(name="zThreshold", type="number", defaultValue=2.0, label="Z-Score Threshold (σ)", constraints={min: 0.5, max: 5.0, step: 0.1}, group="Z-Score")
// --- Display Group ---
var showRawDev = input(name="showRawDev", type="boolean", defaultValue=true, label="Show Raw Deviation Histogram", group="Display")
var showDevEma = input(name="showDevEma", type="boolean", defaultValue=true, label="Show Deviation EMA", group="Display")
var devEmaLen = input(name="devEmaLen", type="number", defaultValue=9, label="Deviation EMA Length", constraints={min: 2, max: 50, step: 1}, group="Display")
var showVwapCross = input(name="showVwapCross", type="boolean", defaultValue=true, label="Show VWAP Cross Shapes", group="Display")
var showBandTouch = input(name="showBandTouch", type="boolean", defaultValue=true, label="Show Band Touch Shapes", group="Display")
var showExtreme = input(name="showExtreme", type="boolean", defaultValue=true, label="Show Extreme Z-Score Shapes", 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 devAboveColor = input(name="devAboveColor", type="color", defaultValue="#26a69a", label="Deviation Above Color (Bull)", group="Colors")
var devBelowColor = input(name="devBelowColor", type="color", defaultValue="#ef5350", label="Deviation Below Color (Bear)", group="Colors")
var zScoreColor = input(name="zScoreColor", type="color", defaultValue="#ff9800", label="Z-Score Line Color", group="Colors")
var band1Color = input(name="band1Color", type="color", defaultValue="#9e9e9e", label="Band 1 Color", group="Colors")
var band2Color = input(name="band2Color", type="color", defaultValue="#9e9e9e", label="Band 2 Color", group="Colors")
var band3Color = input(name="band3Color", type="color", defaultValue="#9e9e9e", label="Band 3 Color", group="Colors")
var extremeColor = input(name="extremeColor", type="color", defaultValue="#ffeb3b", label="Extreme Signal Color", group="Colors")
// ---------------------------------------------------------------------------
// Data Sources
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries t = bars.time
timeseries close = bars.close
timeseries high = bars.high
timeseries low = bars.low
timeseries typ = (high + low + close) / 3
timeseries pv = typ * bars.volume
// isnan guard: prevent computation on incomplete data
if (isnan(t[0]) || isnan(close[0]) || isnan(bars.volume[0]) || isnan(high[0]) || isnan(low[0])) {
return
}
// ---------------------------------------------------------------------------
// Time Derivation (Calendar Math)
// ---------------------------------------------------------------------------
timeseries rawH = math.floor((t / 3600000) % 24)
timeseries utcH = ((rawH + tzOffsetH) % 24 + 24) % 24
var day_id = math.floor(t / 86400000)
var week_id = math.floor((day_id + 3) / 7)
// ---------------------------------------------------------------------------
// Anchor Detection (static variables for stateful computation)
// ---------------------------------------------------------------------------
static last_day_id = -1
static last_week_id = -1
static last_utcH = -1
static last_4h = -1
static last_8h = -1
static last_12h = -1
static barCount = 0
var newPeriod = false
var isRolling = false
var periodBars = 0
if (anchorMode == "4h") {
var period4h = math.floor(t / 14400000)
newPeriod = last_4h != -1 && period4h > last_4h
last_4h = period4h
} else if (anchorMode == "8h") {
var period8h = math.floor(t / 28800000)
newPeriod = last_8h != -1 && period8h > last_8h
last_8h = period8h
} else if (anchorMode == "12h") {
var period12h = math.floor(t / 43200000)
newPeriod = last_12h != -1 && period12h > last_12h
last_12h = period12h
} else if (anchorMode == "Daily") {
newPeriod = last_day_id != -1 && day_id > last_day_id
last_day_id = day_id
} else if (anchorMode == "Weekly") {
newPeriod = last_week_id != -1 && week_id > last_week_id
last_week_id = week_id
} else if (anchorMode == "Rolling 50 Bars") {
isRolling = true
periodBars = 50
} else if (anchorMode == "Rolling 200 Bars") {
isRolling = true
periodBars = 200
}
if (isRolling) {
if (barCount < periodBars) {
barCount = barCount + 1
} else {
barCount = periodBars
}
} else if (newPeriod || barCount == 0) {
barCount = 1
} else {
barCount = barCount + 1
}
// ---------------------------------------------------------------------------
// Anchored VWAP Computation
// ---------------------------------------------------------------------------
timeseries sumPV = sum(pv, barCount)
timeseries sumV = sum(bars.volume, barCount)
timeseries vwap = sumV > 0 ? sumPV / sumV : typ
// Volume-weighted standard deviation (anchored to current VWAP)
timeseries devSq = (typ - vwap) * (typ - vwap) * bars.volume
timeseries sumSqDev = sum(devSq, barCount)
timeseries variance = sumV > 0 ? sumSqDev / sumV : 0
timeseries sd = math.sqrt(math.max(0, variance))
// Deviation bands in price units
timeseries devBand1 = band1Mult * sd
timeseries devBand2 = band2Mult * sd
timeseries devBand3 = band3Mult * sd
// ---------------------------------------------------------------------------
// Price-VWAP Divergence Metrics
// ---------------------------------------------------------------------------
timeseries dev = close - vwap
timeseries devPct = vwap > 0 ? (close - vwap) / vwap * 100.0 : 0.0
// Z-score of deviation (normalized statistical distance from VWAP)
var devMean = sma(dev, zScoreWindow)
var devStd = stdev(dev, zScoreWindow)
var devZ = devStd > 0 ? (dev - devMean) / devStd : 0.0
// Deviation EMA for trend direction of divergence
var devEma = ema(dev, devEmaLen)
// ---------------------------------------------------------------------------
// Regime Detection (color coding by divergence direction)
// ---------------------------------------------------------------------------
var aboveVwap = close > vwap
var extremeLong = devZ < -zThreshold
var extremeShort = devZ > zThreshold
// ---------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ---------------------------------------------------------------------------
static sessionHighDev = -999999.0
static sessionLowDev = 999999.0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static extremeLongCount = 0
static extremeShortCount = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (dev > sessionHighDev) {
sessionHighDev = dev
}
if (dev < sessionLowDev) {
sessionLowDev = dev
}
if (devZ > sessionHighZ) {
sessionHighZ = devZ
}
if (devZ < sessionLowZ) {
sessionLowZ = devZ
}
if (extremeLong) {
extremeLongCount = extremeLongCount + 1
}
if (extremeShort) {
extremeShortCount = extremeShortCount + 1
}
}
// ---------------------------------------------------------------------------
// Cross & Touch Detection (shape markers)
// ---------------------------------------------------------------------------
var vwapCrossUp = close > vwap && !isnan(close[1]) && close[1] <= vwap[1]
var vwapCrossDown = close < vwap && !isnan(close[1]) && close[1] >= vwap[1]
var touchBand2Up = dev >= devBand2 && !isnan(dev[1]) && dev[1] < devBand2[1]
var touchBand2Dn = dev <= -devBand2 && !isnan(dev[1]) && dev[1] > -devBand2[1]
var touchBand3Up = dev >= devBand3 && !isnan(dev[1]) && dev[1] < devBand3[1]
var touchBand3Dn = dev <= -devBand3 && !isnan(dev[1]) && dev[1] > -devBand3[1]
var extremeZUp = devZ >= zThreshold && !isnan(devZ[1]) && devZ[1] < zThreshold
var extremeZDn = devZ <= -zThreshold && !isnan(devZ[1]) && devZ[1] > -zThreshold
// ---------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Bar, Fill, Shape, HLine)
// ---------------------------------------------------------------------------
// Zero line reference
hline(value=0, color="#ffffff30", width=1)
// --- Raw Deviation Histogram (regime-coded) ---
if (showRawDev) {
plotBar(
value=dev,
colors=[devAboveColor, devBelowColor],
width=1,
label=["Price − VWAP"],
desc=["Raw price deviation from anchored VWAP (positive = above, negative = below)"]
)
}
// --- Deviation Fill (regime-colored area between deviation and zero) ---
if (showFill && showRawDev) {
plotLine(
value=([0, dev]),
width=1,
colors=[opacity(devAboveColor, 15), opacity(devBelowColor, 15)],
colorIndex=aboveVwap ? 0 : 1,
fill=true,
label=["Deviation Fill"],
desc=["Filled deviation zone from VWAP (regime-colored)"]
)
}
// --- Deviation EMA (trend of divergence) ---
if (showDevEma) {
plotLine(
value=devEma,
width=lineWidth,
colors=[devAboveColor, devBelowColor],
colorIndex=aboveVwap ? 0 : 1,
label=["Deviation EMA"],
desc=["EMA of price−VWAP deviation; slope indicates divergence momentum"]
)
}
// --- Standard Deviation Reference Lines ---
if (showBand1) {
plotLine(
value=devBand1,
width=1,
colors=[band1Color],
label=["+1σ"],
desc=["Upper 1σ deviation band from VWAP"]
)
plotLine(
value=-devBand1,
width=1,
colors=[band1Color],
label=["−1σ"],
desc=["Lower 1σ deviation band from VWAP"]
)
}
if (showBand2) {
plotLine(
value=devBand2,
width=1,
colors=[band2Color],
label=["+2σ"],
desc=["Upper 2σ deviation band — ~95.4% containment boundary"]
)
plotLine(
value=-devBand2,
width=1,
colors=[band2Color],
label=["−2σ"],
desc=["Lower 2σ deviation band — ~95.4% containment boundary"]
)
}
if (showBand3) {
plotLine(
value=devBand3,
width=1,
colors=[band3Color],
label=["+3σ"],
desc=["Upper 3σ deviation band — statistical extreme"]
)
plotLine(
value=-devBand3,
width=1,
colors=[band3Color],
label=["−3σ"],
desc=["Lower 3σ deviation band — statistical extreme"]
)
}
// --- Z-Score Line ---
if (showZScore) {
plotLine(
value=devZ,
width=lineWidth,
colors=[zScoreColor],
label=["Z-Score"],
desc=["Statistical z-score of deviation (mean-reversion signal)"]
)
hline(value=zThreshold, color=opacity(devAboveColor, 40), width=1)
hline(value=-zThreshold, color=opacity(devBelowColor, 40), width=1)
}
// --- VWAP Cross Shapes ---
if (showVwapCross && vwapCrossUp) {
plotShape(
value=dev,
shape="triangleup",
colorIndex=devAboveColor,
width=shapeSize,
label=["VWAP Cross Up"],
desc=["Price crossed above anchored VWAP — bullish divergence flip"]
)
}
if (showVwapCross && vwapCrossDown) {
plotShape(
value=dev,
shape="triangledown",
colorIndex=devBelowColor,
width=shapeSize,
label=["VWAP Cross Down"],
desc=["Price crossed below anchored VWAP — bearish divergence flip"]
)
}
// --- Band Touch Shapes ---
if (showBandTouch && touchBand2Up) {
plotShape(
value=dev,
shape="triangledown",
colorIndex=band2Color,
width=shapeSize,
label=["Band 2 Upper Touch"],
desc=["Deviation touched upper 2σ band — potential mean-reversion zone"]
)
}
if (showBandTouch && touchBand2Dn) {
plotShape(
value=dev,
shape="triangleup",
colorIndex=band2Color,
width=shapeSize,
label=["Band 2 Lower Touch"],
desc=["Deviation touched lower 2σ band — potential mean-reversion zone"]
)
}
if (showBandTouch && touchBand3Up) {
plotShape(
value=dev,
shape="diamond",
colorIndex=band3Color,
width=shapeSize + 1,
label=["Band 3 Upper Touch"],
desc=["Deviation touched upper 3σ band — extreme statistical rarity"]
)
}
if (showBandTouch && touchBand3Dn) {
plotShape(
value=dev,
shape="diamond",
colorIndex=band3Color,
width=shapeSize + 1,
label=["Band 3 Lower Touch"],
desc=["Deviation touched lower 3σ band — extreme statistical rarity"]
)
}
// --- Extreme Z-Score Shapes ---
if (showExtreme && extremeZUp) {
plotShape(
value=devZ,
shape="triangledown",
colorIndex=extremeColor,
width=shapeSize + 1,
label=["Extreme Short Z"],
desc=["Z-score crossed above +threshold — overbought divergence extreme"]
)
}
if (showExtreme && extremeZDn) {
plotShape(
value=devZ,
shape="triangleup",
colorIndex=extremeColor,
width=shapeSize + 1,
label=["Extreme Long Z"],
desc=["Z-score crossed below −threshold — oversold divergence extreme"]
)
}