MM Flow
FlowScripts

Perfected FlowScript

testbook

TestBook Pro — Orderbook Depth & Microstructure Analysis is indexed as 314_testbook.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

16.0 KB

Lines

493

Native Signal Candidates

3 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.

3/3 guarded

Buy Extreme

line 430:9

Trigger

(showSignals) && (buyExtreme)

Value

upperBand

Deps

buyExtreme:var, showSignals:input

Sell Extreme

line 440:9

Trigger

(showSignals) && (sellExtreme)

Value

lowerBand

Deps

sellExtreme:var, showSignals:input

Unlabeled shape

line 453:5

Trigger

(showRegime && isLastBar)

Value

hi

Deps

isLastBar:builtin, showRegime:input

314_testbook.flowscript

source path: kscripts/perfected/314_testbook.flowscript · sha256:98978d7aef208392c003d78a8ddd38b82d30cbcbac59812605bc6699538d84b0

hash verified
//@version=2
// ============================================================================
// TestBook Pro — Orderbook Depth Analysis & Microstructure Indicator
// Author: kScript Perfection Engineer
// Tags: CORE, #orderbook, #microstructure, #depth, #zscore, #liquidity, #regime
//
// Production-grade orderbook depth analysis indicator using OHLCV-derived
// proxies for bid/ask pressure, imbalance scoring, z-score normalization,
// regime detection, and liquidity zone visualization. Designed as a
// comprehensive microstructure overlay even when true Level 2 data is
// unavailable.
//
// Academic foundations:
//  - Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events"
//    (J. Financial Econometrics, 12(1), 47–88). OFI metric demonstrates
//    linear relationship between order flow imbalance and short-term price
//    changes. Slope ∝ 1/depth. [^1]
//  - Kyle (1985), "Continuous Auctions and Insider Trading" (Econometrica,
//    53(6), 1315–1335). Kyle's Lambda: price impact per unit order flow.
//    Three liquidity dimensions: tightness, depth, resiliency. [^2]
//  - Amihud & Mendelson (1986), "Asset Pricing and the Bid-Ask Spread"
//    (J. Financial Economics, 17(2), 223–249). Spread as proxy for
//    illiquidity; expected returns increase with spread. [^3]
//  - Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity in
//    a High-Frequency World" (RFS, 25(5), 1547–1574). VPIN: volume-
//    synchronized probability of informed trading. Anticipated Flash Crash
//    >1 hour in advance. [^4]
//  - Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint"
//    (IEEE TSP). Z-score normalization: z̄_t = (z_t − μ_z) / σ_z. Entry
//    thresholds at Δ = d × σ_z (typically d = 1 or 2). [^5]
//  - Lo & MacKinlay (1988), "Stock Market Prices Do Not Follow Random Walks"
//    (RFS, 1(1), 41–66). Variance ratio test: VR(q) < 1 signals negative
//    autocorrelation (mean reversion), the regime where z-score strategies
//    are profitable. [^6]
//  - Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
//    Supply and Demand". Square-root impact law; liquidity memory explains
//    absorption and exhaustion. [^7]
// ============================================================================

define(
    title="TestBook Pro — Orderbook Depth & Microstructure Analysis",
    position="onchart",
    axis=false
)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// ---------------------------------------------------------------------------

// --- Depth Analysis ---
var depthLevels = input(
    name="depthLevels",
    type="number",
    defaultValue=5,
    label="Depth Levels (L1-LN proxy)",
    constraints={min: 1, max: 20, step: 1},
    group="Depth Analysis"
)
var lookback = input(
    name="lookback",
    type="number",
    defaultValue=20,
    label="Smoothing Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Depth Analysis"
)
var decayFactor = input(
    name="decayFactor",
    type="number",
    defaultValue=0.8,
    label="Depth Decay Factor",
    constraints={min: 0.1, max: 1.0, step: 0.05},
    group="Depth Analysis"
)

// --- Z-Score ---
var zscoreLen = input(
    name="zscoreLen",
    type="number",
    defaultValue=20,
    label="Z-Score Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Z-Score Normalization"
)
var zscoreThreshold = input(
    name="zscoreThreshold",
    type="number",
    defaultValue=2.0,
    label="Z-Score Signal Threshold",
    constraints={min: 0.5, max: 4.0, step: 0.25},
    group="Z-Score Normalization"
)

// --- Pressure Bands ---
var bandWidth = input(
    name="bandWidth",
    type="number",
    defaultValue=1.0,
    label="Pressure Band Width (ATR mult)",
    constraints={min: 0.1, max: 5.0, step: 0.1},
    group="Pressure Bands"
)
var atrLen = input(
    name="atrLen",
    type="number",
    defaultValue=14,
    label="ATR Length",
    constraints={min: 5, max: 100, step: 1},
    group="Pressure Bands"
)

// --- Display ---
var showMidpoint = input(
    name="showMidpoint",
    type="boolean",
    defaultValue=true,
    label="Show Midpoint Line",
    group="Display"
)
var showBands = input(
    name="showBands",
    type="boolean",
    defaultValue=true,
    label="Show Pressure Bands",
    group="Display"
)
var showDepth = input(
    name="showDepth",
    type="boolean",
    defaultValue=true,
    label="Show Depth Histogram",
    group="Display"
)
var showZscore = input(
    name="showZscore",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Panel",
    group="Display"
)
var showSignals = input(
    name="showSignals",
    type="boolean",
    defaultValue=true,
    label="Show Extreme Signal Shapes",
    group="Display"
)
var showRegime = input(
    name="showRegime",
    type="boolean",
    defaultValue=true,
    label="Show Regime Label",
    group="Display"
)

// --- Colors ---
var bidColor = input(
    name="bidColor",
    type="color",
    defaultValue="#26a69a",
    label="Bid Pressure Color",
    group="Colors"
)
var askColor = input(
    name="askColor",
    type="color",
    defaultValue="#ef5350",
    label="Ask Pressure Color",
    group="Colors"
)
var midColor = input(
    name="midColor",
    type="color",
    defaultValue="#2962ff",
    label="Midpoint Color",
    group="Colors"
)
var imbalanceColor = input(
    name="imbalanceColor",
    type="color",
    defaultValue="#ff9800",
    label="Imbalance Signal Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)

// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries hi = bars.high
timeseries lo = bars.low
timeseries op = bars.open
timeseries vol = bars.volume

if (isnan(px[0]) || isnan(hi[0]) || isnan(lo[0]) || isnan(op[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. CORE CALCULATIONS
// ---------------------------------------------------------------------------

// True Range / ATR
timeseries prevClose = isnan(px[1]) ? px : px[1]
timeseries tr1 = hi - lo
timeseries tr2 = math.abs(hi - prevClose)
timeseries tr3 = math.abs(lo - prevClose)
timeseries trueRange = math.max(tr1, math.max(tr2, tr3))
timeseries atrV = sma(trueRange, atrLen)

// --- Orderbook Depth Proxy (multi-level) ---
// Since true LOB data is unavailable, we derive bid/ask pressure proxies
// from candle body position, wick distribution, and volume.
// Body position: +1 = close at high (max buyer aggression), -1 = close at low
// Wick analysis: upper wick = selling pressure, lower wick = buying pressure
// Volume-weighted: larger volume = more confident pressure signal

timeseries rangePx = (hi - lo) > 0 ? (hi - lo) : 1.0

// Normalized body position: -1 (bottom) to +1 (top)
timeseries bodyPos = (px - op) / rangePx

// Wick ratios: measure rejection
var upperWick = hi - math.max(px, op)
var lowerWick = math.min(px, op) - lo
var upperWickRatio = rangePx > 0 ? upperWick / rangePx : 0
var lowerWickRatio = rangePx > 0 ? lowerWick / rangePx : 0

// Bid/ask pressure components (volume-weighted)
// Bid pressure = buying aggression: positive body + lower wick rejection + volume
timeseries bidRaw = (bodyPos > 0 ? bodyPos : 0) + lowerWickRatio
// Ask pressure = selling aggression: negative body + upper wick rejection + volume
timeseries askRaw = (bodyPos < 0 ? -bodyPos : 0) + upperWickRatio

// Volume normalization: scale by relative volume
timeseries volSma = sma(vol, lookback)
timeseries volRatio = volSma > 0 ? vol / volSma : 1.0

// Smoothed bid/ask depth proxies
timeseries bidDepth = sma(bidRaw * volRatio, lookback)
timeseries askDepth = sma(askRaw * volRatio, lookback)

// Multi-level depth proxy (decaying weights for deeper levels)
// Level 1 = current bar, Level 2 = 1 bar ago, etc.
// Weighted sum: w_i = decayFactor^(i-1)
timeseries bidMultiLevel = 0.0
timeseries askMultiLevel = 0.0
timeseries weightSum = 0.0
for (var i = 0; i < depthLevels; i = i + 1) {
    var w = math.pow(decayFactor, i)
    var b = bidRaw[i] * volRatio[i]
    var a = askRaw[i] * volRatio[i]
    if (!isnan(b) && !isnan(a)) {
        bidMultiLevel = bidMultiLevel + w * b
        askMultiLevel = askMultiLevel + w * a
        weightSum = weightSum + w
    }
}
if (weightSum > 0) {
    bidMultiLevel = bidMultiLevel / weightSum
    askMultiLevel = askMultiLevel / weightSum
}

// --- Imbalance Score (Cont et al. 2014 OFI-inspired) ---
// Imbalance = (bid - ask) / (bid + ask), range [-1, +1]
// +1 = extreme buy imbalance, -1 = extreme sell imbalance
timeseries totalDepth = bidMultiLevel + askMultiLevel
var imbalanceScore = totalDepth > 0 ? (bidMultiLevel - askMultiLevel) / totalDepth : 0

// --- Z-Score Normalization (Zhao & Palomar 2018) ---
// z_t = (imbalance_t - mu_t) / sigma_t
timeseries imbMean = sma(imbalanceScore, zscoreLen)
timeseries imbStd = stddev(imbalanceScore, zscoreLen)
var zscore = imbStd > 0 ? (imbalanceScore - imbMean) / imbStd : 0

// Clamp z-score to avoid extreme outliers on startup
if (zscore > 4) {
    zscore = 4
}
if (zscore < -4) {
    zscore = -4
}

// --- Pressure Bands (ATR-scaled) ---
timeseries bandHalf = atrV * bandWidth / 2.0
timeseries upperBand = px + bandHalf
timeseries lowerBand = px - bandHalf

// ---------------------------------------------------------------------------
// 4. REGIME DETECTION
// ---------------------------------------------------------------------------
// Regime classification based on z-score and imbalance:
//   Buy-heavy: zscore > +threshold  (contagious buying, expect mean reversion)
//   Sell-heavy: zscore < -threshold (contagious selling, expect mean reversion)
//   Neutral: |zscore| <= threshold (balanced, no signal)
//
// Per Cartea et al. (2018): segmented into three regimes:
//   Sell-heavy: −1 to −1/3, Neutral: −1/3 to +1/3, Buy-heavy: +1/3 to +1

var regimeBuyHeavy = zscore > zscoreThreshold
var regimeSellHeavy = zscore < -zscoreThreshold
var regimeNeutral = !regimeBuyHeavy && !regimeSellHeavy

var regimeColor = regimeBuyHeavy ? bidColor : (regimeSellHeavy ? askColor : "#9e9e9e")
var regimeLabel = regimeBuyHeavy ? "BUY-HEAVY IMBALANCE" : (regimeSellHeavy ? "SELL-HEAVY IMBALANCE" : "BALANCED / NEUTRAL")

// ---------------------------------------------------------------------------
// 5. STATIC STATE: SIGNAL TRACKING
// ---------------------------------------------------------------------------
static barCount = 0
if (!isLiveUpdate) {
    barCount = barCount + 1
}

static lastZscoreCrossBar = 0
static lastZscoreCrossType = 0  // 1 = buy extreme, -1 = sell extreme

var buyExtreme = false
var sellExtreme = false

if (!isLiveUpdate) {
    // Buy extreme: zscore crosses above threshold from below
    if (zscore > zscoreThreshold && zscore[1] <= zscoreThreshold) {
        buyExtreme = true
        lastZscoreCrossBar = barCount
        lastZscoreCrossType = 1
    }
    // Sell extreme: zscore crosses below -threshold from above
    if (zscore < -zscoreThreshold && zscore[1] >= -zscoreThreshold) {
        sellExtreme = true
        lastZscoreCrossBar = barCount
        lastZscoreCrossType = -1
    }
}

// ---------------------------------------------------------------------------
// 6. PLOTTING
// ---------------------------------------------------------------------------

// --- Midpoint Line ---
if (showMidpoint) {
    plotLine(
        value=px,
        width=2,
        colors=[midColor],
        label=["Midpoint"],
        desc=["Current price midpoint reference. Serves as equilibrium for pressure band calculation."]
    )
}

// --- Pressure Bands (bid/ask zones) ---
if (showBands) {
    var bandFill = transparency(neutralColor, 15)
    plotLine(
        value=[upperBand, lowerBand],
        width=1,
        colors=[transparency(askColor, 30), transparency(bidColor, 30)],
        fill=bandFill,
        label=["Ask Pressure Zone", "Bid Pressure Zone"],
        desc=["Upper ATR band: ask-side pressure zone (" + bandWidth + "×ATR)", "Lower ATR band: bid-side pressure zone (" + bandWidth + "×ATR)"]
    )
    plotLine(
        value=upperBand,
        width=1,
        colors=[transparency(askColor, 50)],
        label=["Ask Band"],
        desc=["Upper pressure band boundary — potential resistance from ask imbalance."]
    )
    plotLine(
        value=lowerBand,
        width=1,
        colors=[transparency(bidColor, 50)],
        label=["Bid Band"],
        desc=["Lower pressure band boundary — potential support from bid imbalance."]
    )
}

// --- Depth Histogram (bid/ask depth proxy) ---
if (showDepth) {
    var depthBull = bidMultiLevel > askMultiLevel
    plotBar(
        value=bidMultiLevel * 100,
        colors=[transparency(bidColor, 60)],
        label=["Bid Depth"],
        desc=["Smoothed bid depth proxy (volume-weighted, multi-level, decay-scaled)."]
    )
    plotBar(
        value=-askMultiLevel * 100,
        colors=[transparency(askColor, 60)],
        label=["Ask Depth"],
        desc=["Smoothed ask depth proxy (volume-weighted, multi-level, decay-scaled). Negative for visual separation."]
    )
    hline(value=0, color="#ffffff20", width=1)
}

// --- Z-Score Panel ---
if (showZscore) {
    var zColor = zscore > 0 ? bidColor : askColor
    plotBar(
        value=zscore,
        colors=[transparency(zColor, 60)],
        label=["Z-Score"],
        desc=["Normalized orderbook imbalance z-score: (imbalance − μ) / σ over " + zscoreLen + " bars."]
    )
    hline(value=zscoreThreshold, color=transparency(bidColor, 40), width=1)
    hline(value=-zscoreThreshold, color=transparency(askColor, 40), width=1)
    hline(value=0, color="#ffffff20", width=1)
}

// --- Imbalance Line (on-chart) ---
plotLine(
    value=imbalanceScore * atrV + px,
    width=1,
    colors=[imbalanceColor],
    label=["Imbalance Offset"],
    desc=["Orderbook imbalance mapped to price offset: +ATR = buy-heavy, −ATR = sell-heavy."]
)

// --- Extreme Signal Shapes ---
if (showSignals) {
    if (buyExtreme) {
        plotShape(
            value=upperBand,
            shape="triangleup",
            colorIndex=imbalanceColor,
            width=5,
            label=["Buy Extreme"],
            desc=["Buy-heavy imbalance extreme detected: z-score = " + zscore + ". Expect mean reversion per Zhao & Palomar (2018)."]
        )
    }
    if (sellExtreme) {
        plotShape(
            value=lowerBand,
            shape="triangledown",
            colorIndex=imbalanceColor,
            width=5,
            label=["Sell Extreme"],
            desc=["Sell-heavy imbalance extreme detected: z-score = " + zscore + ". Expect mean reversion per Zhao & Palomar (2018)."]
        )
    }
}

// --- Regime Label (last bar only) ---
if (showRegime && isLastBar) {
    plotPriceLabel(
        price=hi,
        text=regimeLabel,
        type="callout",
        color="#ffffff",
        backgroundColor=regimeColor,
        size=10,
        fontWeight=700
    )
}

// --- Info Table (last bar only) ---
if (isLastBar) {
    var imbalancePct = math.round(imbalanceScore * 100, 2)
    var zText = zscore > zscoreThreshold ? "EXTREME BUY" : (zscore < -zscoreThreshold ? "EXTREME SELL" : "NORMAL")
    var zTextColor = zscore > zscoreThreshold ? bidColor : (zscore < -zscoreThreshold ? askColor : "#9e9e9e")

    plotTable(
        data=[
            ["TestBook Pro", regimeLabel],
            ["Imbalance", imbalancePct + "%"],
            ["Z-Score", zscore],
            ["Z-State", zText],
            ["Bid Depth", bidMultiLevel],
            ["Ask Depth", askMultiLevel],
            ["ATR", atrV]
        ],
        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
    )
}