Perfected FlowScript
Dr Lucky Bid Ask Depth Fork
Bid-Ask Depth Fork — Perfected Edition is indexed as 182_dr_lucky_bid_ask_depth_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
14.0 KB
Lines
476
Native Signal Candidates
4 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Bid Shift
line 403:9
Trigger
(showShapes) && (compShiftUp)
Value
composite
Deps
compShiftUp:var, showShapes:input
Ask Shift
line 413:9
Trigger
(showShapes) && (compShiftDown)
Value
composite
Deps
compShiftDown:var, showShapes:input
Extreme Bid
line 423:9
Trigger
(showShapes) && (extremeBid)
Value
composite
Deps
extremeBid:var, showShapes:input
Extreme Ask
line 433:9
Trigger
(showShapes) && (extremeAsk)
Value
composite
Deps
extremeAsk:var, showShapes:input
182_dr_lucky_bid_ask_depth_fork.flowscript
source path: kscripts/perfected/182_dr_lucky_bid_ask_depth_fork.flowscript · sha256:1117fcd6199ad78f30a8ef0e6eb09e2fdfedb0601967ca832eee9eb6567f1da8
//@version=2
// Source: kiyotaka.ai/hub/kscript (original) — Perfected by kScript_Perfection_Engineer
// ============================================================================
// Dr Lucky Bid-Ask Depth Fork — Multi-Depth Orderbook Imbalance [Perfected]
// Author: D (@DrLuckyX) — Perfected by kScript_Perfection_Engineer
// Tags: ADVANCED, #bid, #ask, #orderbook, #depth, #imbalance, #microstructure
//
// Production-quality multi-depth bid-ask delta visualization with normalized
// depth ratios, regime detection (bid/ask dominant), depth ratio analysis,
// color-coded fills, and shape markers for regime shifts and extreme
// imbalances. Implements static variables for stateful tracking of depth
// crossovers and regime transitions across three configurable depth levels.
//
// Research papers underpinning this design:
// - Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events":
// OFI = Σ(ΔBidVol - ΔAskVol) / (BidVol + AskVol); linearly predicts price.
// Slope inversely proportional to depth — deeper levels absorb more flow.
// - Xu, Gould & Howison (2019), "Multi-Level Order-Flow Imbalance in a
// Limit Order Book": multi-level imbalance significantly improves short-
// horizon price prediction vs. top-of-book alone. Validates depth forks.
// - Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
// Order Book Signals": segmented volume imbalance into three regimes
// (Sell-heavy, Neutral, Buy-heavy) that predict future price moves.
// - Gould & Bonart (2016), "Queue Imbalance as a One-Tick-Ahead Price
// Predictor": queue imbalance at best bid/ask strongly predicts next-tick
// direction; logistic regression shows significant classification power.
// ============================================================================
define(
title="Bid-Ask Depth Fork — Perfected Edition",
position="offchart",
axis=true
)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// ---------------------------------------------------------------------------
// --- Data Source ---
var src = input(
name="src",
type="select",
defaultValue="BTC",
label="Symbol",
options=["BTC","ETH","SOL"],
group="Data Source"
)
var exc = input(
name="exc",
type="select",
defaultValue="BYBIT",
label="Exchange",
options=["BYBIT","BINANCE_FUTURES","OKEX_SWAP","DERIBIT"],
group="Data Source"
)
// --- Depth Levels ---
var depth1 = input(
name="depth1",
type="number",
defaultValue=5,
label="Depth Level 1 (shallow)",
constraints={min: 1, max: 50, step: 1},
group="Depth Levels"
)
var depth2 = input(
name="depth2",
type="number",
defaultValue=10,
label="Depth Level 2 (medium)",
constraints={min: 1, max: 100, step: 1},
group="Depth Levels"
)
var depth3 = input(
name="depth3",
type="number",
defaultValue=20,
label="Depth Level 3 (deep)",
constraints={min: 1, max: 200, step: 1},
group="Depth Levels"
)
// --- Smoothing ---
var smoothLen = input(
name="smoothLen",
type="number",
defaultValue=3,
label="Smoothing Length",
constraints={min: 1, max: 20, step: 1},
group="Smoothing"
)
// --- Display ---
var showD1 = input(
name="showD1",
type="boolean",
defaultValue=true,
label="Show Depth 1",
group="Display"
)
var showD2 = input(
name="showD2",
type="boolean",
defaultValue=true,
label="Show Depth 2",
group="Display"
)
var showD3 = input(
name="showD3",
type="boolean",
defaultValue=true,
label="Show Depth 3",
group="Display"
)
var showFills = input(
name="showFills",
type="boolean",
defaultValue=true,
label="Show Depth Fills",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Regime Shift Shapes",
group="Display"
)
var showComposite = input(
name="showComposite",
type="boolean",
defaultValue=true,
label="Show Composite Depth Ratio",
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 ---
var posColor = input(
name="posColor",
type="color",
defaultValue="#26a69a",
label="Bid-Dominant Color",
group="Colors"
)
var negColor = input(
name="negColor",
type="color",
defaultValue="#ef5350",
label="Ask-Dominant Color",
group="Colors"
)
var c1 = input(
name="c1",
type="color",
defaultValue="#42a5f5",
label="Depth 1 Color",
group="Colors"
)
var c2 = input(
name="c2",
type="color",
defaultValue="#ffa726",
label="Depth 2 Color",
group="Colors"
)
var c3 = input(
name="c3",
type="color",
defaultValue="#ab47bc",
label="Depth 3 Color",
group="Colors"
)
var compositeColor = input(
name="compositeColor",
type="color",
defaultValue="#ffffff",
label="Composite Ratio Color",
group="Colors"
)
var shiftBullColor = input(
name="shiftBullColor",
type="color",
defaultValue="#00e676",
label="Bullish Shift Color",
group="Colors"
)
var shiftBearColor = input(
name="shiftBearColor",
type="color",
defaultValue="#ff5252",
label="Bearish Shift Color",
group="Colors"
)
// ---------------------------------------------------------------------------
// 2. DATA SOURCE & NaN GUARD
// ---------------------------------------------------------------------------
timeseries book = source("orderbook", src, exc)
if (isnan(book[0])) {
return
}
// ---------------------------------------------------------------------------
// 3. DELTA COMPUTATION AT EACH DEPTH
// ---------------------------------------------------------------------------
// Raw bid/ask sums at each depth, then smoothed EMA of the delta
timeseries bid1 = sumBids(book, depth1)
timeseries ask1 = sumAsks(book, depth1)
timeseries delta1 = ema(bid1 - ask1, smoothLen)
timeseries bid2 = sumBids(book, depth2)
timeseries ask2 = sumAsks(book, depth2)
timeseries delta2 = ema(bid2 - ask2, smoothLen)
timeseries bid3 = sumBids(book, depth3)
timeseries ask3 = sumAsks(book, depth3)
timeseries delta3 = ema(bid3 - ask3, smoothLen)
// Total depth volume for normalization
timeseries total1 = bid1 + ask1
timeseries total2 = bid2 + ask2
timeseries total3 = bid3 + ask3
// Normalized deltas (bid-ask ratio / total depth)
// Positive = bid dominant; Negative = ask dominant; Range: [-1, +1]
timeseries normDelta1 = total1 > 0 ? delta1 / total1 : 0
timeseries normDelta2 = total2 > 0 ? delta2 / total2 : 0
timeseries normDelta3 = total3 > 0 ? delta3 / total3 : 0
// ---------------------------------------------------------------------------
// 4. COMPOSITE DEPTH RATIO
// ---------------------------------------------------------------------------
// Weighted composite across all three depths, with deeper levels getting
// lower weight (shallow depth = higher price impact, per Cont et al. 2014)
timeseries composite = (normDelta1 * 0.5 + normDelta2 * 0.3 + normDelta3 * 0.2)
// Composite SMA for smoother signal
timeseries compSMA = sma(composite, smoothLen * 2)
// ---------------------------------------------------------------------------
// 5. REGIME DETECTION
// ---------------------------------------------------------------------------
var isPos1 = normDelta1 > 0
var isPos2 = normDelta2 > 0
var isPos3 = normDelta3 > 0
var compBull = composite > 0
var compBear = composite < 0
// Regime classification: how many depths agree?
// 3/3 = strong consensus; 2/3 = moderate; 1/3 or 0/3 = weak/mixed
var consensusScore = (isPos1 ? 1 : 0) + (isPos2 ? 1 : 0) + (isPos3 ? 1 : 0)
var strongBidConsensus = consensusScore == 3
var strongAskConsensus = consensusScore == 0
var mixedRegime = consensusScore == 1 || consensusScore == 2
// ---------------------------------------------------------------------------
// 6. REGIME SHIFT DETECTION (static variables for stateful tracking)
// ---------------------------------------------------------------------------
// Track when the composite or any depth crosses zero (bid→ask or ask→bid)
static prevComp = 0.0
static prevD1 = 0.0
static prevD2 = 0.0
static prevD3 = 0.0
var compShiftUp = false
var compShiftDown = false
var d1ShiftUp = false
var d1ShiftDown = false
if (prevComp != 0.0) {
compShiftUp = composite > 0 && prevComp <= 0
compShiftDown = composite < 0 && prevComp >= 0
}
if (prevD1 != 0.0) {
d1ShiftUp = normDelta1 > 0 && prevD1 <= 0
d1ShiftDown = normDelta1 < 0 && prevD1 >= 0
}
prevComp = composite
prevD1 = normDelta1
prevD2 = normDelta2
prevD3 = normDelta3
// Extreme imbalance detection (all depths aligned and extreme magnitude)
var extremeBid = strongBidConsensus && composite > 0.3
var extremeAsk = strongAskConsensus && composite < -0.3
// ---------------------------------------------------------------------------
// 7. PLOTTING
// ---------------------------------------------------------------------------
// --- Depth 1 Line + Fill ---
if (showD1) {
if (showFills) {
plotLine(
value=[0, normDelta1],
colors=[opacity(posColor, 20), opacity(negColor, 20)],
colorIndex=isPos1 ? 0 : 1,
fill=true,
width=1,
label=["Depth " + depth1 + " Fill"],
desc=["Normalized delta fill at depth " + depth1]
)
}
plotLine(
value=normDelta1,
colors=[c1],
width=lineWidth,
label=["Depth " + depth1],
desc=["Normalized bid-ask delta at depth " + depth1 + " (shallow)"]
)
}
// --- Depth 2 Line + Fill ---
if (showD2) {
if (showFills) {
plotLine(
value=[0, normDelta2],
colors=[opacity(posColor, 15), opacity(negColor, 15)],
colorIndex=isPos2 ? 0 : 1,
fill=true,
width=1,
label=["Depth " + depth2 + " Fill"],
desc=["Normalized delta fill at depth " + depth2]
)
}
plotLine(
value=normDelta2,
colors=[c2],
width=lineWidth,
label=["Depth " + depth2],
desc=["Normalized bid-ask delta at depth " + depth2 + " (medium)"]
)
}
// --- Depth 3 Line + Fill ---
if (showD3) {
if (showFills) {
plotLine(
value=[0, normDelta3],
colors=[opacity(posColor, 10), opacity(negColor, 10)],
colorIndex=isPos3 ? 0 : 1,
fill=true,
width=1,
label=["Depth " + depth3 + " Fill"],
desc=["Normalized delta fill at depth " + depth3]
)
}
plotLine(
value=normDelta3,
colors=[c3],
width=lineWidth,
label=["Depth " + depth3],
desc=["Normalized bid-ask delta at depth " + depth3 + " (deep)"]
)
}
// --- Composite Depth Ratio ---
if (showComposite) {
plotLine(
value=composite,
colors=[compositeColor],
width=lineWidth + 1,
label=["Composite"],
desc=["Weighted composite depth ratio (0.5×d1 + 0.3×d2 + 0.2×d3)"]
)
plotLine(
value=compSMA,
colors=[transparency(compositeColor, 50)],
width=1,
label=["Comp SMA"],
desc=["Composite depth ratio SMA (smoothed signal)"]
)
}
// --- Zero Line ---
hline(value=0, color=transparency("#ffffff", 80), width=1)
// --- Shape Markers: Regime Shifts ---
if (showShapes) {
if (compShiftUp) {
plotShape(
value=composite,
shape="triangleup",
colorIndex=shiftBullColor,
width=shapeSize,
label=["Bid Shift"],
desc=["Composite shifted to bid-dominant (all-depth weighted)"]
)
}
if (compShiftDown) {
plotShape(
value=composite,
shape="triangledown",
colorIndex=shiftBearColor,
width=shapeSize,
label=["Ask Shift"],
desc=["Composite shifted to ask-dominant (all-depth weighted)"]
)
}
if (extremeBid) {
plotShape(
value=composite,
shape="circle",
colorIndex=shiftBullColor,
width=shapeSize,
label=["Extreme Bid"],
desc=["Extreme bid dominance: all depths aligned, composite > 0.3"]
)
}
if (extremeAsk) {
plotShape(
value=composite,
shape="circle",
colorIndex=shiftBearColor,
width=shapeSize,
label=["Extreme Ask"],
desc=["Extreme ask dominance: all depths aligned, composite < -0.3"]
)
}
}
// ---------------------------------------------------------------------------
// 8. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
var regimeText = strongBidConsensus ? "STRONG BID" : (strongAskConsensus ? "STRONG ASK" : (mixedRegime ? "MIXED" : "NEUTRAL"))
var regimeTextColor = strongBidConsensus ? posColor : (strongAskConsensus ? negColor : (mixedRegime ? "#ffa726" : "#9e9e9e"))
var d1Text = isPos1 ? "BID (+" + normDelta1[0] + ")" : "ASK (" + normDelta1[0] + ")"
var d2Text = isPos2 ? "BID (+" + normDelta2[0] + ")" : "ASK (" + normDelta2[0] + ")"
var d3Text = isPos3 ? "BID (+" + normDelta3[0] + ")" : "ASK (" + normDelta3[0] + ")"
plotTable(
data=[
["Depth Fork — Perfected", regimeText],
["Composite", composite[0]],
["Depth " + depth1, d1Text],
["Depth " + depth2, d2Text],
["Depth " + depth3, d3Text],
["Consensus", consensusScore + "/3"]
],
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
)
}