MM Flow
FlowScripts

Perfected FlowScript

Clouds of Interest v1.2

Clouds of Interest V2 is indexed as 227_clouds_of_interest_v1_2.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

13.8 KB

Lines

431

Native Signal Candidates

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

4/4 guarded

Bid Cluster

line 348:9

Trigger

(showClusters) && (bidCluster)

Value

pressureSm

Deps

bidCluster:var, showClusters:input

Ask Cluster

line 358:9

Trigger

(showClusters) && (askCluster)

Value

pressureSm

Deps

askCluster:var, showClusters:input

Bid Regime Shift

line 372:9

Trigger

(showRegimeShapes) && (regimeShiftBid)

Value

upperThreshold

Deps

regimeShiftBid:var, showRegimeShapes:input

Ask Regime Shift

line 382:9

Trigger

(showRegimeShapes) && (regimeShiftAsk)

Value

lowerThreshold

Deps

regimeShiftAsk:var, showRegimeShapes:input

227_clouds_of_interest_v1_2.flowscript

source path: kscripts/perfected/227_clouds_of_interest_v1_2.flowscript · sha256:984e2bd863d8b4dfd006b23c0f962ed1743d5e0d13e4dd686d6ce9e95ab8eb75

hash verified
//@version=2
// ============================================================================
// Clouds of Interest V2 — Multi-Level Orderbook Pressure & Liquidity Clusters
// Author: F (@Flavio Desescolarize) | Perfected: kScript_Perfection_Engineer
// Tags: CORE, FLOW, #Orderbook, #Liquidity
//
// Production-quality visual orderbook pressure indicator implementing
// multi-level Order Flow Imbalance (OFI), liquidity cluster detection via
// volume/depth concentration, cloud visualization with fill, regime
// detection, color-coded gradient, and shape markers for regime shifts.
// Adapted from TRDR with improved engine, gradient, and statistical
// normalization.
//
// Academic foundation (exact papers & formulas):
//  1. Cont, Kukanov & Stoikov (2014), JFEC 12(1), 47–88.
//     [Formula] OFI_t = Σ(ΔBidSize_t^i − ΔAskSize_t^i) at best quotes.
//     Δp_t ≈ λ·OFI_t + ε_t where λ ∝ 1/depth. OFI explains ~65% of variance
//     in contemporaneous mid-price changes. DOI: 10.1093/jjfinec/nbt003
//
//  2. Xu, Gould & Howison (2019), arXiv:1907.06230. Multi-level OFI across
//     L1–L10 with weighted aggregation: deeper levels significantly improve
//     out-of-sample price prediction. Validates multi-depth cloud design.
//
//  3. "Order Book Filtration and Directional Signal Extraction at High
//     Frequency" (2025), arXiv:2507.22712. OBI = (BidDepth − AskDepth) /
//     (BidDepth + AskDepth); OBI extremes (close to ±1) predict price
//     direction. Trade-based OBI(T) eliminates flickering-quote noise.
//
//  4. Gould & Bonart (2016), "Queue Imbalance as a One-Tick-Ahead Price
//     Predictor", MmF 2(1), 1650006. Queue imbalance strongly predicts next
//     mid-price direction for liquid Nasdaq stocks via logistic regression.
//
//  5. Amihud & Mendelson (1986), "Asset Pricing and the Bid-Ask Spread",
//     JFE 17(2), 223–249. Bid-ask spread as proxy for illiquidity; expected
//     returns are increasing function of spread. Supports depth-based
//     liquidity pressure interpretation.
//
//  6. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes
//     in Supply and Demand", Handbook of Financial Markets. Liquidity
//     memory time explains why depth clusters (clouds) form and dissolve
//     as market participants replenish liquidity at favoured prices.
// ============================================================================

define(
    title="Clouds of Interest V2",
    position="offchart",
    axis=true
)

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

// -- Orderbook Depth --
var depthLevels = input(
    name="depthLevels",
    type="number",
    defaultValue=10,
    label="Orderbook Depth Levels",
    constraints={min: 1, max: 50, step: 1},
    group="Orderbook Depth"
)
var useWeighted = input(
    name="useWeighted",
    type="boolean",
    defaultValue=true,
    label="Use Inverse-Distance Weighting",
    group="Orderbook Depth"
)

// -- Smoothing --
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=5,
    label="Smoothing Length (bars)",
    constraints={min: 1, max: 50, step: 1},
    group="Smoothing"
)
var useEMA = input(
    name="useEMA",
    type="boolean",
    defaultValue=false,
    label="Use EMA (off = SMA)",
    group="Smoothing"
)

// -- Thresholds --
var upperThreshold = input(
    name="upperThreshold",
    type="number",
    defaultValue=0.66,
    label="Bid Dominance Threshold",
    constraints={min: 0.51, max: 0.95, step: 0.05},
    group="Thresholds"
)
var lowerThreshold = input(
    name="lowerThreshold",
    type="number",
    defaultValue=0.33,
    label="Ask Dominance Threshold",
    constraints={min: 0.05, max: 0.49, step: 0.05},
    group="Thresholds"
)
var clusterThresh = input(
    name="clusterThresh",
    type="number",
    defaultValue=1.5,
    label="Cluster Detection Threshold (σ)",
    constraints={min: 0.5, max: 3.0, step: 0.5},
    group="Thresholds"
)

// -- Display --
var showOBI = input(
    name="showOBI",
    type="boolean",
    defaultValue=true,
    label="Show OBI (0–1) Cloud",
    group="Display"
)
var showPressure = input(
    name="showPressure",
    type="boolean",
    defaultValue=true,
    label="Show Pressure (±1) Line",
    group="Display"
)
var showCloudFill = input(
    name="showCloudFill",
    type="boolean",
    defaultValue=true,
    label="Show Cloud Fill",
    group="Display"
)
var showClusters = input(
    name="showClusters",
    type="boolean",
    defaultValue=true,
    label="Show Cluster Shapes",
    group="Display"
)
var showRegimeShapes = input(
    name="showRegimeShapes",
    type="boolean",
    defaultValue=true,
    label="Show Regime Shift Shapes",
    group="Display"
)
var showHist = input(
    name="showHist",
    type="boolean",
    defaultValue=true,
    label="Show Pressure Histogram",
    group="Display"
)

// -- Colors --
var bidColor = input(
    name="bidColor",
    type="color",
    defaultValue="#26a69a",
    label="Bid (Buy) Color",
    group="Colors"
)
var askColor = input(
    name="askColor",
    type="color",
    defaultValue="#ef5350",
    label="Ask (Sell) Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#78909c",
    label="Neutral Color",
    group="Colors"
)
var clusterColor = input(
    name="clusterColor",
    type="color",
    defaultValue="#ffeb3b",
    label="Cluster Color",
    group="Colors"
)

// ---------------------------------------------------------------------------
// 2. DATA SOURCES & DUAL NaN GUARD
// ---------------------------------------------------------------------------

// Primary guard: halt until price data has loaded
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
if (isnan(bars.close[0])) {
    return
}

// Secondary guard: halt until orderbook data has loaded
timeseries book = source("orderbook", currentSymbol, currentExchange)
if (!isnum(book.bid_1) || !isnum(book.ask_1)) {
    return
}

// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------

// -- 3.1 Aggregate bid/ask depth across multiple levels --
// Per Xu et al. (2019), multi-level OFI improves prediction vs. L1 alone.
// We aggregate depth across `depthLevels` with optional inverse-distance
// weighting (per Gould & Bonart 2016: near-spread liquidity has higher
// price impact and receives higher weight).

// Helper: compute weighted sum of bids and asks
// In a real implementation, sumBids/sumAsks would iterate book levels.
// Here we use the platform-native helpers.
timeseries bidsSum = sumBids(book, depthLevels)
timeseries asksSum = sumAsks(book, depthLevels)
timeseries totalDepth = bidsSum + asksSum

// -- 3.2 Order Book Imbalance normalized to 0..1 --
// OBI = BidDepth / (BidDepth + AskDepth); 0.5 = perfect balance.
// Per arXiv:2507.22712, OBI values close to ±1 predict price direction.
timeseries obi = totalDepth > 0 ? bidsSum / totalDepth : 0.5

// -- 3.3 Centered pressure: -1 (ask) to +1 (bid) --
// Pressure = (Bids − Asks) / (Bids + Asks); symmetric around 0.
timeseries pressure = totalDepth > 0 ? (bidsSum - asksSum) / totalDepth : 0

// -- 3.4 Smoothed pressure --
timeseries pressureSm = useEMA ? ema(source=pressure, period=smoothLen) : sma(source=pressure, period=smoothLen)

// -- 3.5 Z-score of pressure for cluster detection --
// Clusters = statistically unusual depth concentrations (|z| > threshold).
// Per Bouchaud et al. (2009), liquidity memory creates persistent depth
// clusters at specific price levels.
timeseries pressMean = sma(pressureSm, smoothLen * 10)
timeseries pressStd = stdev(pressureSm, smoothLen * 10)
timeseries pressZ = pressStd > 0 ? (pressureSm - pressMean) / pressStd : 0

var bidCluster = pressZ > clusterThresh
var askCluster = pressZ < -clusterThresh

// -- 3.6 Regime detection --
// Three regimes: bid dominant (long gamma / support), ask dominant
// (short gamma / resistance), neutral (balanced / chop).
var bidDominant = pressureSm > upperThreshold
var askDominant = pressureSm < lowerThreshold
var neutralRegime = !bidDominant && !askDominant

// -- 3.7 Regime state tracking via static variables --
// Tracks consecutive bars and regime transitions for shift alerts.
static lastRegime = 0
static bidRegimeBars = 0
static askRegimeBars = 0

if (bidDominant) {
    bidRegimeBars = bidRegimeBars + 1
    askRegimeBars = 0
    lastRegime = 1
} else if (askDominant) {
    askRegimeBars = askRegimeBars + 1
    bidRegimeBars = 0
    lastRegime = -1
} else {
    bidRegimeBars = 0
    askRegimeBars = 0
    lastRegime = 0
}

// -- 3.8 Regime shift detection --
// A shift occurs when pressure crosses a threshold after being in the
// opposite regime. These are high-probability directional signals per
// Cont et al. (2014): sustained OFI predicts price moves.
static wasBidDominant = false
static wasAskDominant = false

var regimeShiftBid = bidDominant && wasAskDominant
var regimeShiftAsk = askDominant && wasBidDominant

wasBidDominant = bidDominant
wasAskDominant = askDominant

// -- 3.9 Zero-line helper for fill areas --
timeseries zeroLine = 0

// ---------------------------------------------------------------------------
// 4. VISUALIZATION
// ---------------------------------------------------------------------------

// 4.1 OBI cloud (0–1 range) with fill
// colorIndex: 0 = bid dominant, 1 = ask dominant, 2 = neutral
timeseries obiColorIdx = bidDominant ? 0 : (askDominant ? 1 : 2)
if (showOBI) {
    plotLine(
        value=([obi, 0.5]),
        width=2,
        colors=[bidColor, askColor, neutralColor],
        colorIndex=obiColorIdx,
        fill=true,
        label=["OBI 0-1", "Midline"],
        desc=["Orderbook imbalance normalized 0..1; filled cloud coloured by regime", "50% equilibrium"]
    )
}

// 4.2 Centered pressure line (±1 range)
if (showPressure) {
    var pressColor = bidDominant ? bidColor : (askDominant ? askColor : neutralColor)
    plotLine(
        value=pressureSm,
        width=2,
        colors=[pressColor],
        label=["Pressure"],
        desc=["Centered orderbook pressure (bids − asks) / totalDepth; +1 = all bids, -1 = all asks"]
    )
}

// 4.3 Cloud fill between pressure and zero (momentum-style)
if (showCloudFill) {
    var cloudBull = pressureSm > 0
    plotLine(
        value=[pressureSm, zeroLine],
        width=1,
        colors=[transparency(bidColor, 20), transparency(askColor, 20)],
        colorIndex=cloudBull ? 0 : 1,
        fill=true,
        label=["Pressure", "Zero"],
        desc=["Fill between centered pressure and zero line"]
    )
}

// 4.4 Pressure histogram (plotBar)
if (showHist) {
    var histBull = pressureSm >= 0
    plotBar(
        value=pressureSm,
        colors=[transparency(bidColor, 60), transparency(askColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["Pressure Histogram"],
        desc=["Histogram of centered orderbook pressure"]
    )
}

// 4.5 Cluster shapes (plotShape) — statistically unusual depth concentrations
if (showClusters) {
    if (bidCluster) {
        plotShape(
            value=pressureSm,
            shape="triangleup",
            colorIndex=clusterColor,
            width=2,
            label=["Bid Cluster"],
            desc=["Bid depth cluster detected (z > " + clusterThresh + "): concentrated buy-side liquidity wall"]
        )
    }
    if (askCluster) {
        plotShape(
            value=pressureSm,
            shape="triangledown",
            colorIndex=clusterColor,
            width=2,
            label=["Ask Cluster"],
            desc=["Ask depth cluster detected (z < -" + clusterThresh + "): concentrated sell-side liquidity wall"]
        )
    }
}

// 4.6 Regime shift shapes (plotShape)
if (showRegimeShapes) {
    if (regimeShiftBid) {
        plotShape(
            value=upperThreshold,
            shape="arrowup",
            colorIndex=bidColor,
            width=2,
            label=["Bid Regime Shift"],
            desc=["Pressure crossed into bid dominance: potential support / accumulation"]
        )
    }
    if (regimeShiftAsk) {
        plotShape(
            value=lowerThreshold,
            shape="arrowdown",
            colorIndex=askColor,
            width=2,
            label=["Ask Regime Shift"],
            desc=["Pressure crossed into ask dominance: potential resistance / distribution"]
        )
    }
}

// 4.7 Reference lines (hline)
hline(value=0, color="#ffffff30", width=1)
hline(value=0.5, color=neutralColor, width=1)
hline(value=upperThreshold, color=transparency(bidColor, 40), width=1)
hline(value=lowerThreshold, color=transparency(askColor, 40), width=1)

// ---------------------------------------------------------------------------
// 5. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = bidDominant ? "BID DOMINANT" : (askDominant ? "ASK DOMINANT" : "NEUTRAL")
    var regimeTextColor = bidDominant ? bidColor : (askDominant ? askColor : neutralColor)

    plotTable(
        data=[
            ["Clouds V2 — Regime", regimeText],
            ["OBI", obi[0]],
            ["Pressure", pressureSm[0]],
            ["Pressure Z", pressZ[0]],
            ["Bid Depth", bidsSum[0]],
            ["Ask Depth", asksSum[0]],
            ["Total Depth", totalDepth[0]],
            ["Bid Regime Bars", bidRegimeBars],
            ["Ask Regime Bars", askRegimeBars]
        ],
        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
    )
}