MM Flow
FlowScripts

Perfected FlowScript

Rolling VWAP - Tradingriot

Rolling VWAP [Tradingriot] Perfected is indexed as 008_rolling_vwap_tradingriot.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

17.2 KB

Lines

424

Native Signal Candidates

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

6/6 guarded

Short Cross Up

line 226:9

Trigger

(showShort) && (showCrosses && shortCrossUp)

Value

low

Deps

shortCrossUp:var, showCrosses:input, showShort:input

Short Cross Down

line 236:9

Trigger

(showShort) && (showCrosses && shortCrossDown)

Value

high

Deps

shortCrossDown:var, showCrosses:input, showShort:input

Med Cross Up

line 292:9

Trigger

(showMed) && (showCrosses && medCrossUp)

Value

low

Deps

medCrossUp:var, showCrosses:input, showMed:input

Med Cross Down

line 302:9

Trigger

(showMed) && (showCrosses && medCrossDown)

Value

high

Deps

medCrossDown:var, showCrosses:input, showMed:input

Long Cross Up

line 358:9

Trigger

(showLong) && (showCrosses && longCrossUp)

Value

low

Deps

longCrossUp:var, showCrosses:input, showLong:input

Long Cross Down

line 368:9

Trigger

(showLong) && (showCrosses && longCrossDown)

Value

high

Deps

longCrossDown:var, showCrosses:input, showLong:input

008_rolling_vwap_tradingriot.flowscript

source path: kscripts/perfected/008_rolling_vwap_tradingriot.flowscript · sha256:16c41ffcdeaa94880e5aa16088fca11dd3a1d16dd1bab1dd89bab7041edeb23d

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

// ============================================================================
// Rolling VWAP [Tradingriot Perfected]
// Author: abetrade (@abetrade) — Perfected by kScript_Perfection_Engineer
// Tags: CORE, #vwap, #rollingvwap, #bands, #regime
//
// Production-quality rolling VWAP with standard deviation bands, fill areas,
// regime color coding, and cross detection. Implements three cumulative VWAPs
// (30/90/365-day) with static state tracking for proper rolling computation,
// volume-weighted standard deviation bands, and comprehensive shape markers.
//
// 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":
//    rolling VWAP is a natural extension across fixed windows.
//  - StudyRaid (2026), "Standard Deviation Bands in VWAP": σ = √[Σ(Vᵢ·(Pᵢ−VWAP)²)/ΣVᵢ];
//    ~68.2% of price activity within ±1σ, ~95.4% within ±2σ.
//  - McCulloch & Kazakov (2007), "Optimal VWAP Trading Strategy and Relative
//    Volume": relative volume analysis for VWAP strategy optimization.
// ============================================================================

define(
    title="Rolling VWAP [Tradingriot] Perfected",
    position="onchart",
    axis=false
)

// ---------------------------------------------------------------------------
// User Inputs
// ---------------------------------------------------------------------------

// --- VWAP Settings ---
var shortLen = input(name="shortLen", type="number", defaultValue=30, label="Short Window (days)", constraints={min: 5, max: 100, step: 1}, group="VWAP Settings")
var medLen = input(name="medLen", type="number", defaultValue=90, label="Medium Window (days)", constraints={min: 10, max: 250, step: 1}, group="VWAP Settings")
var longLen = input(name="longLen", type="number", defaultValue=365, label="Long Window (days)", constraints={min: 50, max: 500, step: 1}, group="VWAP Settings")

// --- 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 showBands = input(name="showBands", type="boolean", defaultValue=true, label="Show Standard Deviation Bands", group="Bands")
var showBand1 = input(name="showBand1", type="boolean", defaultValue=true, label="Show Band 1 (±1σ)", group="Bands")
var showBand2 = input(name="showBand2", type="boolean", defaultValue=true, label="Show Band 2 (±2σ)", group="Bands")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Band Fills", group="Bands")

// --- Display ---
var showShort = input(name="showShort", type="boolean", defaultValue=true, label="Show Short VWAP", group="Display")
var showMed = input(name="showMed", type="boolean", defaultValue=true, label="Show Medium VWAP", group="Display")
var showLong = input(name="showLong", type="boolean", defaultValue=true, label="Show Long VWAP", group="Display")
var showCrosses = input(name="showCrosses", type="boolean", defaultValue=true, label="Show VWAP Cross 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 ---
var shortColor = input(name="shortColor", type="color", defaultValue="#26a69a", label="Short VWAP Color", group="Colors")
var medColor = input(name="medColor", type="color", defaultValue="#2962ff", label="Medium VWAP Color", group="Colors")
var longColor = input(name="longColor", type="color", defaultValue="#d50000", label="Long VWAP Color", group="Colors")
var bandColor = input(name="bandColor", type="color", defaultValue="#9e9e9e", label="Band Line Color", group="Colors")
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Bull Color (Above VWAP)", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Bear Color (Below VWAP)", group="Colors")

// ---------------------------------------------------------------------------
// Data Sources & NaN Guard
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = bars.close
timeseries high = bars.high
timeseries low = bars.low
timeseries typ = (high + low + close) / 3
timeseries pv = typ * bars.volume

if (isnan(close[0]) || isnan(high[0]) || isnan(low[0]) || isnan(bars.volume[0])) {
    return
}

// ---------------------------------------------------------------------------
// Rolling VWAP Computation (static state for cumulative tracking)
// ---------------------------------------------------------------------------

// --- Short VWAP ---
static shortBarCount = 0
if (shortBarCount < shortLen) {
    shortBarCount = shortBarCount + 1
} else {
    shortBarCount = shortLen
}

timeseries shortSumPV = sum(pv, shortBarCount)
timeseries shortSumV = sum(bars.volume, shortBarCount)
timeseries vwapShort = shortSumV > 0 ? shortSumPV / shortSumV : typ

// --- Medium VWAP ---
static medBarCount = 0
if (medBarCount < medLen) {
    medBarCount = medBarCount + 1
} else {
    medBarCount = medLen
}

timeseries medSumPV = sum(pv, medBarCount)
timeseries medSumV = sum(bars.volume, medBarCount)
timeseries vwapMed = medSumV > 0 ? medSumPV / medSumV : typ

// --- Long VWAP ---
static longBarCount = 0
if (longBarCount < longLen) {
    longBarCount = longBarCount + 1
} else {
    longBarCount = longLen
}

timeseries longSumPV = sum(pv, longBarCount)
timeseries longSumV = sum(bars.volume, longBarCount)
timeseries vwapLong = longSumV > 0 ? longSumPV / longSumV : typ

// ---------------------------------------------------------------------------
// Standard Deviation Bands (volume-weighted)
// ---------------------------------------------------------------------------

// Short VWAP bands
timeseries shortDevSq = (typ - vwapShort) * (typ - vwapShort) * bars.volume
timeseries shortSumSqDev = sum(shortDevSq, shortBarCount)
timeseries shortVar = shortSumV > 0 ? shortSumSqDev / shortSumV : 0
timeseries shortSD = math.sqrt(math.max(0, shortVar))

timeseries shortBand1Hi = vwapShort + band1Mult * shortSD
timeseries shortBand1Lo = vwapShort - band1Mult * shortSD
timeseries shortBand2Hi = vwapShort + band2Mult * shortSD
timeseries shortBand2Lo = vwapShort - band2Mult * shortSD

// Medium VWAP bands
timeseries medDevSq = (typ - vwapMed) * (typ - vwapMed) * bars.volume
timeseries medSumSqDev = sum(medDevSq, medBarCount)
timeseries medVar = medSumV > 0 ? medSumSqDev / medSumV : 0
timeseries medSD = math.sqrt(math.max(0, medVar))

timeseries medBand1Hi = vwapMed + band1Mult * medSD
timeseries medBand1Lo = vwapMed - band1Mult * medSD
timeseries medBand2Hi = vwapMed + band2Mult * medSD
timeseries medBand2Lo = vwapMed - band2Mult * medSD

// Long VWAP bands
timeseries longDevSq = (typ - vwapLong) * (typ - vwapLong) * bars.volume
timeseries longSumSqDev = sum(longDevSq, longBarCount)
timeseries longVar = longSumV > 0 ? longSumSqDev / longSumV : 0
timeseries longSD = math.sqrt(math.max(0, longVar))

timeseries longBand1Hi = vwapLong + band1Mult * longSD
timeseries longBand1Lo = vwapLong - band1Mult * longSD
timeseries longBand2Hi = vwapLong + band2Mult * longSD
timeseries longBand2Lo = vwapLong - band2Mult * longSD

// ---------------------------------------------------------------------------
// Regime Detection (above/below each VWAP)
// ---------------------------------------------------------------------------
var aboveShort = close > vwapShort
var aboveMed = close > vwapMed
var aboveLong = close > vwapLong

// ---------------------------------------------------------------------------
// Cross Detection
// ---------------------------------------------------------------------------
var shortCrossUp = close > vwapShort && close[1] <= vwapShort[1]
var shortCrossDown = close < vwapShort && close[1] >= vwapShort[1]
var medCrossUp = close > vwapMed && close[1] <= vwapMed[1]
var medCrossDown = close < vwapMed && close[1] >= vwapMed[1]
var longCrossUp = close > vwapLong && close[1] <= vwapLong[1]
var longCrossDown = close < vwapLong && close[1] >= vwapLong[1]

// ---------------------------------------------------------------------------
// Plotting
// ---------------------------------------------------------------------------

// --- Short VWAP (regime-colored) ---
if (showShort) {
    plotLine(
        value=vwapShort,
        width=lineWidth,
        colors=[bullColor, bearColor],
        colorIndex=aboveShort ? 0 : 1,
        label=["Short VWAP"],
        desc=["30-day rolling VWAP (regime-colored)"]
    )

    // Short VWAP bands
    if (showBands) {
        if (showBand1) {
            if (showFill) {
                plotLine(
                    value=([shortBand1Lo, shortBand1Hi]),
                    width=1,
                    colors=[opacity(bullColor, 10), opacity(bearColor, 10)],
                    colorIndex=aboveShort ? 0 : 1,
                    fill=true,
                    label=["Short ±1σ Fill"],
                    desc=["Short VWAP ±1σ band fill"]
                )
            }
            plotLine(value=shortBand1Hi, width=1, colors=[bandColor], label=["Short +1σ"], desc=["Short VWAP upper 1σ band"])
            plotLine(value=shortBand1Lo, width=1, colors=[bandColor], label=["Short -1σ"], desc=["Short VWAP lower 1σ band"])
        }
        if (showBand2) {
            if (showFill) {
                plotLine(
                    value=([shortBand2Lo, shortBand2Hi]),
                    width=1,
                    colors=[opacity(bullColor, 5), opacity(bearColor, 5)],
                    colorIndex=aboveShort ? 0 : 1,
                    fill=true,
                    label=["Short ±2σ Fill"],
                    desc=["Short VWAP ±2σ band fill"]
                )
            }
            plotLine(value=shortBand2Hi, width=1, colors=[bandColor], label=["Short +2σ"], desc=["Short VWAP upper 2σ band"])
            plotLine(value=shortBand2Lo, width=1, colors=[bandColor], label=["Short -2σ"], desc=["Short VWAP lower 2σ band"])
        }
    }

    // Short VWAP cross shapes
    if (showCrosses && shortCrossUp) {
        plotShape(
            value=low,
            shape="triangleup",
            colorIndex=bullColor,
            width=shapeSize,
            label=["Short Cross Up"],
            desc=["Price crossed above short VWAP"]
        )
    }
    if (showCrosses && shortCrossDown) {
        plotShape(
            value=high,
            shape="triangledown",
            colorIndex=bearColor,
            width=shapeSize,
            label=["Short Cross Down"],
            desc=["Price crossed below short VWAP"]
        )
    }
}

// --- Medium VWAP ---
if (showMed) {
    plotLine(
        value=vwapMed,
        width=lineWidth,
        colors=[bullColor, bearColor],
        colorIndex=aboveMed ? 0 : 1,
        label=["Medium VWAP"],
        desc=["90-day rolling VWAP (regime-colored)"]
    )

    if (showBands) {
        if (showBand1) {
            if (showFill) {
                plotLine(
                    value=([medBand1Lo, medBand1Hi]),
                    width=1,
                    colors=[opacity(bullColor, 10), opacity(bearColor, 10)],
                    colorIndex=aboveMed ? 0 : 1,
                    fill=true,
                    label=["Med ±1σ Fill"],
                    desc=["Medium VWAP ±1σ band fill"]
                )
            }
            plotLine(value=medBand1Hi, width=1, colors=[bandColor], label=["Med +1σ"], desc=["Medium VWAP upper 1σ band"])
            plotLine(value=medBand1Lo, width=1, colors=[bandColor], label=["Med -1σ"], desc=["Medium VWAP lower 1σ band"])
        }
        if (showBand2) {
            if (showFill) {
                plotLine(
                    value=([medBand2Lo, medBand2Hi]),
                    width=1,
                    colors=[opacity(bullColor, 5), opacity(bearColor, 5)],
                    colorIndex=aboveMed ? 0 : 1,
                    fill=true,
                    label=["Med ±2σ Fill"],
                    desc=["Medium VWAP ±2σ band fill"]
                )
            }
            plotLine(value=medBand2Hi, width=1, colors=[bandColor], label=["Med +2σ"], desc=["Medium VWAP upper 2σ band"])
            plotLine(value=medBand2Lo, width=1, colors=[bandColor], label=["Med -2σ"], desc=["Medium VWAP lower 2σ band"])
        }
    }

    if (showCrosses && medCrossUp) {
        plotShape(
            value=low,
            shape="triangleup",
            colorIndex=bullColor,
            width=shapeSize,
            label=["Med Cross Up"],
            desc=["Price crossed above medium VWAP"]
        )
    }
    if (showCrosses && medCrossDown) {
        plotShape(
            value=high,
            shape="triangledown",
            colorIndex=bearColor,
            width=shapeSize,
            label=["Med Cross Down"],
            desc=["Price crossed below medium VWAP"]
        )
    }
}

// --- Long VWAP ---
if (showLong) {
    plotLine(
        value=vwapLong,
        width=lineWidth,
        colors=[bullColor, bearColor],
        colorIndex=aboveLong ? 0 : 1,
        label=["Long VWAP"],
        desc=["365-day rolling VWAP (regime-colored)"]
    )

    if (showBands) {
        if (showBand1) {
            if (showFill) {
                plotLine(
                    value=([longBand1Lo, longBand1Hi]),
                    width=1,
                    colors=[opacity(bullColor, 10), opacity(bearColor, 10)],
                    colorIndex=aboveLong ? 0 : 1,
                    fill=true,
                    label=["Long ±1σ Fill"],
                    desc=["Long VWAP ±1σ band fill"]
                )
            }
            plotLine(value=longBand1Hi, width=1, colors=[bandColor], label=["Long +1σ"], desc=["Long VWAP upper 1σ band"])
            plotLine(value=longBand1Lo, width=1, colors=[bandColor], label=["Long -1σ"], desc=["Long VWAP lower 1σ band"])
        }
        if (showBand2) {
            if (showFill) {
                plotLine(
                    value=([longBand2Lo, longBand2Hi]),
                    width=1,
                    colors=[opacity(bullColor, 5), opacity(bearColor, 5)],
                    colorIndex=aboveLong ? 0 : 1,
                    fill=true,
                    label=["Long ±2σ Fill"],
                    desc=["Long VWAP ±2σ band fill"]
                )
            }
            plotLine(value=longBand2Hi, width=1, colors=[bandColor], label=["Long +2σ"], desc=["Long VWAP upper 2σ band"])
            plotLine(value=longBand2Lo, width=1, colors=[bandColor], label=["Long -2σ"], desc=["Long VWAP lower 2σ band"])
        }
    }

    if (showCrosses && longCrossUp) {
        plotShape(
            value=low,
            shape="triangleup",
            colorIndex=bullColor,
            width=shapeSize,
            label=["Long Cross Up"],
            desc=["Price crossed above long VWAP"]
        )
    }
    if (showCrosses && longCrossDown) {
        plotShape(
            value=high,
            shape="triangledown",
            colorIndex=bearColor,
            width=shapeSize,
            label=["Long Cross Down"],
            desc=["Price crossed below long VWAP"]
        )
    }
}

// --- Price-to-VWAP Fill (shortest active VWAP) ---
if (showFill) {
    var closestVwap = showShort ? vwapShort : (showMed ? vwapMed : vwapLong)
    var closestAbove = close > closestVwap
    plotLine(
        value=([closestVwap, close]),
        width=1,
        colors=[opacity(bullColor, 15), opacity(bearColor, 15)],
        colorIndex=closestAbove ? 0 : 1,
        fill=true,
        label=["Price-VWAP Fill"],
        desc=["Fill between price and closest VWAP"]
    )
}

// ---------------------------------------------------------------------------
// VWAP Table (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = aboveShort ? "ABOVE Short" : "BELOW Short"
    var regimeTextColor = aboveShort ? bullColor : bearColor

    plotTable(
        data=[
            ["Rolling VWAP", "Regime"],
            ["Short VWAP", vwapShort[0]],
            ["Medium VWAP", vwapMed[0]],
            ["Long VWAP", vwapLong[0]],
            ["Short SD", shortSD[0]],
            ["Medium SD", medSD[0]],
            ["Long SD", longSD[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
    )
}