MM Flow
FlowScripts

Perfected FlowScript

VWAP • [Leviathan]

VWAP [Leviathan] Perfected is indexed as 013_vwap_leviathan.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

20.1 KB

Lines

518

Native Signal Candidates

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

7/7 guarded

POC

line 336:5

Trigger

(showPoc && !isnan(pocPrice))

Value

pocPrice

Deps

pocPrice:var, showPoc:input

VWAP Cross Up

line 459:5

Trigger

(showVwapCross && vwapCrossUp)

Value

low

Deps

showVwapCross:input, vwapCrossUp:var

VWAP Cross Down

line 469:5

Trigger

(showVwapCross && vwapCrossDown)

Value

high

Deps

showVwapCross:input, vwapCrossDown:var

Band 1 High Touch

line 479:5

Trigger

(showBandTouch && touchBand1Hi)

Value

band1Hi

Deps

showBandTouch:input, touchBand1Hi:var

Band 1 Low Touch

line 489:5

Trigger

(showBandTouch && touchBand1Lo)

Value

band1Lo

Deps

showBandTouch:input, touchBand1Lo:var

Band 2 High Touch

line 499:5

Trigger

(showBandTouch && touchBand2Hi)

Value

band2Hi

Deps

showBandTouch:input, touchBand2Hi:var

Band 2 Low Touch

line 509:5

Trigger

(showBandTouch && touchBand2Lo)

Value

band2Lo

Deps

showBandTouch:input, touchBand2Lo:var

013_vwap_leviathan.flowscript

source path: kscripts/perfected/pilot/013_vwap_leviathan.flowscript · sha256:a7e46cafcf456204891af12b84ea6bfadbc98ed9ff4e7a0b08b31dd67b7571f0

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

// ============================================================================
// Anchored VWAP with Standard Deviation Bands [Leviathan Perfected]
// Author: Leviathan (@Leviathan) — Perfected by kScript_Perfection_Engineer
// Tags: CORE, #vwap, #anchoredvwap, #rollingvwap, #leviathan
//
// Comprehensive VWAP with 17 anchor modes (fixed periods, trading sessions,
// rolling windows) and up to three standard-deviation band pairs. Properly
// implements anchored/reset logic using static variables for cumulative sums,
// correcting the original rolling-sum 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% of price activity within ±1σ, ~95.4% within ±2σ.
//  - 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 [Leviathan] Perfected",
    position="onchart",
    axis=false
)

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

// --- Anchor Group ---
var anchorMode = input(name="anchorMode", type="select", defaultValue="Daily", label="Primary Anchor Mode", options=["4h", "8h", "12h", "Daily", "2 Days", "3 Days", "Weekly", "2 Weeks", "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=["4h", "8h", "12h", "Daily", "2 Days", "3 Days", "Weekly", "2 Weeks", "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")

// --- 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 (from 203_key_level)
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

// ---------------------------------------------------------------------------
// 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_4h = -1
static last_8h = -1
static last_12h = -1
static last_2d = -1
static last_3d = -1
static last_2w = -1
static last_q = -1
static last_y = -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 == "2 Days") {
    var period2d = math.floor(day_id / 2)
    newPeriod = last_2d != -1 && period2d > last_2d
    last_2d = period2d
} else if (anchorMode == "3 Days") {
    var period3d = math.floor(day_id / 3)
    newPeriod = last_3d != -1 && period3d > last_3d
    last_3d = period3d
} else if (anchorMode == "Weekly") {
    newPeriod = last_week_id != -1 && week_id > last_week_id
    last_week_id = week_id
} else if (anchorMode == "2 Weeks") {
    var period2w = math.floor(week_id / 2)
    newPeriod = last_2w != -1 && period2w > last_2w
    last_2w = period2w
} else if (anchorMode == "Monthly") {
    newPeriod = last_month_id != -1 && month_id > last_month_id
    last_month_id = month_id
} else if (anchorMode == "Quarterly") {
    var quarter_id = math.floor((month_id - 1) / 3)
    newPeriod = last_q != -1 && quarter_id > last_q
    last_q = quarter_id
} else if (anchorMode == "Yearly") {
    var year_id = year_final
    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))

// No division by zero: 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

// ---------------------------------------------------------------------------
// 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_4h = -1
static sec_last_8h = -1
static sec_last_12h = -1
static sec_last_2d = -1
static sec_last_3d = -1
static sec_last_2w = -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 == "4h") {
        var sec_period4h = math.floor(t / 14400000)
        secNewPeriod = sec_last_4h != -1 && sec_period4h > sec_last_4h
        sec_last_4h = sec_period4h
    } else if (secondaryAnchorMode == "8h") {
        var sec_period8h = math.floor(t / 28800000)
        secNewPeriod = sec_last_8h != -1 && sec_period8h > sec_last_8h
        sec_last_8h = sec_period8h
    } else if (secondaryAnchorMode == "12h") {
        var sec_period12h = math.floor(t / 43200000)
        secNewPeriod = sec_last_12h != -1 && sec_period12h > sec_last_12h
        sec_last_12h = sec_period12h
    } 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 == "2 Days") {
        var sec_period2d = math.floor(day_id / 2)
        secNewPeriod = sec_last_2d != -1 && sec_period2d > sec_last_2d
        sec_last_2d = sec_period2d
    } else if (secondaryAnchorMode == "3 Days") {
        var sec_period3d = math.floor(day_id / 3)
        secNewPeriod = sec_last_3d != -1 && sec_period3d > sec_last_3d
        sec_last_3d = sec_period3d
    } 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 == "2 Weeks") {
        var sec_period2w = math.floor(week_id / 2)
        secNewPeriod = sec_last_2w != -1 && sec_period2w > sec_last_2w
        sec_last_2w = sec_period2w
    } 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") {
        var sec_quarter_id = math.floor((month_id - 1) / 3)
        secNewPeriod = sec_last_q != -1 && sec_quarter_id > sec_last_q
        sec_last_q = sec_quarter_id
    } else if (secondaryAnchorMode == "Yearly") {
        var sec_year_id = year_final
        secNewPeriod = sec_last_y != -1 && sec_year_id > sec_last_y
        sec_last_y = sec_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

// ---------------------------------------------------------------------------
// 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"]
    )
}

// --- Shape Markers ---
if (showVwapCross && vwapCrossUp) {
    plotShape(
        value=low,
        shape="triangleup",
        colorIndex=vwapAboveColor,
        width=shapeSize,
        label=["VWAP Cross Up"],
        desc=["Price crossed above VWAP"]
    )
}
if (showVwapCross && vwapCrossDown) {
    plotShape(
        value=high,
        shape="triangledown",
        colorIndex=vwapBelowColor,
        width=shapeSize,
        label=["VWAP Cross Down"],
        desc=["Price crossed below VWAP"]
    )
}
if (showBandTouch && touchBand1Hi) {
    plotShape(
        value=band1Hi,
        shape="triangledown",
        colorIndex=band1Color,
        width=shapeSize,
        label=["Band 1 High Touch"],
        desc=["Price touched upper 1σ band"]
    )
}
if (showBandTouch && touchBand1Lo) {
    plotShape(
        value=band1Lo,
        shape="triangleup",
        colorIndex=band1Color,
        width=shapeSize,
        label=["Band 1 Low Touch"],
        desc=["Price touched lower 1σ band"]
    )
}
if (showBandTouch && touchBand2Hi) {
    plotShape(
        value=band2Hi,
        shape="triangledown",
        colorIndex=band2Color,
        width=shapeSize,
        label=["Band 2 High Touch"],
        desc=["Price touched upper 2σ band"]
    )
}
if (showBandTouch && touchBand2Lo) {
    plotShape(
        value=band2Lo,
        shape="triangleup",
        colorIndex=band2Color,
        width=shapeSize,
        label=["Band 2 Low Touch"],
        desc=["Price touched lower 2σ band"]
    )
}