MM Flow
FlowScripts

Perfected FlowScript

Anchored CVD (Fork)

Anchored CVD Fork — Perfected is indexed as 206_anchored_cvd_fork.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

20.8 KB

Lines

546

Native Signal Candidates

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

4/4 guarded

Zero Cross Up

line 473:5

Trigger

(showZeroCross && zeroCrossUp)

Value

cvd

Deps

showZeroCross:input, zeroCrossUp:var

Zero Cross Down

line 483:5

Trigger

(showZeroCross && zeroCrossDown)

Value

cvd

Deps

showZeroCross:input, zeroCrossDown:var

Bull Div

line 496:9

Trigger

(showDivShapes && enableDiv) && (bullDiv)

Value

cvd

Deps

bullDiv:var, enableDiv:input, showDivShapes:input

Bear Div

line 506:9

Trigger

(showDivShapes && enableDiv) && (bearDiv)

Value

cvd

Deps

bearDiv:var, enableDiv:input, showDivShapes:input

206_anchored_cvd_fork.flowscript

source path: kscripts/perfected/206_anchored_cvd_fork.flowscript · sha256:3ecbadd060e409b46f7b8a4b77a0423f9a1397dba4b5eb8d75cc1300fad149cc

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

// ============================================================================
// Anchored CVD Fork — Cumulative Volume Delta with Event Anchoring [Perfected]
// Author: Tzen Yang (@Tzen Yang) — Perfected by kScript_Perfection_Engineer
// Tags: ADVANCED, SPECIALIZED, #cvd, #anchored, #oscillator, #divergence
//
// Comprehensive anchored CVD with 17 anchor modes (fixed periods, trading sessions,
// rolling windows), multiple CVD tracks, divergence detection between CVD and price,
// and full regime color-coding with shape alerts. Properly implements anchored/reset
// logic using static variables for cumulative delta, with taker-volume feed or
// Lee-Ready fallback for per-bar trade classification.
//
// Research papers underpinning this design:
//  - 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.
//  - 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 driving trends.
//  - Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//    Market Returns": extreme imbalances predict return reversals.
//    Zero-line flips mark control changes.
//  - Lee & Ready (1991), "Inferring Trade Direction from Intraday Data":
//    foundational tick-classification algorithm (85–93% accuracy).
//    Classify as buy if close > open, else sell, when taker feed unavailable.
//  - Kyle (1985), "Continuous Auctions and Insider Trading":
//    p_t = p_{t−1} + λ·OFI_t + noise. Kyle's λ establishes the linear
//    price-impact coefficient underpinning every delta-based signal.
// ============================================================================

define(
    title="Anchored CVD Fork — Perfected",
    position="offchart",
    axis=true
)

// ---------------------------------------------------------------------------
// User Inputs
// ---------------------------------------------------------------------------

// --- Anchor Group ---
var anchorMode = input(name="anchorMode", type="select", defaultValue="Daily", label="Primary Anchor Mode", options=["4h", "8h", "12h", "Daily", "2 Days", "3 Days", "Weekly", "2 Weeks", "Monthly", "Quarterly", "Yearly", "Tokyo", "London", "New York", "Sydney", "Rolling 50 Bars", "Rolling 200 Bars"], group="Anchor")
var tzOffsetH = input(name="tzOffsetH", type="number", defaultValue=0, label="Timezone Offset (hours from UTC)", constraints={min: -12, max: 14, step: 1}, group="Anchor")
var showSecondary = input(name="showSecondary", type="boolean", defaultValue=false, label="Show Secondary CVD", group="Anchor")
var secondaryAnchorMode = input(name="secondaryAnchorMode", type="select", defaultValue="Weekly", label="Secondary Anchor Mode", options=["4h", "8h", "12h", "Daily", "2 Days", "3 Days", "Weekly", "2 Weeks", "Monthly", "Quarterly", "Yearly", "Tokyo", "London", "New York", "Sydney", "Rolling 50 Bars", "Rolling 200 Bars"], group="Anchor")

// --- Computation Group ---
var smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="CVD Smoothing Length", constraints={min: 1, max: 20, step: 1}, group="Computation")
var useTaker = input(name="useTaker", type="boolean", defaultValue=true, label="Use Taker Volume Feed (if available)", group="Computation")
var divLookback = input(name="divLookback", type="number", defaultValue=10, label="Divergence Lookback (pivot bars)", constraints={min: 5, max: 50, step: 1}, group="Computation")
var enableDiv = input(name="enableDiv", type="boolean", defaultValue=true, label="Enable Divergence Detection", group="Computation")

// --- Display Group ---
var showRaw = input(name="showRaw", type="boolean", defaultValue=false, label="Show Raw CVD (unsmoothed)", group="Display")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Signed Fill", group="Display")
var showZeroCross = input(name="showZeroCross", type="boolean", defaultValue=true, label="Show Zero-Cross Shapes", group="Display")
var showDivShapes = input(name="showDivShapes", type="boolean", defaultValue=true, label="Show Divergence 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 Group ---
var upColor = input(name="upColor", type="color", defaultValue="#26a69a", label="Positive Fill Color", group="Colors")
var dnColor = input(name="dnColor", type="color", defaultValue="#ef5350", label="Negative Fill Color", group="Colors")
var lineColor = input(name="lineColor", type="color", defaultValue="#ffffff", label="CVD Line Color", group="Colors")
var divBullColor = input(name="divBullColor", type="color", defaultValue="#00e676", label="Bullish Divergence Color", group="Colors")
var divBearColor = input(name="divBearColor", type="color", defaultValue="#ff5252", label="Bearish Divergence Color", group="Colors")
var secondaryColor = input(name="secondaryColor", type="color", defaultValue="#ff6d00", label="Secondary CVD 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

// Attempt to fetch taker volume feed
timeseries taker = source("taker_volume", currentSymbol, currentExchange)

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

// ---------------------------------------------------------------------------
// Per-bar Volume Delta (Lee-Ready fallback when taker feed unavailable)
// Lee-Ready (1991): close > open → buyer-initiated; else seller-initiated.
// ---------------------------------------------------------------------------
timeseries buyVol = 0.0
timeseries sellVol = 0.0

if (useTaker && isnum(taker.buy) && isnum(taker.sell)) {
    buyVol = taker.buy
    sellVol = taker.sell
} else {
    buyVol = close > bars.open ? bars.volume : 0
    sellVol = close <= bars.open ? bars.volume : 0
}

timeseries delta = buyVol - sellVol

// ---------------------------------------------------------------------------
// Time Derivation (Calendar Math)
// ---------------------------------------------------------------------------
timeseries rawH = math.floor((t / 3600000) % 24)
timeseries utcH = ((rawH + tzOffsetH) % 24 + 24) % 24
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

// ---------------------------------------------------------------------------
// Primary Anchor Detection (static variables for stateful computation)
// ---------------------------------------------------------------------------
static last_day_id = -1
static last_week_id = -1
static last_month_id = -1
static last_utcH = -1
static last_4h = -1
static last_8h = -1
static last_12h = -1
static last_2d = -1
static last_3d = -1
static last_2w = -1
static last_q = -1
static last_y = -1
static barCount = 0

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

if (anchorMode == "4h") {
    var period4h = math.floor(t / 14400000)
    newPeriod = last_4h != -1 && period4h > last_4h
    last_4h = period4h
} else if (anchorMode == "8h") {
    var period8h = math.floor(t / 28800000)
    newPeriod = last_8h != -1 && period8h > last_8h
    last_8h = period8h
} else if (anchorMode == "12h") {
    var period12h = math.floor(t / 43200000)
    newPeriod = last_12h != -1 && period12h > last_12h
    last_12h = period12h
} else if (anchorMode == "Daily") {
    newPeriod = last_day_id != -1 && day_id > last_day_id
    last_day_id = day_id
} else if (anchorMode == "2 Days") {
    var period2d = math.floor(day_id / 2)
    newPeriod = last_2d != -1 && period2d > last_2d
    last_2d = period2d
} else if (anchorMode == "3 Days") {
    var period3d = math.floor(day_id / 3)
    newPeriod = last_3d != -1 && period3d > last_3d
    last_3d = period3d
} else if (anchorMode == "Weekly") {
    newPeriod = last_week_id != -1 && week_id > last_week_id
    last_week_id = week_id
} else if (anchorMode == "2 Weeks") {
    var period2w = math.floor(week_id / 2)
    newPeriod = last_2w != -1 && period2w > last_2w
    last_2w = period2w
} else if (anchorMode == "Monthly") {
    newPeriod = last_month_id != -1 && month_id > last_month_id
    last_month_id = month_id
} else if (anchorMode == "Quarterly") {
    var quarter_id = math.floor((month_id - 1) / 3)
    newPeriod = last_q != -1 && quarter_id > last_q
    last_q = quarter_id
} else if (anchorMode == "Yearly") {
    var year_id = year_final
    newPeriod = last_y != -1 && year_id > last_y
    last_y = year_id
} else if (anchorMode == "Tokyo") {
    newPeriod = last_utcH != -1 && last_utcH != 0 && utcH == 0
    last_utcH = utcH
} else if (anchorMode == "London") {
    newPeriod = last_utcH != -1 && last_utcH != 8 && utcH == 8
    last_utcH = utcH
} else if (anchorMode == "New York") {
    newPeriod = last_utcH != -1 && last_utcH != 13 && utcH == 13
    last_utcH = utcH
} else if (anchorMode == "Sydney") {
    newPeriod = last_utcH != -1 && last_utcH != 21 && utcH == 21
    last_utcH = utcH
} else if (anchorMode == "Rolling 50 Bars") {
    isRolling = true
    periodBars = 50
} else if (anchorMode == "Rolling 200 Bars") {
    isRolling = true
    periodBars = 200
}

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

// ---------------------------------------------------------------------------
// Primary CVD Computation (anchored, not rolling)
// ---------------------------------------------------------------------------
timeseries cvdRaw = 0.0
timeseries cvd = 0.0

// We compute anchored CVD by summing delta within the anchor window.
// For rolling windows, sum(delta, barCount). For anchored periods, we
// maintain the cumulative sum from the anchor start.
if (isRolling) {
    cvdRaw = sum(delta, barCount)
} else {
    // Use static cumulative sum for anchored periods
    static cvdCum = 0.0
    if (newPeriod || barCount == 1) {
        cvdCum = delta[0]
    } else {
        cvdCum = cvdCum + delta[0]
    }
    cvdRaw = cvdCum
}

cvd = sma(source=cvdRaw, period=smoothLen)

// ---------------------------------------------------------------------------
// Secondary CVD Computation (static variables for independent anchor)
// ---------------------------------------------------------------------------
static sec_last_day_id = -1
static sec_last_week_id = -1
static sec_last_month_id = -1
static sec_last_utcH = -1
static sec_last_4h = -1
static sec_last_8h = -1
static sec_last_12h = -1
static sec_last_2d = -1
static sec_last_3d = -1
static sec_last_2w = -1
static sec_last_q = -1
static sec_last_y = -1
static secBarCount = 0

var secNewPeriod = false
var secIsRolling = false
var secPeriodBars = 0

if (showSecondary) {
    if (secondaryAnchorMode == "4h") {
        var sec_period4h = math.floor(t / 14400000)
        secNewPeriod = sec_last_4h != -1 && sec_period4h > sec_last_4h
        sec_last_4h = sec_period4h
    } else if (secondaryAnchorMode == "8h") {
        var sec_period8h = math.floor(t / 28800000)
        secNewPeriod = sec_last_8h != -1 && sec_period8h > sec_last_8h
        sec_last_8h = sec_period8h
    } else if (secondaryAnchorMode == "12h") {
        var sec_period12h = math.floor(t / 43200000)
        secNewPeriod = sec_last_12h != -1 && sec_period12h > sec_last_12h
        sec_last_12h = sec_period12h
    } else if (secondaryAnchorMode == "Daily") {
        secNewPeriod = sec_last_day_id != -1 && day_id > sec_last_day_id
        sec_last_day_id = day_id
    } else if (secondaryAnchorMode == "2 Days") {
        var sec_period2d = math.floor(day_id / 2)
        secNewPeriod = sec_last_2d != -1 && sec_period2d > sec_last_2d
        sec_last_2d = sec_period2d
    } else if (secondaryAnchorMode == "3 Days") {
        var sec_period3d = math.floor(day_id / 3)
        secNewPeriod = sec_last_3d != -1 && sec_period3d > sec_last_3d
        sec_last_3d = sec_period3d
    } else if (secondaryAnchorMode == "Weekly") {
        secNewPeriod = sec_last_week_id != -1 && week_id > sec_last_week_id
        sec_last_week_id = week_id
    } else if (secondaryAnchorMode == "2 Weeks") {
        var sec_period2w = math.floor(week_id / 2)
        secNewPeriod = sec_last_2w != -1 && sec_period2w > sec_last_2w
        sec_last_2w = sec_period2w
    } else if (secondaryAnchorMode == "Monthly") {
        secNewPeriod = sec_last_month_id != -1 && month_id > sec_last_month_id
        sec_last_month_id = month_id
    } else if (secondaryAnchorMode == "Quarterly") {
        var sec_quarter_id = math.floor((month_id - 1) / 3)
        secNewPeriod = sec_last_q != -1 && sec_quarter_id > sec_last_q
        sec_last_q = sec_quarter_id
    } else if (secondaryAnchorMode == "Yearly") {
        var sec_year_id = year_final
        secNewPeriod = sec_last_y != -1 && sec_year_id > sec_last_y
        sec_last_y = sec_year_id
    } else if (secondaryAnchorMode == "Tokyo") {
        secNewPeriod = sec_last_utcH != -1 && sec_last_utcH != 0 && utcH == 0
        sec_last_utcH = utcH
    } else if (secondaryAnchorMode == "London") {
        secNewPeriod = sec_last_utcH != -1 && sec_last_utcH != 8 && utcH == 8
        sec_last_utcH = utcH
    } else if (secondaryAnchorMode == "New York") {
        secNewPeriod = sec_last_utcH != -1 && sec_last_utcH != 13 && utcH == 13
        sec_last_utcH = utcH
    } else if (secondaryAnchorMode == "Sydney") {
        secNewPeriod = sec_last_utcH != -1 && sec_last_utcH != 21 && utcH == 21
        sec_last_utcH = utcH
    } else if (secondaryAnchorMode == "Rolling 50 Bars") {
        secIsRolling = true
        secPeriodBars = 50
    } else if (secondaryAnchorMode == "Rolling 200 Bars") {
        secIsRolling = true
        secPeriodBars = 200
    }

    if (secIsRolling) {
        if (secBarCount < secPeriodBars) {
            secBarCount = secBarCount + 1
        } else {
            secBarCount = secPeriodBars
        }
    } else if (secNewPeriod || secBarCount == 0) {
        secBarCount = 1
    } else {
        secBarCount = secBarCount + 1
    }
} else {
    secBarCount = 1
}

timeseries secCvd = 0.0
if (showSecondary) {
    if (secIsRolling) {
        secCvd = sma(source=sum(delta, secBarCount), period=smoothLen)
    } else {
        static secCvdCum = 0.0
        if (secNewPeriod || secBarCount == 1) {
            secCvdCum = delta[0]
        } else {
            secCvdCum = secCvdCum + delta[0]
        }
        secCvd = sma(source=secCvdCum, period=smoothLen)
    }
}

// ---------------------------------------------------------------------------
// Regime Detection (color coding by CVD sign)
// ---------------------------------------------------------------------------
var cvdPositive = cvd > 0
var cvdNegative = cvd < 0

// ---------------------------------------------------------------------------
// Divergence Detection (stateful via static variables — CVD vs Price)
// ---------------------------------------------------------------------------
static prevPriceHigh = -1.0
static prevCvdHigh = -1.0
static prevPriceLow = -1.0
static prevCvdLow = -1.0

var bearDiv = false
var bullDiv = false

// Initialize on first real bar after NaN guard
if (prevPriceHigh < 0) {
    prevPriceHigh = high[0]
    prevCvdHigh = cvd[0]
    prevPriceLow = low[0]
    prevCvdLow = cvd[0]
}

if (!isLiveUpdate && enableDiv) {
    // Regular Bearish Divergence: price higher high, CVD lower high
    if (high[0] > prevPriceHigh) {
        if (cvd[0] < prevCvdHigh) {
            bearDiv = true
        }
        prevPriceHigh = high[0]
        prevCvdHigh = cvd[0]
    }

    // Regular Bullish Divergence: price lower low, CVD higher low
    if (low[0] < prevPriceLow) {
        if (cvd[0] > prevCvdLow) {
            bullDiv = true
        }
        prevPriceLow = low[0]
        prevCvdLow = cvd[0]
    }
}

// ---------------------------------------------------------------------------
// Zero-line Cross Detection (shape markers)
// ---------------------------------------------------------------------------
var zeroCrossUp = cvd > 0 && cvd[1] <= 0
var zeroCrossDown = cvd < 0 && cvd[1] >= 0

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

// --- Zero line ---
hline(value=0, color="#ffffff30", width=1)

// --- Raw CVD (optional) ---
if (showRaw) {
    plotLine(
        value=cvdRaw,
        width=1,
        colors=[opacity(lineColor, 40)],
        label=["CVD Raw"],
        desc=["Unsmoothed anchored cumulative volume delta"]
    )
}

// --- Primary CVD Line (regime-colored) ---
plotLine(
    value=cvd,
    width=lineWidth,
    colors=[lineColor],
    label=["Anchored CVD"],
    desc=["Smoothed anchored cumulative volume delta"]
)

// --- Secondary CVD ---
if (showSecondary) {
    plotLine(
        value=secCvd,
        width=lineWidth,
        colors=[secondaryColor],
        label=["CVD 2"],
        desc=["Secondary anchored CVD (" + secondaryAnchorMode + ")"]
    )
}

// --- Signed Fill ---
if (showFill) {
    var fillBull = cvd > 0
    plotLine(
        value=([cvd, 0]),
        width=2,
        colors=[upColor, dnColor],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=["CVD Fill"],
        desc=["Signed fill between CVD and zero line"]
    )
}

// --- CVD Bars (sign-based) ---
plotBar(
    value=cvd,
    colors=[upColor, dnColor],
    colorIndex=cvdPositive ? 0 : 1,
    width=1,
    label=["CVD Bars"],
    desc=["Anchored CVD as bars (green = positive, red = negative)"]
)

// --- Zero-Cross Shapes ---
if (showZeroCross && zeroCrossUp) {
    plotShape(
        value=cvd,
        shape="triangleup",
        colorIndex=upColor,
        width=shapeSize,
        label=["Zero Cross Up"],
        desc=["CVD crossed above zero — buyers took control"]
    )
}
if (showZeroCross && zeroCrossDown) {
    plotShape(
        value=cvd,
        shape="triangledown",
        colorIndex=dnColor,
        width=shapeSize,
        label=["Zero Cross Down"],
        desc=["CVD crossed below zero — sellers took control"]
    )
}

// --- Divergence Shapes ---
if (showDivShapes && enableDiv) {
    if (bullDiv) {
        plotShape(
            value=cvd,
            shape="triangleup",
            colorIndex=divBullColor,
            width=shapeSize,
            label=["Bull Div"],
            desc=["Bullish divergence: price lower low, CVD higher low"]
        )
    }
    if (bearDiv) {
        plotShape(
            value=cvd,
            shape="triangledown",
            colorIndex=divBearColor,
            width=shapeSize,
            label=["Bear Div"],
            desc=["Bearish divergence: price higher high, CVD lower high"]
        )
    }
}

// ---------------------------------------------------------------------------
// Regime Table (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = cvdPositive ? "BULLISH FLOW" : (cvdNegative ? "BEARISH FLOW" : "NEUTRAL")
    var regimeTextColor = cvdPositive ? upColor : (cvdNegative ? dnColor : "#9e9e9e")
    var anchorText = "Anchor: " + anchorMode

    plotTable(
        data=[
            ["Anchored CVD — Perfected", regimeText],
            ["CVD", cvd[0]],
            [anchorText, "Smoothed: " + smoothLen],
            ["Zero Cross Up", zeroCrossUp],
            ["Zero Cross Down", zeroCrossDown]
        ],
        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
    )
}