MM Flow
FlowScripts

Perfected FlowScript

Vwap backtest

VWAP Backtest — Perfected is indexed as 292_vwap_backtest.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

13.2 KB

Lines

473

Native Signal Candidates

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

6/6 guarded

Long Entry

line 376:9

Trigger

(showBacktestShapes && enableBacktest) && (crossUp)

Value

low

Deps

crossUp:var, enableBacktest:input, showBacktestShapes:input

Short Entry

line 386:9

Trigger

(showBacktestShapes && enableBacktest) && (crossDown)

Value

high

Deps

crossDown:var, enableBacktest:input, showBacktestShapes:input

Band 1 High Touch

line 399:5

Trigger

(touchBand1Hi)

Value

band1Hi

Deps

touchBand1Hi:var

Band 1 Low Touch

line 409:5

Trigger

(touchBand1Lo)

Value

band1Lo

Deps

touchBand1Lo:var

Band 2 High Touch

line 419:5

Trigger

(touchBand2Hi)

Value

band2Hi

Deps

touchBand2Hi:var

Band 2 Low Touch

line 429:5

Trigger

(touchBand2Lo)

Value

band2Lo

Deps

touchBand2Lo:var

292_vwap_backtest.flowscript

source path: kscripts/perfected/292_vwap_backtest.flowscript · sha256:3f327b18e751ca1f0c19d2c31817b59d030d9e79de37e5cfd3ff6da1ad5a5656

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

// ============================================================================
// VWAP Backtest — Perfected Edition
// Author: I (@Iopl147u) — Perfected by kScript_Perfection_Engineer
// Tags: CORE, #vwap, #backtest, #vwapbands, #execution
// Index: 292
//
// Rolling VWAP with volume-weighted standard deviation bands and integrated
// backtest metrics. Evaluates a simple VWAP trend-following strategy:
// long when price crosses above VWAP, short when price crosses below.
// Computes win rate, profit factor, total trades, and net profit in real-time.
//
// 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 the institutional execution benchmark.
//  - Madhavan (2002), "VWAP Strategies": when VWAP is a sensible benchmark
//    and how traders adjust strategies to match it.
//  - McCulloch & Kazakov (2007), "Optimal VWAP Trading Strategy and Relative
//    Volume": mean-variance optimization for VWAP execution quality.
//  - StudyRaid (2026), "Standard Deviation Bands in VWAP": volume-weighted
//    σ = √[Σ(Vᵢ·(Pᵢ−VWAP)²)/ΣVᵢ]; ~68.2% within ±1σ, ~95.4% within ±2σ.
//  - Shannon (2021), "Maximum Trading Gains with the Anchored VWAP":
//    VWAP as fair-value reference; deviation bands for mean reversion.
// ============================================================================

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

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

// --- VWAP Settings ---
var sessionLen = input(
    name="sessionLen",
    type="number",
    defaultValue=24,
    label="Session Length (bars)",
    constraints={min: 2, max: 500, step: 1},
    group="VWAP"
)
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="VWAP"
)
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="VWAP"
)
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="VWAP"
)

// --- Bands Display ---
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"
)

// --- Backtest Settings ---
var enableBacktest = input(
    name="enableBacktest",
    type="boolean",
    defaultValue=true,
    label="Enable Backtest Metrics",
    group="Backtest"
)
var showBacktestShapes = input(
    name="showBacktestShapes",
    type="boolean",
    defaultValue=true,
    label="Show Entry/Exit Shapes",
    group="Backtest"
)

// --- Colors ---
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 Color",
    group="Colors"
)
var band2Color = input(
    name="band2Color",
    type="color",
    defaultValue="#9e9e9e",
    label="Band 2 Color",
    group="Colors"
)
var band3Color = input(
    name="band3Color",
    type="color",
    defaultValue="#9e9e9e",
    label="Band 3 Color",
    group="Colors"
)
var longEntryColor = input(
    name="longEntryColor",
    type="color",
    defaultValue="#00e676",
    label="Long Entry Color",
    group="Colors"
)
var shortEntryColor = input(
    name="shortEntryColor",
    type="color",
    defaultValue="#ff5252",
    label="Short Entry Color",
    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 volume = bars.volume
timeseries typ = (high + low + close) / 3
timeseries pv = typ * volume

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

// ---------------------------------------------------------------------------
// Rolling VWAP & Volume-Weighted Standard Deviation
// ---------------------------------------------------------------------------
timeseries sumPV = sum(pv, sessionLen)
timeseries sumV = sum(volume, sessionLen)
timeseries vwap = sumV > 0 ? sumPV / sumV : typ

// Volume-weighted standard deviation
timeseries devSq = (typ - vwap) * (typ - vwap) * volume
timeseries sumSqDev = sum(devSq, sessionLen)
timeseries variance = sumV > 0 ? sumSqDev / sumV : 0
timeseries vwStddev = math.sqrt(math.max(0, variance))

// Deviation bands
timeseries band1Hi = vwap + band1Mult * vwStddev
timeseries band1Lo = vwap - band1Mult * vwStddev
timeseries band2Hi = vwap + band2Mult * vwStddev
timeseries band2Lo = vwap - band2Mult * vwStddev
timeseries band3Hi = vwap + band3Mult * vwStddev
timeseries band3Lo = vwap - band3Mult * vwStddev

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

// ---------------------------------------------------------------------------
// Backtest Logic (static variables for stateful trade tracking)
// ---------------------------------------------------------------------------
static inLong = false
static inShort = false
static entryPrice = 0.0
static tradeCount = 0
static winCount = 0
static totalProfit = 0.0
static totalLoss = 0.0

// Cross detection (manual, with NaN guard)
var crossUp = false
var crossDown = false
if (!isnan(close[1]) && !isnan(vwap[1])) {
    crossUp = close > vwap && close[1] <= vwap[1]
    crossDown = close < vwap && close[1] >= vwap[1]
}

if (enableBacktest && !isLiveUpdate) {
    if (crossUp && !inLong) {
        // Close short if in short
        if (inShort) {
            var pnl = entryPrice - close[0]
            tradeCount = tradeCount + 1
            if (pnl > 0) {
                winCount = winCount + 1
                totalProfit = totalProfit + pnl
            } else {
                totalLoss = totalLoss + (-pnl)
            }
        }
        // Enter long
        inLong = true
        inShort = false
        entryPrice = close[0]
    }

    if (crossDown && !inShort) {
        // Close long if in long
        if (inLong) {
            var pnl = close[0] - entryPrice
            tradeCount = tradeCount + 1
            if (pnl > 0) {
                winCount = winCount + 1
                totalProfit = totalProfit + pnl
            } else {
                totalLoss = totalLoss + (-pnl)
            }
        }
        // Enter short
        inShort = true
        inLong = false
        entryPrice = close[0]
    }
}

// ---------------------------------------------------------------------------
// Band Touch Detection
// ---------------------------------------------------------------------------
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=2,
    colors=[vwapAboveColor, vwapBelowColor],
    colorIndex=aboveVwap ? 0 : 1,
    label=["VWAP"],
    desc=["Rolling volume-weighted average price"]
)

// --- 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σ volume-weighted band fill"]
        )
    }
    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σ volume-weighted band fill"]
        )
    }
    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"]
    )
}

// --- Backtest Entry/Exit Shapes ---
if (showBacktestShapes && enableBacktest) {
    if (crossUp) {
        plotShape(
            value=low,
            shape="triangleup",
            colorIndex=longEntryColor,
            width=2,
            label=["Long Entry"],
            desc=["Price crossed above VWAP — long entry"]
        )
    }
    if (crossDown) {
        plotShape(
            value=high,
            shape="triangledown",
            colorIndex=shortEntryColor,
            width=2,
            label=["Short Entry"],
            desc=["Price crossed below VWAP — short entry"]
        )
    }
}

// --- Band Touch Shapes ---
if (touchBand1Hi) {
    plotShape(
        value=band1Hi,
        shape="triangledown",
        colorIndex=band1Color,
        width=2,
        label=["Band 1 High Touch"],
        desc=["Price touched upper 1σ band"]
    )
}
if (touchBand1Lo) {
    plotShape(
        value=band1Lo,
        shape="triangleup",
        colorIndex=band1Color,
        width=2,
        label=["Band 1 Low Touch"],
        desc=["Price touched lower 1σ band"]
    )
}
if (touchBand2Hi) {
    plotShape(
        value=band2Hi,
        shape="triangledown",
        colorIndex=band2Color,
        width=2,
        label=["Band 2 High Touch"],
        desc=["Price touched upper 2σ band"]
    )
}
if (touchBand2Lo) {
    plotShape(
        value=band2Lo,
        shape="triangleup",
        colorIndex=band2Color,
        width=2,
        label=["Band 2 Low Touch"],
        desc=["Price touched lower 2σ band"]
    )
}

// ---------------------------------------------------------------------------
// Backtest Metrics Table (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar && enableBacktest) {
    var winRate = tradeCount > 0 ? (winCount / tradeCount) * 100 : 0
    var profitFactor = totalLoss > 0 ? totalProfit / totalLoss : (totalProfit > 0 ? 999 : 0)
    var netProfit = totalProfit - totalLoss

    var regimeText = aboveVwap ? "ABOVE VWAP" : "BELOW VWAP"
    var regimeTextColor = aboveVwap ? vwapAboveColor : vwapBelowColor

    plotTable(
        data=[
            ["VWAP Backtest", regimeText],
            ["Total Trades", tradeCount],
            ["Win Rate", winRate + "%"],
            ["Profit Factor", profitFactor],
            ["Net Profit", netProfit],
            ["Gross Profit", totalProfit],
            ["Gross Loss", totalLoss]
        ],
        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
    )
}