MM Flow
FlowScripts

Perfected FlowScript

VWAP Suite

VWAP Suite Perfected is indexed as 068_vwap_suite.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.7 KB

Lines

449

Native Signal Candidates

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

8/8 guarded

D VWAP Cross Up

line 310:9

Trigger

(showDaily) && (showCrosses && crossUpDaily)

Value

l

Deps

crossUpDaily:var, showCrosses:input, showDaily:input

D VWAP Cross Down

line 313:9

Trigger

(showDaily) && (showCrosses && crossDownDaily)

Value

h

Deps

crossDownDaily:var, showCrosses:input, showDaily:input

D +1σ Touch

line 316:9

Trigger

(showDaily) && (showTouches && touchDailyB1Hi)

Value

dB1Hi

Deps

showDaily:input, showTouches:input, touchDailyB1Hi:var

D -1σ Touch

line 319:9

Trigger

(showDaily) && (showTouches && touchDailyB1Lo)

Value

dB1Lo

Deps

showDaily:input, showTouches:input, touchDailyB1Lo:var

R VWAP Cross Up

line 437:9

Trigger

(showRolling) && (showCrosses && crossUpRoll)

Value

l

Deps

crossUpRoll:var, showCrosses:input, showRolling:input

R VWAP Cross Down

line 440:9

Trigger

(showRolling) && (showCrosses && crossDownRoll)

Value

h

Deps

crossDownRoll:var, showCrosses:input, showRolling:input

R +1σ Touch

line 443:9

Trigger

(showRolling) && (showTouches && touchRollB1Hi)

Value

rB1Hi

Deps

showRolling:input, showTouches:input, touchRollB1Hi:var

R -1σ Touch

line 446:9

Trigger

(showRolling) && (showTouches && touchRollB1Lo)

Value

rB1Lo

Deps

showRolling:input, showTouches:input, touchRollB1Lo:var

068_vwap_suite.flowscript

source path: kscripts/perfected/068_vwap_suite.flowscript · sha256:520b6ceba9de77879170fa5b1d8452e4b4449494c24f5522093f7fd3f70c98bc

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

// ============================================================================
// VWAP Suite — Multi-Timeframe Anchored VWAP with Standard Deviation Bands
// Author: BackQuant (@BackQuant) — Perfected by kScript_Perfection_Engineer
// Tags: CORE, #vwap, #anchoredvwap, #multivwap, #leviathan
//
// Production-grade multi-timeframe VWAP suite: Daily, Weekly, Monthly, and
// Session-anchored VWAPs plus rolling VWAP, each with configurable standard
// deviation bands, fill areas, regime color coding, and cross markers. Properly
// implements anchored/reset logic 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.
//  - Madhavan (2002), "VWAP Strategies": when VWAP is a sensible benchmark.
//  - Shannon (2021), "Maximum Trading Gains with the Anchored VWAP": AVWAP
//    from significant events 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σ.
//  - Harris (1986), "A Transaction Data Study": intraday seasonality supports
//    session anchoring (Tokyo, London, New York, Sydney).
//  - McCulloch & Kazakov (2007), "Optimal VWAP Trading Strategy": relative
//    volume analysis and front-loading/back-loading dynamics.
// ============================================================================

define(
    title="VWAP Suite Perfected",
    position="onchart",
    axis=false
)

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

// --- VWAP Selection ---
var showDaily    = input(name="showDaily",    type="boolean", defaultValue=true,  label="Show Daily VWAP",    group="VWAP Selection")
var showWeekly   = input(name="showWeekly",   type="boolean", defaultValue=true,  label="Show Weekly VWAP",   group="VWAP Selection")
var showMonthly  = input(name="showMonthly",  type="boolean", defaultValue=true,  label="Show Monthly VWAP",  group="VWAP Selection")
var showSession  = input(name="showSession",  type="boolean", defaultValue=false, label="Show Session VWAP",  group="VWAP Selection")
var sessionMode  = input(name="sessionMode",  type="select",  defaultValue="London", label="Session Anchor",    options=["Tokyo", "London", "New York", "Sydney"], group="VWAP Selection")
var showRolling  = input(name="showRolling",  type="boolean", defaultValue=true,  label="Show Rolling VWAP",  group="VWAP Selection")
var rollLen      = input(name="rollLen",      type="number",  defaultValue=50,    label="Rolling Length (bars)", constraints={min: 5, max: 500, step: 1}, group="VWAP Selection")

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

// --- Display ---
var showCrosses  = input(name="showCrosses",  type="boolean", defaultValue=true,  label="Show VWAP Cross Markers", group="Display")
var showTouches  = input(name="showTouches",  type="boolean", defaultValue=true,  label="Show Band Touch Markers", 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 dailyColor    = input(name="dailyColor",    type="color", defaultValue="#26a69a", label="Daily Color",    group="Colors")
var weeklyColor   = input(name="weeklyColor",   type="color", defaultValue="#42a5f5", label="Weekly Color",   group="Colors")
var monthlyColor  = input(name="monthlyColor",  type="color", defaultValue="#ab47bc", label="Monthly Color",  group="Colors")
var sessionColor  = input(name="sessionColor",  type="color", defaultValue="#ff7043", label="Session Color",  group="Colors")
var rollColor     = input(name="rollColor",     type="color", defaultValue="#90caf9", label="Rolling Color",  group="Colors")
var aboveColor    = input(name="aboveColor",    type="color", defaultValue="#26a69a", label="Above VWAP (Bull)", group="Colors")
var belowColor    = input(name="belowColor",    type="color", defaultValue="#ef5350", label="Below VWAP (Bear)", group="Colors")
var bandColor     = input(name="bandColor",     type="color", defaultValue="#9e9e9e", label="Band Line Color", group="Colors")

// ---------------------------------------------------------------------------
// Data Sources
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries t = bars.time
timeseries c = bars.close
timeseries h = bars.high
timeseries l = bars.low
timeseries v = bars.volume
timeseries typ = (h + l + c) / 3.0
timeseries pv = typ * v

// isnan guard: prevent NaN propagation on startup
if (isnan(t[0]) || isnan(c[0]) || isnan(h[0]) || isnan(l[0]) || isnan(v[0])) {
    return
}

// ---------------------------------------------------------------------------
// Calendar & Time Derivation
// ---------------------------------------------------------------------------
timeseries rawH = math.floor((t / 3600000) % 24)
timeseries utcH = ((rawH + 0) % 24 + 24) % 24
var dayId = math.floor(t / 86400000)
var weekId = math.floor((dayId + 3) / 7)

// Monthly calendar math (reused from 013_vwap_leviathan)
var z = dayId + 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 yearFinal = y + (m <= 2 ? 1 : 0)
var monthId = yearFinal * 12 + m

// Session hour detection
var sessTokyoOpen   = (utcH == 0)
var sessLondonOpen  = (utcH == 8)
var sessNyOpen      = (utcH == 13)
var sessSydneyOpen  = (utcH == 21)

// ---------------------------------------------------------------------------
// Daily VWAP — Static Anchor Tracking
// ---------------------------------------------------------------------------
static d_lastDay = -1
static d_barCount = 0

var d_newDay = d_lastDay != -1 && dayId > d_lastDay
d_lastDay = dayId

if (d_newDay || d_barCount == 0) {
    d_barCount = 1
} else {
    d_barCount = d_barCount + 1
}

timeseries dSumPV = sum(pv, d_barCount)
timeseries dSumV  = sum(v, d_barCount)
timeseries dVwap  = dSumV > 0 ? dSumPV / dSumV : typ

timeseries dDevSq = (typ - dVwap) * (typ - dVwap) * v
timeseries dSumSq = sum(dDevSq, d_barCount)
timeseries dVar   = dSumV > 0 ? dSumSq / dSumV : 0
timeseries dSd    = math.sqrt(math.max(0, dVar))

timeseries dB1Hi = dVwap + band1Mult * dSd
timeseries dB1Lo = dVwap - band1Mult * dSd
timeseries dB2Hi = dVwap + band2Mult * dSd
timeseries dB2Lo = dVwap - band2Mult * dSd

// ---------------------------------------------------------------------------
// Weekly VWAP — Static Anchor Tracking
// ---------------------------------------------------------------------------
static w_lastWeek = -1
static w_barCount = 0

var w_newWeek = w_lastWeek != -1 && weekId > w_lastWeek
w_lastWeek = weekId

if (w_newWeek || w_barCount == 0) {
    w_barCount = 1
} else {
    w_barCount = w_barCount + 1
}

timeseries wSumPV = sum(pv, w_barCount)
timeseries wSumV  = sum(v, w_barCount)
timeseries wVwap  = wSumV > 0 ? wSumPV / wSumV : typ

timeseries wDevSq = (typ - wVwap) * (typ - wVwap) * v
timeseries wSumSq = sum(wDevSq, w_barCount)
timeseries wVar   = wSumV > 0 ? wSumSq / wSumV : 0
timeseries wSd    = math.sqrt(math.max(0, wVar))

timeseries wB1Hi = wVwap + band1Mult * wSd
timeseries wB1Lo = wVwap - band1Mult * wSd
timeseries wB2Hi = wVwap + band2Mult * wSd
timeseries wB2Lo = wVwap - band2Mult * wSd

// ---------------------------------------------------------------------------
// Monthly VWAP — Static Anchor Tracking
// ---------------------------------------------------------------------------
static m_lastMonth = -1
static m_barCount = 0

var m_newMonth = m_lastMonth != -1 && monthId > m_lastMonth
m_lastMonth = monthId

if (m_newMonth || m_barCount == 0) {
    m_barCount = 1
} else {
    m_barCount = m_barCount + 1
}

timeseries mSumPV = sum(pv, m_barCount)
timeseries mSumV  = sum(v, m_barCount)
timeseries mVwap  = mSumV > 0 ? mSumPV / mSumV : typ

timeseries mDevSq = (typ - mVwap) * (typ - mVwap) * v
timeseries mSumSq = sum(mDevSq, m_barCount)
timeseries mVar   = mSumV > 0 ? mSumSq / mSumV : 0
timeseries mSd    = math.sqrt(math.max(0, mVar))

timeseries mB1Hi = mVwap + band1Mult * mSd
timeseries mB1Lo = mVwap - band1Mult * mSd
timeseries mB2Hi = mVwap + band2Mult * mSd
timeseries mB2Lo = mVwap - band2Mult * mSd

// ---------------------------------------------------------------------------
// Session VWAP — Static Anchor Tracking (selected session)
// ---------------------------------------------------------------------------
static s_lastBar = 0
static s_barCount = 0
static s_inSession = 0

var sessOpenNow = false
if (sessionMode == "Tokyo") {
    sessOpenNow = sessTokyoOpen
} else if (sessionMode == "London") {
    sessOpenNow = sessLondonOpen
} else if (sessionMode == "New York") {
    sessOpenNow = sessNyOpen
} else if (sessionMode == "Sydney") {
    sessOpenNow = sessSydneyOpen
}

if (sessOpenNow && s_inSession == 0) {
    s_inSession = 1
    s_barCount = 1
} else if (!sessOpenNow && s_inSession == 1) {
    s_inSession = 0
} else if (s_inSession == 1) {
    s_barCount = s_barCount + 1
}

timeseries sSumPV = sum(pv, s_barCount)
timeseries sSumV  = sum(v, s_barCount)
timeseries sVwap  = sSumV > 0 ? sSumPV / sSumV : typ

timeseries sDevSq = (typ - sVwap) * (typ - sVwap) * v
timeseries sSumSq = sum(sDevSq, s_barCount)
timeseries sVar   = sSumV > 0 ? sSumSq / sSumV : 0
timeseries sSd    = math.sqrt(math.max(0, sVar))

timeseries sB1Hi = sVwap + band1Mult * sSd
timeseries sB1Lo = sVwap - band1Mult * sSd
timeseries sB2Hi = sVwap + band2Mult * sSd
timeseries sB2Lo = sVwap - band2Mult * sSd

// ---------------------------------------------------------------------------
// Rolling VWAP — Fixed Window
// ---------------------------------------------------------------------------
timeseries rSumPV = sum(pv, rollLen)
timeseries rSumV  = sum(v, rollLen)
timeseries rVwap  = rSumV > 0 ? rSumPV / rSumV : typ

timeseries rDevSq = (typ - rVwap) * (typ - rVwap) * v
timeseries rSumSq = sum(rDevSq, rollLen)
timeseries rVar   = rSumV > 0 ? rSumSq / rSumV : 0
timeseries rSd    = math.sqrt(math.max(0, rVar))

timeseries rB1Hi = rVwap + band1Mult * rSd
timeseries rB1Lo = rVwap - band1Mult * rSd
timeseries rB2Hi = rVwap + band2Mult * rSd
timeseries rB2Lo = rVwap - band2Mult * rSd

// ---------------------------------------------------------------------------
// Regime Detection (price relative to primary VWAP)
// Use rolling VWAP as primary if shown, else daily.
// ---------------------------------------------------------------------------
var primaryVwap = showRolling ? rVwap : dVwap
var abovePrimary = c > primaryVwap

// ---------------------------------------------------------------------------
// Cross & Touch Detection
// ---------------------------------------------------------------------------
var crossUpDaily   = showDaily   && cross(c, dVwap) && c > dVwap
var crossDownDaily = showDaily   && cross(c, dVwap) && c < dVwap
var crossUpRoll    = showRolling && cross(c, rVwap) && c > rVwap
var crossDownRoll  = showRolling && cross(c, rVwap) && c < rVwap

var touchDailyB1Hi = showDaily && showBands && h >= dB1Hi && l <= dB1Hi
var touchDailyB1Lo = showDaily && showBands && h >= dB1Lo && l <= dB1Lo
var touchRollB1Hi  = showRolling && showBands && h >= rB1Hi && l <= rB1Hi
var touchRollB1Lo  = showRolling && showBands && h >= rB1Lo && l <= rB1Lo

// ---------------------------------------------------------------------------
// Plotting: Daily VWAP
// ---------------------------------------------------------------------------
if (showDaily) {
    var dAbove = c > dVwap
    plotLine(
        value=dVwap,
        width=lineWidth,
        colors=[aboveColor, belowColor],
        colorIndex=dAbove ? 0 : 1,
        label=["Daily VWAP"],
        desc=["Daily anchored VWAP: resets at UTC midnight"]
    )
    if (showBands) {
        if (showFill) {
            plotLine(
                value=[dB1Lo, dB1Hi],
                width=1,
                colors=[opacity(aboveColor, 15), opacity(belowColor, 15)],
                colorIndex=dAbove ? 0 : 1,
                fill=true,
                label=["D ±1σ Fill", "D ±1σ Fill"],
                desc=["Daily ±1σ band fill", "Daily ±1σ fill bottom"]
            )
        }
        plotLine(value=dB1Hi, width=1, colors=[bandColor], label=["D +1σ"], desc=["Daily +1σ band"])
        plotLine(value=dB1Lo, width=1, colors=[bandColor], label=["D -1σ"], desc=["Daily -1σ band"])
        plotLine(value=dB2Hi, width=1, colors=[bandColor], label=["D +2σ"], desc=["Daily +2σ band"])
        plotLine(value=dB2Lo, width=1, colors=[bandColor], label=["D -2σ"], desc=["Daily -2σ band"])
    }
    if (showCrosses && crossUpDaily) {
        plotShape(value=l, shape="triangleup", colorIndex=aboveColor, width=shapeSize, label=["D VWAP Cross Up"], desc=["Price crossed above daily VWAP"])
    }
    if (showCrosses && crossDownDaily) {
        plotShape(value=h, shape="triangledown", colorIndex=belowColor, width=shapeSize, label=["D VWAP Cross Down"], desc=["Price crossed below daily VWAP"])
    }
    if (showTouches && touchDailyB1Hi) {
        plotShape(value=dB1Hi, shape="triangledown", colorIndex=bandColor, width=shapeSize, label=["D +1σ Touch"], desc=["Price touched daily upper 1σ band"])
    }
    if (showTouches && touchDailyB1Lo) {
        plotShape(value=dB1Lo, shape="triangleup", colorIndex=bandColor, width=shapeSize, label=["D -1σ Touch"], desc=["Price touched daily lower 1σ band"])
    }
}

// ---------------------------------------------------------------------------
// Plotting: Weekly VWAP
// ---------------------------------------------------------------------------
if (showWeekly) {
    var wAbove = c > wVwap
    plotLine(
        value=wVwap,
        width=lineWidth,
        colors=[weeklyColor],
        label=["Weekly VWAP"],
        desc=["Weekly anchored VWAP: resets on Monday"]
    )
    if (showBands) {
        if (showFill) {
            plotLine(
                value=[wB1Lo, wB1Hi],
                width=1,
                colors=[opacity(weeklyColor, 15)],
                fill=true,
                label=["W ±1σ Fill", "W ±1σ Fill"],
                desc=["Weekly ±1σ band fill", "Weekly ±1σ fill bottom"]
            )
        }
        plotLine(value=wB1Hi, width=1, colors=[bandColor], label=["W +1σ"], desc=["Weekly +1σ band"])
        plotLine(value=wB1Lo, width=1, colors=[bandColor], label=["W -1σ"], desc=["Weekly -1σ band"])
    }
}

// ---------------------------------------------------------------------------
// Plotting: Monthly VWAP
// ---------------------------------------------------------------------------
if (showMonthly) {
    var mAbove = c > mVwap
    plotLine(
        value=mVwap,
        width=lineWidth,
        colors=[monthlyColor],
        label=["Monthly VWAP"],
        desc=["Monthly anchored VWAP: resets on 1st of month"]
    )
    if (showBands) {
        if (showFill) {
            plotLine(
                value=[mB1Lo, mB1Hi],
                width=1,
                colors=[opacity(monthlyColor, 15)],
                fill=true,
                label=["M ±1σ Fill", "M ±1σ Fill"],
                desc=["Monthly ±1σ band fill", "Monthly ±1σ fill bottom"]
            )
        }
        plotLine(value=mB1Hi, width=1, colors=[bandColor], label=["M +1σ"], desc=["Monthly +1σ band"])
        plotLine(value=mB1Lo, width=1, colors=[bandColor], label=["M -1σ"], desc=["Monthly -1σ band"])
    }
}

// ---------------------------------------------------------------------------
// Plotting: Session VWAP
// ---------------------------------------------------------------------------
if (showSession) {
    var sAbove = c > sVwap
    plotLine(
        value=sVwap,
        width=lineWidth,
        colors=[sessionColor],
        label=["Session VWAP"],
        desc=["Session-anchored VWAP: resets at " + sessionMode + " open"]
    )
    if (showBands) {
        if (showFill) {
            plotLine(
                value=[sB1Lo, sB1Hi],
                width=1,
                colors=[opacity(sessionColor, 15)],
                fill=true,
                label=["S ±1σ Fill", "S ±1σ Fill"],
                desc=["Session ±1σ band fill", "Session ±1σ fill bottom"]
            )
        }
        plotLine(value=sB1Hi, width=1, colors=[bandColor], label=["S +1σ"], desc=["Session +1σ band"])
        plotLine(value=sB1Lo, width=1, colors=[bandColor], label=["S -1σ"], desc=["Session -1σ band"])
    }
}

// ---------------------------------------------------------------------------
// Plotting: Rolling VWAP (primary, with full bands and fill)
// ---------------------------------------------------------------------------
if (showRolling) {
    var rAbove = c > rVwap
    plotLine(
        value=rVwap,
        width=lineWidth + 1,
        colors=[rollColor],
        label=["Rolling VWAP"],
        desc=["Rolling VWAP: " + rollLen + "-bar window"]
    )
    if (showBands) {
        if (showFill) {
            plotLine(
                value=[rB1Lo, rB1Hi],
                width=1,
                colors=[opacity(aboveColor, 15), opacity(belowColor, 15)],
                colorIndex=rAbove ? 0 : 1,
                fill=true,
                label=["R ±1σ Fill", "R ±1σ Fill"],
                desc=["Rolling ±1σ band fill (regime-colored)", "Rolling ±1σ fill bottom"]
            )
        }
        plotLine(value=rB1Hi, width=1, colors=[bandColor], label=["R +1σ"], desc=["Rolling +1σ band"])
        plotLine(value=rB1Lo, width=1, colors=[bandColor], label=["R -1σ"], desc=["Rolling -1σ band"])
        plotLine(value=rB2Hi, width=1, colors=[bandColor], label=["R +2σ"], desc=["Rolling +2σ band"])
        plotLine(value=rB2Lo, width=1, colors=[bandColor], label=["R -2σ"], desc=["Rolling -2σ band"])
    }
    if (showCrosses && crossUpRoll) {
        plotShape(value=l, shape="triangleup", colorIndex=aboveColor, width=shapeSize, label=["R VWAP Cross Up"], desc=["Price crossed above rolling VWAP"])
    }
    if (showCrosses && crossDownRoll) {
        plotShape(value=h, shape="triangledown", colorIndex=belowColor, width=shapeSize, label=["R VWAP Cross Down"], desc=["Price crossed below rolling VWAP"])
    }
    if (showTouches && touchRollB1Hi) {
        plotShape(value=rB1Hi, shape="triangledown", colorIndex=bandColor, width=shapeSize, label=["R +1σ Touch"], desc=["Price touched rolling upper 1σ band"])
    }
    if (showTouches && touchRollB1Lo) {
        plotShape(value=rB1Lo, shape="triangleup", colorIndex=bandColor, width=shapeSize, label=["R -1σ Touch"], desc=["Price touched rolling lower 1σ band"])
    }
}