MM Flow
FlowScripts

Perfected FlowScript

Orderbook Entropy

Orderbook Entropy Pro is indexed as 178_orderbook_entropy.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

17.7 KB

Lines

571

Native Signal Candidates

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

6/6 guarded

Entropy Up

line 477:9

Trigger

(showAlerts) && (crossUp)

Value

entropySmooth

Deps

crossUp:var, showAlerts:input

Entropy Down

line 487:9

Trigger

(showAlerts) && (crossDown)

Value

entropySmooth

Deps

crossDown:var, showAlerts:input

Retail Regime

line 497:9

Trigger

(showAlerts) && (enterHigh)

Value

entropySmooth

Deps

enterHigh:var, showAlerts:input

Institutional Regime

line 507:9

Trigger

(showAlerts) && (enterLow)

Value

entropySmooth

Deps

enterLow:var, showAlerts:input

Z-Extreme High

line 517:9

Trigger

(showAlerts) && (zExtremeUp)

Value

entropySmooth

Deps

showAlerts:input, zExtremeUp:var

Z-Extreme Low

line 527:9

Trigger

(showAlerts) && (zExtremeDown)

Value

entropySmooth

Deps

showAlerts:input, zExtremeDown:var

178_orderbook_entropy.flowscript

source path: kscripts/perfected/178_orderbook_entropy.flowscript · sha256:e6150b5f7848704cbce3c307e2545f8405c2eda7353b4ea0a6d6b718c55703d8

hash verified
//@version=2
// ============================================================================
// Orderbook Entropy Pro — Perfected Edition
// Author: D (@ddave334) | Enhanced by kScript Perfection Engineer
// Tags: FLOW, #orderbook, #entropy, #microstructure, #regime, #shannon
//
// Production-quality Shannon entropy analysis of orderbook depth distribution
// with z-score normalization, regime detection (high/low entropy), color coding,
// signal-line crossovers, and comprehensive fill / shape visualization.
// Distinguishes institutional (low-entropy, concentrated) from retail
// (high-entropy, dispersed) orderbook patterns.
//
// Research papers underpinning this design:
//  1. Mehl et al. (2019), "Fast Trading and the Virtue of Entropy: Evidence
//     from the Foreign Exchange Market": HFT positively correlated with entropy;
//     higher entropy brings prices closer to random walk.
//  2. Shternshis et al. (2022), "Measuring Market Efficiency: The Shannon Entropy
//     of High-Frequency Financial Time Series": genuine entropy requires filtering
//     seasonality, clustering, and microstructure noise.
//  3. Kızılersü et al. (2016), "Universal Behaviour in the Stock Market":
//     orderbook changes follow left-truncated Weibull with universal shape
//     parameter corresponding to maximum entropy.
//  4. Lehalle & Laruelle (2018), "Market Microstructure in Practice": entropy
//     measurements for understanding market participant behavior.
//  5. Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
//     Order Book Signals": three-regime segmentation model.
// ============================================================================

define(
    title="Orderbook Entropy Pro",
    position="offchart",
    axis=true
)

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

// --- Depth Configuration ---
var depth = input(
    name="depth",
    type="number",
    defaultValue=10,
    label="Depth Levels",
    constraints={min: 2, max: 50, step: 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.85,
    label="Weight Decay Factor",
    constraints={min: 0.0, max: 1.0, step: 0.05},
    group="Depth"
)

// --- Smoothing ---
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=5,
    label="EMA Smoothing Length",
    constraints={min: 1, max: 50, step: 1},
    group="Smoothing"
)
var signalLen = input(
    name="signalLen",
    type="number",
    defaultValue=14,
    label="Signal SMA Length",
    constraints={min: 2, max: 50, 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 zThresh = input(
    name="zThresh",
    type="number",
    defaultValue=2.0,
    label="Z-Score Threshold",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Z-Score"
)

// --- Regime Thresholds ---
var lowEntropyThresh = input(
    name="lowEntropyThresh",
    type="number",
    defaultValue=0.35,
    label="Low Entropy Threshold (institutional)",
    constraints={min: 0.0, max: 0.8, step: 0.05},
    group="Regime"
)
var highEntropyThresh = input(
    name="highEntropyThresh",
    type="number",
    defaultValue=0.65,
    label="High Entropy Threshold (retail)",
    constraints={min: 0.2, max: 1.0, step: 0.05},
    group="Regime"
)

// --- Display ---
var showSignal = input(
    name="showSignal",
    type="boolean",
    defaultValue=true,
    label="Show Signal Line",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show Entropy/Signal Fill",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Entropy Change Histogram",
    group="Display"
)
var showBidAsk = input(
    name="showBidAsk",
    type="boolean",
    defaultValue=true,
    label="Show Bid/Ask Entropy Differential",
    group="Display"
)
var showZScore = input(
    name="showZScore",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Band",
    group="Display"
)
var showAlerts = input(
    name="showAlerts",
    type="boolean",
    defaultValue=true,
    label="Show Alert Shapes",
    group="Display"
)

// --- Colors ---
var lowEntropyColor = input(
    name="lowEntropyColor",
    type="color",
    defaultValue="#00e676",
    label="Low Entropy (Institutional) Color",
    group="Colors"
)
var highEntropyColor = input(
    name="highEntropyColor",
    type="color",
    defaultValue="#ff1744",
    label="High Entropy (Retail) Color",
    group="Colors"
)
var neutralEntropyColor = input(
    name="neutralEntropyColor",
    type="color",
    defaultValue="#ffa726",
    label="Neutral Entropy Color",
    group="Colors"
)
var signalColor = input(
    name="signalColor",
    type="color",
    defaultValue="#42a5f5",
    label="Signal Line Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. 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
}

// -----------------------------------------------------------------------------
// 3. BID ENTROPY (Shannon H = -Σ p_i log(p_i))
// -----------------------------------------------------------------------------
timeseries bidTotal = 0.0
var i = 1
while (i <= depth) {
    timeseries v = sumBids(book, i)
    bidTotal = bidTotal + v
    i = i + 1
}

timeseries bidEntropy = 0.0
i = 1
while (i <= depth) {
    timeseries v = sumBids(book, i)
    timeseries p = bidTotal > 0 ? v / bidTotal : 0
    timeseries term = (p > 0) ? -p * math.log(p) : 0
    bidEntropy = bidEntropy + term
    i = i + 1
}

// -----------------------------------------------------------------------------
// 4. ASK ENTROPY
// -----------------------------------------------------------------------------
timeseries askTotal = 0.0
i = 1
while (i <= depth) {
    timeseries v = sumAsks(book, i)
    askTotal = askTotal + v
    i = i + 1
}

timeseries askEntropy = 0.0
i = 1
while (i <= depth) {
    timeseries v = sumAsks(book, i)
    timeseries p = askTotal > 0 ? v / askTotal : 0
    timeseries term = (p > 0) ? -p * math.log(p) : 0
    askEntropy = askEntropy + term
    i = i + 1
}

// -----------------------------------------------------------------------------
// 5. COMBINED ENTROPY with depth-weighted distribution
// -----------------------------------------------------------------------------
// Combined entropy: bids + asks as one distribution, with optional depth decay

timeseries totalVol = bidTotal + askTotal
timeseries combinedEntropy = 0.0
i = 1
while (i <= depth) {
    timeseries bv = sumBids(book, i)
    timeseries av = sumAsks(book, i)
    timeseries w = useDepthWeighting ? math.pow(weightDecay, i - 1) : 1.0
    timeseries bp = totalVol > 0 ? (bv / totalVol) * w : 0
    timeseries ap = totalVol > 0 ? (av / totalVol) * w : 0
    combinedEntropy = combinedEntropy
        + (bp > 0 ? -bp * math.log(bp) : 0)
        + (ap > 0 ? -ap * math.log(ap) : 0)
    i = i + 1
}

// Maximum entropy for uniform distribution over 2*depth levels
timeseries maxEntropy = math.log(2.0 * depth)
timeseries normEntropy = combinedEntropy / math.max(maxEntropy, 0.0001)

// Clamp normalized entropy to [0,1]
if (normEntropy > 1.0) {
    normEntropy = 1.0
}
if (normEntropy < 0.0) {
    normEntropy = 0.0
}

// -----------------------------------------------------------------------------
// 6. CONCENTRATION (Herfindahl-style inverse HHI)
// -----------------------------------------------------------------------------
timeseries bidHHI = 0.0
timeseries askHHI = 0.0
i = 1
while (i <= depth) {
    timeseries bv = sumBids(book, i)
    timeseries av = sumAsks(book, i)
    timeseries bp = bidTotal > 0 ? bv / bidTotal : 0
    timeseries ap = askTotal > 0 ? av / askTotal : 0
    bidHHI = bidHHI + bp * bp
    askHHI = askHHI + ap * ap
    i = i + 1
}
timeseries concentration = 1.0 - (bidHHI + askHHI) / 2.0

// -----------------------------------------------------------------------------
// 7. SMOOTHING & SIGNAL
// -----------------------------------------------------------------------------
timeseries entropySmooth = ema(source=normEntropy, period=smoothLen)
timeseries concSmooth = ema(source=concentration, period=smoothLen)
timeseries entropySignal = sma(source=entropySmooth, period=signalLen)

// Entropy change histogram
timeseries entropyHist = entropySmooth - entropySignal

// -----------------------------------------------------------------------------
// 8. Z-SCORE NORMALIZATION
// -----------------------------------------------------------------------------
var entropyMean = sma(source=entropySmooth, period=zLookback)
var entropyStd = stddev(source=entropySmooth, period=zLookback)
var entropyZ = entropyStd > 0 ? (entropySmooth - entropyMean) / entropyStd : 0.0

// -----------------------------------------------------------------------------
// 9. REGIME DETECTION (Cartea et al. 2018 three-segment model)
// -----------------------------------------------------------------------------
// Low entropy  = institutional (concentrated liquidity)
// High entropy = retail (dispersed liquidity)
// Neutral      = mixed participant structure

var regime = 0      // 0 = neutral, 1 = high entropy (retail), -1 = low entropy (institutional)
var extremeRegime = 0  // 0 = normal, 1 = extreme retail, -1 = extreme institutional

if (entropySmooth >= highEntropyThresh) {
    regime = 1
} else if (entropySmooth <= lowEntropyThresh) {
    regime = -1
}

if (entropyZ >= zThresh) {
    extremeRegime = 1
} else if (entropyZ <= -zThresh) {
    extremeRegime = -1
}

var regimeColor = regime == 1 ? highEntropyColor : (regime == -1 ? lowEntropyColor : neutralEntropyColor)

// -----------------------------------------------------------------------------
// 10. STATIC STATE TRACKING (Session-level persistence)
// -----------------------------------------------------------------------------
static lastRegime = 0
static regimeChangeCount = 0
static sessionHighEntropy = -999999.0
static sessionLowEntropy = 999999.0
static extremeHighCount = 0
static extremeLowCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    lastBarIndex = currentBarIndex

    if (entropySmooth > sessionHighEntropy) {
        sessionHighEntropy = entropySmooth
    }
    if (entropySmooth < sessionLowEntropy) {
        sessionLowEntropy = entropySmooth
    }

    if (lastRegime != regime) {
        lastRegime = regime
        regimeChangeCount = regimeChangeCount + 1
    }

    if (extremeRegime == 1) {
        extremeHighCount = extremeHighCount + 1
    } else if (extremeRegime == -1) {
        extremeLowCount = extremeLowCount + 1
    }
}

// -----------------------------------------------------------------------------
// 11. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Signal crossovers
var crossUp = entropySmooth > entropySignal && entropySmooth[1] <= entropySignal[1]
var crossDown = entropySmooth < entropySignal && entropySmooth[1] >= entropySignal[1]

// Regime transitions
var enterHigh = entropySmooth >= highEntropyThresh && entropySmooth[1] < highEntropyThresh
var exitHigh = entropySmooth < highEntropyThresh && entropySmooth[1] >= highEntropyThresh
var enterLow = entropySmooth <= lowEntropyThresh && entropySmooth[1] > lowEntropyThresh
var exitLow = entropySmooth > lowEntropyThresh && entropySmooth[1] <= lowEntropyThresh

// Z-score extremes
var zExtremeUp = entropyZ >= zThresh && entropyZ[1] < zThresh
var zExtremeDown = entropyZ <= -zThresh && entropyZ[1] > -zThresh

// -----------------------------------------------------------------------------
// 12. PLOTTING
// -----------------------------------------------------------------------------

// --- Reference lines ---
hline(value=0.5, color="#ffffff30", width=1)
hline(value=1.0, color=transparency(lowEntropyColor, 70), width=1)
hline(value=0.0, color=transparency(highEntropyColor, 70), width=1)

// --- Regime threshold lines ---
hline(value=highEntropyThresh, color=transparency(highEntropyColor, 50), width=1)
hline(value=lowEntropyThresh, color=transparency(lowEntropyColor, 50), width=1)

// --- Z-Score band (optional fill) ---
if (showZScore) {
    var zUpper = entropyMean + zThresh * entropyStd
    var zLower = entropyMean - zThresh * entropyStd
    plotLine(
        value=[zUpper, zLower],
        width=1,
        colors=[transparency(highEntropyColor, 15), transparency(lowEntropyColor, 15)],
        fill=true,
        label=["Z+" + zThresh, "Z-" + zThresh],
        desc=["Z-score upper band", "Z-score lower band"]
    )
}

// --- Entropy Line (regime-colored) ---
plotLine(
    value=entropySmooth,
    width=2,
    colors=[regimeColor],
    label=["Orderbook Entropy"],
    desc=["Normalized Shannon entropy of bid/ask distribution (regime-colored)"]
)

// --- Signal Line ---
if (showSignal) {
    plotLine(
        value=entropySignal,
        width=1,
        colors=[signalColor],
        label=["Entropy Signal"],
        desc=["SMA of normalized entropy (" + signalLen + ")"]
    )
}

// --- Entropy vs Signal Fill ---
if (showFill && showSignal) {
    var signalBull = entropySmooth > entropySignal
    plotLine(
        value=[entropySmooth, entropySignal],
        width=1,
        colors=[transparency(lowEntropyColor, 20), transparency(highEntropyColor, 20)],
        colorIndex=signalBull ? 0 : 1,
        fill=true,
        label=["Entropy", "Signal"],
        desc=["Fill between entropy and signal SMA"]
    )
}

// --- Entropy Change Histogram ---
if (showHistogram) {
    var histBull = entropyHist >= 0
    plotBar(
        value=entropyHist,
        colors=[transparency(lowEntropyColor, 60), transparency(highEntropyColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["Entropy Change"],
        desc=["Histogram of entropy minus signal SMA"]
    )
}

// --- Bid/Ask Entropy Differential ---
if (showBidAsk) {
    var bidAskNorm = bidEntropy - askEntropy
    var bidAskSmooth = ema(source=bidAskNorm, period=smoothLen)
    plotLine(
        value=bidAskSmooth,
        width=1,
        colors=[transparency(signalColor, 70)],
        label=["Bid-Ask Entropy Δ"],
        desc=["Bid entropy minus ask entropy (smoothed)"]
    )
}

// --- Regime Transition Shapes ---
if (showAlerts) {
    if (crossUp) {
        plotShape(
            value=entropySmooth,
            shape="triangleup",
            color=lowEntropyColor,
            width=2,
            label=["Entropy Up"],
            desc=["Entropy crossed above signal SMA"]
        )
    }
    if (crossDown) {
        plotShape(
            value=entropySmooth,
            shape="triangledown",
            color=highEntropyColor,
            width=2,
            label=["Entropy Down"],
            desc=["Entropy crossed below signal SMA"]
        )
    }
    if (enterHigh) {
        plotShape(
            value=entropySmooth,
            shape="diamond",
            color=highEntropyColor,
            width=3,
            label=["Retail Regime"],
            desc=["High entropy regime entered (retail/dispersed)"]
        )
    }
    if (enterLow) {
        plotShape(
            value=entropySmooth,
            shape="diamond",
            color=lowEntropyColor,
            width=3,
            label=["Institutional Regime"],
            desc=["Low entropy regime entered (institutional/concentrated)"]
        )
    }
    if (zExtremeUp) {
        plotShape(
            value=entropySmooth,
            shape="xcross",
            color=highEntropyColor,
            width=2,
            label=["Z-Extreme High"],
            desc=["Entropy Z-score exceeded +" + zThresh]
        )
    }
    if (zExtremeDown) {
        plotShape(
            value=entropySmooth,
            shape="xcross",
            color=lowEntropyColor,
            width=2,
            label=["Z-Extreme Low"],
            desc=["Entropy Z-score exceeded -" + zThresh]
        )
    }
}

// -----------------------------------------------------------------------------
// 13. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regime == 1 ? "RETAIL (High)" : (regime == -1 ? "INST (Low)" : "NEUTRAL")
    var regimeTextColor = regime == 1 ? highEntropyColor : (regime == -1 ? lowEntropyColor : neutralEntropyColor)

    plotTable(
        data=[
            ["Entropy Pro — Perfected", regimeText],
            ["Entropy", entropySmooth[0]],
            ["Signal", entropySignal[0]],
            ["Z-Score", entropyZ[0]],
            ["Concentration", concSmooth[0]],
            ["Session High", sessionHighEntropy],
            ["Session Low", sessionLowEntropy],
            ["Regime Changes", regimeChangeCount],
            ["Extreme High Events", extremeHighCount],
            ["Extreme Low Events", extremeLowCount]
        ],
        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
    )
}