Perfected FlowScript
SCF Delta Bubbles
SCF Delta Bubbles V2 is indexed as 063_scf_delta_bubbles.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
3 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Delta Bubble
line 205:5
Trigger
(showBubbles && isBubble)
Value
yPos
Deps
isBubble:timeseries, showBubbles:input
Extreme Buy
line 217:5
Trigger
(showExtremeShapes && extremeBull)
Value
yPos
Deps
extremeBull:var, showExtremeShapes:input
Extreme Sell
line 227:5
Trigger
(showExtremeShapes && extremeBear)
Value
yPos
Deps
extremeBear:var, showExtremeShapes:input
063_scf_delta_bubbles.flowscript
source path: kscripts/perfected/063_scf_delta_bubbles.flowscript · sha256:ac9022f2872c0bdc9971aae3ce50b7283e26d114ca2b515cc7b0e00c3abd2bfb
//@version=2
// ============================================================================
// SCF Delta Bubbles V2 — Z-Score Normalized Volume-Delta Bubble Visualization
// Author: SoulzBTC (@SoulzBTC) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, FLOW, #delta, #bubbles, #zscore, #volume
//
// Visualizes statistically significant volume-delta events as on-chart bubbles
// with z-score sizing, opacity scaling, and directional color coding. Extreme
// delta events are flagged with shape markers for rapid identification of
// aggressive buying or selling pressure clusters.
//
// Academic foundation (exact papers & formulas):
// 1. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
// Journal of Finance, 46(2), 733–746.
// [Formula] Tick test: classify as buy if close > open, else sell.
// Accuracy: 85–93% on NYSE TORQ data. Foundational trade-direction
// inference when taker-buy/sell feeds are unavailable.
// DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
//
// 2. Easley, López de Prado & O'Hara (2012), "Bulk Classification of
// Trading Activity" (BVC). Probabilistic bar-level volume classification:
// BuyFrac = (close − low) / (high − low); SellFrac = (high − close) / (high − low).
// Superior to Lee-Ready in high-frequency environments (data efficiency).
// SSRN: https://ssrn.com/abstract=1989555
//
// 3. 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. Validates delta as primary price driver.
// DOI: https://doi.org/10.1093/jjfinec/nbt003
//
// 4. 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. Motivates the extreme-delta threshold design.
// DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
// 5. 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 underpinning
// all delta-based trading signals.
// DOI: https://doi.org/10.2307/1913210
//
// 6. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes
// in Supply and Demand", Handbook of Financial Markets, 57–160.
// Square-root impact law: large delta events have sublinear price impact
// due to liquidity memory. Explains why extreme bubbles may signal
// absorption rather than continuation.
// ============================================================================
define(title="SCF Delta Bubbles V2", position="onchart", axis=false)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// -- Computation --
var zLen = input(name="zLen", type="number", defaultValue=50, label="Z-Score Window (bars)", constraints={min: 10, max: 200, step: 5}, group="Computation")
var zThreshold = input(name="zThreshold", type="number", defaultValue=1.5, label="Bubble Threshold (|z|)", constraints={min: 0.5, max: 4.0, step: 0.1}, group="Computation")
var extremeZ = input(name="extremeZ", type="number", defaultValue=2.5, label="Extreme Delta Threshold (|z|)", constraints={min: 1.5, max: 5.0, step: 0.1}, group="Computation")
var bubbleScale = input(name="bubbleScale", type="number", defaultValue=4, label="Bubble Scale Factor", constraints={min: 1, max: 10, step: 1}, group="Computation")
var maxBubbleSize = input(name="maxBubbleSize", type="number", defaultValue=14, label="Max Bubble Size", constraints={min: 4, max: 24, step: 1}, group="Computation")
var opacityMin = input(name="opacityMin", type="number", defaultValue=30, label="Min Opacity (%)", constraints={min: 10, max: 80, step: 5}, group="Computation")
var opacityMax = input(name="opacityMax", type="number", defaultValue=90, label="Max Opacity (%)", constraints={min: 40, max: 100, step: 5}, group="Computation")
// -- Display --
var showBubbles = input(name="showBubbles", type="boolean", defaultValue=true, label="Show Delta Bubbles", group="Display")
var showExtremeShapes = input(name="showExtremeShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showDeltaBar = input(name="showDeltaBar", type="boolean", defaultValue=false, label="Show Delta Histogram", group="Display")
var showZLine = input(name="showZLine", type="boolean", defaultValue=false, label="Show Z-Score Line (offchart)", group="Display")
// -- Colors --
var buyColor = input(name="buyColor", type="color", defaultValue="#26a69a", label="Buy Bubble Color", group="Colors")
var sellColor = input(name="sellColor", type="color", defaultValue="#ef5350", label="Sell Bubble Color", group="Colors")
var extremeBuyColor = input(name="extremeBuyColor", type="color", defaultValue="#00e676", label="Extreme Buy Color", group="Colors")
var extremeSellColor = input(name="extremeSellColor", type="color", defaultValue="#ff1744", label="Extreme Sell 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 h = pxTS.high
timeseries l = pxTS.low
timeseries v = pxTS.volume
timeseries taker = source("taker_volume", currentSymbol, currentExchange)
// Guard: halt until price data has loaded to avoid NaN propagation
if (isnan(c[0]) || isnan(v[0])) {
return
}
// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------
// -- 3.1 Volume Delta — taker feed preferred, Lee-Ready fallback, BVC final fallback --
// Lee-Ready (1991): close > open → buyer-initiated; else seller-initiated.
// BVC (Easley et al. 2012): probabilistic split by bar position within range.
// Cont et al. (2014): OFI = buyVol − sellVol is the primary price driver.
timeseries buyVol = 0.0
timeseries sellVol = 0.0
if (isnum(taker.buy) && isnum(taker.sell)) {
// Direct taker feed available — highest accuracy
buyVol = taker.buy
sellVol = taker.sell
} else {
// Fallback 1: Lee-Ready tick test (85–93% accuracy)
// Fallback 2: BVC probabilistic split when doji / ambiguous
timeseries range_ = h - l
timeseries upW = math.max(c - o, 0.0)
timeseries dnW = math.max(o - c, 0.0)
buyVol = range_ > 0 ? v * (upW / range_) : v * 0.5
sellVol = range_ > 0 ? v * (dnW / range_) : v * 0.5
}
timeseries delta = buyVol - sellVol
// -- 3.2 Z-score normalisation (all denominators guarded against zero) --
// Z_t = (Δ_t − μ_t) / σ_t, where μ_t = SMA(Δ, W), σ_t = StDev(Δ, W).
// Guards: if σ_t == 0 we emit 0 to prevent division-by-zero crashes.
timeseries deltaMean = sma(delta, zLen)
timeseries deltaStd = stdev(delta, zLen)
timeseries z = (deltaStd > 0) ? (delta - deltaMean) / deltaStd : 0.0
// -- 3.3 Bubble sizing & opacity (z-score magnitude) --
// Bubble size scales linearly with |z|, clamped to maxBubbleSize.
// Opacity scales from opacityMin to opacityMax as |z| increases.
timeseries absZ = abs(z)
timeseries isBubble = absZ > zThreshold
timeseries isExtreme = absZ > extremeZ
timeseries yPos = z > 0 ? l : h
// Size: linear interpolation between zThreshold and extremeZ
timeseries rawSize = bubbleScale * absZ / zThreshold
timeseries bubbleSize = math.min(rawSize, maxBubbleSize)
// Opacity: linear interpolation between opacityMin and opacityMax
timeseries opacityPct = opacityMin + (opacityMax - opacityMin) * math.min(absZ / extremeZ, 1.0)
// Directional color
timeseries bubbleColor = z > 0 ? buyColor : sellColor
timeseries extremeColor = z > 0 ? extremeBuyColor : extremeSellColor
// -- 3.4 Regime detection (configurable thresholds, no magic numbers) --
var bullishDelta = z > zThreshold
var bearishDelta = z < -zThreshold
var extremeBull = z > extremeZ
var extremeBear = z < -extremeZ
var neutralDelta = !bullishDelta && !bearishDelta
// -- 3.5 Static state tracking — session-level persistence --
// Tracks bubble counts, extreme-event counts, and session extremes for
// context-aware alerting and diagnostics.
static bubbleCount = 0
static extremeCount = 0
static lastRegime = 0
static sessionMaxZ = 0.0
static sessionMinZ = 0.0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (absZ > sessionMaxZ) {
sessionMaxZ = absZ
}
if (z < sessionMinZ) {
sessionMinZ = z
}
if (isBubble && lastRegime == 0) {
bubbleCount = bubbleCount + 1
}
if (isExtreme && lastRegime != 2) {
extremeCount = extremeCount + 1
}
if (extremeBull || extremeBear) {
lastRegime = 2
} else if (bullishDelta || bearishDelta) {
lastRegime = 1
} else {
lastRegime = 0
}
}
// ---------------------------------------------------------------------------
// 4. VISUALIZATION — Multiple types: plotShape, plotBar, plotLine, hline
// ---------------------------------------------------------------------------
// 4.1 Delta bubbles (plotShape) — z-score sized, opacity-scaled, color-coded by direction
if (showBubbles && isBubble) {
plotShape(
value=yPos,
shape="circle",
colorIndex=opacity(bubbleColor, opacityPct),
width=bubbleSize,
label=["Delta Bubble"],
desc=["Z-score normalized volume delta; size = significance, color = direction, opacity = intensity"]
)
}
// 4.2 Extreme delta shapes (plotShape) — diamonds for extreme events
if (showExtremeShapes && extremeBull) {
plotShape(
value=yPos,
shape="diamond",
colorIndex=extremeBuyColor,
width=5,
label=["Extreme Buy"],
desc=["Extreme aggressive buying detected; potential absorption or continuation cluster"]
)
}
if (showExtremeShapes && extremeBear) {
plotShape(
value=yPos,
shape="diamond",
colorIndex=extremeSellColor,
width=5,
label=["Extreme Sell"],
desc=["Extreme aggressive selling detected; potential absorption or distribution cluster"]
)
}
// 4.3 Delta histogram (plotBar) — optional overlay for bar-level delta context
if (showDeltaBar) {
plotBar(
value=delta,
colors=[buyColor, sellColor],
width=1,
label=["Volume Delta"],
desc=["Per-bar volume delta (buy − sell); positive = buy-heavy, negative = sell-heavy"]
)
}
// 4.4 Z-score line (optional offchart reference)
if (showZLine) {
plotLine(
value=z,
width=1,
colors=[buyColor, sellColor, "#78909c"],
colorIndex=z > zThreshold ? 0 : (z < -zThreshold ? 1 : 2),
label=["Delta Z-Score"],
desc=["Rolling-window z-score of volume delta; regime-coded by direction"]
)
}
// 4.5 Reference thresholds (hline)
hline(value=0, color="#ffffff30", width=1)