MM Flow
FlowScripts

Perfected FlowScript

clouds of interest

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

14.0 KB

Lines

444

Native Signal Candidates

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

5/5 guarded

Vol Cluster

line 382:5

Trigger

(showVolClusters && isVolCluster)

Value

px

Deps

isVolCluster:var, showVolClusters:input

Cloud Breakout

line 404:9

Trigger

(showShapes) && (breakoutUp)

Value

px

Deps

breakoutUp:var, showShapes:input

Cloud Breakdown

line 414:9

Trigger

(showShapes) && (breakoutDn)

Value

px

Deps

breakoutDn:var, showShapes:input

Mid Cross Up

line 424:9

Trigger

(showShapes) && (midCrossUp)

Value

midPx

Deps

midCrossUp:var, showShapes:input

Mid Cross Down

line 434:9

Trigger

(showShapes) && (midCrossDn)

Value

midPx

Deps

midCrossDn:var, showShapes:input

303_clouds_of_interest.flowscript

source path: kscripts/perfected/303_clouds_of_interest.flowscript · sha256:3901cc1269be2998438c9ff50e0a5b4e3cad12fc52b18e13a93740f9e7774af1

hash verified
//@version=2
// ============================================================================
// Clouds of Interest V2 — Production-Quality Liquidity Cloud Indicator
// Author: F (@Flavio Desescolarize Diretas ja! Nunca tivemos!)  |  Perfected by: kScript Perfection Engineer
// Tags: FLOW, #orderbook, #liquidity, #clouds, #support, #resistance
//
// Visualizes order book pressure as dynamic liquidity clouds — adaptive
// support/resistance zones driven by volume clustering, orderbook imbalance,
// and volatility-adjusted banding. The clouds represent areas of concentrated
// orderbook interest that act as structural support/resistance zones.
//
// FORMULA FOUNDATION:
// 1. Order Book Imbalance Proxy: OBI = (BidVol − AskVol) / (BidVol + AskVol)
//    per Cont, Kukanov & Stoikov (2014) and Order Book Filtration (2025).
// 2. Volume Liquidity Clustering: σ(V) threshold clustering to identify
//    significant volume accumulation zones per Paddrik et al. (2014).
// 3. Cloud Thickness: ATR-adaptive bands per Bollinger (2001) with regime
//    coloring based on imbalance direction.
// 4. Dynamic Color Coding: Support (bid-heavy) vs Resistance (ask-heavy)
//    regimes per Cartea, Donnelly & Jaimungal (2018) three-segment model.
//
// RESEARCH BASIS:
//  • Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//    J. Financial Econometrics 12(1), 47–88. OFI = Σ(E_i × ΔP_i); linear
//    price-impact with slope ∝ 1/depth.
//  • Order Book Filtration and Directional Signal Extraction (2025).
//    OBI = (BidVol − AskVol)/(BidVol + AskVol) as regime indicator.
//  • Paddrik, Hayes, Scherer & Beling (2014), "Effects of Limit Order Book
//    Information Level on Market Stability Metrics". OBWA using L1-L10 depth;
//    deeper book information improves stability assessment.
//  • Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
//    Order Book Signals", Appl. Math. Finance 25(1), 1–35. Three-regime
//    segmentation: Sell-heavy, Neutral, Buy-heavy.
//  • Bollinger (2001), "Bollinger on Bollinger Bands". ATR/volatility bands
//    as dynamic support/resistance envelopes.
// ============================================================================

define(
    title="Clouds of Interest V2",
    position="onchart",
    axis=false
)

// ------------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ------------------------------------------------------------------------------

// --- Cloud Configuration ---
var lookback = input(
    name="lookback",
    type="number",
    defaultValue=20,
    label="Pressure Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Cloud"
)
var depth = input(
    name="depth",
    type="number",
    defaultValue=10,
    label="Book Depth (%)",
    constraints={min: 1, max: 50, step: 1},
    group="Cloud"
)
var atrMult = input(
    name="atrMult",
    type="number",
    defaultValue=1.5,
    label="Cloud Thickness (ATR mult)",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Cloud"
)
var cloudWidth = input(
    name="cloudWidth",
    type="number",
    defaultValue=2,
    label="Cloud Border Width",
    constraints={min: 1, max: 5, step: 1},
    group="Cloud"
)

// --- Volume Clustering ---
var volCluster = input(
    name="volCluster",
    type="boolean",
    defaultValue=true,
    label="Enable Volume Cluster Detection",
    group="Volume"
)
var volLookback = input(
    name="volLookback",
    type="number",
    defaultValue=20,
    label="Volume Cluster Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Volume"
)
var volSigmaThresh = input(
    name="volSigmaThresh",
    type="number",
    defaultValue=2.0,
    label="Volume Sigma Threshold",
    constraints={min: 1.0, max: 4.0, step: 0.1},
    group="Volume"
)

// --- Orderbook ---
var useOrderbook = input(
    name="useOrderbook",
    type="boolean",
    defaultValue=true,
    label="Use Real Orderbook Data",
    group="Orderbook"
)
var obDepth1 = input(
    name="obDepth1",
    type="number",
    defaultValue=1.0,
    label="OB Depth Band 1 (%)",
    constraints={min: 0.1, max: 50.0, step: 0.1},
    group="Orderbook"
)
var obDepth2 = input(
    name="obDepth2",
    type="number",
    defaultValue=5.0,
    label="OB Depth Band 2 (%)",
    constraints={min: 0.1, max: 50.0, step: 0.1},
    group="Orderbook"
)
var obDepth3 = input(
    name="obDepth3",
    type="number",
    defaultValue=10.0,
    label="OB Depth Band 3 (%)",
    constraints={min: 0.1, max: 50.0, step: 0.1},
    group="Orderbook"
)

// --- Display ---
var showBands = input(
    name="showBands",
    type="boolean",
    defaultValue=true,
    label="Show Cloud Bands",
    group="Display"
)
var showMidline = input(
    name="showMidline",
    type="boolean",
    defaultValue=true,
    label="Show Cloud Midline",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Breakout Shapes",
    group="Display"
)
var showVolClusters = input(
    name="showVolClusters",
    type="boolean",
    defaultValue=true,
    label="Show Volume Cluster Markers",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show Cloud Fill",
    group="Display"
)

// --- Colors ---
var cloudColor = input(
    name="cloudColor",
    type="color",
    defaultValue="#2962ff",
    label="Midline Color",
    group="Colors"
)
var upColor = input(
    name="upColor",
    type="color",
    defaultValue="#26a69a",
    label="Support Cloud Color",
    group="Colors"
)
var dnColor = input(
    name="dnColor",
    type="color",
    defaultValue="#ef5350",
    label="Resistance Cloud Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Cloud Color",
    group="Colors"
)
var clusterColor = input(
    name="clusterColor",
    type="color",
    defaultValue="#ffeb3b",
    label="Volume Cluster Color",
    group="Colors"
)

// ------------------------------------------------------------------------------
// Data Sources
// ------------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries book = source("orderbook", currentSymbol, currentExchange)

// NaN guard — prevent execution before data is loaded
if (isnan(px[0])) {
    return
}

// ------------------------------------------------------------------------------
// Orderbook Imbalance Calculation (Cont et al. 2014)
// ------------------------------------------------------------------------------
// When real orderbook data is available, compute multi-depth OBI.
// Otherwise, fall back to candle-structure proxy.

var obiReal = 0.0
var bookAvailable = false

if (useOrderbook && !isnan(book)) {
    var bids1 = sumBids(book, obDepth1)
    var asks1 = sumAsks(book, obDepth1)
    var bids2 = sumBids(book, obDepth2)
    var asks2 = sumAsks(book, obDepth2)
    var bids3 = sumBids(book, obDepth3)
    var asks3 = sumAsks(book, obDepth3)

    bookAvailable = bids1 > 0 && asks1 > 0 && bids2 > 0 && asks2 > 0 && bids3 > 0 && asks3 > 0

    var denom1 = bids1 + asks1
    var denom2 = bids2 + asks2
    var denom3 = bids3 + asks3

    var obi1 = bookAvailable && denom1 > 0 ? (bids1 - asks1) / denom1 : 0.0
    var obi2 = bookAvailable && denom2 > 0 ? (bids2 - asks2) / denom2 : 0.0
    var obi3 = bookAvailable && denom3 > 0 ? (bids3 - asks3) / denom3 : 0.0

    // Depth-weighted composite with decay: 1.0, 0.75, 0.5625
    var w1 = 1.0
    var w2 = 0.75
    var w3 = 0.5625
    var wSum = w1 + w2 + w3
    obiReal = wSum > 0 ? (w1 * obi1 + w2 * obi2 + w3 * obi3) / wSum : 0.0
}

// ------------------------------------------------------------------------------
// Candle-Structure Imbalance Proxy (fallback when orderbook unavailable)
// ------------------------------------------------------------------------------
// Close position within bar: 0 = low, 1 = high, 0.5 = mid
// Positive = close near high (buying pressure), negative = close near low
var rng = bars.high - bars.low
var closePos = rng > 0 ? (bars.close - bars.low) / rng : 0.5
var imbalanceProxy = sma(closePos, lookback) - 0.5

// Use real OBI if available, otherwise proxy
var imbalance = useOrderbook && bookAvailable ? obiReal : imbalanceProxy

// ------------------------------------------------------------------------------
// Cloud Boundaries — ATR-Adaptive (Bollinger 2001)
// ------------------------------------------------------------------------------
var atrV = rng > 0 ? sma(rng, lookback) : 0.0
var halfW = atrV * atrMult / 2.0

var upper = px + halfW
var lower = px - halfW
var midPx = sma(px, lookback)

// Cloud regime: bid-heavy = support (green), ask-heavy = resistance (red)
var cloudRegime = imbalance > 0.05 ? 1 : (imbalance < -0.05 ? -1 : 0)
// 1 = support/bull, -1 = resistance/bear, 0 = neutral

var cloudUpColor = cloudRegime == 1 ? upColor : (cloudRegime == -1 ? dnColor : neutralColor)
var cloudDnColor = cloudRegime == 1 ? upColor : (cloudRegime == -1 ? dnColor : neutralColor)

// ------------------------------------------------------------------------------
// Volume / Liquidity Cluster Detection (Paddrik et al. 2014)
// ------------------------------------------------------------------------------
// Identifies bars where volume exceeds N standard deviations from mean,
// flagging significant liquidity events that anchor cloud zones.

var volMean = sma(bars.volume, volLookback)
var volStd = stddev(bars.volume, volLookback)
var volZ = volMean > 0 && !isnan(volStd) ? (bars.volume - volMean) / (volStd + 1e-9) : 0.0
var isVolCluster = volCluster && volZ > volSigmaThresh

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks cloud breakouts, session extremes, and volume cluster history.

static lastBarIndex = 0
static sessionHighPx = -999999.0
static sessionLowPx = 999999.0
static cloudBreakoutCount = 0
static cloudBreakdownCount = 0
static lastCloudRegime = 0

var currentBarIndex = bar_index[0]

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

    if (px > sessionHighPx) {
        sessionHighPx = px
    }
    if (px < sessionLowPx) {
        sessionLowPx = px
    }

    if (lastCloudRegime != cloudRegime) {
        lastCloudRegime = cloudRegime
        if (cloudRegime == 1) {
            cloudBreakoutCount = cloudBreakoutCount + 1
        } else if (cloudRegime == -1) {
            cloudBreakdownCount = cloudBreakdownCount + 1
        }
    }
}

// ------------------------------------------------------------------------------
// Plots — Cloud Visualization with Fill, Color Coding, and Shapes
// ------------------------------------------------------------------------------

// --- Cloud bands with regime-colored fill ---
if (showBands) {
    if (showFill) {
        plotLine(
            value=[upper, lower],
            width=cloudWidth,
            colors=[transparency(cloudUpColor, 70), transparency(cloudDnColor, 70)],
            colorIndex=cloudRegime == 1 ? 0 : 1,
            fill=true,
            label=["Resistance Band", "Support Band"],
            desc=["Upper cloud boundary — resistance zone", "Lower cloud boundary — support zone"]
        )
    } else {
        plotLine(
            value=upper,
            colors=[cloudUpColor],
            width=cloudWidth,
            label=["Resistance Band"],
            desc=["Upper cloud boundary — resistance zone"]
        )
        plotLine(
            value=lower,
            colors=[cloudDnColor],
            width=cloudWidth,
            label=["Support Band"],
            desc=["Lower cloud boundary — support zone"]
        )
    }
}

// --- Cloud midline ---
if (showMidline) {
    plotLine(
        value=midPx,
        colors=[cloudColor],
        width=1,
        label=["Cloud Midline"],
        desc=["Center of the liquidity cloud — SMA(lookback) anchor"]
    )
}

// --- Volume cluster markers (diamonds at high-volume bars) ---
if (showVolClusters && isVolCluster) {
    plotShape(
        value=px,
        shape="diamond",
        color=clusterColor,
        width=2,
        label=["Vol Cluster"],
        desc=["Volume cluster detected: volume > " + volSigmaThresh + "σ above mean"]
    )
}

// --- Breakout / breakdown shapes ---
if (showShapes) {
    // Breakout: price closes above upper cloud boundary
    var breakoutUp = bars.close > upper && !isnan(bars.close[1]) && bars.close[1] <= upper[1]
    // Breakdown: price closes below lower cloud boundary
    var breakoutDn = bars.close < lower && !isnan(bars.close[1]) && bars.close[1] >= lower[1]
    // Midline cross up
    var midCrossUp = bars.close > midPx && !isnan(bars.close[1]) && bars.close[1] <= midPx[1]
    // Midline cross down
    var midCrossDn = bars.close < midPx && !isnan(bars.close[1]) && bars.close[1] >= midPx[1]

    if (breakoutUp) {
        plotShape(
            value=px,
            shape="triangleup",
            color=upColor,
            width=3,
            label=["Cloud Breakout"],
            desc=["Price broke above upper cloud boundary — bullish breakout"]
        )
    }
    if (breakoutDn) {
        plotShape(
            value=px,
            shape="triangledown",
            color=dnColor,
            width=3,
            label=["Cloud Breakdown"],
            desc=["Price broke below lower cloud boundary — bearish breakdown"]
        )
    }
    if (midCrossUp) {
        plotShape(
            value=midPx,
            shape="arrowup",
            color=cloudColor,
            width=2,
            label=["Mid Cross Up"],
            desc=["Price crossed above cloud midline"]
        )
    }
    if (midCrossDn) {
        plotShape(
            value=midPx,
            shape="arrowdown",
            color=cloudColor,
            width=2,
            label=["Mid Cross Down"],
            desc=["Price crossed below cloud midline"]
        )
    }
}