MM Flow
FlowScripts

Perfected FlowScript

VWAP & StDev Bands

VWAP & StDev Bands [Perfected] is indexed as 111_vwap_stdev_bands.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

19.6 KB

Lines

513

Native Signal Candidates

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

10/10 guarded

POC

line 297:5

Trigger

(showPoc && !isnan(pocPrice))

Value

pocPrice

Deps

pocPrice:var, showPoc:input

Band Pinch

line 422:5

Trigger

(showBandPinch && isPinch)

Value

vwap

Deps

isPinch:var, showBandPinch:input

VWAP Cross Up

line 434:5

Trigger

(showVwapCross && vwapCrossUp)

Value

low

Deps

showVwapCross:input, vwapCrossUp:var

VWAP Cross Down

line 444:5

Trigger

(showVwapCross && vwapCrossDown)

Value

high

Deps

showVwapCross:input, vwapCrossDown:var

Band 1 High Touch

line 454:5

Trigger

(showBandTouch && touchBand1Hi)

Value

band1Hi

Deps

showBandTouch:input, touchBand1Hi:var

Band 1 Low Touch

line 464:5

Trigger

(showBandTouch && touchBand1Lo)

Value

band1Lo

Deps

showBandTouch:input, touchBand1Lo:var

Band 2 High Touch

line 474:5

Trigger

(showBandTouch && touchBand2Hi)

Value

band2Hi

Deps

showBandTouch:input, touchBand2Hi:var

Band 2 Low Touch

line 484:5

Trigger

(showBandTouch && touchBand2Lo)

Value

band2Lo

Deps

showBandTouch:input, touchBand2Lo:var

Band 3 High Touch

line 494:5

Trigger

(showBandTouch && touchBand3Hi)

Value

band3Hi

Deps

showBandTouch:input, touchBand3Hi:var

Band 3 Low Touch

line 504:5

Trigger

(showBandTouch && touchBand3Lo)

Value

band3Lo

Deps

showBandTouch:input, touchBand3Lo:var

111_vwap_stdev_bands.flowscript

source path: kscripts/perfected/111_vwap_stdev_bands.flowscript · sha256:275a84bbd7db4b73a2317f7d9e343c46908d97408c5b9e2ec5bddd3dcfd35c8f

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

// ============================================================================
// VWAP with Standard Deviation Bands [Perfected Edition]
// Author: C (@chaincoder) — Perfected by kScript_Perfection_Engineer
// Tags: CORE, #vwap, #stdevbands, #anchoredvwap, #rollingvwap, #volatility
//
// Comprehensive VWAP with volume-weighted standard deviation bands,
// multiple anchor modes (session, daily, weekly, rolling), regime color
// coding, fill between bands, and shape markers for crosses and band touches.
// Properly implements anchored VWAP using static variables for cumulative
// sums, correcting the original rolling-SMA implementation.
//
// 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% within ±1σ, ~95.4% within ±2σ.
//  - TheVWAP.com (2023), "The Detailed Guide to VWAP": band pinch indicates
//    low volatility/consolidation; bands expand in trending environments.
//  - Harris (1986), "A Transaction Data Study of Weekly and Intradaily
//    Patterns in Stock Returns": intraday seasonality supports session
//    anchoring (Tokyo, London, New York, Sydney).
// ============================================================================

define(
    title="VWAP & StDev Bands [Perfected]",
    position="onchart",
    axis=false
)

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

// --- Anchor Group ---
var anchorMode = input(name="anchorMode", type="select", defaultValue="Daily", label="Primary Anchor Mode", options=["Session", "Daily", "Weekly", "Monthly", "Quarterly", "Yearly", "Tokyo", "London", "New York", "Sydney", "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")
var showSecondary = input(name="showSecondary", type="boolean", defaultValue=false, label="Show Secondary VWAP", group="Anchor")
var secondaryAnchorMode = input(name="secondaryAnchorMode", type="select", defaultValue="Weekly", label="Secondary Anchor Mode", options=["Session", "Daily", "Weekly", "Monthly", "Quarterly", "Yearly", "Tokyo", "London", "New York", "Sydney", "Rolling 50 Bars", "Rolling 200 Bars"], 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 Band Fills", group="Bands")
var showBandPinch = input(name="showBandPinch", type="boolean", defaultValue=true, label="Show Band Pinch Alert", group="Bands")

// --- Display Group ---
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 showPoc = input(name="showPoc", type="boolean", defaultValue=false, label="Show Volume Profile POC", 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 vwapColor = input(name="vwapColor", type="color", defaultValue="#2962ff", label="VWAP Line Color", group="Colors")
var vwapAboveColor = input(name="vwapAboveColor", type="color", defaultValue="#26a69a", label="VWAP Above Color (Bull)", group="Colors")
var vwapBelowColor = input(name="vwapBelowColor", type="color", defaultValue="#ef5350", label="VWAP Below Color (Bear)", group="Colors")
var band1Color = input(name="band1Color", type="color", defaultValue="#9e9e9e", label="Band 1 Line Color", group="Colors")
var band2Color = input(name="band2Color", type="color", defaultValue="#9e9e9e", label="Band 2 Line Color", group="Colors")
var band3Color = input(name="band3Color", type="color", defaultValue="#9e9e9e", label="Band 3 Line Color", group="Colors")
var pocColor = input(name="pocColor", type="color", defaultValue="#ff6d00", label="POC Color", group="Colors")
var secondaryVwapColor = input(name="secondaryVwapColor", type="color", defaultValue="#ff6d00", label="Secondary VWAP 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)

// Monthly calendar math
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
var quarter_id = math.floor((month_id - 1) / 3)
var year_id = year_final

// ---------------------------------------------------------------------------
// Primary Anchor Detection (static variables for stateful computation)
// ---------------------------------------------------------------------------
static last_day_id = -1
static last_week_id = -1
static last_month_id = -1
static last_utcH = -1
static last_q = -1
static last_y = -1
static barCount = 0

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

if (anchorMode == "Session") {
    // Reset on new session (UTC midnight by default, or when utcH wraps)
    newPeriod = last_utcH != -1 && last_utcH > utcH
    last_utcH = utcH
} 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 == "Quarterly") {
    newPeriod = last_q != -1 && quarter_id > last_q
    last_q = quarter_id
} else if (anchorMode == "Yearly") {
    newPeriod = last_y != -1 && year_id > last_y
    last_y = year_id
} else if (anchorMode == "Tokyo") {
    newPeriod = last_utcH != -1 && last_utcH != 0 && utcH == 0
    last_utcH = utcH
} else if (anchorMode == "London") {
    newPeriod = last_utcH != -1 && last_utcH != 8 && utcH == 8
    last_utcH = utcH
} else if (anchorMode == "New York") {
    newPeriod = last_utcH != -1 && last_utcH != 13 && utcH == 13
    last_utcH = utcH
} else if (anchorMode == "Sydney") {
    newPeriod = last_utcH != -1 && last_utcH != 21 && utcH == 21
    last_utcH = utcH
} 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
}

// ---------------------------------------------------------------------------
// Primary VWAP Computation (anchored, not rolling)
// ---------------------------------------------------------------------------
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))

// All denominators guarded with sumV > 0
timeseries band1Hi = vwap + band1Mult * sd
timeseries band1Lo = vwap - band1Mult * sd
timeseries band2Hi = vwap + band2Mult * sd
timeseries band2Lo = vwap - band2Mult * sd
timeseries band3Hi = vwap + band3Mult * sd
timeseries band3Lo = vwap - band3Mult * sd

// Band width for pinch detection (consolidation signal)
timeseries bandWidth = band1Hi - band1Lo
static avgBandWidth = 0.0
static bwCount = 0
if (bwCount < 50) {
    bwCount = bwCount + 1
    avgBandWidth = (avgBandWidth * (bwCount - 1) + bandWidth) / bwCount
} else {
    avgBandWidth = (avgBandWidth * 49 + bandWidth) / 50
}
var isPinch = bandWidth < avgBandWidth * 0.5 && avgBandWidth > 0

// ---------------------------------------------------------------------------
// Secondary VWAP Computation (static variables for independent anchor)
// ---------------------------------------------------------------------------
static sec_last_day_id = -1
static sec_last_week_id = -1
static sec_last_month_id = -1
static sec_last_utcH = -1
static sec_last_q = -1
static sec_last_y = -1
static secBarCount = 0

var secNewPeriod = false
var secIsRolling = false
var secPeriodBars = 0

if (showSecondary) {
    if (secondaryAnchorMode == "Session") {
        secNewPeriod = sec_last_utcH != -1 && sec_last_utcH > utcH
        sec_last_utcH = utcH
    } else if (secondaryAnchorMode == "Daily") {
        secNewPeriod = sec_last_day_id != -1 && day_id > sec_last_day_id
        sec_last_day_id = day_id
    } else if (secondaryAnchorMode == "Weekly") {
        secNewPeriod = sec_last_week_id != -1 && week_id > sec_last_week_id
        sec_last_week_id = week_id
    } else if (secondaryAnchorMode == "Monthly") {
        secNewPeriod = sec_last_month_id != -1 && month_id > sec_last_month_id
        sec_last_month_id = month_id
    } else if (secondaryAnchorMode == "Quarterly") {
        secNewPeriod = sec_last_q != -1 && quarter_id > sec_last_q
        sec_last_q = quarter_id
    } else if (secondaryAnchorMode == "Yearly") {
        secNewPeriod = sec_last_y != -1 && year_id > sec_last_y
        sec_last_y = year_id
    } else if (secondaryAnchorMode == "Tokyo") {
        secNewPeriod = sec_last_utcH != -1 && sec_last_utcH != 0 && utcH == 0
        sec_last_utcH = utcH
    } else if (secondaryAnchorMode == "London") {
        secNewPeriod = sec_last_utcH != -1 && sec_last_utcH != 8 && utcH == 8
        sec_last_utcH = utcH
    } else if (secondaryAnchorMode == "New York") {
        secNewPeriod = sec_last_utcH != -1 && sec_last_utcH != 13 && utcH == 13
        sec_last_utcH = utcH
    } else if (secondaryAnchorMode == "Sydney") {
        secNewPeriod = sec_last_utcH != -1 && sec_last_utcH != 21 && utcH == 21
        sec_last_utcH = utcH
    } else if (secondaryAnchorMode == "Rolling 50 Bars") {
        secIsRolling = true
        secPeriodBars = 50
    } else if (secondaryAnchorMode == "Rolling 200 Bars") {
        secIsRolling = true
        secPeriodBars = 200
    }

    if (secIsRolling) {
        if (secBarCount < secPeriodBars) {
            secBarCount = secBarCount + 1
        } else {
            secBarCount = secPeriodBars
        }
    } else if (secNewPeriod || secBarCount == 0) {
        secBarCount = 1
    } else {
        secBarCount = secBarCount + 1
    }
} else {
    secBarCount = 1
}

timeseries secSumPV = sum(pv, secBarCount)
timeseries secSumV = sum(bars.volume, secBarCount)
timeseries secVwap = secSumV > 0 ? secSumPV / secSumV : typ

// ---------------------------------------------------------------------------
// Regime Detection (color coding by position relative to VWAP)
// ---------------------------------------------------------------------------
var aboveVwap = close > vwap

// ---------------------------------------------------------------------------
// Volume Profile Integration (POC relative to VWAP)
// ---------------------------------------------------------------------------
timeseries vp = volume_profile(symbol=currentSymbol, exchange=currentExchange)
var pocPrice = vpPoc(vp)
if (showPoc && !isnan(pocPrice)) {
    plotShape(
        value=pocPrice,
        shape="triangleup",
        colorIndex=pocColor,
        width=shapeSize,
        label=["POC"],
        desc=["Point of Control relative to VWAP"]
    )
}

// ---------------------------------------------------------------------------
// Cross & Touch Detection (shape markers)
// ---------------------------------------------------------------------------
var vwapCrossUp = cross(close, vwap) && close > vwap
var vwapCrossDown = cross(close, vwap) && close < vwap
var touchBand1Hi = high >= band1Hi && low <= band1Hi
var touchBand1Lo = high >= band1Lo && low <= band1Lo
var touchBand2Hi = high >= band2Hi && low <= band2Hi
var touchBand2Lo = high >= band2Lo && low <= band2Lo
var touchBand3Hi = high >= band3Hi && low <= band3Hi
var touchBand3Lo = high >= band3Lo && low <= band3Lo

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

// --- VWAP Line (regime-colored) ---
plotLine(
    value=vwap,
    width=lineWidth,
    colors=[vwapAboveColor, vwapBelowColor],
    colorIndex=aboveVwap ? 0 : 1,
    label=["VWAP"],
    desc=["Anchored volume-weighted average price"]
)

// --- Secondary VWAP ---
if (showSecondary) {
    plotLine(
        value=secVwap,
        width=lineWidth,
        colors=[secondaryVwapColor],
        label=["VWAP 2"],
        desc=["Secondary anchored VWAP"]
    )
}

// --- Band 1 Fill & Lines ---
if (showBand1) {
    if (showFill) {
        plotLine(
            value=([band1Lo, band1Hi]),
            width=1,
            colors=[opacity(vwapAboveColor, 15), opacity(vwapBelowColor, 15)],
            colorIndex=aboveVwap ? 0 : 1,
            fill=true,
            label=["±1σ Fill"],
            desc=["±1σ band fill (regime-colored)"]
        )
    }
    plotLine(
        value=band1Hi,
        width=1,
        colors=[band1Color],
        label=["+1σ"],
        desc=["Upper band at 1σ multiplier"]
    )
    plotLine(
        value=band1Lo,
        width=1,
        colors=[band1Color],
        label=["-1σ"],
        desc=["Lower band at 1σ multiplier"]
    )
}

// --- Band 2 Fill & Lines ---
if (showBand2) {
    if (showFill) {
        plotLine(
            value=([band2Lo, band2Hi]),
            width=1,
            colors=[opacity(vwapAboveColor, 10), opacity(vwapBelowColor, 10)],
            colorIndex=aboveVwap ? 0 : 1,
            fill=true,
            label=["±2σ Fill"],
            desc=["±2σ band fill (regime-colored)"]
        )
    }
    plotLine(
        value=band2Hi,
        width=1,
        colors=[band2Color],
        label=["+2σ"],
        desc=["Upper band at 2σ multiplier"]
    )
    plotLine(
        value=band2Lo,
        width=1,
        colors=[band2Color],
        label=["-2σ"],
        desc=["Lower band at 2σ multiplier"]
    )
}

// --- Band 3 Lines ---
if (showBand3) {
    plotLine(
        value=band3Hi,
        width=1,
        colors=[band3Color],
        label=["+3σ"],
        desc=["Upper band at 3σ multiplier"]
    )
    plotLine(
        value=band3Lo,
        width=1,
        colors=[band3Color],
        label=["-3σ"],
        desc=["Lower band at 3σ multiplier"]
    )
}

// --- Band Pinch Alert ---
if (showBandPinch && isPinch) {
    plotShape(
        value=vwap,
        shape="diamond",
        colorIndex="#ffd700",
        width=shapeSize,
        label=["Band Pinch"],
        desc=["Band width < 50% of average — consolidation / volatility contraction"]
    )
}

// --- Shape Markers ---
if (showVwapCross && vwapCrossUp) {
    plotShape(
        value=low,
        shape="triangleup",
        colorIndex=vwapAboveColor,
        width=shapeSize,
        label=["VWAP Cross Up"],
        desc=["Price crossed above VWAP — bullish regime shift"]
    )
}
if (showVwapCross && vwapCrossDown) {
    plotShape(
        value=high,
        shape="triangledown",
        colorIndex=vwapBelowColor,
        width=shapeSize,
        label=["VWAP Cross Down"],
        desc=["Price crossed below VWAP — bearish regime shift"]
    )
}
if (showBandTouch && touchBand1Hi) {
    plotShape(
        value=band1Hi,
        shape="triangledown",
        colorIndex=band1Color,
        width=shapeSize,
        label=["Band 1 High Touch"],
        desc=["Price touched upper 1σ band — potential resistance"]
    )
}
if (showBandTouch && touchBand1Lo) {
    plotShape(
        value=band1Lo,
        shape="triangleup",
        colorIndex=band1Color,
        width=shapeSize,
        label=["Band 1 Low Touch"],
        desc=["Price touched lower 1σ band — potential support"]
    )
}
if (showBandTouch && touchBand2Hi) {
    plotShape(
        value=band2Hi,
        shape="triangledown",
        colorIndex=band2Color,
        width=shapeSize,
        label=["Band 2 High Touch"],
        desc=["Price touched upper 2σ band — statistical extreme (~95.4%)"]
    )
}
if (showBandTouch && touchBand2Lo) {
    plotShape(
        value=band2Lo,
        shape="triangleup",
        colorIndex=band2Color,
        width=shapeSize,
        label=["Band 2 Low Touch"],
        desc=["Price touched lower 2σ band — statistical extreme (~95.4%)"]
    )
}
if (showBandTouch && touchBand3Hi) {
    plotShape(
        value=band3Hi,
        shape="triangledown",
        colorIndex=band3Color,
        width=shapeSize,
        label=["Band 3 High Touch"],
        desc=["Price touched upper 3σ band — rare statistical outlier"]
    )
}
if (showBandTouch && touchBand3Lo) {
    plotShape(
        value=band3Lo,
        shape="triangleup",
        colorIndex=band3Color,
        width=shapeSize,
        label=["Band 3 Low Touch"],
        desc=["Price touched lower 3σ band — rare statistical outlier"]
    )
}