MM Flow
FlowScripts

Perfected FlowScript

ITC WAP

ITC VWAP — Perfected Edition is indexed as 166_itc_wap.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.3 KB

Lines

658

Native Signal Candidates

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

8/8 guarded

VWAP Cross Up

line 542:9

Trigger

(showVwapCross) && (primCrossUp)

Value

low

Deps

primCrossUp:var, showVwapCross:input

VWAP Cross Down

line 552:9

Trigger

(showVwapCross) && (primCrossDown)

Value

high

Deps

primCrossDown:var, showVwapCross:input

1σ High Touch

line 566:9

Trigger

(showBandTouch) && (touchBand1Hi)

Value

primBand1Hi

Deps

showBandTouch:input, touchBand1Hi:var

1σ Low Touch

line 576:9

Trigger

(showBandTouch) && (touchBand1Lo)

Value

primBand1Lo

Deps

showBandTouch:input, touchBand1Lo:var

2σ High Touch

line 586:9

Trigger

(showBandTouch) && (touchBand2Hi)

Value

primBand2Hi

Deps

showBandTouch:input, touchBand2Hi:var

2σ Low Touch

line 596:9

Trigger

(showBandTouch) && (touchBand2Lo)

Value

primBand2Lo

Deps

showBandTouch:input, touchBand2Lo:var

3σ High Touch

line 606:9

Trigger

(showBandTouch) && (touchBand3Hi)

Value

primBand3Hi

Deps

showBandTouch:input, touchBand3Hi:var

3σ Low Touch

line 616:9

Trigger

(showBandTouch) && (touchBand3Lo)

Value

primBand3Lo

Deps

showBandTouch:input, touchBand3Lo:var

166_itc_wap.flowscript

source path: kscripts/perfected/166_itc_wap.flowscript · sha256:ae9990be4f4cdc181dd4ad42b8f2a6856991fd5305c5138b0a177ba598567353

hash verified
//@version=2
// ============================================================================
// ITC VWAP — Perfected Edition
// Author: P (@PatrikHaim) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #vwap, #itc, #anchoredvwap, #deviation, #bands, #multivwap
//
// Production-quality ITC VWAP with multiple anchored VWAPs (session, daily,
// weekly), volume-weighted standard deviation bands, regime detection, color
// coding, and comprehensive shape-marker visualization.
//
// Research papers underpinning this design:
//  1. Berkowitz, Logue & Noser (1988), "The Total Cost of Transactions on the
//     NYSE": VWAP = Σ(Price_i × Volume_i) / ΣVolume_i as institutional
//     benchmark. Journal of Finance, 43(1), 97–112.
//  2. Madhavan (2002), "VWAP Strategies": when VWAP is a sensible benchmark
//     and how traders adjust strategies to match it. ITG / Journal of Trading.
//  3. Shannon (2021), "Maximum Trading Gains with the Anchored VWAP":
//     AVWAP from user-selected event reveals institutional fair value;
//     anchor quality decays over 60–90 trading days.
//  4. StudyRaid (2026), "Standard Deviation Bands in VWAP": σ = √[Σ(Vᵢ·(Pᵢ−
//     VWAP)²)/ΣVᵢ]; ~68.2% within ±1σ, ~95.4% within ±2σ.
//  5. Harris (1986), "A Transaction Data Study of Weekly and Intradaily
//     Patterns in Stock Returns": intraday seasonality supports session-based
//     anchoring (Tokyo, London, New York, Sydney).
//  6. McCulloch & Kazakov (2007), "Optimal VWAP Trading Strategy and Relative
//     Volume": mean-variance optimization for VWAP execution strategies.
// ============================================================================

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

// ---------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// ---------------------------------------------------------------------------

// --- Primary VWAP ---
var primaryAnchor = input(
    name="primaryAnchor",
    type="select",
    defaultValue="Session",
    label="Primary VWAP Anchor",
    options=["Session", "Daily", "Weekly", "Monthly", "Quarterly", "Yearly"],
    group="Primary VWAP"
)
var showPrimary = input(
    name="showPrimary",
    type="boolean",
    defaultValue=true,
    label="Show Primary VWAP",
    group="Primary VWAP"
)

// --- Secondary VWAP ---
var showSecondary = input(
    name="showSecondary",
    type="boolean",
    defaultValue=true,
    label="Show Secondary VWAP",
    group="Secondary VWAP"
)
var secondaryAnchor = input(
    name="secondaryAnchor",
    type="select",
    defaultValue="Weekly",
    label="Secondary VWAP Anchor",
    options=["Session", "Daily", "Weekly", "Monthly", "Quarterly", "Yearly"],
    group="Secondary VWAP"
)

// --- Tertiary VWAP ---
var showTertiary = input(
    name="showTertiary",
    type="boolean",
    defaultValue=false,
    label="Show Tertiary VWAP",
    group="Tertiary VWAP"
)
var tertiaryAnchor = input(
    name="tertiaryAnchor",
    type="select",
    defaultValue="Monthly",
    label="Tertiary VWAP Anchor",
    options=["Session", "Daily", "Weekly", "Monthly", "Quarterly", "Yearly"],
    group="Tertiary VWAP"
)

// --- Deviation 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="Deviation 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="Deviation 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="Deviation Bands"
)
var showBand1 = input(
    name="showBand1",
    type="boolean",
    defaultValue=true,
    label="Show Band 1",
    group="Deviation Bands"
)
var showBand2 = input(
    name="showBand2",
    type="boolean",
    defaultValue=true,
    label="Show Band 2",
    group="Deviation Bands"
)
var showBand3 = input(
    name="showBand3",
    type="boolean",
    defaultValue=false,
    label="Show Band 3",
    group="Deviation Bands"
)
var showBandFill = input(
    name="showBandFill",
    type="boolean",
    defaultValue=true,
    label="Show Band Fills",
    group="Deviation Bands"
)

// --- Display ---
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 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 vwapColor = input(
    name="vwapColor",
    type="color",
    defaultValue="#ffa726",
    label="Primary VWAP 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 secondaryColor = input(
    name="secondaryColor",
    type="color",
    defaultValue="#42a5f5",
    label="Secondary VWAP Color",
    group="Colors"
)
var tertiaryColor = input(
    name="tertiaryColor",
    type="color",
    defaultValue="#ab47bc",
    label="Tertiary VWAP Color",
    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="#757575",
    label="Band 2 Color",
    group="Colors"
)
var band3Color = input(
    name="band3Color",
    type="color",
    defaultValue="#616161",
    label="Band 3 Color",
    group="Colors"
)

// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries t = bars.time
timeseries close = bars.close
timeseries high = bars.high
timeseries low = bars.low
timeseries volume = bars.volume

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

// Typical price for VWAP computation
timeseries typicalPrice = (high + low + close) / 3.0
timeseries pv = typicalPrice * volume

// ---------------------------------------------------------------------------
// 3. ANCHOR PERIOD DETECTION (static stateful computation)
// ---------------------------------------------------------------------------
// Calendar math for time-based anchor detection
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

// Quarter and year IDs
var quarter_id = math.floor((month_id - 1) / 3)
var year_id = year_final

// ---------------------------------------------------------------------------
// 4. VWAP COMPUTATION HELPER (static variables per anchor)
// ---------------------------------------------------------------------------
// We need independent static variables for each VWAP anchor to track
// cumulative sums across bars properly.

static prim_last_anchor = -1
static prim_cumPV = 0.0
static prim_cumV = 0.0
static prim_cumPV2 = 0.0
static prim_bars = 0

static sec_last_anchor = -1
static sec_cumPV = 0.0
static sec_cumV = 0.0
static sec_cumPV2 = 0.0
static sec_bars = 0

static tert_last_anchor = -1
static tert_cumPV = 0.0
static tert_cumV = 0.0
static tert_cumPV2 = 0.0
static tert_bars = 0

// --- Anchor ID resolver ---
function getAnchorId(anchorType) {
    if (anchorType == "Session") {
        return day_id
    } else if (anchorType == "Daily") {
        return day_id
    } else if (anchorType == "Weekly") {
        return week_id
    } else if (anchorType == "Monthly") {
        return month_id
    } else if (anchorType == "Quarterly") {
        return quarter_id
    } else if (anchorType == "Yearly") {
        return year_id
    }
    return day_id
}

var primAnchorId = getAnchorId(primaryAnchor)
var secAnchorId = getAnchorId(secondaryAnchor)
var tertAnchorId = getAnchorId(tertiaryAnchor)

// --- Primary VWAP ---
if (prim_last_anchor == -1) {
    prim_last_anchor = primAnchorId
    prim_cumPV = 0.0
    prim_cumV = 0.0
    prim_cumPV2 = 0.0
    prim_bars = 0
} else if (primAnchorId != prim_last_anchor) {
    prim_last_anchor = primAnchorId
    prim_cumPV = 0.0
    prim_cumV = 0.0
    prim_cumPV2 = 0.0
    prim_bars = 0
}
prim_cumPV = prim_cumPV + pv
prim_cumV = prim_cumV + volume
prim_cumPV2 = prim_cumPV2 + volume * (typicalPrice * typicalPrice)
prim_bars = prim_bars + 1

timeseries primVwap = prim_cumV > 0 ? prim_cumPV / prim_cumV : typicalPrice
timeseries primVar = prim_cumV > 0 ? (prim_cumPV2 / prim_cumV) - (primVwap * primVwap) : 0
timeseries primStd = math.sqrt(math.max(primVar, 0))

timeseries primBand1Hi = primVwap + band1Mult * primStd
timeseries primBand1Lo = primVwap - band1Mult * primStd
timeseries primBand2Hi = primVwap + band2Mult * primStd
timeseries primBand2Lo = primVwap - band2Mult * primStd
timeseries primBand3Hi = primVwap + band3Mult * primStd
timeseries primBand3Lo = primVwap - band3Mult * primStd

// --- Secondary VWAP ---
if (sec_last_anchor == -1) {
    sec_last_anchor = secAnchorId
    sec_cumPV = 0.0
    sec_cumV = 0.0
    sec_cumPV2 = 0.0
    sec_bars = 0
} else if (secAnchorId != sec_last_anchor) {
    sec_last_anchor = secAnchorId
    sec_cumPV = 0.0
    sec_cumV = 0.0
    sec_cumPV2 = 0.0
    sec_bars = 0
}
sec_cumPV = sec_cumPV + pv
sec_cumV = sec_cumV + volume
sec_cumPV2 = sec_cumPV2 + volume * (typicalPrice * typicalPrice)
sec_bars = sec_bars + 1

timeseries secVwap = sec_cumV > 0 ? sec_cumPV / sec_cumV : typicalPrice
timeseries secVar = sec_cumV > 0 ? (sec_cumPV2 / sec_cumV) - (secVwap * secVwap) : 0
timeseries secStd = math.sqrt(math.max(secVar, 0))

// --- Tertiary VWAP ---
if (tert_last_anchor == -1) {
    tert_last_anchor = tertAnchorId
    tert_cumPV = 0.0
    tert_cumV = 0.0
    tert_cumPV2 = 0.0
    tert_bars = 0
} else if (tertAnchorId != tert_last_anchor) {
    tert_last_anchor = tertAnchorId
    tert_cumPV = 0.0
    tert_cumV = 0.0
    tert_cumPV2 = 0.0
    tert_bars = 0
}
tert_cumPV = tert_cumPV + pv
tert_cumV = tert_cumV + volume
tert_cumPV2 = tert_cumPV2 + volume * (typicalPrice * typicalPrice)
tert_bars = tert_bars + 1

timeseries tertVwap = tert_cumV > 0 ? tert_cumPV / tert_cumV : typicalPrice
timeseries tertVar = tert_cumV > 0 ? (tert_cumPV2 / tert_cumV) - (tertVwap * tertVwap) : 0
timeseries tertStd = math.sqrt(math.max(tertVar, 0))

// ---------------------------------------------------------------------------
// 5. REGIME DETECTION (price relative to primary VWAP)
// ---------------------------------------------------------------------------
var abovePrimary = close > primVwap
var belowPrimary = close < primVwap
var atPrimary = !abovePrimary && !belowPrimary

var regimeBull = close > primVwap && close > primVwap[1]
var regimeBear = close < primVwap && close < primVwap[1]

var regimeColor = abovePrimary ? vwapAboveColor : (belowPrimary ? vwapBelowColor : vwapColor)

// VWAP deviation (distance from VWAP in units of std dev)
timeseries vwapDev = primStd > 0 ? (close - primVwap) / primStd : 0

// ---------------------------------------------------------------------------
// 6. CROSS & TOUCH DETECTION (shape markers)
// ---------------------------------------------------------------------------
var primCrossUp = close > primVwap && close[1] <= primVwap[1]
var primCrossDown = close < primVwap && close[1] >= primVwap[1]

var touchBand1Hi = high >= primBand1Hi && low <= primBand1Hi
var touchBand1Lo = high >= primBand1Lo && low <= primBand1Lo
var touchBand2Hi = high >= primBand2Hi && low <= primBand2Hi
var touchBand2Lo = high >= primBand2Lo && low <= primBand2Lo
var touchBand3Hi = high >= primBand3Hi && low <= primBand3Hi
var touchBand3Lo = high >= primBand3Lo && low <= primBand3Lo

// ---------------------------------------------------------------------------
// 7. PLOTTING
// ---------------------------------------------------------------------------

// --- Primary VWAP (regime-colored) ---
if (showPrimary) {
    plotLine(
        value=primVwap,
        width=lineWidth,
        colors=[vwapAboveColor, vwapBelowColor],
        colorIndex=abovePrimary ? 0 : 1,
        label=["VWAP " + primaryAnchor],
        desc=["Anchored VWAP (" + primaryAnchor + ") — cumulative volume-weighted average"]
    )
}

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

// --- Tertiary VWAP ---
if (showTertiary) {
    plotLine(
        value=tertVwap,
        width=lineWidth,
        colors=[tertiaryColor],
        label=["VWAP " + tertiaryAnchor],
        desc=["Tertiary anchored VWAP (" + tertiaryAnchor + ")"]
    )
}

// --- Band 1 Fill & Lines ---
if (showBand1) {
    if (showBandFill) {
        plotLine(
            value=[primBand1Lo, primBand1Hi],
            width=1,
            colors=[transparency(vwapAboveColor, 15), transparency(vwapBelowColor, 15)],
            colorIndex=abovePrimary ? 0 : 1,
            fill=true,
            label=["±1σ Fill"],
            desc=["±1σ deviation band fill (regime-colored)"]
        )
    }
    plotLine(
        value=primBand1Hi,
        width=1,
        colors=[band1Color],
        label=["+1σ"],
        desc=["Upper band at " + band1Mult + "× σ"]
    )
    plotLine(
        value=primBand1Lo,
        width=1,
        colors=[band1Color],
        label=["-1σ"],
        desc=["Lower band at " + band1Mult + "× σ"]
    )
}

// --- Band 2 Fill & Lines ---
if (showBand2) {
    if (showBandFill) {
        plotLine(
            value=[primBand2Lo, primBand2Hi],
            width=1,
            colors=[transparency(vwapAboveColor, 10), transparency(vwapBelowColor, 10)],
            colorIndex=abovePrimary ? 0 : 1,
            fill=true,
            label=["±2σ Fill"],
            desc=["±2σ deviation band fill (regime-colored)"]
        )
    }
    plotLine(
        value=primBand2Hi,
        width=1,
        colors=[band2Color],
        label=["+2σ"],
        desc=["Upper band at " + band2Mult + "× σ"]
    )
    plotLine(
        value=primBand2Lo,
        width=1,
        colors=[band2Color],
        label=["-2σ"],
        desc=["Lower band at " + band2Mult + "× σ"]
    )
}

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

// --- VWAP Cross Shapes ---
if (showVwapCross) {
    if (primCrossUp) {
        plotShape(
            value=low,
            shape="triangleup",
            colorIndex=vwapAboveColor,
            width=shapeSize,
            label=["VWAP Cross Up"],
            desc=["Price crossed above VWAP (" + primaryAnchor + ")"]
        )
    }
    if (primCrossDown) {
        plotShape(
            value=high,
            shape="triangledown",
            colorIndex=vwapBelowColor,
            width=shapeSize,
            label=["VWAP Cross Down"],
            desc=["Price crossed below VWAP (" + primaryAnchor + ")"]
        )
    }
}

// --- Band Touch Shapes ---
if (showBandTouch) {
    if (touchBand1Hi) {
        plotShape(
            value=primBand1Hi,
            shape="triangledown",
            colorIndex=band1Color,
            width=shapeSize,
            label=["1σ High Touch"],
            desc=["Price touched upper " + band1Mult + "σ band"]
        )
    }
    if (touchBand1Lo) {
        plotShape(
            value=primBand1Lo,
            shape="triangleup",
            colorIndex=band1Color,
            width=shapeSize,
            label=["1σ Low Touch"],
            desc=["Price touched lower " + band1Mult + "σ band"]
        )
    }
    if (touchBand2Hi) {
        plotShape(
            value=primBand2Hi,
            shape="triangledown",
            colorIndex=band2Color,
            width=shapeSize,
            label=["2σ High Touch"],
            desc=["Price touched upper " + band2Mult + "σ band"]
        )
    }
    if (touchBand2Lo) {
        plotShape(
            value=primBand2Lo,
            shape="triangleup",
            colorIndex=band2Color,
            width=shapeSize,
            label=["2σ Low Touch"],
            desc=["Price touched lower " + band2Mult + "σ band"]
        )
    }
    if (touchBand3Hi) {
        plotShape(
            value=primBand3Hi,
            shape="triangledown",
            colorIndex=band3Color,
            width=shapeSize,
            label=["3σ High Touch"],
            desc=["Price touched upper " + band3Mult + "σ band — statistical extreme"]
        )
    }
    if (touchBand3Lo) {
        plotShape(
            value=primBand3Lo,
            shape="triangleup",
            colorIndex=band3Color,
            width=shapeSize,
            label=["3σ Low Touch"],
            desc=["Price touched lower " + band3Mult + "σ band — statistical extreme"]
        )
    }
}

// ---------------------------------------------------------------------------
// 8. SUMMARY TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = abovePrimary ? "ABOVE VWAP" : (belowPrimary ? "BELOW VWAP" : "AT VWAP")
    var regimeTextColor = abovePrimary ? vwapAboveColor : (belowPrimary ? vwapBelowColor : vwapColor)

    plotTable(
        data=[
            ["ITC VWAP — Perfected", regimeText],
            ["VWAP (" + primaryAnchor + ")", primVwap[0]],
            ["VWAP (" + secondaryAnchor + ")", secVwap[0]],
            ["VWAP Dev (σ)", vwapDev[0]],
            ["Band 1", "±" + band1Mult + "σ"],
            ["Band 2", "±" + band2Mult + "σ"],
            ["Band 3", "±" + band3Mult + "σ"],
            ["Bars in Anchor", prim_bars]
        ],
        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
    )
}