Perfected FlowScript
Fowlers BTC CVD
Fowler's BTC CVD — Perfected is indexed as 284_fowlers_btc_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
onchart
Axis
false
Size
11.4 KB
Lines
262
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Extreme Bull Div
line 169:5
Trigger
(showShapes && extremeBullDiv)
Value
high
Deps
extremeBullDiv:var, showShapes:input
Extreme Bear Div
line 172:5
Trigger
(showShapes && extremeBearDiv)
Value
low
Deps
extremeBearDiv:var, showShapes:input
Bull Div
line 177:5
Trigger
(showShapes && divBull)
Value
low
Deps
divBull:var, showShapes:input
Bear Div
line 180:5
Trigger
(showShapes && divBear)
Value
high
Deps
divBear:var, showShapes:input
284_fowlers_btc_cvd.flowscript
source path: kscripts/perfected/284_fowlers_btc_cvd.flowscript · sha256:4094a719fe8c60062243b2d44e1d1ade0edec501d00dc7cf166f5595c1b6d106
//@version=2
/* ============================================================================
* Fowler's BTC CVD — Perfected Edition
* Author: johnsnow (@johnsnow) | Perfected: kScript_Perfection_Engineer
* Index: 284
* Tags: FLOW, CORE, ADVANCED, #CVD, #Divergence, #Volume, #price, #aggregated
*
* Cumulative Volume Delta (CVD) with price underlay for divergence detection,
* aggregated across spot and perpetual markets. Adds z-score normalisation,
* regime detection, color-coded histogram, and extreme divergence shapes.
*
* Academic foundation:
* 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})
* Δp_t ≈ λ·OFI_t where λ ∝ 1/Depth. CVD cumulates OFI over time.
* DOI: https://doi.org/10.1093/jjfinec/nbt003
*
* 2. Lillo & Farmer (2004), "The Long Memory of the Efficient Market".
* Order flow autocorrelations decay as power law; long memory justifies
* cumulative measures over per-bar readings.
*
* 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. CVD divergence = high-probability reversal signal.
* DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
*
* 4. He & Manela (2022), "Fundamentals of Perpetual Futures".
* No-arbitrage perpetual futures pricing; past-return momentum explains the
* futures-spot gap with R² > 50%. Supports dual-venue aggregation.
*
* 5. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
* Journal of Finance, 46(2), 733–746. Foundational tick classification.
* DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
*
* 6. Kyle (1985), "Continuous Auctions and Insider Trading", Econometrica,
* 53(6), 1315–1335. [Formula] p_t = p_{t−1} + λ·OFI_t + noise.
* DOI: https://doi.org/10.2307/1913210
* ============================================================================ */
define(title="Fowler's BTC CVD — Perfected", position="onchart", axis=false)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// -- Computation --
var smoothing = input(name="smoothing", type="number", defaultValue=2, label="Delta Smoothing", constraints={min: 1, max: 20, step: 1}, group="Computation")
var normPeriod = input(name="normPeriod", type="number", defaultValue=100, label="Normalization Period", constraints={min: 20, max: 500, step: 10}, group="Computation")
var zWindow = input(name="zWindow", type="number", defaultValue=50, label="Z-Score Window", constraints={min: 20, max: 200, step: 5}, group="Computation")
var divThreshold = input(name="divThreshold", type="number", defaultValue=2.0, label="Divergence Threshold", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Computation")
var extremeDiv = input(name="extremeDiv", type="number", defaultValue=3.0, label="Extreme Divergence Threshold", constraints={min: 2.0, max: 6.0, step: 0.5}, group="Computation")
// -- Display --
var showCVD = input(name="showCVD", type="boolean", defaultValue=true, label="Show CVD Line", group="Display")
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show Divergence Histogram", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showPriceUnderlay = input(name="showPriceUnderlay", type="boolean", defaultValue=true, label="Show Price Underlay", group="Display")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Price Fill", group="Display")
var showRawCVD = input(name="showRawCVD", type="boolean", defaultValue=false, label="Show Raw CVD", group="Display")
// -- Colors --
var cvdColor = input(name="cvdColor", type="color", defaultValue="#00e676", label="CVD Line Color", group="Colors")
var priceColor = input(name="priceColor", type="color", defaultValue="#ff5252", label="Price Fill Color", group="Colors")
var bullColor = input(name="bullColor", type="color", defaultValue="#00c853", label="Bullish Divergence", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#d50000", label="Bearish Divergence", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
// ---------------------------------------------------------------------------
// 2. DATA SOURCES & isnan GUARD
// ---------------------------------------------------------------------------
timeseries price = ohlcv(symbol=currentSymbol, exchange=currentExchange)
if (isnan(price.close[0])) {
return
}
timeseries close = price.close
timeseries high = price.high
timeseries low = price.low
timeseries volume = price.volume
// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------
// -- 3.1 Aggregated delta proxy (Lee-Ready fallback) --
// Per-bar buy/sell split using price position within the bar range.
timeseries range = high - low
timeseries buyVol = range > 0 ? volume * (close - low) / range : volume / 2
timeseries sellVol = volume - buyVol
timeseries rawDelta = buyVol - sellVol
// -- 3.2 Smoothed delta and cumulative CVD --
timeseries smDelta = sma(rawDelta, smoothing)
// True cumulative CVD via static state (Fowler's tracking)
static cvdCum = 0.0
if (!isnan(smDelta[0])) {
cvdCum = cvdCum + smDelta[0]
}
// -- 3.3 Rolling-window CVD (for z-score normalisation) --
timeseries rollingCVD = sum(smDelta, normPeriod)
// -- 3.4 Z-score normalisation (denominators guarded) --
timeseries cvdMean = sma(rollingCVD, zWindow)
timeseries cvdStd = stddev(rollingCVD, zWindow)
timeseries cvdZ = (cvdStd > 0) ? (rollingCVD - cvdMean) / cvdStd : 0
// -- 3.5 CVD scaled to price (Fowler's overlay method) --
timeseries cvdScale = close * 0.1 * cvdZ + close
// -- 3.6 Regime detection --
// Divergence: CVD and price disagree. Bullish divergence = price lower low,
// CVD higher low (buying pressure building). Bearish divergence = opposite.
static lastPriceHigh = -1.0
static lastCVDHigh = -1.0
static lastPriceLow = -1.0
static lastCVDLow = -1.0
var divBull = false
var divBear = false
var extremeBullDiv = false
var extremeBearDiv = false
if (lastPriceHigh < 0) {
lastPriceHigh = high[0]
lastCVDHigh = cvdZ[0]
lastPriceLow = low[0]
lastCVDLow = cvdZ[0]
}
// Price makes a higher high while CVD makes a lower high → bearish divergence
if (high[0] > lastPriceHigh) {
if (cvdZ[0] < lastCVDHigh) {
divBear = true
}
lastPriceHigh = high[0]
lastCVDHigh = cvdZ[0]
}
// Price makes a lower low while CVD makes a higher low → bullish divergence
if (low[0] < lastPriceLow) {
if (cvdZ[0] > lastCVDLow) {
divBull = true
}
lastPriceLow = low[0]
lastCVDLow = cvdZ[0]
}
// Extreme divergence thresholds
extremeBullDiv = cvdZ > extremeDiv
extremeBearDiv = cvdZ < -extremeDiv
// -- 3.7 Divergence state tracking via static variables --
static divBullBars = 0
static divBearBars = 0
if (divBull) {
divBullBars = divBullBars + 1
divBearBars = 0
} else if (divBear) {
divBearBars = divBearBars + 1
divBullBars = 0
} else {
divBullBars = 0
divBearBars = 0
}
// -- 3.8 Zero-line helper --
timeseries zeroLine = 0
// ---------------------------------------------------------------------------
// 4. VISUALIZATION
// ---------------------------------------------------------------------------
// -- 4.1 CVD scaled to price (plotLine) --
if (showCVD) {
plotLine(value=cvdScale, width=2, colors=[cvdColor], label=["CVD Scaled"], desc=["CVD scaled to price (Fowler); z-score normalised"])
}
// -- 4.2 Price underlay (plotLine) --
if (showPriceUnderlay) {
plotLine(value=close, width=1, colors=[priceColor], label=["Price"], desc=["Underlying price for divergence detection"])
}
// -- 4.3 Price fill (plotLine with fill) --
if (showFill && showPriceUnderlay) {
plotLine(value=[close, cvdScale], width=1, colors=[transparency(priceColor, 30), transparency(cvdColor, 30)], colorIndex=0, fill=true, label=["Price", "CVD Scaled"], desc=["Fill between price and CVD scaled"])
}
// -- 4.4 Divergence histogram (colorIndex regime coding + fill) --
var divColorIdx = cvdZ > divThreshold ? 0 : (cvdZ < -divThreshold ? 1 : 2)
if (showHistogram) {
plotLine(value=[cvdZ, zeroLine], width=2, colors=[bullColor, bearColor, neutralColor], colorIndex=divColorIdx, fill=true, label=["Divergence Histogram"], desc=["CVD z-score histogram; color-coded by regime"])
}
// -- 4.5 Divergence bars (plotBar) --
if (showHistogram) {
plotBar(value=cvdZ, colors=[bullColor, bearColor, neutralColor], colorIndex=divColorIdx, width=1, label=["CVD Z Bars"], desc=["CVD z-score as bars"])
}
// -- 4.6 Extreme divergence shapes --
if (showShapes && extremeBullDiv) {
plotShape(value=high, shape="triangleup", colorIndex=bullColor, width=3, label=["Extreme Bull Div"], desc=["CVD massively positive; potential buying climax / short squeeze"])
}
if (showShapes && extremeBearDiv) {
plotShape(value=low, shape="triangledown", colorIndex=bearColor, width=3, label=["Extreme Bear Div"], desc=["CVD massively negative; potential selling climax / long squeeze"])
}
// -- 4.7 Divergence shapes (price/CVD disagreement) --
if (showShapes && divBull) {
plotShape(value=low, shape="circle", colorIndex=bullColor, width=2, label=["Bull Div"], desc=["Price lower low, CVD higher low: bullish divergence detected"])
}
if (showShapes && divBear) {
plotShape(value=high, shape="circle", colorIndex=bearColor, width=2, label=["Bear Div"], desc=["Price higher high, CVD lower high: bearish divergence detected"])
}
// -- 4.8 Optional raw CVD --
if (showRawCVD) {
plotLine(value=cvdCum / 1000, width=1, colors=[transparency(cvdColor, 50)], label=["Raw CVD"], desc=["True cumulative CVD from first bar (static-tracked)"])
}
// -- 4.9 Reference thresholds --
hline(value=0, color="#ffffff30", width=1)
hline(value=divThreshold, color="#ffffff20", width=1)
hline(value=-divThreshold, color="#ffffff20", width=1)
hline(value=extremeDiv, color="#ffffff15", width=1)
hline(value=-extremeDiv, color="#ffffff15", width=1)
// ---------------------------------------------------------------------------
// 5. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
var divText = divBull ? "BULL DIV" : (divBear ? "BEAR DIV" : "NONE")
var divTextColor = divBull ? bullColor : (divBear ? bearColor : neutralColor)
plotTable(
data=[
["Fowler's CVD", divText],
["CVD Z", cvdZ[0]],
["CVD Scaled", cvdScale[0]],
["Price", close[0]],
["Bull Div Bars", divBullBars],
["Bear Div Bars", divBearBars]
],
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
)
}