MM Flow
FlowScripts

Perfected FlowScript

FLOODGATE

FLOODGATE — Perfected Edition is indexed as 332_floodgate.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

15.5 KB

Lines

465

Native Signal Candidates

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

6/6 guarded

Light Flood +

line 355:9

Trigger

(showShapes) && (crossUpLight && !heavyFlood)

Value

pressZ

Deps

crossUpLight:var, heavyFlood:var, showShapes:input

Heavy Flood +

line 365:9

Trigger

(showShapes) && (crossUpHeavy && !extremeFlood)

Value

pressZ

Deps

crossUpHeavy:var, extremeFlood:var, showShapes:input

EXTREME FLOOD +

line 375:9

Trigger

(showShapes) && (crossUpExtreme)

Value

pressZ

Deps

crossUpExtreme:var, showShapes:input

Light Flood -

line 387:9

Trigger

(showShapes) && (crossDownLight && !heavyFlood)

Value

pressZ

Deps

crossDownLight:var, heavyFlood:var, showShapes:input

Heavy Flood -

line 397:9

Trigger

(showShapes) && (crossDownHeavy && !extremeFlood)

Value

pressZ

Deps

crossDownHeavy:var, extremeFlood:var, showShapes:input

EXTREME FLOOD -

line 407:9

Trigger

(showShapes) && (crossDownExtreme)

Value

pressZ

Deps

crossDownExtreme:var, showShapes:input

332_floodgate.flowscript

source path: kscripts/perfected/332_floodgate.flowscript · sha256:c3cbf8093ae8d6c02ea8d5dd32ed4ed55fb60ce867cd1dc82753ca268743a057

hash verified
//@version=2
// ============================================================================
// FLOODGATE — Perfected Edition
// Author: laegend1 | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, ADVANCED, SPECIALIZED, #volume, #liquidity, #buy-sell-pressure,
//       #flood, #threshold, #regime
//
// Production-grade real-time liquidity balance oscillator measuring normalized
// buy-sell pressure per bar. Upgrades the original with taker-volume-aware
// delta computation, z-score standardisation of liquidity floods, multi-level
// threshold detection (light → heavy → extreme), and full static-state tracking
// of flood duration and intensity. Visualizes as regime-colored fill areas,
// histogram bars, and shape alerts for threshold crossings.
//
// Academic foundation:
//  1. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book Events",
//     Journal of Financial Econometrics, 12(1), 47–88.
//     [Formula] OFI_t = Δq_t^b·I_{Δq_t^b>0} − Δq_t^a·I_{Δq_t^a>0}
//     Cumulative OFI (CVD) linearly predicts short-term price changes.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  2. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//     Market Returns", Journal of Financial Economics, 65(1), 111–130.
//     [Formula] Imbalance_t = Buy_t − Sell_t; extreme |Imbalance| predicts
//     return reversals. Directly motivates the multi-threshold design.
//     DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  3. Easley, López de Prado & O'Hara (2012), "Flow Toxicity and Liquidity in
//     a High-Frequency World", Journal of Financial Management, 38(2), 1–32.
//     VPIN = Σ|Buy − Sell| / Total Volume over volume buckets. Informs the
//     volume-bucket normalization and toxicity-threshold logic.
//     DOI: https://doi.org/10.1111/j.1755-053X.2012.01193.x
//
//  4. Lee & Ready (1991), "Inferring Trade Direction from Intraday Data",
//     Journal of Finance, 46(2), 733–746. Foundational tick-classification
//     algorithm (85–93% accuracy) used when granular taker-buy/sell data
//     is unavailable: classify as buy if close > open, else sell.
//     DOI: https://doi.org/10.1111/j.1540-6261.1991.tb02683.x
//
//  5. Bouchaud, Farmer & Lillo (2009), "How Markets Slowly Digest Changes in
//     Supply and Demand", Journal of Economic Literature, 47(2), 326–378.
//     Liquidity memory explains why volume spikes may or may not move price.
//     Informs the rolling-window normalization instead of raw cumulative sums.
// ============================================================================

define(
    title="FLOODGATE — Perfected Edition",
    position="offchart",
    axis=true
)

// -----------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// -----------------------------------------------------------------------------

// --- Computation ---
var len = input(
    name="len",
    type="number",
    defaultValue=14,
    label="Pressure Smoothing Window",
    constraints={min: 5, max: 50, step: 1},
    group="Computation"
)
var zWindow = input(
    name="zWindow",
    type="number",
    defaultValue=50,
    label="Z-Score Normalization Window",
    constraints={min: 20, max: 200, step: 5},
    group="Computation"
)
var useTaker = input(
    name="useTaker",
    type="boolean",
    defaultValue=true,
    label="Prefer Taker Volume (higher accuracy)",
    group="Computation"
)

// --- Thresholds ---
var lightThresh = input(
    name="lightThresh",
    type="number",
    defaultValue=1.0,
    label="Light Flood Threshold (z)",
    constraints={min: 0.5, max: 2.0, step: 0.1},
    group="Thresholds"
)
var heavyThresh = input(
    name="heavyThresh",
    type="number",
    defaultValue=2.0,
    label="Heavy Flood Threshold (z)",
    constraints={min: 1.5, max: 3.5, step: 0.1},
    group="Thresholds"
)
var extremeThresh = input(
    name="extremeThresh",
    type="number",
    defaultValue=3.0,
    label="Extreme Flood Threshold (z)",
    constraints={min: 2.5, max: 5.0, step: 0.1},
    group="Thresholds"
)

// --- Display ---
var showPressure = input(
    name="showPressure",
    type="boolean",
    defaultValue=true,
    label="Show Pressure Line",
    group="Display"
)
var showZScore = input(
    name="showZScore",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Line",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show Regime Fill",
    group="Display"
)
var showBars = input(
    name="showBars",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Bars",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Threshold Crossing Shapes",
    group="Display"
)
var showConv = input(
    name="showConv",
    type="boolean",
    defaultValue=true,
    label="Show Conviction Threshold Lines",
    group="Display"
)

// --- Colors ---
var upColor = input(
    name="upColor",
    type="color",
    defaultValue="#26a69a",
    label="Buyers in Control",
    group="Colors"
)
var dnColor = input(
    name="dnColor",
    type="color",
    defaultValue="#ef5350",
    label="Sellers in Control",
    group="Colors"
)
var zeroColor = input(
    name="zeroColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)
var lightColor = input(
    name="lightColor",
    type="color",
    defaultValue="#81c784",
    label="Light Flood Color",
    group="Colors"
)
var heavyColor = input(
    name="heavyColor",
    type="color",
    defaultValue="#ffeb3b",
    label="Heavy Flood Color",
    group="Colors"
)
var extremeColor = input(
    name="extremeColor",
    type="color",
    defaultValue="#d500f9",
    label="Extreme Flood Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first external access
// -----------------------------------------------------------------------------

timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries taker = source("taker_volume", currentSymbol, currentExchange)

if (isnan(bars.close[0]) || (useTaker && !isnum(taker.buy))) {
    return
}

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

// -- 3.1 Per-bar buy/sell pressure (Lee-Ready fallback when taker unavailable) --
// Lee-Ready (1991): close > open → buyer-initiated; else seller-initiated.
// When taker.buy/sell is available, prefer direct feed for higher accuracy.
timeseries buyVol = useTaker && isnum(taker.buy) ? taker.buy :
                    (bars.close > bars.open ? bars.volume : 0)
timeseries sellVol = useTaker && isnum(taker.sell) ? taker.sell :
                     (bars.close <= bars.open ? bars.volume : 0)
timeseries delta = buyVol - sellVol

// -- 3.2 Raw pressure: candle body position scaled by volume intensity --
// Buy/sell pressure proxy using close position within the bar's range
timeseries rng = bars.high - bars.low
rng = rng > 0 ? rng : bars.close * 0.001  // avoid zero range
timeseries midPt = (bars.high + bars.low) / 2.0
timeseries closeN = (bars.close - midPt) / rng
timeseries buyPressure = bars.volume * (0.5 + math.max(closeN, 0))
timeseries sellPressure = bars.volume * (0.5 + math.max(-closeN, 0))
timeseries netPressure = buyPressure - sellPressure

// -- 3.3 Normalize to -100 .. +100 using rolling max absolute net --
timeseries absNet = math.abs(netPressure)
timeseries maxAbs = highest(absNet, len)
timeseries pressureRaw = maxAbs > 0 ? (netPressure / maxAbs) * 100.0 : 0.0
timeseries pressure = sma(pressureRaw, len)

// -- 3.4 Z-score standardisation of pressure (rolling window) --
// Z_t = (Pressure_t − μ_t) / σ_t, where μ_t = SMA(Pressure, W), σ_t = StDev.
// Guards: if σ_t == 0 emit 0 to prevent division-by-zero crashes.
timeseries pressMean = sma(pressure, zWindow)
timeseries pressStd = stddev(pressure, zWindow)
timeseries pressZ = (pressStd > 0) ? (pressure - pressMean) / pressStd : 0

// -- 3.5 Flood regime classification (multi-level) --
var lightFlood = math.abs(pressZ) > lightThresh && math.abs(pressZ) <= heavyThresh
var heavyFlood = math.abs(pressZ) > heavyThresh && math.abs(pressZ) <= extremeThresh
var extremeFlood = math.abs(pressZ) > extremeThresh
var noFlood = !lightFlood && !heavyFlood && !extremeFlood

var buyersDom = pressure > 0

// -- 3.6 Flood state tracking via static variables --
// Tracks consecutive bars in each flood level for context-aware alerting.
static floodLightBars = 0
static floodHeavyBars = 0
static floodExtremeBars = 0
static lastFloodRegime = 0

if (lightFlood) {
    floodLightBars = floodLightBars + 1
    floodHeavyBars = 0
    floodExtremeBars = 0
    lastFloodRegime = 1
} else if (heavyFlood) {
    floodHeavyBars = floodHeavyBars + 1
    floodLightBars = 0
    floodExtremeBars = 0
    lastFloodRegime = 2
} else if (extremeFlood) {
    floodExtremeBars = floodExtremeBars + 1
    floodLightBars = 0
    floodHeavyBars = 0
    lastFloodRegime = 3
} else {
    floodLightBars = 0
    floodHeavyBars = 0
    floodExtremeBars = 0
    lastFloodRegime = 0
}

// -- 3.7 Threshold crossing detection --
var crossUpLight = pressZ > lightThresh && pressZ[1] <= lightThresh
var crossUpHeavy = pressZ > heavyThresh && pressZ[1] <= heavyThresh
var crossUpExtreme = pressZ > extremeThresh && pressZ[1] <= extremeThresh
var crossDownLight = pressZ < -lightThresh && pressZ[1] >= -lightThresh
var crossDownHeavy = pressZ < -heavyThresh && pressZ[1] >= -heavyThresh
var crossDownExtreme = pressZ < -extremeThresh && pressZ[1] >= -extremeThresh

// -- 3.8 Zero-line helper --
timeseries zeroLine = 0

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

// 4.1 Raw pressure line (plotLine) — regime-colored
timeseries pressColor = buyersDom ? upColor : dnColor
if (showPressure) {
    plotLine(
        value=pressure,
        width=2,
        colors=[pressColor],
        label=["FLOODGATE Pressure"],
        desc=["Normalized liquidity balance (-100 sellers / +100 buyers)"]
    )
}

// 4.2 Z-Score line (plotLine)
if (showZScore) {
    var zColor = noFlood ? zeroColor :
                 (lightFlood ? lightColor :
                 (heavyFlood ? heavyColor : extremeColor))
    plotLine(
        value=pressZ,
        width=2,
        colors=[zColor],
        label=["Pressure Z-Score"],
        desc=["Standardised pressure deviation (σ units); |z| > " + lightThresh + " = flood"]
    )
}

// 4.3 Regime fill (plotLine + fill) — color-coded by flood intensity
if (showFill) {
    var fillColor = noFlood ? transparency(zeroColor, 20) :
                    (lightFlood ? transparency(lightColor, 30) :
                    (heavyFlood ? transparency(heavyColor, 40) : transparency(extremeColor, 50)))
    plotLine(
        value=[pressure, zeroLine],
        width=1,
        colors=[fillColor, fillColor],
        colorIndex=0,
        fill=true,
        label=["Flood Fill"],
        desc=["Regime-colored fill between pressure and zero line"]
    )
}

// 4.4 Z-Score bars (plotBar) — sign-based with flood intensity overlay
if (showBars) {
    var barColor = buyersDom ?
        (extremeFlood ? extremeColor : (heavyFlood ? heavyColor : (lightFlood ? lightColor : upColor))) :
        (extremeFlood ? extremeColor : (heavyFlood ? heavyColor : (lightFlood ? lightColor : dnColor)))
    plotBar(
        value=pressZ,
        colors=[barColor, barColor],
        colorIndex=0,
        width=1,
        label=["Z-Score Bars"],
        desc=["Standardised pressure bars colored by flood regime"]
    )
}

// 4.5 Threshold crossing shapes (plotShape)
if (showShapes) {
    // Upward crossings (buy pressure floods)
    if (crossUpLight && !heavyFlood) {
        plotShape(
            value=pressZ,
            shape="triangleup",
            colorIndex=lightColor,
            width=2,
            label=["Light Flood +"],
            desc=["Buy pressure crossed light flood threshold (z > " + lightThresh + ")"]
        )
    }
    if (crossUpHeavy && !extremeFlood) {
        plotShape(
            value=pressZ,
            shape="triangleup",
            colorIndex=heavyColor,
            width=2,
            label=["Heavy Flood +"],
            desc=["Buy pressure crossed heavy flood threshold (z > " + heavyThresh + ")"]
        )
    }
    if (crossUpExtreme) {
        plotShape(
            value=pressZ,
            shape="triangleup",
            colorIndex=extremeColor,
            width=3,
            label=["EXTREME FLOOD +"],
            desc=["Buy pressure at EXTREME flood level (z > " + extremeThresh + ") — potential reversal zone"]
        )
    }

    // Downward crossings (sell pressure floods)
    if (crossDownLight && !heavyFlood) {
        plotShape(
            value=pressZ,
            shape="triangledown",
            colorIndex=lightColor,
            width=2,
            label=["Light Flood -"],
            desc=["Sell pressure crossed light flood threshold (z < -" + lightThresh + ")"]
        )
    }
    if (crossDownHeavy && !extremeFlood) {
        plotShape(
            value=pressZ,
            shape="triangledown",
            colorIndex=heavyColor,
            width=2,
            label=["Heavy Flood -"],
            desc=["Sell pressure crossed heavy flood threshold (z < -" + heavyThresh + ")"]
        )
    }
    if (crossDownExtreme) {
        plotShape(
            value=pressZ,
            shape="triangledown",
            colorIndex=extremeColor,
            width=3,
            label=["EXTREME FLOOD -"],
            desc=["Sell pressure at EXTREME flood level (z < -" + extremeThresh + ") — potential reversal zone"]
        )
    }
}

// 4.6 Reference thresholds (hline)
hline(value=0, color="#ffffff30", width=1)
if (showConv) {
    hline(value=lightThresh, color="#81c78460", width=1)
    hline(value=-lightThresh, color="#ef535060", width=1)
    hline(value=heavyThresh, color="#ffeb3b60", width=1)
    hline(value=-heavyThresh, color="#ef535060", width=1)
    hline(value=extremeThresh, color="#d500f960", width=1)
    hline(value=-extremeThresh, color="#ef535060", width=1)
}

// -----------------------------------------------------------------------------
// 5. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar) {
    var floodText = extremeFlood ? "EXTREME FLOOD" :
                    (heavyFlood ? "HEAVY FLOOD" :
                    (lightFlood ? "LIGHT FLOOD" : "NORMAL"))
    var floodTextColor = extremeFlood ? extremeColor :
                         (heavyFlood ? heavyColor :
                         (lightFlood ? lightColor : zeroColor))
    var domText = buyersDom ? "BUYERS DOMINATE" : "SELLERS DOMINATE"
    var domTextColor = buyersDom ? upColor : dnColor

    plotTable(
        data=[
            ["FLOODGATE — Perfected", floodText],
            ["Dominance", domText],
            ["Pressure", pressure[0]],
            ["Z-Score", pressZ[0]],
            ["Light Bars", floodLightBars],
            ["Heavy Bars", floodHeavyBars],
            ["Extreme Bars", floodExtremeBars]
        ],
        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
    )
}