MM Flow
FlowScripts

Perfected FlowScript

short_lm

Short LM — Short-Term Liquidity Metric (Perfected) is indexed as 321_short_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

14.7 KB

Lines

459

Native Signal Candidates

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

3/3 guarded

Extreme Crowded

line 397:9

Trigger

(showShapes) && (extremeCrowded)

Value

shortZ

Deps

extremeCrowded:var, showShapes:input

Extreme Light

line 407:9

Trigger

(showShapes) && (extremeLight)

Value

shortZ

Deps

extremeLight:var, showShapes:input

Squeeze Alert

line 417:9

Trigger

(showShapes) && (squeezeAlert)

Value

shortZ

Deps

showShapes:input, squeezeAlert:var

321_short_lm.flowscript

source path: kscripts/perfected/321_short_lm.flowscript · sha256:206566f642a244938e8ed27dc78a456597acb3341d84c8b697ce2fa6ac9ffcaa

hash verified
//@version=2
// ============================================================================
// Short LM — Short-Term Liquidity Metric (Perfected Edition)
// Author: I (@Iopl147u) | Enhanced by kScript_Perfection_Engineer
// Tags: ADVANCED, #short, #liquidity, #squeeze, #regime, #zscore
//
// Production-quality short-term liquidity metric measuring bearish pressure
// from price action and volume. Estimates a short-interest proxy via aggressive
// selling intensity, applies rolling-window z-score normalisation for regime
// detection, and surfaces squeeze-risk alerts via color-coded histograms,
// filled divergence bands, and extreme shape markers.
//
// Academic foundation (exact papers & formulas):
//  1. Brunnermeier & Pedersen (2005), "Predatory Trading", Journal of Finance,
//     60(4), 1825–1863. [Formula] Crowded positioning amplifies price moves;
//     short squeezes arise when predatory traders exploit margin-constrained
//     shorts. DOI: https://doi.org/10.1111/j.1540-6261.2005.00781.x
//
//  2. Bian et al. (2023), "Deleveraging Commonality", Journal of Financial
//     Economics, 147(1), 103–120. Systematic deleveraging creates feedback loops
//     where short covering triggers further covering. DOI: 10.1016/j.jfineco.2022.103720
//
//  3. Forex Mechanics (2026), "Retail Positioning as a Contrarian Indicator".
//     Extreme long/short ratios (>70/30) act as contrarian signals; squeeze risk
//     peaks when retail shorts are maximally crowded.
//
//  4. Chordia, Roll & Subrahmanyam (2002), "Order Imbalance, Liquidity, and
//     Market Returns", JFE 65(1), 111–130. Extreme order imbalances predict
//     return reversals; motivates the z-score divergence-threshold design.
//     DOI: https://doi.org/10.1016/S0304-405X(02)00136-8
//
//  5. Poterba & Summers (1988), "Mean Reversion in Stock Prices", Journal of
//     Financial Economics, 22(1), 27–59. Negative autocorrelation at medium
//     horizons supports dynamic threshold calibration to rolling volatility.
//     DOI: https://doi.org/10.1016/0304-405X(88)90021-9
// ============================================================================

define(
    title="Short LM — Short-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 Short Threshold (raw)",
    constraints={min: 50, max: 95, step: 1},
    group="Thresholds"
)
var thrLow = input(
    name="thrLow",
    type="number",
    defaultValue=30,
    label="Light Short 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 Short 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"
)

// -- Colors --
var dnColor = input(
    name="dnColor",
    type="color",
    defaultValue="#ef5350",
    label="Heavy Short / Bearish Color",
    group="Colors"
)
var upColor = input(
    name="upColor",
    type="color",
    defaultValue="#26a69a",
    label="Light Short / Bullish 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 squeezeColor = input(
    name="squeezeColor",
    type="color",
    defaultValue="#ffeb3b",
    label="Squeeze 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. SHORT PRESSURE CALCULATION
// ---------------------------------------------------------------------------
// Selling pressure proxy: sell volume (close in lower part of bar) weighted by
// relative volume intensity. Per Lee-Ready (1991) tick-test intuition: close
// near the low signals aggressive seller-initiated flow.

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

// Normalise to 0-100 scale via rolling percentile of total volume
timeseries avgSell = sma(sellVol, len)
timeseries maxSell = highest(sellVol, len)
timeseries shortScore = maxSell > 0 ? (avgSell / maxSell) * 100.0 : 0.0
timeseries smoothed = sma(shortScore, smooth)

// ---------------------------------------------------------------------------
// 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 shortZ = (scoreStd > 0) ? (smoothed - scoreMean) / scoreStd : 0

// ---------------------------------------------------------------------------
// 5. DYNAMIC THRESHOLDS
// ---------------------------------------------------------------------------
// Per Poterba & Summers (1988), mean-reversion intensity varies with volatility.
// We adjust OB/OS bands by rolling short-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 Short (squeeze risk): shortZ > divThreshold  → high bearish pressure
//   Light Short (continuation room): shortZ < -divThreshold → low bearish pressure
//   Neutral: everything else

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

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

// ---------------------------------------------------------------------------
// 7. STATIC STATE TRACKING
// ---------------------------------------------------------------------------
// Tracks consecutive bars in each regime for context-aware alerting and
// squeeze-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(shortZ[0])) {
    if (regimeCrowded) {
        crowdedBars = crowdedBars + 1
        lightBars = 0
        neutralBars = 0
        if (shortZ[0] > maxCrowdedZ) {
            maxCrowdedZ = shortZ[0]
        }
        lastRegime = 1
    } else if (regimeLight) {
        lightBars = lightBars + 1
        crowdedBars = 0
        neutralBars = 0
        if (shortZ[0] < minLightZ) {
            minLightZ = shortZ[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
// squeeze (crowded) or continuation exhaustion (light).

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

// Squeeze risk alert: crowded short + increasing consecutive bars
var squeezeAlert = 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(dnColor, 60), width=1)
    hline(value=dynLow,  color=transparency(upColor, 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 Short Score (plotLine)
if (showRaw) {
    plotLine(
        value=smoothed,
        width=2,
        colors=[lineColor],
        label=["Short Score"],
        desc=["Short positioning score (0-100); higher = more crowded shorts (squeeze risk)"]
    )
}

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

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

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

// 9.7 Extreme divergence shapes (plotShape)
if (showShapes) {
    if (extremeCrowded) {
        plotShape(
            value=shortZ,
            shape="triangledown",
            colorIndex=dnColor,
            width=3,
            label=["Extreme Crowded"],
            desc=["Extreme crowded short (z > " + extremeDiv + "); squeeze risk elevated"]
        )
    }
    if (extremeLight) {
        plotShape(
            value=shortZ,
            shape="triangleup",
            colorIndex=upColor,
            width=3,
            label=["Extreme Light"],
            desc=["Extreme light short (z < -" + extremeDiv + "); continuation room / bearish exhaustion"]
        )
    }
    if (squeezeAlert) {
        plotShape(
            value=shortZ,
            shape="circle",
            colorIndex=squeezeColor,
            width=3,
            label=["Squeeze Alert"],
            desc=["Squeeze alert: " + crowdedBars + " consecutive crowded bars; max z = " + maxCrowdedZ]
        )
    }
}

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

    plotTable(
        data=[
            ["Short LM — Perfected", regimeText],
            ["Short Score", smoothed[0]],
            ["Short Z-Score", shortZ[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
    )
}