Perfected FlowScript
BA Delta Filter
BA Delta Filter V2 is indexed as 263_ba_delta_filter.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
15.5 KB
Lines
360
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Bull Regime
line 289:9
Trigger
(showShapes) && (crossUp)
Value
deltaSmoothed
Deps
crossUp:var, showShapes:input
Bear Regime
line 299:9
Trigger
(showShapes) && (crossDn)
Value
deltaSmoothed
Deps
crossDn:var, showShapes:input
Extreme Buy
line 309:9
Trigger
(showShapes) && (extremeUp)
Value
deltaSmoothed
Deps
extremeUp:var, showShapes:input
Extreme Sell
line 319:9
Trigger
(showShapes) && (extremeDn)
Value
deltaSmoothed
Deps
extremeDn:var, showShapes:input
263_ba_delta_filter.flowscript
source path: kscripts/perfected/263_ba_delta_filter.flowscript · sha256:9f5312cc239d02a238bdd04c96428dfbd8f89b4b0357ecff09bf419b09f710ae
//@version=2
// ============================================================================
// BA Delta Filter V2 — Production-Quality Bid-Ask Delta with Z-Score & Regime
// Author: Mark (@Mark) | Perfected by: kScript Perfection Engineer
// Index: 263
// Tags: FLOW, #bid-ask, #delta, #orderflow, #z-score, #regime, #filter
//
// Computes a filtered bid-ask delta with multi-depth aggregation, Z-score
// normalization, and regime detection. Implements size-based filtering,
// smoothing, and comprehensive visualization for orderflow analysis.
//
// FORMULA FOUNDATION:
// 1. Filtered Delta: Δ = (BidSize × I(bid ≥ minBid)) − (AskSize × I(ask ≥ minAsk))
// Filters out noise from small orders; focuses on meaningful liquidity.
// 2. Z-Score Normalization: Z = (Δ − μ_Δ) / σ_Δ (rolling lookback)
// Per VPIN methodology (Easley et al. 2012), normalization against recent
// distribution enables cross-asset and cross-regime comparison.
// 3. Regime Detection: Bull (Z > +1σ), Bear (Z < −1σ), Neutral (−1σ, +1σ)
// Per Cartea, Donnelly & Jaimungal (2018) three-segment model.
// 4. Delta Momentum: dZ/dt via EMA of Z-score — captures directional
// acceleration of orderflow imbalance.
//
// RESEARCH BASIS:
// • Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity in
// a High-Frequency World", J. Portfolio Management 39(1), 107–121. VPIN
// metric; orderflow imbalance as toxicity/price-move predictor.
// • Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
// Order Book Signals", Appl. Math. Finance 25(1), 1–35. Three-regime
// segmentation for microstructure signals.
// • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
// J. Financial Econometrics 12(1), 47–88. Bid-ask imbalance as predictor
// of short-term price direction; slope ∝ 1/depth.
// • Gould & Bonart (2016), "Queue Imbalance as a One-Tick-Ahead Price
// Predictor", Market Microstructure & Liquidity 2(1), 1650006. Queue
// imbalance logistic regression for next-tick direction.
// • Han, Yang & Wilding (2019), "VPIN and the Flash Crash: A Reassessment",
// J. Banking & Finance. Z-score normalization of orderflow metrics for
// extreme event detection.
// ============================================================================
define(
title="BA Delta Filter V2",
position="offchart",
axis=true
)
// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------
// --- Size Filters ---
var minBid = input(name="minBid", type="number", defaultValue=0.0, label="Min Bid Size Filter", constraints={min: 0, max: 1000000, step: 1000}, group="Size Filters")
var minAsk = input(name="minAsk", type="number", defaultValue=0.0, label="Min Ask Size Filter", constraints={min: 0, max: 1000000, step: 1000}, group="Size Filters")
// --- Depth Configuration ---
var depth1 = input(name="depth1", type="number", defaultValue=1.0, label="Depth Band 1 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Depth")
var depth2 = input(name="depth2", type="number", defaultValue=2.5, label="Depth Band 2 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Depth")
var depth3 = input(name="depth3", type="number", defaultValue=5.0, label="Depth Band 3 (%)", constraints={min: 0.1, max: 50.0, step: 0.1}, group="Depth")
var useDepthWeighting = input(name="useDepthWeighting", type="boolean", defaultValue=true, label="Use Depth-Decaying Weights", group="Depth")
var weightDecay = input(name="weightDecay", type="number", defaultValue=0.75, label="Weight Decay Factor", constraints={min: 0.0, max: 1.0, step: 0.05}, group="Depth")
// --- Smoothing ---
var smooth = input(name="smooth", type="number", defaultValue=5, label="Delta Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Smoothing")
var zSmooth = input(name="zSmooth", type="number", defaultValue=3, label="Z-Score EMA Smoothing", constraints={min: 1, max: 20, step: 1}, group="Smoothing")
// --- Z-Score ---
var zLookback = input(name="zLookback", type="number", defaultValue=20, label="Z-Score Lookback", constraints={min: 5, max: 100, step: 1}, group="Z-Score")
var zThreshold = input(name="zThreshold", type="number", defaultValue=1.0, label="Regime Z-Score Threshold", constraints={min: 0.5, max: 3.0, step: 0.1}, group="Z-Score")
var extremeZ = input(name="extremeZ", type="number", defaultValue=2.5, label="Extreme Z-Score Threshold", constraints={min: 1.5, max: 4.0, step: 0.1}, group="Z-Score")
// --- Display ---
var showDeltaLine = input(name="showDeltaLine", type="boolean", defaultValue=true, label="Show Delta Line", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showBars = input(name="showBars", type="boolean", defaultValue=true, label="Show Delta Histogram", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")
var showMomentum = input(name="showMomentum", type="boolean", defaultValue=false, label="Show Delta Momentum", group="Display")
// --- Colors ---
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Net Buying Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Net Selling Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeBullColor = input(name="extremeBullColor", type="color", defaultValue="#00e676", label="Extreme Buying Color", group="Colors")
var extremeBearColor = input(name="extremeBearColor", type="color", defaultValue="#ff1744", label="Extreme Selling Color", group="Colors")
// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries priceBars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = priceBars.close
timeseries book = source("orderbook", currentSymbol, currentExchange)
if (isnan(px[0])) {
return
}
// ------------------------------------------------------------------------------
// Multi-Depth Bid-Ask Aggregation with Size Filtering
// ------------------------------------------------------------------------------
// Apply minBid/minAsk filters to each depth band individually
var bid1raw = sumBids(book, depth1)
var ask1raw = sumAsks(book, depth1)
var bid2raw = sumBids(book, depth2)
var ask2raw = sumAsks(book, depth2)
var bid3raw = sumBids(book, depth3)
var ask3raw = sumAsks(book, depth3)
var bookAvailable = bid1raw > 0 && ask1raw > 0 && bid2raw > 0 && ask2raw > 0 && bid3raw > 0 && ask3raw > 0
// Apply size filters
var bid1 = bid1raw >= minBid ? bid1raw : 0.0
var ask1 = ask1raw >= minAsk ? ask1raw : 0.0
var bid2 = bid2raw >= minBid ? bid2raw : 0.0
var ask2 = ask2raw >= minAsk ? ask2raw : 0.0
var bid3 = bid3raw >= minBid ? bid3raw : 0.0
var ask3 = ask3raw >= minAsk ? ask3raw : 0.0
// ------------------------------------------------------------------------------
// Raw Delta per Depth Band
// ------------------------------------------------------------------------------
var delta1 = bookAvailable ? (bid1 - ask1) : 0.0
var delta2 = bookAvailable ? (bid2 - ask2) : 0.0
var delta3 = bookAvailable ? (bid3 - ask3) : 0.0
// ------------------------------------------------------------------------------
// Depth-Weighted Composite Delta (Cont et al. 2014 multi-level approach)
// ------------------------------------------------------------------------------
var w1 = 1.0
var w2 = useDepthWeighting ? weightDecay : 1.0
var w3 = useDepthWeighting ? weightDecay * weightDecay : 1.0
var wSum = w1 + w2 + w3
var compositeDelta = wSum > 0 ? (w1 * delta1 + w2 * delta2 + w3 * delta3) / wSum : 0.0
// ------------------------------------------------------------------------------
// Smoothing (EMA noise reduction per Cont et al. 2014)
// ------------------------------------------------------------------------------
var deltaSmoothed = ema(compositeDelta, smooth)
// ------------------------------------------------------------------------------
// Z-Score Normalization (Easley et al. 2012 VPIN methodology)
// ------------------------------------------------------------------------------
var deltaMean = sma(deltaSmoothed, zLookback)
var deltaStd = stddev(deltaSmoothed, zLookback)
var deltaZ = deltaStd > 0 ? (deltaSmoothed - deltaMean) / deltaStd : 0.0
var deltaZSmoothed = ema(deltaZ, zSmooth)
// Delta momentum (rate of change of Z-score)
var deltaMomentum = deltaZSmoothed - ema(deltaZSmoothed, zSmooth)
// ------------------------------------------------------------------------------
// Regime Detection (Cartea et al. 2018 three-segment model, Z-score based)
// ------------------------------------------------------------------------------
var regime = 0 // 0 = neutral, 1 = bull, -1 = bear
var extremeRegime = 0 // 0 = normal, 1 = extreme bull, -1 = extreme bear
if (deltaZSmoothed >= zThreshold) {
regime = 1
} else if (deltaZSmoothed <= -zThreshold) {
regime = -1
}
if (deltaZSmoothed >= extremeZ) {
extremeRegime = 1
} else if (deltaZSmoothed <= -extremeZ) {
extremeRegime = -1
}
// ------------------------------------------------------------------------------
// Static State Tracking (session-level persistence)
// ------------------------------------------------------------------------------
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighDelta = -999999.0
static sessionLowDelta = 999999.0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static extremeBullCount = 0
static extremeBearCount = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (deltaSmoothed > sessionHighDelta) {
sessionHighDelta = deltaSmoothed
}
if (deltaSmoothed < sessionLowDelta) {
sessionLowDelta = deltaSmoothed
}
if (deltaZSmoothed > sessionHighZ) {
sessionHighZ = deltaZSmoothed
}
if (deltaZSmoothed < sessionLowZ) {
sessionLowZ = deltaZSmoothed
}
if (lastRegime != regime) {
lastRegime = regime
regimeChangeCount = regimeChangeCount + 1
}
if (extremeRegime == 1) {
extremeBullCount = extremeBullCount + 1
} else if (extremeRegime == -1) {
extremeBearCount = extremeBearCount + 1
}
}
// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types
// ------------------------------------------------------------------------------
// Zero line
hline(value=0, color="#ffffff30", width=1)
// Z-score threshold lines
hline(value=zThreshold, color=opacity(bullColor, 30), width=1)
hline(value=-zThreshold, color=opacity(bearColor, 30), width=1)
if (showZScore) {
hline(value=extremeZ, color=opacity(extremeBullColor, 20), width=1)
hline(value=-extremeZ, color=opacity(extremeBearColor, 20), width=1)
}
// Delta smoothed line (regime-colored with fill)
if (showDeltaLine) {
plotLine(
value=deltaSmoothed,
width=2,
colors=[bullColor, bearColor, neutralColor],
colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
label=["Delta"],
desc=["Filtered bid-ask delta (depth-weighted, EMA-smoothed)"],
fill=true
)
}
// Z-Score line (normalized regime view)
if (showZScore) {
plotLine(
value=deltaZSmoothed,
width=2,
colors=[bullColor, bearColor, neutralColor],
colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
label=["Z-Score"],
desc=["Z-score of filtered delta (σ-normalized, cross-comparable)"],
fill=true
)
}
// Delta momentum line (optional)
if (showMomentum) {
plotLine(
value=deltaMomentum,
width=1,
colors=[bullColor, bearColor, neutralColor],
colorIndex=deltaMomentum > 0 ? 0 : (deltaMomentum < 0 ? 1 : 2),
label=["Momentum"],
desc=["Delta Z-score momentum (acceleration of orderflow imbalance)"]
)
}
// Delta histogram (bid/ask colored)
if (showBars) {
var histColor = extremeRegime == 1 ? extremeBullColor : (extremeRegime == -1 ? extremeBearColor : (regime == 1 ? bullColor : (regime == -1 ? bearColor : neutralColor)))
plotBar(
value=deltaSmoothed,
colors=[histColor, neutralColor],
colorIndex=regime != 0 ? 0 : 1,
width=1,
label=["Delta Bar"],
desc=["Filtered bid-ask delta bar (buy + / sell −)"]
)
}
// Regime transition and extreme shapes
if (showShapes) {
// Cross into bull regime
var crossUp = deltaZSmoothed >= zThreshold && !isnan(deltaZSmoothed[1]) && deltaZSmoothed[1] < zThreshold
// Cross into bear regime
var crossDn = deltaZSmoothed <= -zThreshold && !isnan(deltaZSmoothed[1]) && deltaZSmoothed[1] > -zThreshold
// Extreme bull
var extremeUp = deltaZSmoothed >= extremeZ && !isnan(deltaZSmoothed[1]) && deltaZSmoothed[1] < extremeZ
// Extreme bear
var extremeDn = deltaZSmoothed <= -extremeZ && !isnan(deltaZSmoothed[1]) && deltaZSmoothed[1] > -extremeZ
if (crossUp) {
plotShape(
value=deltaSmoothed,
shape="triangleup",
color=extremeBullColor,
width=3,
label=["Bull Regime"],
desc=["Bid-ask delta crossed into bullish regime (Z ≥ +" + zThreshold + ")"]
)
}
if (crossDn) {
plotShape(
value=deltaSmoothed,
shape="triangledown",
color=extremeBearColor,
width=3,
label=["Bear Regime"],
desc=["Bid-ask delta crossed into bearish regime (Z ≤ −" + zThreshold + ")"]
)
}
if (extremeUp) {
plotShape(
value=deltaSmoothed,
shape="diamond",
color=extremeBullColor,
width=4,
label=["Extreme Buy"],
desc=["Extreme buying pressure: Z-score ≥ +" + extremeZ]
)
}
if (extremeDn) {
plotShape(
value=deltaSmoothed,
shape="diamond",
color=extremeBearColor,
width=4,
label=["Extreme Sell"],
desc=["Extreme selling pressure: Z-score ≤ −" + extremeZ]
)
}
}
// ------------------------------------------------------------------------------
// Regime Table (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
var regimeText = regime == 1 ? "BULLISH" : (regime == -1 ? "BEARISH" : "NEUTRAL")
var regimeTextColor = regime == 1 ? bullColor : (regime == -1 ? bearColor : neutralColor)
plotTable(
data=[
["BA Delta V2", regimeText],
["Delta", deltaSmoothed],
["Z-Score", deltaZSmoothed],
["Momentum", deltaMomentum],
["Regime Changes", regimeChangeCount],
["Extreme Bull", extremeBullCount],
["Extreme Bear", extremeBearCount]
],
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
)
}