Perfected FlowScript
Sweep & Refill Tracker
Sweep & Refill Tracker V2 is indexed as 241_sweep_refill_tracker.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.9 KB
Lines
263
Native Signal Candidates
2 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Sweep Up
line 227:9
Trigger
(showShapes) && (sweepUp)
Value
sigSmooth
Deps
showShapes:input, sweepUp:var
Sweep Down
line 237:9
Trigger
(showShapes) && (sweepDown)
Value
sigSmooth
Deps
showShapes:input, sweepDown:var
241_sweep_refill_tracker.flowscript
source path: kscripts/perfected/241_sweep_refill_tracker.flowscript · sha256:d7a09eb294eb3d424a55d5e31366fc37ef9bdd814b175ef66f03fc0fcbf3fb1b
//@version=2
// ============================================================================
// Sweep & Refill Tracker V2 — Liquidity Sweep Detection with Refill Quality
// Author: D (@ddave334) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, FLOW, #liquidity, #sweep, #refill, #orderbook, #microstructure
//
// Detects aggressive price moves with orderbook depletion (sweeps) followed
// by liquidity recovery (refills) over a configurable window. Distinguishes
// real breakouts from liquidity grabs by measuring depth collapse and
// subsequent refill quality. Color-coded histograms, refill scoring, and
// extreme shape alerts provide multi-layered visual confirmation.
//
// 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] Price Impact = λ × OFI; λ ∝ 1/Depth. A "sweep" (sharp
// price move with depth collapse) occurs when imbalance overwhelms
// shallow depth; a "refill" represents depth recovery.
// DOI: https://doi.org/10.1093/jjfinec/nbt003
//
// 2. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes
// in Supply and Demand", Handbook of Financial Markets: Dynamics
// and Evolution, 57–160.
// [Formula] Liquidity memory time: after trade, liquidity depletes
// then gradually recovers. Square-root impact law: cumulative impact
// is sublinear, explaining why refills may not fully restore pre-sweep
// depth.
//
// 3. Order Book Filtration and Directional Signal Extraction (2025),
// arXiv:2507.22712.
// [Formula] Trade-based OBI(T) eliminates flickering quote noise and
// better reflects market commitment. The sweep detection (>threshold%
// price move with >threshold% depth collapse) filters flickering noise
// to capture genuine committed flow.
//
// 4. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity,
// and Market Returns", Journal of Financial Economics, 65(1), 111–130.
// [Formula] Extreme imbalances predict return reversals. Sweeps at
// extremes often mark exhaustion; refills indicate whether the market
// defends the level or capitulates.
//
// 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 price-impact coefficient that increases when depth collapses
// during a sweep.
// DOI: https://doi.org/10.2307/1913210
// ============================================================================
define(title="Sweep & Refill Tracker V2", position="offchart", axis=true)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// -- Sweep Detection --
var moveThresh = input(name="moveThresh", type="number", defaultValue=0.5, label="Move Threshold (%)", constraints={min: 0.1, max: 5.0, step: 0.1}, group="Sweep Detection")
var depthThresh = input(name="depthThresh", type="number", defaultValue=0.3, label="Depth Collapse Threshold (%)", constraints={min: 0.05, max: 0.9, step: 0.05}, group="Sweep Detection")
var volAmplify = input(name="volAmplify", type="boolean", defaultValue=true, label="Require Volume Amplification", group="Sweep Detection")
var volMult = input(name="volMult", type="number", defaultValue=2.0, label="Volume Amplification Multiplier", constraints={min: 1.0, max: 10.0, step: 0.5}, group="Sweep Detection")
// -- Refill Tracking --
var refillBars = input(name="refillBars", type="number", defaultValue=18, label="Refill Window (bars)", constraints={min: 5, max: 50, step: 1}, group="Refill Tracking")
var refillMin = input(name="refillMin", type="number", defaultValue=0.6, label="Minimum Refill Quality", constraints={min: 0.1, max: 1.0, step: 0.05}, group="Refill Tracking")
// -- Display --
var showSweepSignal = input(name="showSweepSignal", type="boolean", defaultValue=true, label="Show Sweep Signal", group="Display")
var showRefillScore = input(name="showRefillScore", type="boolean", defaultValue=true, label="Show Refill Score", group="Display")
var showRefillBars = input(name="showRefillBars", type="boolean", defaultValue=true, label="Show Refill Quality Bars", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showCumScore = input(name="showCumScore", type="boolean", defaultValue=false, label="Show Cumulative Sweep Score", group="Display")
// -- Colors --
var sweepUpColor = input(name="sweepUpColor", type="color", defaultValue="#26a69a", label="Sweep Up Color", group="Colors")
var sweepDownColor = input(name="sweepDownColor", type="color", defaultValue="#ef5350", label="Sweep Down Color", group="Colors")
var refillColor = input(name="refillColor", type="color", defaultValue="#ffeb3b", label="Refill Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var strongRefillColor = input(name="strongRefillColor", type="color", defaultValue="#00c853", label="Strong Refill Color", group="Colors")
var weakRefillColor = input(name="weakRefillColor", type="color", defaultValue="#d50000", label="Weak Refill Color", group="Colors")
// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first external access
// ---------------------------------------------------------------------------
timeseries ohlcvTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries close = ohlcvTS.close
timeseries high = ohlcvTS.high
timeseries low = ohlcvTS.low
timeseries volume = ohlcvTS.volume
timeseries book = source("orderbook", currentSymbol, currentExchange)
// Guard: halt until all external feeds have loaded to avoid NaN propagation
if (isnan(close[0]) || isnan(volume[0]) || isnan(high[0]) || isnan(low[0])) {
return
}
// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------
// -- 3.1 Bar move (% of close) --
// Per-bar percentage move used for sweep magnitude detection.
timeseries pctMove = close > 0 && close[1] > 0 ? math.abs(close - close[1]) / close[1] * 100.0 : 0.0
// -- 3.2 Volume as depth proxy (deviation from rolling mean) --
// Cont et al. (2014): price impact slope ∝ 1/depth. Volume surges above
// rolling average proxy depth collapse when orderbook data is sparse.
timeseries volMean = sma(volume, refillBars)
timeseries volDev = volMean > 0 ? (volume - volMean) / volMean : 0.0
// -- 3.3 Orderbook depth proxy (if available) --
// Use 1% depth band from orderbook; fall back to volume proxy if book unavailable.
timeseries bids1 = sumBids(book, 1.0)
timeseries asks1 = sumAsks(book, 1.0)
var bookAvailable = bids1 > 0 && asks1 > 0
// Depth collapse: current 1% depth vs. rolling average of depth
timeseries depthMean = sma(bids1 + asks1, refillBars)
timeseries depthProxy = (bookAvailable && depthMean > 0)
? 1.0 - ((bids1 + asks1) / depthMean)
: (volDev > 0 ? volDev : 0.0)
// -- 3.4 Sweep detection (large move + depth collapse + optional volume amplification) --
// Cont et al. (2014): sweep occurs when OFI overwhelms shallow depth.
// Bouchaud et al. (2009): depth recovery follows liquidity memory time.
var volCondition = !volAmplify || (volDev > (volMult - 1.0))
var sweepUp = pctMove > moveThresh && close > close[1] && depthProxy > depthThresh && volCondition
var sweepDown = pctMove > moveThresh && close < close[1] && depthProxy > depthThresh && volCondition
// -- 3.5 Refill score: subsequent depth recovery (normalized) --
// Refill quality = how much depth recovers relative to pre-sweep average.
// Values > 1.0 = above-average depth recovery; < 1.0 = below-average.
timeseries refillScore = (bookAvailable && depthMean > 0)
? (bids1 + asks1) / depthMean
: (volMean > 0 ? volume / volMean : 1.0)
// Refill quality classification
var strongRefill = refillScore > 1.0 && refillScore > refillMin
var weakRefill = refillScore < refillMin
// -- 3.6 Combined signal: +1 sweep up, −1 sweep down, 0 otherwise; smoothed --
timeseries sig = sweepUp ? 1.0 : (sweepDown ? -1.0 : 0.0)
timeseries sigSmooth = sma(sig, refillBars)
// -- 3.7 Regime index (0 = sweep up, 1 = sweep down, 2 = neutral) --
var colIdx = sigSmooth > 0 ? 0 : (sigSmooth < 0 ? 1 : 2)
// -- 3.8 Static state tracking (session-level persistence) --
// Tracks cumulative sweep score, sweep counts, and last refill state.
static cumSweepScore = 0.0
static sweepUpCount = 0
static sweepDownCount = 0
static lastSweepRegime = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
// Cumulative sweep score
if (!isnan(sig[0])) {
cumSweepScore = cumSweepScore + sig[0]
}
// Sweep counting
if (sweepUp) {
sweepUpCount = sweepUpCount + 1
lastSweepRegime = 1
} else if (sweepDown) {
sweepDownCount = sweepDownCount + 1
lastSweepRegime = -1
} else if (sig[0] == 0) {
lastSweepRegime = 0
}
}
// -- 3.9 Zero-line helper for fill areas --
timeseries zeroLine = 0.0
// ---------------------------------------------------------------------------
// 4. VISUALIZATION — Multiple types: plotLine, plotShape, plotBar, fill, hline
// ---------------------------------------------------------------------------
// 4.1 Sweep signal as color-coded histogram bars (regime-based)
if (showSweepSignal) {
plotBar(
value=sigSmooth,
colors=[sweepUpColor, sweepDownColor, neutralColor],
colorIndex=colIdx,
width=2,
label=["Sweep Signal"],
desc=["Smoothed sweep signal: +1 = aggressive sweep up, −1 = sweep down, 0 = neutral"]
)
}
// 4.2 Refill score line with fill area
if (showRefillScore) {
plotLine(
value=([refillScore, zeroLine]),
width=2,
colors=[refillColor],
label=["Refill Score"],
desc=["Depth recovery ratio vs. rolling average; >1.0 = above-average refill, <1.0 = weak refill"],
fill=true
)
}
// 4.3 Refill quality bars (strong/weak/neutral)
if (showRefillBars) {
timeseries refillColorIdx = strongRefill ? 0 : (weakRefill ? 1 : 2)
plotLine(
value=refillScore,
width=1,
colors=[strongRefillColor, weakRefillColor, neutralColor],
colorIndex=refillColorIdx,
label=["Refill Quality"],
desc=["Color-coded refill quality: strong (>threshold), weak (<threshold), neutral"]
)
}
// 4.4 Sweep shapes (plotShape) — diamond alerts on sweep events
if (showShapes) {
if (sweepUp) {
plotShape(
value=sigSmooth,
shape="diamond",
color=sweepUpColor,
width=4,
label=["Sweep Up"],
desc=["Liquidity sweep up detected: sharp move + depth collapse + volume surge"]
)
}
if (sweepDown) {
plotShape(
value=sigSmooth,
shape="diamond",
color=sweepDownColor,
width=4,
label=["Sweep Down"],
desc=["Liquidity sweep down detected: sharp move + depth collapse + volume surge"]
)
}
}
// 4.5 Optional cumulative sweep score line (true cumulative from static state)
if (showCumScore) {
plotLine(
value=cumSweepScore,
width=1,
colors=[refillColor],
label=["Cumulative Sweep Score"],
desc=["True cumulative sweep score from first bar; static-tracked across session"]
)
}
// 4.6 Reference thresholds (hline)
hline(value=0, color="#ffffff30", width=1)
hline(value=refillMin, color=opacity(strongRefillColor, 30), width=1)
hline(value=1.0, color=opacity(refillColor, 30), width=1)