MM Flow
FlowScripts

Perfected FlowScript

OI/CVD Divergence [borkiss727]

OI/CVD Divergence [borkiss727 Perfected] is indexed as 071_oi_cvd_divergence_borkiss727.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

offchart

Axis

true

Size

13.2 KB

Lines

288

Native Signal Candidates

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

2/2 guarded

Hidden Distribution

line 268:9

Trigger

(showDiv && showShapes) && (divUp)

Value

oiZ

Deps

divUp:var, showDiv:input, showShapes:input

Hidden Accumulation

line 278:9

Trigger

(showDiv && showShapes) && (divDn)

Value

oiZ

Deps

divDn:var, showDiv:input, showShapes:input

071_oi_cvd_divergence_borkiss727.flowscript

source path: kscripts/perfected/071_oi_cvd_divergence_borkiss727.flowscript · sha256:6891d0a1b3be4a1e1c4a651b5414111f8e4091898f241f7c5e137fdcf834e67f

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

// ============================================================================
// OI/CVD Divergence [borkiss727 Perfected]
// Author: B (@borkiss727) — Perfected by kScript_Perfection_Engineer
// Tags: ADVANCED, FLOW, CORE, #oi, #cvd, #divergence, #zscore, #correlation
//
// Detects divergences between Open Interest and Cumulative Volume Delta (CVD)
// using z-score normalization, rolling correlation, and regime-coded color
// with shape markers for divergence signals. OI rising + CVD falling = hidden
// distribution (positioning building without aggressive flow). OI falling + CVD
// rising = hidden accumulation (aggressive flow without position building).
//
// FORMULA FOUNDATION:
// 1. CVD (Resetting): buyVol − selVol cumulated, reset every N bars per
//    MarketDelta footprint conventions (MarketDelta 2007).
// 2. Z-Score Normalization: z = (x − μ) / σ over rolling window (Zhao & Palomar 2018).
// 3. Rolling Correlation: ρ(OI_z, CVD_z) over lookback — measures directional
//    alignment between positioning and flow (Cont et al. 2014 linear impact model).
// 4. Divergence Regimes:
//      • Hidden Distribution: OI_z rising, CVD_z falling (positive OI change, negative CVD)
//      • Hidden Accumulation: OI_z falling, CVD_z rising (negative OI change, positive CVD)
//      • Aligned: both moving same direction — trend confirmation
//
// RESEARCH BASIS:
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//    J. Financial Econometrics 12(1), 47–88. Net aggressive order flow (delta) is
//    the primary driver of short-term price changes. CVD cumulates this delta,
//    making persistent pressure visible. Divergence = flow/positioning mismatch.
//  • Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//    Market Returns", J. Financial Economics 65(1), 111–130. Extreme imbalances
//    predict return reversals. CVD divergence (price rising while CVD falling) is
//    a direct implementation of return-reversal-after-imbalance.
//  • Harris (1986), "A Transaction Data Study of Weekly and Intraday Patterns in
//    Stock Returns", J. Finance 41(4), 815–830. Intraday seasonality supports
//    the OI-Price-Volume framework: OI direction + price direction = trend strength.
//  • Heston, Korajczyk & Sadka (2010), "Intra-day Patterns in the Cross-Section
//    of Stock Returns". Return effects are pronounced in first/last half-hours;
//    divergence signals are most reliable during high-participation windows.
//  • Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
//    Supply and Demand". Liquidity memory time explains why OI/CVD divergences
//    persist: when aggressive volume fails to move price (absorption), it reflects
//    liquidity replenishment by passive participants — the divergence signature.
//  • Lillo & Farmer (2004), "The Long Memory of the Efficient Market". Order flow
//    has long-memory properties (autocorrelations decay as power law). Cumulative
//    measures capture sustained pressure that drives trends — divergence breaks this
//    persistence, signaling regime shift.
// ============================================================================

define(
    title="OI/CVD Divergence [borkiss727 Perfected]",
    position="offchart",
    axis=true
)

// ---------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ---------------------------------------------------------------------------

// --- OI ---
var oiLen = input(name="oiLen", type="number", defaultValue=20, label="OI Z-Score Lookback", constraints={min: 5, max: 200, step: 1}, group="OI")
var oiSmooth = input(name="oiSmooth", type="boolean", defaultValue=false, label="Smooth OI Z (EMA)", group="OI")
var oiSmoothLen = input(name="oiSmoothLen", type="number", defaultValue=5, label="OI Z EMA Length", constraints={min: 1, max: 50, step: 1}, group="OI")

// --- CVD ---
var cvdLen = input(name="cvdLen", type="number", defaultValue=20, label="CVD Z-Score Lookback", constraints={min: 5, max: 200, step: 1}, group="CVD")
var cvdReset = input(name="cvdReset", type="number", defaultValue=50, label="CVD Reset Length", constraints={min: 10, max: 500, step: 1}, group="CVD")
var cvdSmooth = input(name="cvdSmooth", type="boolean", defaultValue=false, label="Smooth CVD Z (EMA)", group="CVD")
var cvdSmoothLen = input(name="cvdSmoothLen", type="number", defaultValue=5, label="CVD Z EMA Length", constraints={min: 1, max: 50, step: 1}, group="CVD")

// --- Correlation ---
var corrLen = input(name="corrLen", type="number", defaultValue=20, label="Correlation Lookback", constraints={min: 5, max: 100, step: 1}, group="Correlation")
var showCorrelation = input(name="showCorrelation", type="boolean", defaultValue=true, label="Show Correlation Line", group="Correlation")

// --- Divergence ---
var showDiv = input(name="showDiv", type="boolean", defaultValue=true, label="Show Divergence Signals", group="Divergence")
var divThresh = input(name="divThresh", type="number", defaultValue=0.5, label="Divergence Sensitivity", constraints={min: 0.1, max: 2.0, step: 0.1}, group="Divergence")

// --- Display ---
var showOIZ = input(name="showOIZ", type="boolean", defaultValue=true, label="Plot OI Z-Score", group="Display")
var showCVDZ = input(name="showCVDZ", type="boolean", defaultValue=true, label="Plot CVD Z-Score", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Divergence Shapes", group="Display")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Regime Fill", group="Display")

// --- Colors ---
var oiColor = input(name="oiColor", type="color", defaultValue="#ff9800", label="OI Z-Score Color", group="Colors")
var cvdColor = input(name="cvdColor", type="color", defaultValue="#42a5f5", label="CVD Z-Score Color", group="Colors")
var corrColor = input(name="corrColor", type="color", defaultValue="#ab47bc", label="Correlation Color", group="Colors")
var divUpColor = input(name="divUpColor", type="color", defaultValue="#ef5350", label="Hidden Distribution Color", group="Colors")
var divDnColor = input(name="divDnColor", type="color", defaultValue="#26a69a", label="Hidden Accumulation Color", group="Colors")
var alignColor = input(name="alignColor", type="color", defaultValue="#9e9e9e", label="Aligned Color", group="Colors")

// ---------------------------------------------------------------------------
// Data Sources
// ---------------------------------------------------------------------------
timeseries oiTS = open_interest(symbol=currentSymbol, exchange=currentExchange)
timeseries oi = oiTS.close

timeseries pxTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries o = pxTS.open
timeseries c = pxTS.close
timeseries h = pxTS.high
timeseries l = pxTS.low
timeseries v = pxTS.volume

// isnan guard: prevent execution before data is loaded
if (isnan(oi[0]) || isnan(c[0]) || isnan(h[0]) || isnan(l[0]) || isnan(v[0])) {
    return
}

// ---------------------------------------------------------------------------
// CVD (Resetting) — MarketDelta footprint convention
// ---------------------------------------------------------------------------
// Buy/sell volume estimation using intra-bar price movement (BVC-style
// probabilistic allocation per Easley, López de Prado & O'Hara 2012).
timeseries range_ = h - l
timeseries upW = math.max(c - o, 0.0)
timeseries dnW = math.max(o - c, 0.0)
timeseries buyVol = range_ > 0 ? v * (upW / range_) : v * 0.5
timeseries selVol = range_ > 0 ? v * (dnW / range_) : v * 0.5
timeseries delta = buyVol - selVol

// Resetting CVD accumulator (static for session persistence)
static counter = 0
static cvd = 0.0
counter = counter + 1
cvd = cvd + delta
if (counter >= cvdReset) { counter = 0; cvd = 0.0 }

// ---------------------------------------------------------------------------
// Z-Score Normalization (Zhao & Palomar 2018)
// ---------------------------------------------------------------------------
// Both OI and CVD are normalized to standard-deviation units for
// comparable divergence measurement across instruments and timeframes.

timeseries oiM = sma(oi, oiLen)
timeseries oiSD = stddev(oi, oiLen)
timeseries oiZ_raw = oiSD > 0 ? (oi - oiM) / oiSD : 0.0

timeseries cvdM = sma(cvd, cvdLen)
timeseries cvdSD = stddev(cvd, cvdLen)
timeseries cvdZ_raw = cvdSD > 0 ? (cvd - cvdM) / cvdSD : 0.0

// Optional smoothing
timeseries oiZ = oiSmooth ? ema(oiZ_raw, oiSmoothLen) : oiZ_raw
timeseries cvdZ = cvdSmooth ? ema(cvdZ_raw, cvdSmoothLen) : cvdZ_raw

// ---------------------------------------------------------------------------
// Rolling Correlation (Cont et al. 2014 alignment measure)
// ---------------------------------------------------------------------------
// Pearson correlation between OI z-score and CVD z-score over rolling window.
// ρ ≈ +1 = aligned (positioning and flow agree); ρ ≈ −1 = divergent (flow/positioning
// disagree); ρ ≈ 0 = uncorrelated (independent dynamics).
timeseries corr = correlation(oiZ, cvdZ, corrLen)

// ---------------------------------------------------------------------------
// Divergence Detection (Chordia et al. 2002 + Bouchaud et al. 2009)
// ---------------------------------------------------------------------------
// Divergence = OI and CVD moving in opposite directions over the lookback.
// Hidden Distribution: OI up, CVD down — positioning building without flow.
// Hidden Accumulation: OI down, CVD up — flow without position building.

timeseries oiChg = oiZ - oiZ[1]
timeseries cvdChg = cvdZ - cvdZ[1]

// Regime classification
var divUp = oiChg > divThresh && cvdChg < -divThresh    // Hidden Distribution
var divDn = oiChg < -divThresh && cvdChg > divThresh   // Hidden Accumulation
var aligned = !divUp && !divDn

var regimeColorIdx = divUp ? 0 : (divDn ? 1 : 2)

// ---------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ---------------------------------------------------------------------------
static lastDivRegime = 2  // 0=distrib, 1=accum, 2=aligned
static divChangeCount = 0
static sessionHighCorr = -1.0
static sessionLowCorr = 1.0
static divUpCount = 0
static divDnCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    lastBarIndex = currentBarIndex

    if (!isnan(corr)) {
        if (corr > sessionHighCorr) { sessionHighCorr = corr }
        if (corr < sessionLowCorr) { sessionLowCorr = corr }
    }

    var currentDivRegime = divUp ? 0 : (divDn ? 1 : 2)
    if (lastDivRegime != currentDivRegime) {
        lastDivRegime = currentDivRegime
        divChangeCount = divChangeCount + 1
    }

    if (divUp) { divUpCount = divUpCount + 1 }
    if (divDn) { divDnCount = divDnCount + 1 }
}

// ---------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Fill, Shape, HLine)
// ---------------------------------------------------------------------------

// Zero reference line
hline(value=0, color="#88888840", width=1)

// Correlation reference line
if (showCorrelation) {
    hline(value=0, color="#88888820", width=1)
}

// OI Z-Score line
timeseries oiZ_plot = showOIZ ? oiZ : 0.0
if (showOIZ) {
    plotLine(
        value=oiZ,
        width=2,
        colors=[oiColor],
        label=["OI Z"],
        desc=["Rolling z-score of open interest (positioning magnitude)"]
    )
}

// CVD Z-Score line
timeseries cvdZ_plot = showCVDZ ? cvdZ : 0.0
if (showCVDZ) {
    plotLine(
        value=cvdZ,
        width=2,
        colors=[cvdColor],
        label=["CVD Z"],
        desc=["Rolling z-score of resetting CVD (flow pressure)"]
    )
}

// Regime fill between OI and CVD z-scores (divergence visualization)
if (showFill && showOIZ && showCVDZ) {
    plotLine(
        value=([math.min(oiZ, cvdZ), math.max(oiZ, cvdZ)]),
        width=1,
        colors=[opacity(divUpColor, 12), opacity(divDnColor, 12), opacity(alignColor, 8)],
        colorIndex=regimeColorIdx,
        fill=true,
        label=["Divergence Fill"],
        desc=["Fill between OI and CVD z-scores: red=hidden distribution, green=hidden accumulation, grey=aligned"]
    )
}

// Correlation line (secondary, scaled to axis)
if (showCorrelation) {
    plotLine(
        value=corr,
        width=1,
        colors=[corrColor],
        label=["Correlation"],
        desc=["Rolling correlation between OI z-score and CVD z-score (±1 = perfect alignment/divergence)"]
    )
}

// Divergence shape markers (Bouchaud et al. 2009 absorption/exhaustion framework)
if (showDiv && showShapes) {
    if (divUp) {
        plotShape(
            value=oiZ,
            shape="triangledown",
            color=divUpColor,
            width=4,
            label=["Hidden Distribution"],
            desc=["OI rising, CVD falling — positioning building without aggressive flow (potential distribution)"]
        )
    }
    if (divDn) {
        plotShape(
            value=oiZ,
            shape="triangleup",
            color=divDnColor,
            width=4,
            label=["Hidden Accumulation"],
            desc=["OI falling, CVD rising — flow without position building (potential accumulation)"]
        )
    }
}