MM Flow
FlowScripts

Perfected FlowScript

Open Interest Weighted Average Price

OIWAP [Perfected] is indexed as 096_open_interest_weighted_average_price.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

17.6 KB

Lines

609

Native Signal Candidates

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

9/9 guarded

POC

line 358:5

Trigger

(showPoc && !isnan(pocPrice))

Value

pocPrice

Deps

pocPrice:var, showPoc:input

OIWAP Cross Up

line 476:5

Trigger

(showOiwapCross && oiwapCrossUp)

Value

low

Deps

oiwapCrossUp:var, showOiwapCross:input

OIWAP Cross Down

line 486:5

Trigger

(showOiwapCross && oiwapCrossDown)

Value

high

Deps

oiwapCrossDown:var, showOiwapCross:input

Band 1 High Touch

line 496:5

Trigger

(showBandTouch && touchBand1Hi)

Value

band1Hi

Deps

showBandTouch:input, touchBand1Hi:var

Band 1 Low Touch

line 506:5

Trigger

(showBandTouch && touchBand1Lo)

Value

band1Lo

Deps

showBandTouch:input, touchBand1Lo:var

Band 2 High Touch

line 516:5

Trigger

(showBandTouch && touchBand2Hi)

Value

band2Hi

Deps

showBandTouch:input, touchBand2Hi:var

Band 2 Low Touch

line 526:5

Trigger

(showBandTouch && touchBand2Lo)

Value

band2Lo

Deps

showBandTouch:input, touchBand2Lo:var

Z-Extreme High

line 559:9

Trigger

(showZscore) && (zExtremeHigh)

Value

zscore

Deps

showZscore:input, zExtremeHigh:var

Z-Extreme Low

line 569:9

Trigger

(showZscore) && (zExtremeLow)

Value

zscore

Deps

showZscore:input, zExtremeLow:var

096_open_interest_weighted_average_price.flowscript

source path: kscripts/perfected/096_open_interest_weighted_average_price.flowscript · sha256:03e8d6f82907bc1e10f0b1ce04aeecc8e55b942a86be559274f379682da1ef21

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

// ============================================================================
// Open Interest Weighted Average Price [OIWAP Perfected]
// Author: BackQuant (@BackQuant) — Perfected by kScript_Perfection_Engineer
// Tags: CORE, #oiwap, #openinterest, #futures, #microstructure, #positioning
//
// Production-quality OIWAP with OI-weighted average price, volume-weighted
// standard deviation bands, z-score normalization, regime detection, color-coded
// fills, and comprehensive shape markers. Uses static variables for anchored
// cumulative sums and stateful period tracking.
//
// Research papers underpinning this design:
//  - Berkowitz, Logue & Noser (1988), "The Total Cost of Transactions on the
//    NYSE": foundational VWAP formula; OIWAP extends weights from volume to OI.
//  - Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the Basis
//    and Open Interest in Futures Contracts": OI levels contain information about
//    future price volatility; higher OI = greater information flow.
//  - LeviathanCapital (2024), "Open Interest Profile [Fixed Range] Indicator":
//    OIWAP = Σ(Price_i × OI_i) / ΣOI_i; POC marks peak OI concentration;
//    high-density OI areas act as support/resistance.
//  - Definedge Securities (2024), "OIWAP (Open Interest Weighted Average Price)":
//    OIWAP serves as benchmark reflecting average transaction price of contracts
//    opened; LIWAP/SIWAP decomposition for directional analysis.
//  - StudyRaid (2026), "Standard Deviation Bands in VWAP": σ = √[Σ(Wᵢ·(Pᵢ−VWAP)²)/ΣWᵢ];
//    ~68.2% of price activity within ±1σ, ~95.4% within ±2σ.
// ============================================================================

define(
    title="OIWAP [Perfected]",
    position="onchart",
    axis=false
)

// ---------------------------------------------------------------------------
// User Inputs — grouped with constraints
// ---------------------------------------------------------------------------

// --- OIWAP Settings ---
var lookback = input(
    name="lookback",
    type="number",
    defaultValue=50,
    label="OIWAP Lookback",
    constraints={min: 10, max: 500, step: 5},
    group="OIWAP Settings"
)
var usePosDelta = input(
    name="usePosDelta",
    type="boolean",
    defaultValue=false,
    label="Use Positive OI Delta Only",
    group="OIWAP Settings"
)
var anchorMode = input(
    name="anchorMode",
    type="select",
    defaultValue="Rolling",
    label="Anchor Mode",
    options=["Rolling", "Daily", "Weekly", "Monthly"],
    group="OIWAP Settings"
)

// --- 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="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"
)

// --- Z-Score ---
var showZscore = input(
    name="showZscore",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Panel",
    group="Z-Score"
)
var zLookback = input(
    name="zLookback",
    type="number",
    defaultValue=50,
    label="Z-Score Lookback",
    constraints={min: 10, max: 200, step: 5},
    group="Z-Score"
)
var zExtreme = input(
    name="zExtreme",
    type="number",
    defaultValue=2.0,
    label="Extreme Z-Score Threshold",
    constraints={min: 1.0, max: 4.0, step: 0.25},
    group="Z-Score"
)

// --- Display ---
var showOiwapCross = input(
    name="showOiwapCross",
    type="boolean",
    defaultValue=true,
    label="Show OIWAP 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 OI 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 ---
var oiwapColor = input(
    name="oiwapColor",
    type="color",
    defaultValue="#2962ff",
    label="OIWAP Line Color",
    group="Colors"
)
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bull Color (Above OIWAP)",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bear Color (Below OIWAP)",
    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"
)

// ---------------------------------------------------------------------------
// 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 oiData = open_interest(symbol=currentSymbol, exchange=currentExchange)

// isnan guard: prevent computation on incomplete data
if (isnan(t[0]) || isnan(close[0]) || isnan(high[0]) || isnan(low[0]) || isnan(oiData.close[0])) {
    return
}

// ---------------------------------------------------------------------------
// Time Derivation (Calendar Math for Anchoring)
// ---------------------------------------------------------------------------
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

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

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

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 {
    isRolling = true
    periodBars = lookback
}

if (isRolling) {
    if (barCount < periodBars) {
        barCount = barCount + 1
    } else {
        barCount = periodBars
    }
} else if (newPeriod || barCount == 0) {
    barCount = 1
} else {
    barCount = barCount + 1
}

// ---------------------------------------------------------------------------
// OIWAP Computation (anchored, not rolling)
// ---------------------------------------------------------------------------
// Typical price (used for weighting)
timeseries typ = (high + low + close) / 3

// OI weight: total OI or positive OI delta
timeseries oiRaw = oiData.close
timeseries oiDelta = oiRaw - oiRaw[1]
timeseries oiWeight = usePosDelta ? math.max(oiDelta, 0) : oiRaw

// OIWAP = sum(typical * oiWeight) / sum(oiWeight) over barCount
timeseries pv = typ * oiWeight
timeseries sumPV = sum(pv, barCount)
timeseries sumOI = sum(oiWeight, barCount)
timeseries oiwap = sumOI > 0 ? sumPV / sumOI : typ

// OI-weighted standard deviation (anchored to current OIWAP)
timeseries devSq = oiWeight * ((typ - oiwap) * (typ - oiwap))
timeseries sumSqDev = sum(devSq, barCount)
timeseries variance = sumOI > 0 ? sumSqDev / sumOI : 0
timeseries sd = math.sqrt(math.max(0, variance))

// Standard deviation bands
timeseries band1Hi = oiwap + band1Mult * sd
timeseries band1Lo = oiwap - band1Mult * sd
timeseries band2Hi = oiwap + band2Mult * sd
timeseries band2Lo = oiwap - band2Mult * sd
timeseries band3Hi = oiwap + band3Mult * sd
timeseries band3Lo = oiwap - band3Mult * sd

// ---------------------------------------------------------------------------
// Z-Score Computation (price deviation from OIWAP in σ units)
// ---------------------------------------------------------------------------
timeseries zscore = sd > 0 ? (close - oiwap) / sd : 0
timeseries zscoreMa = sma(source=zscore, period=zLookback)

// ---------------------------------------------------------------------------
// Regime Detection (color coding by position relative to OIWAP)
// ---------------------------------------------------------------------------
var aboveOiwap = close > oiwap
var regimeBull = aboveOiwap && close > band1Hi
var regimeBear = !aboveOiwap && close < band1Lo
var regimeNeutral = !regimeBull && !regimeBear

var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : "#9e9e9e")

// ---------------------------------------------------------------------------
// OI Profile Integration (POC relative to OIWAP)
// ---------------------------------------------------------------------------
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 OIWAP"]
    )
}

// ---------------------------------------------------------------------------
// Cross & Touch Detection (shape markers)
// ---------------------------------------------------------------------------
var oiwapCrossUp = cross(close, oiwap) && close > oiwap
var oiwapCrossDown = cross(close, oiwap) && close < oiwap
var touchBand1Hi = high >= band1Hi && low <= band1Hi
var touchBand1Lo = high >= band1Lo && low <= band1Lo
var touchBand2Hi = high >= band2Hi && low <= band2Hi
var touchBand2Lo = high >= band2Lo && low <= band2Lo

// Z-Score extremes
var zExtremeHigh = zscore > zExtreme && zscore[1] <= zExtreme
var zExtremeLow = zscore < -zExtreme && zscore[1] >= -zExtreme
var zRevertHigh = zscore < zExtreme && zscore[1] >= zExtreme
var zRevertLow = zscore > -zExtreme && zscore[1] <= -zExtreme

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

// --- OIWAP Line (regime-colored) ---
plotLine(
    value=oiwap,
    width=lineWidth,
    colors=[bullColor, bearColor],
    colorIndex=aboveOiwap ? 0 : 1,
    label=["OIWAP"],
    desc=["Open Interest Weighted Average Price"]
)

// --- Band 1 Fill & Lines ---
if (showBand1) {
    if (showFill) {
        plotLine(
            value=([band1Lo, band1Hi]),
            width=1,
            colors=[opacity(bullColor, 15), opacity(bearColor, 15)],
            colorIndex=aboveOiwap ? 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(bullColor, 10), opacity(bearColor, 10)],
            colorIndex=aboveOiwap ? 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 (showOiwapCross && oiwapCrossUp) {
    plotShape(
        value=low,
        shape="triangleup",
        colorIndex=bullColor,
        width=shapeSize,
        label=["OIWAP Cross Up"],
        desc=["Price crossed above OIWAP"]
    )
}
if (showOiwapCross && oiwapCrossDown) {
    plotShape(
        value=high,
        shape="triangledown",
        colorIndex=bearColor,
        width=shapeSize,
        label=["OIWAP Cross Down"],
        desc=["Price crossed below OIWAP"]
    )
}
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"]
    )
}

// --- Z-Score Panel ---
if (showZscore) {
    plotLine(
        value=zscore,
        width=2,
        colors=[bullColor, bearColor],
        colorIndex=zscore >= 0 ? 0 : 1,
        label=["Z-Score"],
        desc=["Price deviation from OIWAP in standard deviations"]
    )
    plotLine(
        value=zscoreMa,
        width=1,
        colors=["#ffffff80"],
        label=["Z-Score MA"],
        desc=["Moving average of Z-Score"]
    )
    hline(value=zExtreme, color=transparency(bearColor, 60), width=1)
    hline(value=-zExtreme, color=transparency(bullColor, 60), width=1)
    hline(value=0, color="#ffffff20", width=1)

    // Z-Score extreme shapes
    if (zExtremeHigh) {
        plotShape(
            value=zscore,
            shape="triangledown",
            colorIndex=bearColor,
            width=shapeSize,
            label=["Z-Extreme High"],
            desc=["Z-Score exceeded +" + zExtreme + " (potential mean reversion)"]
        )
    }
    if (zExtremeLow) {
        plotShape(
            value=zscore,
            shape="triangleup",
            colorIndex=bullColor,
            width=shapeSize,
            label=["Z-Extreme Low"],
            desc=["Z-Score exceeded -" + zExtreme + " (potential mean reversion)"]
        )
    }
}

// ---------------------------------------------------------------------------
// Regime Table (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : "#9e9e9e")

    plotTable(
        data=[
            ["OIWAP [Perfected]", regimeText],
            ["OIWAP", oiwap[0]],
            ["Z-Score", zscore[0]],
            ["1σ Band", band1Hi[0] + " / " + band1Lo[0]],
            ["2σ Band", band2Hi[0] + " / " + band2Lo[0]],
            ["OI Weight", oiWeight[0]]
        ],
        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
    )
}