MM Flow
FlowScripts

Perfected FlowScript

net short

Net Short Positioning V2 is indexed as 232_net_short.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.0 KB

Lines

341

Native Signal Candidates

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

4/4 guarded

Squeeze Risk

line 268:9

Trigger

(showShapes) && (crossSqueeze)

Value

zScore

Deps

crossSqueeze:var, showShapes:input

Crowded Long

line 278:9

Trigger

(showShapes) && (crossCrowded)

Value

zScore

Deps

crossCrowded:var, showShapes:input

Extreme Squeeze

line 288:9

Trigger

(showShapes) && (extremeSqz)

Value

zScore

Deps

extremeSqz:var, showShapes:input

Extreme Long

line 298:9

Trigger

(showShapes) && (extremeLng)

Value

zScore

Deps

extremeLng:var, showShapes:input

232_net_short.flowscript

source path: kscripts/perfected/232_net_short.flowscript · sha256:3ef3d0d309aa45a58526c9d40db33bb3835926e28ba033e5654d7f4f117eb863

hash verified
//@version=2
// ============================================================================
// Net Short Positioning V2 — Production-Quality Sentiment & Squeeze Detector
// Author: Y (@yigit) | Perfected by: kScript Perfection Engineer
// Tags: SENTIMENT, #positioning, #shortsqueeze, #crowding, #contrarian, #zscore
//
// Displays net-short positioning ratio with z-score normalization, regime
// detection (short squeeze / crowded short), and comprehensive visualization.
// Extreme short readings flag contrarian squeeze setups per Brunnermeier &
// Pedersen (2005) predatory trading framework.
//
// FORMULA FOUNDATION:
// 1. Net Short % = 100 − [LongRatio / (LongRatio + 1)] × 100
//    where LongRatio = long_short_ratio total_account.
// 2. Z-Score Normalization: (netShort − rollingMean) / rollingStd per
//    Zhao & Palomar (2018) for standardized regime thresholds.
// 3. Regime Segmentation: Crowded Short (z > 1), Neutral (−1 ≤ z ≤ 1),
//    Long-Heavy (z < −1) per Forex Mechanics (2026) contrarian thresholds.
// 4. Squeeze Detection: z > 2 flags extreme short crowding; predatory buy
//    pressure risk per Brunnermeier & Pedersen (2005).
// 5. Dynamic Thresholds: volatility-adjusted bands adapt to market conditions
//    per Poterba & Summers (1988) mean-reversion framework.
//
// RESEARCH BASIS:
//  • Forex Mechanics (2026), "Retail Positioning as a Contrarian Indicator".
//    L/S ratios above 70/30 are extreme; retail positioning is contrarian.
//  • Brunnermeier & Pedersen (2005), "Predatory Trading" — J. Finance 60(4):
//    1825-1863. When net short is extreme, predatory traders may buy to push
//    prices up, forcing short covering. The squeeze mechanics model.
//  • Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity" —
//    RFS 22(6). Liquidity spirals amplify squeeze dynamics; funding tightness
//    forces leveraged short covering, creating feedback loops.
//  • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint" —
//    IEEE TSP. Z-score normalization for standardized regime thresholds.
//  • Poterba & Summers (1988), "Mean Reversion in Stock Prices" — JFE 22(1).
//    Negative autocorrelation supports contrarian reversal strategies at extremes.
//  • He & Manela (2022), "Fundamentals of Perpetual Futures" — arXiv:2212.06888.
//    Funding rate momentum explains futures-spot gap; extreme positioning
//    correlates with R² > 50% for momentum-driven premiums.
// ============================================================================

define(
    title="Net Short Positioning V2",
    position="offchart",
    axis=true
)

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

// --- Data Source ---
var exchange = input(name="exchange", type="select", defaultValue="BINANCE_FUTURES",
    label="Data Exchange",
    options=["BINANCE_FUTURES", "BYBIT", "OKEX_SWAP", "DERIBIT", "HYPERLIQUID_FUTURES"],
    group="Data Source")
var symbol = input(name="symbol", type="string", defaultValue="BTCUSDT", label="Symbol", group="Data Source")

// --- Smoothing ---
var smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="SMA Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Smoothing")
var useZScore = input(name="useZScore", type="boolean", defaultValue=true, label="Use Z-Score Normalization", group="Smoothing")
var zLookback = input(name="zLookback", type="number", defaultValue=20, label="Z-Score Lookback", constraints={min: 10, max: 100, step: 1}, group="Smoothing")
var useDynamic = input(name="useDynamic", type="boolean", defaultValue=false, label="Dynamic Thresholds (volatility-adjusted)", group="Smoothing")
var volLookback = input(name="volLookback", type="number", defaultValue=20, label="Volatility Lookback", constraints={min: 5, max: 100, step: 1}, group="Smoothing")

// --- Thresholds & Regime ---
var squeezeThresh = input(name="squeezeThresh", type="number", defaultValue=1.0, label="Squeeze Z-Score Threshold", constraints={min: 0.5, max: 3.0, step: 0.1}, group="Thresholds")
var crowdedThresh = input(name="crowdedThresh", type="number", defaultValue=-1.0, label="Crowded Long Z-Score Threshold", constraints={min: -3.0, max: -0.5, step: 0.1}, group="Thresholds")
var extremeSqueeze = input(name="extremeSqueeze", type="number", defaultValue=2.0, label="Extreme Squeeze Z-Score", constraints={min: 1.5, max: 4.0, step: 0.1}, group="Thresholds")
var extremeLine = input(name="extremeLine", type="number", defaultValue=70, label="Extreme Short Line (%)", constraints={min: 50, max: 95, step: 1}, group="Thresholds")
var contrarianLine = input(name="contrarianLine", type="number", defaultValue=30, label="Contrarian Short Line (%)", constraints={min: 5, max: 50, step: 1}, group="Thresholds")

// --- Display ---
var showRaw = input(name="showRaw", type="boolean", defaultValue=true, label="Show Raw Net Short Histogram", group="Display")
var showZScoreLine = input(name="showZScoreLine", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showSignalFill = input(name="showSignalFill", type="boolean", defaultValue=true, label="Show Signal Fill", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")
var showGuides = input(name="showGuides", type="boolean", defaultValue=true, label="Show Guide Lines", group="Display")

// --- Colors ---
var shortColor = input(name="shortColor", type="color", defaultValue="#ef5350", label="Short Pressure Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var longColor = input(name="longColor", type="color", defaultValue="#26a69a", label="Long Pressure Color", group="Colors")
var squeezeColor = input(name="squeezeColor", type="color", defaultValue="#ff1744", label="Squeeze Alert Color", group="Colors")
var crowdedLongColor = input(name="crowdedLongColor", type="color", defaultValue="#00e676", label="Crowded Long Color", group="Colors")

// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries lsr = long_short_ratio(symbol=symbol, exchange=exchange)

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

// Net short calculation: convert long ratio to short percentage
timeseries ratio = isnum(lsr.total_account) ? lsr.total_account : lsr[1]
timeseries netShort = 100.0 - (ratio / (ratio + 1.0)) * 100.0

// ------------------------------------------------------------------------------
// Smoothing & Z-Score Normalization
// ------------------------------------------------------------------------------
timeseries smoothed = sma(source=netShort, period=smoothLen)

// Z-Score: (value − mean) / stddev over rolling window (Zhao & Palomar 2018)
timeseries rollingMean = sma(source=smoothed, period=zLookback)
timeseries rollingStd = stddev(source=smoothed, period=zLookback)
timeseries zScore = useZScore && rollingStd > 0 ? (smoothed - rollingMean) / rollingStd : 0

// Dynamic thresholds: volatility-adjusted per Poterba & Summers (1988)
var posVol = stddev(source=smoothed, period=volLookback)
var dynSqueeze = useDynamic ? math.min(3.0, squeezeThresh + posVol * 0.5) : squeezeThresh
var dynCrowded = useDynamic ? math.max(-3.0, crowdedThresh - posVol * 0.5) : crowdedThresh

// Guard: ensure dynamic bands never cross
if (dynSqueeze <= dynCrowded) {
    dynSqueeze = 1.0
    dynCrowded = -1.0
}

// ------------------------------------------------------------------------------
// Regime Detection (Brunnermeier & Pedersen 2005 squeeze framework)
// ------------------------------------------------------------------------------
// Regime classification based on z-score:
//   Squeeze Risk: z > squeezeThresh (short-heavy, contrarian buy signal)
//   Neutral: crowdedThresh ≤ z ≤ squeezeThresh (balanced positioning)
//   Crowded Long: z < crowdedThresh (long-heavy, contrarian short signal)
//   Extreme Squeeze: z > extremeSqueeze (very high short %, squeeze imminent)
//   Extreme Long: z < -extremeSqueeze (very low short %, long capitulation risk)

var regime = 0      // 0 = neutral, 1 = squeeze risk, -1 = crowded long
var extremeRegime = 0  // 0 = normal, 1 = extreme squeeze, -1 = extreme long

if (useZScore) {
    if (zScore >= dynSqueeze) {
        regime = 1
    } else if (zScore <= dynCrowded) {
        regime = -1
    }
    if (zScore >= extremeSqueeze) {
        extremeRegime = 1
    } else if (zScore <= -extremeSqueeze) {
        extremeRegime = -1
    }
} else {
    // Fallback for raw percentage scale
    if (smoothed >= extremeLine) {
        regime = 1
    } else if (smoothed <= contrarianLine) {
        regime = -1
    }
    if (smoothed >= 85) {
        extremeRegime = 1
    } else if (smoothed <= 15) {
        extremeRegime = -1
    }
}

var regimeColor = regime == 1 ? shortColor : (regime == -1 ? longColor : neutralColor)

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks regime transitions, session extremes, squeeze events, and crowding counts.

static lastRegime = 0
static regimeChangeCount = 0
static sessionHighShort = -999999.0
static sessionLowShort = 999999.0
static squeezeCount = 0
static crowdedLongCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    // New bar — update session tracking
    lastBarIndex = currentBarIndex

    var val = useZScore ? zScore : smoothed
    if (val > sessionHighShort) {
        sessionHighShort = val
    }
    if (val < sessionLowShort) {
        sessionLowShort = val
    }

    if (lastRegime != regime) {
        lastRegime = regime
        regimeChangeCount = regimeChangeCount + 1
    }

    if (extremeRegime == 1) {
        squeezeCount = squeezeCount + 1
    } else if (extremeRegime == -1) {
        crowdedLongCount = crowdedLongCount + 1
    }
}

// ------------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Bar, Shape, Fill, HLine)
// ------------------------------------------------------------------------------

// Horizontal guide lines
hline(value=0, color="#ffffff30", width=1)

if (showGuides) {
    if (useZScore) {
        hline(value=dynSqueeze, color=opacity(shortColor, 30), width=1)
        hline(value=dynCrowded, color=opacity(longColor, 30), width=1)
        hline(value=extremeSqueeze, color=opacity(squeezeColor, 20), width=1)
        hline(value=-extremeSqueeze, color=opacity(crowdedLongColor, 20), width=1)
    } else {
        hline(value=50, color=neutralColor, width=1)
        hline(value=extremeLine, color=opacity(shortColor, 30), width=1)
        hline(value=contrarianLine, color=opacity(longColor, 30), width=1)
    }
}

// Raw net short as histogram (short/long pressure visualization)
if (showRaw) {
    var plotVal = useZScore ? zScore : (smoothed - 50)
    plotBar(
        value=plotVal,
        colors=[shortColor, longColor],
        width=1,
        label=["Net Short Pressure"],
        desc=["Net short positioning: positive=short-heavy, negative=long-heavy"]
    )
}

// Z-Score line with regime-coded fill area
if (showZScoreLine) {
    plotLine(
        value=zScore,
        width=2,
        colors=[shortColor, longColor, neutralColor],
        colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
        label=["Net Short Z-Score"],
        desc=["Z-score normalized net short. Regime: squeeze/crowded/neutral."],
        fill=true
    )
}

// Signal fill (z-score vs zero reference)
if (showSignalFill) {
    var signalBull = zScore >= 0
    plotLine(
        value=[zScore, 0],
        width=1,
        colors=[opacity(shortColor, 20), opacity(longColor, 20)],
        colorIndex=signalBull ? 0 : 1,
        fill=true,
        label=["Z-Score", "Zero Line"],
        desc=["Fill between z-score and zero reference"]
    )
}

// Regime transition shapes — squeeze/crowded detection (Brunnermeier & Pedersen 2005)
if (showShapes) {
    var crossSqueeze = zScore >= dynSqueeze && !isnan(zScore[1]) && zScore[1] < dynSqueeze
    var crossCrowded = zScore <= dynCrowded && !isnan(zScore[1]) && zScore[1] > dynCrowded
    var extremeSqz = zScore >= extremeSqueeze && !isnan(zScore[1]) && zScore[1] < extremeSqueeze
    var extremeLng = zScore <= -extremeSqueeze && !isnan(zScore[1]) && zScore[1] > -extremeSqueeze

    if (crossSqueeze) {
        plotShape(
            value=zScore,
            shape="triangleup",
            color=squeezeColor,
            width=3,
            label=["Squeeze Risk"],
            desc=["Net short crossed into squeeze-risk regime (short-heavy) — contrarian buy signal"]
        )
    }
    if (crossCrowded) {
        plotShape(
            value=zScore,
            shape="triangledown",
            color=crowdedLongColor,
            width=3,
            label=["Crowded Long"],
            desc=["Net short crossed into crowded-long regime (long-heavy) — contrarian short signal"]
        )
    }
    if (extremeSqz) {
        plotShape(
            value=zScore,
            shape="diamond",
            color=squeezeColor,
            width=4,
            label=["Extreme Squeeze"],
            desc=["Extreme short crowding detected — high squeeze probability per Brunnermeier & Pedersen (2005)"]
        )
    }
    if (extremeLng) {
        plotShape(
            value=zScore,
            shape="diamond",
            color=crowdedLongColor,
            width=4,
            label=["Extreme Long"],
            desc=["Extreme long crowding detected — potential long capitulation risk"]
        )
    }
}

// ------------------------------------------------------------------------------
// Regime Table (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regime == 1 ? "SQUEEZE RISK" : (regime == -1 ? "CROWDED LONG" : "NEUTRAL")
    var regimeTextColor = regime == 1 ? shortColor : (regime == -1 ? longColor : neutralColor)

    plotTable(
        data=[
            ["Net Short V2", regimeText],
            ["Net Short %", smoothed[0]],
            ["Z-Score", zScore[0]],
            ["Raw Ratio", ratio[0]],
            ["Session High", sessionHighShort],
            ["Session Low", sessionLowShort],
            ["Regime Changes", regimeChangeCount],
            ["Squeeze Events", squeezeCount],
            ["Crowded Long Events", crowdedLongCount]
        ],
        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
    )
}