MM Flow
FlowScripts

Perfected FlowScript

30m BTC CVD Liquidity Zones

30m BTC CVD Liquidity Zones V2 is indexed as 117_30m_btc_cvd_liquidity_zones.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

14.3 KB

Lines

333

Native Signal Candidates

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

6/6 guarded

Bull Zone Touch

line 257:5

Trigger

(showShapes && zoneTouchUp)

Value

zoneThreshold

Deps

showShapes:input, zoneTouchUp:var

Bear Zone Touch

line 267:5

Trigger

(showShapes && zoneTouchDn)

Value

-zoneThreshold

Deps

showShapes:input, zoneTouchDn:var

Extreme Bull Zone

line 279:5

Trigger

(showShapes && extremeBull)

Value

cvdZ

Deps

extremeBull:var, showShapes:input

Extreme Bear Zone

line 289:5

Trigger

(showShapes && extremeBear)

Value

cvdZ

Deps

extremeBear:var, showShapes:input

Bull Div

line 301:5

Trigger

(showDivergence && showShapes && bullDiv)

Value

cvdZ

Deps

bullDiv:var, showDivergence:input, showShapes:input

Bear Div

line 311:5

Trigger

(showDivergence && showShapes && bearDiv)

Value

cvdZ

Deps

bearDiv:var, showDivergence:input, showShapes:input

117_30m_btc_cvd_liquidity_zones.flowscript

source path: kscripts/perfected/117_30m_btc_cvd_liquidity_zones.flowscript · sha256:b765fa3d9d0a18c332259987747ba48c942c2a42cbd3ae390772690809224ae6

hash verified
//@version=2

// ============================================================================
// 30m BTC CVD Liquidity Zones V2 — CVD-Based Liquidity Zone Detection
// Author: laroshe1 (@laroshe1) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, FLOW, #BTC, #LIQUIDITY, #CVD
//
// Computes Cumulative Volume Delta (CVD) and maps CVD extremes to price
// levels, creating liquidity zones where sustained order flow imbalance
// indicates potential reversal areas. Uses z-score normalization, regime
// detection, price-CVD divergence, and color-coded zone fills with shape
// markers for zone touches and divergences.
//
// Academic foundation (exact papers & formulas):
//  1. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book
//     Events", Journal of Financial Econometrics, 12(1), 47–88.
//     [Formula] OFI_t = Δq_t^b·I_{Δq_t^b>0} − Δq_t^a·I_{Δq_t^a>0}
//     Cumulative OFI (CVD) linearly predicts short-term price changes:
//     Δp_t = λ·OFI_t + ε_t, where λ is inversely proportional to depth.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  2. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//     Journal of Finance, 46(2), 733–746. Foundational tick-classification
//     algorithm (85–93% accuracy): close > midpoint → buyer-initiated.
//     DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
//
//  3. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity,
//     and Market Returns", Journal of Financial Economics, 65(1), 111–130.
//     [Formula] Imbalance_t = Buy_t − Sell_t; extreme |Imbalance| predicts
//     return reversals. Directly motivates the divergence-threshold design.
//     DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  4. Lillo & Farmer (2004), "The Long Memory of the Efficient Market",
//     Physical Review Letters, 93(2), 028701. Order flow autocorrelations
//     decay as power law; cumulative measures (CVD) capture persistent
//     pressure better than per-bar delta.
//
//  5. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes
//     in Supply and Demand", Quantitative Finance, 9(3), 323–338.
//     [Formula] Square-root impact law: cumulative impact of sequential trades
//     is sublinear due to liquidity memory. Explains why CVD zones form at
//     absorption / exhaustion levels.
//
//  6. Kyle (1985), "Continuous Auctions and Insider Trading", Econometrica,
//     53(6), 1315–1335. [Formula] p_t = p_{t−1} + λ·OFI_t + noise.
//     Kyle's λ establishes the linear price-impact coefficient that underpins
//     every delta-based trading signal.
//     DOI: https://doi.org/10.2307/1913210
// ============================================================================

define(
    title="30m BTC CVD Liquidity Zones V2",
    position="offchart",
    axis=true
)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------

// -- Data Sources --
var symbol = input(name="symbol", type="string", defaultValue="BTCUSDT", label="Symbol", group="Data Sources")
var exchange = input(name="exchange", type="string", defaultValue="BINANCE", label="Exchange", group="Data Sources")

// -- CVD Computation --
var cvdWindow = input(name="cvdWindow", type="number", defaultValue=50, label="CVD Rolling Window", constraints={min: 20, max: 200, step: 5}, group="CVD Computation")
var zWindow = input(name="zWindow", type="number", defaultValue=50, label="Z-Score Window", constraints={min: 20, max: 200, step: 5}, group="CVD Computation")
var smoothLen = input(name="smoothLen", type="number", defaultValue=5, label="CVD EMA Smooth Length", constraints={min: 1, max: 50, step: 1}, group="CVD Computation")

// -- Zone Detection --
var zoneLookback = input(name="zoneLookback", type="number", defaultValue=100, label="Zone Lookback (bars)", constraints={min: 20, max: 500, step: 10}, group="Zone Detection")
var zoneThreshold = input(name="zoneThreshold", type="number", defaultValue=2.0, label="Zone Z-Score Threshold", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Zone Detection")
var extremeZone = input(name="extremeZone", type="number", defaultValue=3.0, label="Extreme Zone Threshold", constraints={min: 2.0, max: 6.0, step: 0.5}, group="Zone Detection")

// -- Divergence --
var swingLen = input(name="swingLen", type="number", defaultValue=10, label="Swing Detection Length", constraints={min: 3, max: 50, step: 1}, group="Divergence")
var divThreshold = input(name="divThreshold", type="number", defaultValue=2.0, label="Divergence Z-Score Threshold", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Divergence")

// -- Display --
var showCVD = input(name="showCVD", type="boolean", defaultValue=true, label="Show CVD Line", group="Display")
var showZones = input(name="showZones", type="boolean", defaultValue=true, label="Show Liquidity Zones", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Zone & Divergence Shapes", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show CVD Z-Score", group="Display")
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show CVD Histogram", group="Display")
var showDivergence = input(name="showDivergence", type="boolean", defaultValue=true, label="Show Price-CVD Divergence", group="Display")

// -- Colors --
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Bullish Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Bearish Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var extremeBullColor = input(name="extremeBullColor", type="color", defaultValue="#00e676", label="Extreme Bullish Color", group="Colors")
var extremeBearColor = input(name="extremeBearColor", type="color", defaultValue="#ff1744", label="Extreme Bearish Color", group="Colors")
var cvdColor = input(name="cvdColor", type="color", defaultValue="#2962ff", label="CVD Line Color", group="Colors")

// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first access
// ---------------------------------------------------------------------------

timeseries bars = ohlcv(symbol=symbol, exchange=exchange)
timeseries taker = source("taker_volume", symbol, exchange)

timeseries c = bars.close
timeseries h = bars.high
timeseries l = bars.low
timeseries v = bars.volume

// Guard: halt until price and volume data have loaded to avoid NaN propagation
if (isnan(c[0]) || isnan(v[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------

// -- 3.1 Per-bar volume delta (Lee-Ready fallback when taker feed unavailable) --
// Lee-Ready (1991) tick test: close ≥ midpoint → buyer-initiated; else seller-initiated.
// When taker.buy/sell is available, prefer the direct feed for higher accuracy.
timeseries midpoint = (h + l) / 2.0
timeseries buyV = isnum(taker.buy) ? taker.buy : (c >= midpoint ? v : 0.0)
timeseries sellV = isnum(taker.sell) ? taker.sell : (c < midpoint ? v : 0.0)
timeseries delta = buyV - sellV

// -- 3.2 Rolling-window CVD (stationary approximation; mean-reverting) --
// CVD_t = Σ_{i=0}^{W-1} Δ_{t-i}; rolling window keeps the series amenable
// to z-score standardisation per Cont et al. (2014).
timeseries cvd = sum(delta, cvdWindow)

// -- 3.3 True cumulative CVD via static state (tracked for reference) --
static cvdCum = 0.0
if (!isnan(delta[0])) {
    cvdCum = cvdCum + delta[0]
}

// -- 3.4 Z-score normalisation (all denominators guarded against zero) --
// Z_t = (CVD_t − μ_t) / σ_t, where μ_t = SMA(CVD, W), σ_t = StDev(CVD, W).
timeseries cvdMean = sma(cvd, zWindow)
timeseries cvdStd = stdev(cvd, zWindow)
timeseries cvdZ = (cvdStd > 0) ? (cvd - cvdMean) / cvdStd : 0

// -- 3.5 CVD smoothing (EMA per Cont et al. 2014 noise-reduction) --
timeseries cvdSmooth = ema(cvd, smoothLen)

// -- 3.6 Swing detection (price extremes for divergence context) --
timeseries swingHi = highest(h, swingLen)
timeseries swingLo = lowest(l, swingLen)

// -- 3.7 Price-CVD divergence detection (Chordia et al. 2002 reversal signal) --
// Price makes new high/low but CVD z-score diverges → potential reversal.
var priceNewHigh = h >= highest(h, zoneLookback)[1]
var priceNewLow = l <= lowest(l, zoneLookback)[1]
var bullDiv = priceNewLow && cvdZ > divThreshold
var bearDiv = priceNewHigh && cvdZ < -divThreshold

// -- 3.8 CVD-based liquidity zone detection --
// Zones form when CVD z-score enters extreme territory; these levels mark
// areas of absorption (bear zone) or exhaustion (bull zone) per Bouchaud
// et al. (2009) liquidity memory framework.
var bullZone = cvdZ > zoneThreshold
var bearZone = cvdZ < -zoneThreshold
var extremeBull = cvdZ > extremeZone
var extremeBear = cvdZ < -extremeZone
var neutralZone = !bullZone && !bearZone

// -- 3.9 Zone touch detection (crossing into zone territory) --
var zoneTouchUp = cvdZ >= zoneThreshold && !isnan(cvdZ[1]) && cvdZ[1] < zoneThreshold
var zoneTouchDn = cvdZ <= -zoneThreshold && !isnan(cvdZ[1]) && cvdZ[1] > -zoneThreshold

// -- 3.10 Static state tracking (session-level persistence) --
// Tracks CVD extremes, zone touches, and divergence counts for context-aware
// alerting and session diagnostics.
static sessionCVDHi = -999999.0
static sessionCVDLo = 999999.0
static zoneTouchCount = 0
static divBullCount = 0
static divBearCount = 0
static lastBarIdx = 0

var currentBarIdx = bar_index[0]
if (!isnan(currentBarIdx) && currentBarIdx != lastBarIdx) {
    lastBarIdx = currentBarIdx

    if (cvdZ > sessionCVDHi) {
        sessionCVDHi = cvdZ
    }
    if (cvdZ < sessionCVDLo) {
        sessionCVDLo = cvdZ
    }

    if (zoneTouchUp || zoneTouchDn) {
        zoneTouchCount = zoneTouchCount + 1
    }
    if (bullDiv) {
        divBullCount = divBullCount + 1
    }
    if (bearDiv) {
        divBearCount = divBearCount + 1
    }
}

// -- 3.11 Zero-line helper for fill areas --
timeseries zeroLine = 0

// ---------------------------------------------------------------------------
// 4. VISUALIZATION — Multiple types: plotLine, plotShape, plotBar, fill, hline
// ---------------------------------------------------------------------------

// 4.1 CVD Z-Score line (plotLine)
if (showZScore) {
    plotLine(
        value=cvdZ,
        width=2,
        colors=[cvdColor],
        label=["CVD Z-Score"],
        desc=["Rolling z-score of CVD; mean-reverting around 0. Extremes flag liquidity zones per Cont et al. (2014)."]
    )
}

// 4.2 CVD histogram with regime-coded fill area (plotLine + fill)
// colorIndex maps: 0 = bullish zone, 1 = bearish zone, 2 = neutral
timeseries zoneColorIdx = bullZone ? 0 : (bearZone ? 1 : 2)
if (showHistogram) {
    plotLine(
        value=([cvdZ, zeroLine]),
        width=2,
        colors=[bullColor, bearColor, neutralColor],
        colorIndex=zoneColorIdx,
        label=["CVD Histogram"],
        desc=["CVD z-score histogram with regime fill; green = bull liquidity zone, red = bear liquidity zone"],
        fill=true
    )
}

// 4.3 CVD bars (plotBar) — sign-based colouring for delta pressure
if (showHistogram) {
    plotBar(
        value=cvdZ,
        colors=[bullColor, bearColor],
        label=["CVD Bars"],
        desc=["CVD z-score as bars; positive = buyer pressure, negative = seller pressure"]
    )
}

// 4.4 Smoothed CVD line (plotLine)
if (showCVD) {
    plotLine(
        value=cvdSmooth,
        width=2,
        colors=[cvdColor],
        label=["CVD Smoothed"],
        desc=["EMA-smoothed CVD; tracks sustained order flow pressure per Lillo & Farmer (2004)"]
    )
}

// 4.5 Liquidity zone touch shapes (plotShape)
if (showShapes && zoneTouchUp) {
    plotShape(
        value=zoneThreshold,
        shape="triangleup",
        color=extremeBullColor,
        width=3,
        label=["Bull Zone Touch"],
        desc=["CVD entered bullish liquidity zone; potential accumulation / short-covering per Bouchaud et al. (2009)"]
    )
}
if (showShapes && zoneTouchDn) {
    plotShape(
        value=-zoneThreshold,
        shape="triangledown",
        color=extremeBearColor,
        width=3,
        label=["Bear Zone Touch"],
        desc=["CVD entered bearish liquidity zone; potential distribution / long-unwind per Bouchaud et al. (2009)"]
    )
}

// 4.6 Extreme zone shapes (plotShape)
if (showShapes && extremeBull) {
    plotShape(
        value=cvdZ,
        shape="diamond",
        color=extremeBullColor,
        width=4,
        label=["Extreme Bull Zone"],
        desc=["CVD z-score at extreme high; bullish order flow exhaustion risk — watch for reversal"]
    )
}
if (showShapes && extremeBear) {
    plotShape(
        value=cvdZ,
        shape="diamond",
        color=extremeBearColor,
        width=4,
        label=["Extreme Bear Zone"],
        desc=["CVD z-score at extreme low; bearish order flow exhaustion risk — watch for reversal"]
    )
}

// 4.7 Price-CVD divergence shapes (plotShape)
if (showDivergence && showShapes && bullDiv) {
    plotShape(
        value=cvdZ,
        shape="triangleup",
        color=extremeBullColor,
        width=3,
        label=["Bull Div"],
        desc=["Bullish divergence: price new low but CVD z-score positive — potential reversal up per Chordia et al. (2002)"]
    )
}
if (showDivergence && showShapes && bearDiv) {
    plotShape(
        value=cvdZ,
        shape="triangledown",
        color=extremeBearColor,
        width=3,
        label=["Bear Div"],
        desc=["Bearish divergence: price new high but CVD z-score negative — potential reversal down per Chordia et al. (2002)"]
    )
}

// 4.8 Optional swing levels as dynamic hlines (liquidity zone context)
if (showZones) {
    hline(value=swingHi, color=opacity(bearColor, 30), width=1)
    hline(value=swingLo, color=opacity(bullColor, 30), width=1)
}

// 4.9 Reference thresholds (hline)
hline(value=0, color="#ffffff30", width=1)
hline(value=zoneThreshold, color=opacity(bullColor, 30), width=1)
hline(value=-zoneThreshold, color=opacity(bearColor, 30), width=1)
hline(value=extremeZone, color=opacity(extremeBullColor, 20), width=1)
hline(value=-extremeZone, color=opacity(extremeBearColor, 20), width=1)