MM Flow
FlowScripts

Perfected FlowScript

Anchored CVD

Anchored CVD V2 is indexed as 040_anchored_cvd.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

11.5 KB

Lines

289

Native Signal Candidates

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

3/3 guarded

Anchor Event

line 255:5

Trigger

(showShapes && isAnchorEvent)

Value

0

Deps

isAnchorEvent:var, showShapes:input

Bullish Div

line 269:9

Trigger

(showDivergence && divergence) && (bullDiv)

Value

cvdSm

Deps

bullDiv:var, divergence:var, showDivergence:input

Bearish Div

line 279:9

Trigger

(showDivergence && divergence) && (bearDiv)

Value

cvdSm

Deps

bearDiv:var, divergence:var, showDivergence:input

040_anchored_cvd.flowscript

source path: kscripts/perfected/040_anchored_cvd.flowscript · sha256:d5e02b2fc1f3525f015075394ce86083fafb7d2fbb4f6129c2bc475d6c3cdcad

hash verified
//@version=2

// ============================================================================
// Anchored CVD V2 — Multi-Mode Cumulative Volume Delta with Event Anchoring
// Author: BackQuant (@BackQuant) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, #cvd, #anchor, #session, #delta, #orderflow
//
// Cumulative Volume Delta that resets at configurable anchor events (session
// open, new day, new week, or fixed bar count).  Exposes net aggressive flow
// since the anchor; fill, color coding, and shape markers reveal when the
// anchored CVD diverges from price — often flagging accumulation/distribution
// or hidden order flow at key structural points.
//
// 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 = Σ(E_i × ΔP_i); cumulative OFI = CVD linearly
//     predicts short-term price changes: Δp_t = λ·OFI_t + ε_t.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  2. Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity
//     in a High-Frequency World", Review of Financial Studies, 25(5), 1457–1493.
//     VPIN volume-bucket approach; bulk classification improves CVD
//     robustness in HFT/crypto environments.  DOI: https://doi.org/10.1093/rfs/hhs053
//
//  3. Lillo & Farmer (2004), "The Long Memory of the Efficient Market",
//     Studies in Nonlinear Dynamics & Econometrics, 8(3), 1–35.
//     Order flow autocorrelations decay as power law; long memory justifies
//     cumulative aggregation from an anchor point.  arXiv:cond-mat/0311053
//
//  4. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity,
//     and Market Returns", Journal of Financial Economics, 65(1), 111–130.
//     Extreme imbalances predict return reversals.  Anchored CVD divergence
//     from price flags potential reversal zones.  DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  5. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//     Journal of Finance, 46(2), 733–746.  Tick-test classification (85–93%
//     accuracy): buy if close > open, else sell.  DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
//
//  6. Shannon (2021), "Maximum Trading Gains with the Anchored VWAP".
//     Anchor quality decays over 60–90 trading days; the most recent anchor
//     carries the highest predictive weight.  Informs anchor-mode selection.
//
//  7. Harris (1986), "A Transaction Data Study of Weekly and Intradaily
//     Patterns in Stock Returns".  Significant time-of-day effects in first
//     45 minutes after open support session-based anchoring.
// ============================================================================

define(title="Anchored CVD V2", position="offchart", axis=true)

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

// -- Anchor Mode --
var anchorMode = input(name="anchorMode", type="select", defaultValue="Bar Count", label="Anchor Mode", options=["Bar Count", "Session", "Day", "Week"], group="Anchor")
var resetLen = input(name="resetLen", type="number", defaultValue=50, label="Bar Count (bars)", constraints={min: 10, max: 500, step: 10}, group="Anchor")

// -- Computation --
var smoothLen = input(name="smoothLen", type="number", defaultValue=2, label="Smoothing Length", constraints={min: 1, max: 20, step: 1}, group="Computation")
var divLookback = input(name="divLookback", type="number", defaultValue=20, label="Divergence Lookback (bars)", constraints={min: 5, max: 100, step: 5}, group="Computation")

// -- Display --
var showLine = input(name="showLine", type="boolean", defaultValue=true, label="Show CVD Line", group="Display")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Area Fill", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Anchor Shapes", group="Display")
var showDivergence = input(name="showDivergence", type="boolean", defaultValue=true, label="Show Divergence Alerts", group="Display")
var showZeroLine = input(name="showZeroLine", type="boolean", defaultValue=true, label="Show Zero Line", group="Display")

// -- Colors --
var upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="Positive CVD Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Negative CVD Color", group="Colors")
var lineColor = input(name="lineColor", type="color", defaultValue="#ffffff", label="CVD Line Color", group="Colors")
var anchorColor = input(name="anchorColor", type="color", defaultValue="#ff9100", label="Anchor Event Color", group="Colors")
var divColor = input(name="divColor", type="color", defaultValue="#9c27b0", label="Divergence Color", group="Colors")

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

timeseries pxTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries o = pxTS.open
timeseries c = pxTS.close
timeseries v = pxTS.volume
timeseries taker = source("taker_volume", currentSymbol, currentExchange)

// Guard: halt until OHLCV has loaded
if (isnan(c[0]) || isnan(o[0]) || isnan(v[0])) {
    return
}

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

// -- 3.1 Per-bar delta (Lee-Ready fallback when taker feed unavailable) --
// Lee-Ready (1991): close > open → buyer-initiated; else seller-initiated.
// Prefer direct taker feed when available for higher accuracy.
timeseries buyVol = isnum(taker.buy) ? taker.buy : (c > o ? v : 0)
timeseries sellVol = isnum(taker.sell) ? taker.sell : (c <= o ? v : 0)
timeseries delta = buyVol - sellVol

// -- 3.2 Anchor detection logic --
// Determines whether the current bar is a reset event based on anchorMode.
static lastDay = 0
static lastWeek = 0
static lastSession = 0
static barsSinceAnchor = 0

var isNewBar = false
var currentBarIdx = bar_index[0]
static prevBarIdx = -1

if (!isnan(currentBarIdx) && currentBarIdx != prevBarIdx) {
    isNewBar = true
    prevBarIdx = currentBarIdx
}

var isAnchorEvent = false

if (anchorMode == "Bar Count") {
    isAnchorEvent = barsSinceAnchor >= resetLen
} else if (anchorMode == "Day") {
    var currentDay = dayofmonth[0]
    isAnchorEvent = currentDay != lastDay && !isnan(currentDay)
    if (isAnchorEvent) {
        lastDay = currentDay
    }
} else if (anchorMode == "Week") {
    var currentWeek = weekofyear[0]
    isAnchorEvent = currentWeek != lastWeek && !isnan(currentWeek)
    if (isAnchorEvent) {
        lastWeek = currentWeek
    }
} else if (anchorMode == "Session") {
    // Session anchor: reset at the first bar of each session (hour == 0 for daily sessions)
    // In kScript, we use a simple proxy: reset when hour changes to a session open hour.
    var currentHour = hour[0]
    isAnchorEvent = currentHour != lastSession && !isnan(currentHour) && currentHour == 0
    if (isAnchorEvent) {
        lastSession = currentHour
    } else if (currentHour != lastSession) {
        lastSession = currentHour
    }
}

// -- 3.3 Anchored CVD via static state (reset at anchor events) --
// CVD_anchor resets to 0 at each anchor event, then accumulates delta.
static anchoredCVD = 0.0

if (isAnchorEvent) {
    anchoredCVD = 0.0
    barsSinceAnchor = 0
} else if (isNewBar) {
    barsSinceAnchor = barsSinceAnchor + 1
}

if (!isnan(delta[0])) {
    anchoredCVD = anchoredCVD + delta[0]
}

// -- 3.4 Smoothing --
timeseries cvdSm = smoothLen > 1 ? ema(anchoredCVD, smoothLen) : anchoredCVD

// -- 3.5 Divergence detection from anchor point --
// Compares price change since anchor to CVD change since anchor.
// If price rises but CVD falls (or vice versa), a divergence is flagged.
static anchorPrice = 0.0
if (isAnchorEvent) {
    anchorPrice = c[0]
}

var priceChange = !isnan(anchorPrice) && anchorPrice != 0 ? (c[0] - anchorPrice) / anchorPrice * 100.0 : 0.0
var cvdChange = anchoredCVD

// Divergence: price and CVD move in opposite directions
var bullDiv = priceChange < 0 && cvdChange > 0   // price down, CVD up = bullish div
var bearDiv = priceChange > 0 && cvdChange < 0   // price up, CVD down = bearish div
var divergence = bullDiv || bearDiv

// -- 3.6 Regime and color coding --
var cvdPositive = cvdSm >= 0
var cvdNegative = cvdSm < 0

// -- 3.7 Session tracking via static variables --
// Tracks anchor events, session high/low CVD, and divergence counts.
static anchorCount = 0
static sessionHighCVD = -999999999999.0
static sessionLowCVD = 999999999999.0
static divCount = 0
static lastBarIndex = 0

var barIdx = bar_index[0]
if (!isnan(barIdx) && barIdx != lastBarIndex) {
    lastBarIndex = barIdx

    if (isAnchorEvent) {
        anchorCount = anchorCount + 1
        sessionHighCVD = cvdSm
        sessionLowCVD = cvdSm
    } else {
        if (cvdSm > sessionHighCVD) {
            sessionHighCVD = cvdSm
        }
        if (cvdSm < sessionLowCVD) {
            sessionLowCVD = cvdSm
        }
    }

    if (divergence) {
        divCount = divCount + 1
    }
}

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

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

// 4.1 Zero line
if (showZeroLine) {
    hline(value=0, color="#ffffff30", width=1)
}

// 4.2 Anchored CVD line with fill between CVD and zero (plotLine + fill)
// colorIndex maps: 0 = positive (buy pressure), 1 = negative (sell pressure)
if (showLine) {
    plotLine(
        value=([cvdSm, zeroLine]),
        width=2,
        colors=[upColor, dnColor],
        colorIndex=cvdPositive ? 0 : 1,
        label=["Anchored CVD"],
        desc=["Net aggressive flow since last anchor event; positive = buy pressure, negative = sell pressure"],
        fill=showFill
    )
}

// 4.3 Raw anchored CVD line (thin reference)
if (showLine) {
    plotLine(
        value=cvdSm,
        width=1,
        colors=[lineColor],
        label=["Anchored CVD (Line)"],
        desc=["Smoothed anchored CVD line for reference"]
    )
}

// 4.4 Anchor event shapes (plotShape)
// Diamond markers at each anchor reset event.
if (showShapes && isAnchorEvent) {
    plotShape(
        value=0,
        shape="diamond",
        color=anchorColor,
        width=4,
        label=["Anchor Event"],
        desc=["CVD reset at anchor event: " + anchorMode + " — flow accumulation restarts from zero"]
    )
}

// 4.5 Divergence alert shapes (plotShape)
// Signals when price and anchored CVD diverge (potential reversal).
if (showDivergence && divergence) {
    if (bullDiv) {
        plotShape(
            value=cvdSm,
            shape="triangleup",
            color=divColor,
            width=3,
            label=["Bullish Div"],
            desc=["Price falling but CVD rising since anchor: bullish divergence / hidden accumulation"]
        )
    }
    if (bearDiv) {
        plotShape(
            value=cvdSm,
            shape="triangledown",
            color=divColor,
            width=3,
            label=["Bearish Div"],
            desc=["Price rising but CVD falling since anchor: bearish divergence / hidden distribution"]
        )
    }
}