MM Flow
FlowScripts

Perfected FlowScript

VWAP Deviation Oscillator

VWAP Deviation Oscillator [Perfected] is indexed as 050_vwap_deviation_oscillator.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

15.3 KB

Lines

497

Native Signal Candidates

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

4/4 guarded

OB Extreme

line 428:9

Trigger

(showShapes) && (extremeOb)

Value

series

Deps

extremeOb:var, showShapes:input

OS Extreme

line 438:9

Trigger

(showShapes) && (extremeOs)

Value

series

Deps

extremeOs:var, showShapes:input

OB Exit

line 448:9

Trigger

(showShapes) && (exitOb)

Value

series

Deps

exitOb:var, showShapes:input

OS Exit

line 458:9

Trigger

(showShapes) && (exitOs)

Value

series

Deps

exitOs:var, showShapes:input

050_vwap_deviation_oscillator.flowscript

source path: kscripts/perfected/050_vwap_deviation_oscillator.flowscript · sha256:9e039c4e973fe8008bfed4872e565ce639bca9b71316ca703d42ff7c7875352d

hash verified
//@version=2
// Source: kiyotaka.ai/hub/kscript (original) — Perfected by kScript_Perfection_Engineer

// ============================================================================
// VWAP Deviation Oscillator [Perfected]
// Author: BackQuant (@BackQuant) — Perfected by kScript_Perfection_Engineer
// Tags: CORE, #vwap, #deviation, #zscore, #oscillator, #meanreversion
//
// Production-quality VWAP deviation oscillator measuring price distance from
// volume-weighted fair value. Computes three output modes: z-score (statistical
// standard-deviation units), percent deviation from VWAP, and raw deviation.
// Features volume-weighted standard deviation bands, regime color coding,
// fill areas, shape markers for extreme deviations, and static session 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.
//  - Madhavan (2002), "VWAP Strategies": when VWAP is a sensible benchmark
//    and how traders adjust strategies to match it.
//  - Shannon (2021), "Maximum Trading Gains with the Anchored VWAP":
//    AVWAP from a user-selected event reveals institutional fair value;
//    anchor quality decays over 60–90 trading days.
//  - StudyRaid (2026), "Standard Deviation Bands in VWAP": σ = √[Σ(Vᵢ·(Pᵢ−VWAP)²)/ΣVᵢ];
//    ~68.2% of price activity within ±1σ, ~95.4% within ±2σ.
//  - Poterba & Summers (1988), "Mean Reversion in Stock Prices": negative
//    autocorrelation at medium horizons supports mean-reversion trading at
//    extreme VWAP deviations.
// ============================================================================

define(
    title="VWAP Deviation Oscillator [Perfected]",
    position="offchart",
    axis=true
)

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

// --- VWAP Settings ---
var anchorMode = input(
    name="anchorMode",
    type="select",
    defaultValue="Daily",
    label="Anchor Mode",
    options=["Session", "Daily", "Weekly", "Monthly", "Rolling"],
    group="VWAP Settings"
)
var rollWindow = input(
    name="rollWindow",
    type="number",
    defaultValue=96,
    label="Rolling Window (bars)",
    constraints={min: 10, max: 500, step: 1},
    group="VWAP Settings"
)
var srcType = input(
    name="srcType",
    type="select",
    defaultValue="hlc3",
    label="Source Price",
    options=["close", "hlc3", "hl2", "ohlc4"],
    group="VWAP Settings"
)

// --- Display Mode ---
var mode = input(
    name="mode",
    type="select",
    defaultValue="zscore",
    label="Display Mode",
    options=["zscore", "percent", "raw"],
    group="Display Mode"
)

// --- Bands ---
var showBands = input(
    name="showBands",
    type="boolean",
    defaultValue=true,
    label="Show StdDev Bands",
    group="Bands"
)
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 showBandFill = input(
    name="showBandFill",
    type="boolean",
    defaultValue=true,
    label="Show Band Fills",
    group="Bands"
)

// --- Thresholds / Regime ---
var showObOs = input(
    name="showObOs",
    type="boolean",
    defaultValue=true,
    label="Show OB/OS Zones",
    group="Thresholds"
)
var obThreshold = input(
    name="obThreshold",
    type="number",
    defaultValue=2.0,
    label="Overbought Threshold",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Thresholds"
)
var osThreshold = input(
    name="osThreshold",
    type="number",
    defaultValue=-2.0,
    label="Oversold Threshold",
    constraints={min: -5.0, max: -0.5, step: 0.1},
    group="Thresholds"
)

// --- Display ---
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Extreme Deviation Shapes",
    group="Display"
)
var showHist = input(
    name="showHist",
    type="boolean",
    defaultValue=true,
    label="Show Momentum Histogram",
    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 ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bull / Positive Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bear / Negative Color",
    group="Colors"
)
var obColor = input(
    name="obColor",
    type="color",
    defaultValue="#ff5252",
    label="Overbought Color",
    group="Colors"
)
var osColor = input(
    name="osColor",
    type="color",
    defaultValue="#00e676",
    label="Oversold Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)

// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries t = bars.time
timeseries close = bars.close
timeseries high = bars.high
timeseries low = bars.low
timeseries v = bars.volume

timeseries src = srcType == "close" ? close : (srcType == "hlc3" ? (high + low + close) / 3.0 : (srcType == "hl2" ? (high + low) / 2.0 : (high + low + close + bars.open) / 4.0))

// isnan guard: prevent computation on incomplete data
if (isnan(t[0]) || isnan(close[0]) || isnan(v[0]) || isnan(high[0]) || isnan(low[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. TIME DERIVATION (Calendar Math for Anchoring)
// ---------------------------------------------------------------------------
var day_id = math.floor(t / 86400000)
var week_id = math.floor((day_id + 3) / 7)

// Monthly calendar math (from 013_vwap_leviathan)
var z = day_id + 719468
var era = math.floor(z / 146097)
var doe = z - era * 146097
var yoe = math.floor((doe - math.floor(doe / 1460) + math.floor(doe / 36524) - math.floor(doe / 146096)) / 365)
var y = yoe + era * 400
var doy = doe - (365 * yoe + math.floor(yoe / 4) - math.floor(yoe / 100))
var mp = math.floor((5 * doy + 2) / 153)
var m = mp + (mp < 10 ? 3 : -9)
var year_final = y + (m <= 2 ? 1 : 0)
var month_id = year_final * 12 + m

// ---------------------------------------------------------------------------
// 4. ANCHOR DETECTION (static variables for stateful computation)
// ---------------------------------------------------------------------------
static last_day_id = -1
static last_week_id = -1
static last_month_id = -1
static barCount = 0

var newPeriod = false
var isRolling = false
var periodBars = 0

if (anchorMode == "Session") {
    // Session-based: reset on UTC day boundary (simple session proxy)
    newPeriod = last_day_id != -1 && day_id > last_day_id
    last_day_id = day_id
} 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 == "Monthly") {
    newPeriod = last_month_id != -1 && month_id > last_month_id
    last_month_id = month_id
} else if (anchorMode == "Rolling") {
    isRolling = true
    periodBars = rollWindow
}

if (isRolling) {
    if (barCount < periodBars) {
        barCount = barCount + 1
    } else {
        barCount = periodBars
    }
} else if (newPeriod || barCount == 0) {
    barCount = 1
} else {
    barCount = barCount + 1
}

// ---------------------------------------------------------------------------
// 5. VWAP COMPUTATION (anchored, volume-weighted)
// ---------------------------------------------------------------------------
timeseries pv = src * v
timeseries sumPV = sum(pv, barCount)
timeseries sumV = sum(v, barCount)
timeseries vwap = sumV > 0 ? sumPV / sumV : src

// Volume-weighted standard deviation (anchored to current VWAP)
timeseries devSq = (src - vwap) * (src - vwap) * v
timeseries sumSqDev = sum(devSq, barCount)
timeseries variance = sumV > 0 ? sumSqDev / sumV : 0
timeseries vwStd = math.sqrt(math.max(0, variance))

// ---------------------------------------------------------------------------
// 6. DEVIATION SERIES (three modes)
// ---------------------------------------------------------------------------
timeseries devRaw = src - vwap
timeseries devPct = vwap > 0 ? (src - vwap) / vwap * 100.0 : 0.0

// Z-score using volume-weighted std dev
timeseries zScore = vwStd > 0 ? (src - vwap) / vwStd : 0.0

// Rolling std dev of deviation for z-score normalization in rolling mode
timeseries rollDevStd = stddev(devRaw, barCount)
timeseries zScoreRoll = rollDevStd > 0 ? devRaw / rollDevStd : 0.0

timeseries series = mode == "zscore" ? zScore : (mode == "percent" ? devPct : devRaw)

// ---------------------------------------------------------------------------
// 7. REGIME DETECTION (color coding by regime)
// ---------------------------------------------------------------------------
var regimeOb = series > obThreshold
var regimeOs = series < osThreshold
var regimeNeutral = !regimeOb && !regimeOs

var regimeColor = regimeOb ? obColor : (regimeOs ? osColor : (series >= 0 ? bullColor : bearColor))

// ---------------------------------------------------------------------------
// 8. BAND COMPUTATION (std dev of series itself)
// ---------------------------------------------------------------------------
timeseries seriesStd = stddev(series, barCount)
timeseries band1Hi = seriesStd > 0 ? series + band1Mult * seriesStd : series
timeseries band1Lo = seriesStd > 0 ? series - band1Mult * seriesStd : series
timeseries band2Hi = seriesStd > 0 ? series + band2Mult * seriesStd : series
timeseries band2Lo = seriesStd > 0 ? series - band2Mult * seriesStd : series

// ---------------------------------------------------------------------------
// 9. EXTREME DEVIATION DETECTION (shape markers)
// ---------------------------------------------------------------------------
var extremeOb = series > obThreshold && series[1] <= obThreshold
var extremeOs = series < osThreshold && series[1] >= osThreshold
var exitOb = series < obThreshold && series[1] >= obThreshold
var exitOs = series > osThreshold && series[1] <= osThreshold

// ---------------------------------------------------------------------------
// 10. PLOTTING
// ---------------------------------------------------------------------------

// --- Midline / Zero ---
hline(value=0, color="#88888860", width=1)

// --- OB / OS Zones ---
if (showObOs) {
    hline(value=obThreshold, color=transparency(obColor, 60), width=1)
    hline(value=osThreshold, color=transparency(osColor, 60), width=1)
}

// --- StdDev Band Fills ---
if (showBands && showBandFill) {
    var fillBull = series >= 0
    plotLine(
        value=[band1Lo, band1Hi],
        width=1,
        colors=[transparency(bullColor, 15), transparency(bearColor, 15)],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=["±1σ Band Fill"],
        desc=["±1 standard deviation band fill around deviation series"]
    )
    plotLine(
        value=[band2Lo, band2Hi],
        width=1,
        colors=[transparency(bullColor, 8), transparency(bearColor, 8)],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=["±2σ Band Fill"],
        desc=["±2 standard deviation band fill around deviation series"]
    )
}

// --- Band Lines ---
if (showBands) {
    plotLine(
        value=band1Hi,
        width=1,
        colors=[neutralColor],
        label=["+1σ"],
        desc=["Upper band at 1 standard deviation"]
    )
    plotLine(
        value=band1Lo,
        width=1,
        colors=[neutralColor],
        label=["-1σ"],
        desc=["Lower band at 1 standard deviation"]
    )
    plotLine(
        value=band2Hi,
        width=1,
        colors=[neutralColor],
        label=["+2σ"],
        desc=["Upper band at 2 standard deviations"]
    )
    plotLine(
        value=band2Lo,
        width=1,
        colors=[neutralColor],
        label=["-2σ"],
        desc=["Lower band at 2 standard deviations"]
    )
}

// --- Main Deviation Line (regime-colored) ---
plotLine(
    value=series,
    width=lineWidth,
    colors=[regimeColor],
    label=["VWAP Deviation"],
    desc=["Price deviation from VWAP in " + mode + " mode"]
)

// --- Momentum Histogram ---
if (showHist) {
    var histBull = series >= 0
    plotBar(
        value=series,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["Deviation Momentum"],
        desc=["Histogram of VWAP deviation from zero"]
    )
}

// --- Shape Markers for Extremes ---
if (showShapes) {
    if (extremeOb) {
        plotShape(
            value=series,
            shape="triangledown",
            colorIndex=obColor,
            width=shapeSize,
            label=["OB Extreme"],
            desc=["Deviation entered overbought zone above " + obThreshold]
        )
    }
    if (extremeOs) {
        plotShape(
            value=series,
            shape="triangleup",
            colorIndex=osColor,
            width=shapeSize,
            label=["OS Extreme"],
            desc=["Deviation entered oversold zone below " + osThreshold]
        )
    }
    if (exitOb) {
        plotShape(
            value=series,
            shape="circle",
            colorIndex=neutralColor,
            width=shapeSize,
            label=["OB Exit"],
            desc=["Deviation exited overbought zone"]
        )
    }
    if (exitOs) {
        plotShape(
            value=series,
            shape="circle",
            colorIndex=neutralColor,
            width=shapeSize,
            label=["OS Exit"],
            desc=["Deviation exited oversold zone"]
        )
    }
}

// ---------------------------------------------------------------------------
// 11. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeOb ? "OVERBOUGHT" : (regimeOs ? "OVERSOLD" : "NEUTRAL")
    var regimeTextColor = regimeOb ? obColor : (regimeOs ? osColor : neutralColor)

    plotTable(
        data=[
            ["VWAP Deviation Oscillator", regimeText],
            ["VWAP", vwap[0]],
            ["Deviation", series[0]],
            ["VW StdDev", vwStd[0]],
            ["Bars in Anchor", barCount]
        ],
        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
    )
}