MM Flow
FlowScripts

Perfected FlowScript

long_lm

Long LM — Long-Term Liquidity Metric (Perfected) is indexed as 322_long_lm.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

487

Native Signal Candidates

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

3/3 guarded

Extreme Crowded

line 424:9

Trigger

(showShapes) && (extremeCrowded)

Value

longZ

Deps

extremeCrowded:var, showShapes:input

Extreme Light

line 434:9

Trigger

(showShapes) && (extremeLight)

Value

longZ

Deps

extremeLight:var, showShapes:input

Dist Alert

line 444:9

Trigger

(showShapes) && (distAlert)

Value

longZ

Deps

distAlert:var, showShapes:input

322_long_lm.flowscript

source path: kscripts/perfected/322_long_lm.flowscript · sha256:617af50e9895b06ec2a783d3caf676910fbf8752426d7c0238f3e7c1cac06376

hash verified
//@version=2
// ============================================================================
// Long LM — Long-Term Liquidity Metric (Perfected Edition)
// Author: I (@Iopl147u) | Enhanced by kScript_Perfection_Engineer
// Tags: ADVANCED, #orderbook, #liquidity, #accumulation, #regime, #zscore
//
// Production-quality long-term liquidity metric measuring bullish pressure
// from price action, volume, and orderbook-style bid-side accumulation.
// Integrates buy-volume proxy with bid-pressure scoring, applies rolling-window
// z-score normalisation for regime detection, and surfaces distribution-risk
// alerts via color-coded histograms, filled divergence bands, and extreme
// shape markers.
//
// Academic foundation (exact papers & formulas):
//  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 linearly predicts short-term price changes:
//     Δp_t = λ·OFI_t + ε_t. Positive OFI predicts upward moves.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//
//  2. Cartea, Donnelly & Jaimungal (2018), "Enhancing Trading Strategies with
//     Order Book Signals", Applied Mathematical Finance, 25(1), 1–35.
//     [Formula] Imbalance regimes: Buy-heavy (1/3 to 1) predicts positive moves;
//     Sell-heavy (−1 to −1/3) predicts negative moves.
//     DOI: https://doi.org/10.1080/1350486X.2018.1434009
//
//  3. Korean Derivatives Association (2015), "Order Imbalance and Return
//     Predictability". Full-book imbalance = (Bid − Ask) / (Bid + Ask);
//     predicts short-horizon returns over 5-, 10-, and 20-minute intervals.
//
//  4. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//     Market Returns", JFE 65(1), 111–130. Extreme imbalances predict return
//     reversals; motivates divergence-threshold design.
//     DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  5. Amihud & Mendelson (1986), "Asset Pricing and the Bid-Ask Spread",
//     Journal of Financial Economics, 17(2), 223–249. Spread as proxy for
//     illiquidity; tighter spreads during accumulation validate bid-pressure
//     signals. DOI: https://doi.org/10.1016/0304-405X(86)90042-6
// ============================================================================

define(
    title="Long LM — Long-Term Liquidity Metric (Perfected)",
    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 Window",
    constraints={min: 5, max: 100, step: 1},
    group="Computation"
)
var smooth = input(
    name="smooth",
    type="number",
    defaultValue=3,
    label="Smoothing Length",
    constraints={min: 1, max: 20, step: 1},
    group="Computation"
)
var zWindow = input(
    name="zWindow",
    type="number",
    defaultValue=50,
    label="Z-Score Window (bars)",
    constraints={min: 20, max: 200, step: 5},
    group="Computation"
)
var divThreshold = input(
    name="divThreshold",
    type="number",
    defaultValue=2.0,
    label="Divergence Regime Threshold (z)",
    constraints={min: 0.5, max: 4.0, step: 0.5},
    group="Computation"
)
var extremeDiv = input(
    name="extremeDiv",
    type="number",
    defaultValue=3.0,
    label="Extreme Divergence Threshold (z)",
    constraints={min: 2.0, max: 6.0, step: 0.5},
    group="Computation"
)

// -- Thresholds --
var thrHigh = input(
    name="thrHigh",
    type="number",
    defaultValue=70,
    label="Crowded Long Threshold (raw)",
    constraints={min: 50, max: 95, step: 1},
    group="Thresholds"
)
var thrLow = input(
    name="thrLow",
    type="number",
    defaultValue=30,
    label="Light Long Threshold (raw)",
    constraints={min: 5, max: 50, step: 1},
    group="Thresholds"
)
var useDynamic = input(
    name="useDynamic",
    type="boolean",
    defaultValue=false,
    label="Dynamic Thresholds (volatility-adjusted)",
    group="Thresholds"
)
var volMultiplier = input(
    name="volMultiplier",
    type="number",
    defaultValue=1.5,
    label="Volatility Multiplier",
    constraints={min: 0.5, max: 5.0, step: 0.1},
    group="Thresholds"
)

// -- Display --
var showRaw = input(
    name="showRaw",
    type="boolean",
    defaultValue=true,
    label="Show Raw Long Score",
    group="Display"
)
var showZ = input(
    name="showZ",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Line",
    group="Display"
)
var showHistogram = input(
    name="showHistogram",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Histogram",
    group="Display"
)
var showFill = input(
    name="showFill",
    type="boolean",
    defaultValue=true,
    label="Show Divergence Fill",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Extreme Divergence Shapes",
    group="Display"
)
var showBands = input(
    name="showBands",
    type="boolean",
    defaultValue=true,
    label="Show Threshold Bands",
    group="Display"
)
var showBid = input(
    name="showBid",
    type="boolean",
    defaultValue=true,
    label="Show Bid Pressure Component",
    group="Display"
)

// -- Colors --
var upColor = input(
    name="upColor",
    type="color",
    defaultValue="#26a69a",
    label="Heavy Long / Bullish Color",
    group="Colors"
)
var dnColor = input(
    name="dnColor",
    type="color",
    defaultValue="#ef5350",
    label="Light Long / Bearish Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#78909c",
    label="Neutral Color",
    group="Colors"
)
var lineColor = input(
    name="lineColor",
    type="color",
    defaultValue="#2962ff",
    label="Base Line Color",
    group="Colors"
)
var distColor = input(
    name="distColor",
    type="color",
    defaultValue="#ff9800",
    label="Distribution Alert Color",
    group="Colors"
)

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

timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries px = bars.close
timeseries vol = bars.volume
timeseries rng = bars.high - bars.low

if (isnan(px[0]) || isnan(vol[0]) || isnan(rng[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. LONG PRESSURE CALCULATION
// ---------------------------------------------------------------------------
// Buying pressure proxy: buy volume (close in upper part of bar) weighted by
// relative volume intensity. Per Lee-Ready (1991) tick-test intuition: close
// near the high signals aggressive buyer-initiated flow.

timeseries midPt = (bars.high + bars.low) / 2.0
timeseries buyFrac = rng > 0 ? math.max((bars.close - midPt) / rng, 0) : 0
timeseries buyVol = vol * buyFrac

// Normalise to 0-100 scale via rolling percentile of total volume
timeseries avgBuy = sma(buyVol, len)
timeseries maxBuy = highest(buyVol, len)
timeseries longScore = maxBuy > 0 ? (avgBuy / maxBuy) * 100.0 : 0.0
timeseries smoothed = sma(longScore, smooth)

// Bid pressure component: average close position within the bar range
// (orderbook-style bid-side accumulation proxy)
timeseries bidPressure = sma(buyFrac, len) * 100.0

// ---------------------------------------------------------------------------
// 4. Z-SCORE NORMALISATION
// ---------------------------------------------------------------------------
// Z_t = (Score_t - mu_t) / sigma_t where mu_t = SMA(Score, W), sigma_t = StDev(Score, W).
// Guards: if sigma_t == 0 emit 0 to prevent division-by-zero crashes.

timeseries scoreMean = sma(smoothed, zWindow)
timeseries scoreStd = stddev(smoothed, zWindow)
timeseries longZ = (scoreStd > 0) ? (smoothed - scoreMean) / scoreStd : 0

// ---------------------------------------------------------------------------
// 5. DYNAMIC THRESHOLDS
// ---------------------------------------------------------------------------
// Per Amihud & Mendelson (1986), illiquidity varies with volatility.
// We adjust high/low bands by rolling long-score standard deviation.

timeseries scoreVol = stddev(smoothed, zWindow)
var dynHigh = useDynamic ? math.min(95, thrHigh + scoreVol * volMultiplier) : thrHigh
var dynLow = useDynamic ? math.max(5, thrLow - scoreVol * volMultiplier) : thrLow

// Guard: ensure dynamic bands never cross
if (dynHigh <= dynLow) {
    dynHigh = 70
    dynLow = 30
}

// ---------------------------------------------------------------------------
// 6. REGIME DETECTION
// ---------------------------------------------------------------------------
// Regime classification based on z-score deviation from neutral (0):
//   Crowded Long (distribution risk): longZ > divThreshold  → high bullish pressure
//   Light Long (accumulation room): longZ < -divThreshold → low bullish pressure
//   Neutral: everything else

var regimeCrowded = longZ > divThreshold
var regimeLight = longZ < -divThreshold
var regimeNeutral = !regimeCrowded && !regimeLight

var regimeColor = regimeCrowded ? upColor : (regimeLight ? dnColor : neutralColor)

// ---------------------------------------------------------------------------
// 7. STATIC STATE TRACKING
// ---------------------------------------------------------------------------
// Tracks consecutive bars in each regime for context-aware alerting and
// distribution-accumulation scoring. Static persists across bars; guarded against NaN.

static lastRegime = 0
static crowdedBars = 0
static lightBars = 0
static neutralBars = 0
static maxCrowdedZ = 0.0
static minLightZ = 0.0

if (!isnan(longZ[0])) {
    if (regimeCrowded) {
        crowdedBars = crowdedBars + 1
        lightBars = 0
        neutralBars = 0
        if (longZ[0] > maxCrowdedZ) {
            maxCrowdedZ = longZ[0]
        }
        lastRegime = 1
    } else if (regimeLight) {
        lightBars = lightBars + 1
        crowdedBars = 0
        neutralBars = 0
        if (longZ[0] < minLightZ) {
            minLightZ = longZ[0]
        }
        lastRegime = -1
    } else {
        neutralBars = neutralBars + 1
        crowdedBars = 0
        lightBars = 0
        lastRegime = 0
    }
}

// ---------------------------------------------------------------------------
// 8. ALERT CONDITIONS
// ---------------------------------------------------------------------------
// Extreme divergence: z-score exceeds extreme threshold — signals potential
// distribution (crowded) or accumulation exhaustion (light).

var extremeCrowded = longZ > extremeDiv
var extremeLight = longZ < -extremeDiv

// Distribution risk alert: crowded long + increasing consecutive bars
var distAlert = extremeCrowded && crowdedBars >= 3

// ---------------------------------------------------------------------------
// 9. VISUALIZATION
// ---------------------------------------------------------------------------

// 9.1 Reference lines (hline)
hline(value=0,                color="#ffffff30", width=1)
hline(value=divThreshold,     color="#ffffff20", width=1)
hline(value=-divThreshold,    color="#ffffff20", width=1)
hline(value=extremeDiv,       color="#ffffff15", width=1)
hline(value=-extremeDiv,      color="#ffffff15", width=1)

// 9.2 Threshold bands (hline with transparency)
if (showBands) {
    hline(value=dynHigh, color=transparency(upColor, 60), width=1)
    hline(value=dynLow,  color=transparency(dnColor, 60), width=1)
    hline(value=50,      color="#ffffff20", width=1)
    hline(value=0,       color="#ffffff20", width=1)
    hline(value=100,     color="#ffffff20", width=1)
}

// 9.3 Raw Long Score (plotLine)
if (showRaw) {
    plotLine(
        value=smoothed,
        width=2,
        colors=[lineColor],
        label=["Long Score"],
        desc=["Long positioning score (0-100); higher = more crowded longs (distribution risk)"]
    )
}

// 9.4 Bid Pressure Component (plotLine)
if (showBid) {
    plotLine(
        value=bidPressure,
        width=1,
        colors=[upColor],
        label=["Bid Pressure"],
        desc=["Orderbook-style bid pressure component; average close position within bar range"]
    )
}

// 9.5 Z-Score Line (regime-colored)
if (showZ) {
    plotLine(
        value=longZ,
        width=2,
        colors=[regimeColor],
        label=["Long Z-Score"],
        desc=["Rolling z-score of long score; mean-reverting around 0"]
    )
}

// 9.6 Z-Score Histogram (color-coded by regime)
if (showHistogram) {
    var histBull = longZ >= 0
    plotBar(
        value=longZ,
        colors=[transparency(upColor, 60), transparency(dnColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["Long Z Histogram"],
        desc=["Z-score histogram; positive = crowded long, negative = light long"]
    )
}

// 9.7 Divergence Fill (z-score vs zero line, color-coded)
if (showFill) {
    timeseries zeroLine = 0
    var fillBull = longZ > 0
    plotLine(
        value=[longZ, zeroLine],
        width=2,
        colors=[transparency(upColor, 20), transparency(dnColor, 20)],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=["Long Z", "Zero"],
        desc=["Fill between long z-score and zero line; colour-coded by regime"]
    )
}

// 9.8 Extreme divergence shapes (plotShape)
if (showShapes) {
    if (extremeCrowded) {
        plotShape(
            value=longZ,
            shape="triangleup",
            colorIndex=upColor,
            width=3,
            label=["Extreme Crowded"],
            desc=["Extreme crowded long (z > " + extremeDiv + "); distribution risk elevated"]
        )
    }
    if (extremeLight) {
        plotShape(
            value=longZ,
            shape="triangledown",
            colorIndex=dnColor,
            width=3,
            label=["Extreme Light"],
            desc=["Extreme light long (z < -" + extremeDiv + "); accumulation room / bullish exhaustion"]
        )
    }
    if (distAlert) {
        plotShape(
            value=longZ,
            shape="circle",
            colorIndex=distColor,
            width=3,
            label=["Dist Alert"],
            desc=["Distribution alert: " + crowdedBars + " consecutive crowded bars; max z = " + maxCrowdedZ]
        )
    }
}

// ---------------------------------------------------------------------------
// 10. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeCrowded ? "CROWDED LONG" : (regimeLight ? "LIGHT LONG" : "NEUTRAL")
    var regimeTextColor = regimeCrowded ? upColor : (regimeLight ? dnColor : neutralColor)
    var highText = useDynamic ? "Dynamic High: " + dynHigh : "Static High: " + thrHigh
    var lowText = useDynamic ? "Dynamic Low: " + dynLow : "Static Low: " + thrLow

    plotTable(
        data=[
            ["Long LM — Perfected", regimeText],
            ["Long Score", smoothed[0]],
            ["Long Z-Score", longZ[0]],
            ["Bid Pressure", bidPressure[0]],
            ["Consecutive Crowded", crowdedBars],
            ["Consecutive Light", lightBars],
            [highText, lowText]
        ],
        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
    )
}