MM Flow
FlowScripts

Perfected FlowScript

Net long / Net short Yigito Bull indicator

Net Long / Net Short (Yigito) — Perfected Edition is indexed as 152_net_long_net_short_yigito_bull.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

18.8 KB

Lines

612

Native Signal Candidates

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

8/8 guarded

Long Squeeze

line 485:9

Trigger

(showShapes) && (squeezeLongEnter)

Value

netSmooth

Deps

showShapes:input, squeezeLongEnter:var

Short Squeeze

line 495:9

Trigger

(showShapes) && (squeezeShortEnter)

Value

netSmooth

Deps

showShapes:input, squeezeShortEnter:var

Extreme Long

line 505:9

Trigger

(showShapes) && (extremeLongEnter)

Value

netSmooth

Deps

extremeLongEnter:var, showShapes:input

Extreme Short

line 515:9

Trigger

(showShapes) && (extremeShortEnter)

Value

netSmooth

Deps

extremeShortEnter:var, showShapes:input

Squeeze Exit

line 525:9

Trigger

(showShapes) && (squeezeLongExit)

Value

netSmooth

Deps

showShapes:input, squeezeLongExit:var

Squeeze Exit

line 535:9

Trigger

(showShapes) && (squeezeShortExit)

Value

netSmooth

Deps

showShapes:input, squeezeShortExit:var

Net Zero Up

line 545:9

Trigger

(showShapes) && (netCrossUp)

Value

0

Deps

netCrossUp:var, showShapes:input

Net Zero Down

line 555:9

Trigger

(showShapes) && (netCrossDn)

Value

0

Deps

netCrossDn:var, showShapes:input

152_net_long_net_short_yigito_bull.flowscript

source path: kscripts/perfected/152_net_long_net_short_yigito_bull.flowscript · sha256:a36af8eb300d19720ea9a1ef84715e54aaf30de9e3eedcbcb4d5194861a65c8b

hash verified
//@version=2
// ============================================================================
// Net Long / Net Short (Yigito) — Perfected Edition
// Author: Y (@yigit) | Enhanced by kScript Perfection Engineer
// Tags: ADVANCED, #long, #short, #net, #positioning, #sentiment, #squeeze, #regime
//
// Production-quality net positioning indicator derived from open interest and
// long/short ratio data. Implements z-score normalization, bull/bear squeeze
// regime detection, color-coded histogram, and comprehensive static state
// tracking for sentiment extreme identification and contrarian signal
// extraction.
//
// Research papers underpinning this design:
//  1. Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the
//     Basis and Open Interest in Futures Contracts": OI levels contain
//     information about future price volatility and market expectations.
//     Underpins the OI-normalization component.
//  2. "Retail Positioning as a Contrarian Indicator" — Forex Mechanics (2026):
//     extreme retail positioning (>70% long or <30% long) is a contrarian
//     signal. Validates the squeeze-threshold logic.
//  3. "Sentiment and Positioning Strategy" — Traders.MBA (2025): two-strategy
//     framework — contrarian at extremes, trend-following at moderate levels.
//     Underpins the dual-regime detection (squeeze vs. confirmation).
//  4. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint":
//     z-score event triggers for mean reversion. z = (X − μ) / σ with entry
//     thresholds at ±1σ and ±2σ. Underpins the z-score normalization layer.
//  5. Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity":
//     liquidity spirals. Crowded positioning → funding stress → squeeze.
//     Explains the causal mechanism behind extreme net positioning signals.
// ============================================================================

define(
    title="Net Long / Net Short (Yigito) — Perfected Edition",
    position="offchart",
    axis=true
)

// -----------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// -----------------------------------------------------------------------------

// --- Data Source ---
var src = input(
    name="src",
    type="select",
    defaultValue="BTCUSDT",
    label="Symbol",
    options=["BTCUSDT","ETHUSDT","SOLUSDT"],
    group="Data Source"
)
var exc = input(
    name="exc",
    type="select",
    defaultValue="BYBIT",
    label="Exchange",
    options=["BYBIT","BINANCE_FUTURES","OKEX_SWAP","DERIBIT"],
    group="Data Source"
)

// --- Smoothing ---
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=7,
    label="Smoothing Length",
    constraints={min: 1, max: 50, step: 1},
    group="Smoothing"
)
var zLen = input(
    name="zLen",
    type="number",
    defaultValue=60,
    label="Z-Score Window",
    constraints={min: 20, max: 252, step: 1},
    group="Smoothing"
)

// --- Thresholds & Regime ---
var squeezeThresh = input(
    name="squeezeThresh",
    type="number",
    defaultValue=2.0,
    label="Squeeze Z-Score Threshold",
    constraints={min: 1.0, max: 4.0, step: 0.1},
    group="Thresholds"
)
var extremeRatio = input(
    name="extremeRatio",
    type="number",
    defaultValue=70.0,
    label="Extreme Long/Short Ratio (%)",
    constraints={min: 50.0, max: 95.0, step: 1.0},
    group="Thresholds"
)
var useDynamic = input(
    name="useDynamic",
    type="boolean",
    defaultValue=true,
    label="Dynamic Squeeze Bands (vol-adjusted)",
    group="Thresholds"
)

// --- Display ---
var showLongs = input(
    name="showLongs",
    type="boolean",
    defaultValue=true,
    label="Show Longs Line",
    group="Display"
)
var showShorts = input(
    name="showShorts",
    type="boolean",
    defaultValue=true,
    label="Show Shorts Line",
    group="Display"
)
var showNet = input(
    name="showNet",
    type="boolean",
    defaultValue=true,
    label="Show Net Histogram",
    group="Display"
)
var showZScore = input(
    name="showZScore",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Line",
    group="Display"
)
var showRegimeFill = input(
    name="showRegimeFill",
    type="boolean",
    defaultValue=true,
    label="Show Regime Fill",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Squeeze Shapes",
    group="Display"
)
var showGuides = input(
    name="showGuides",
    type="boolean",
    defaultValue=true,
    label="Show Guide Lines",
    group="Display"
)
var showTable = input(
    name="showTable",
    type="boolean",
    defaultValue=true,
    label="Show Summary Table",
    group="Display"
)

// --- Colors ---
var longColor = input(
    name="longColor",
    type="color",
    defaultValue="#26a69a",
    label="Longs Color",
    group="Colors"
)
var shortColor = input(
    name="shortColor",
    type="color",
    defaultValue="#ef5350",
    label="Shorts Color",
    group="Colors"
)
var netColor = input(
    name="netColor",
    type="color",
    defaultValue="#42a5f5",
    label="Net Color",
    group="Colors"
)
var squeezeLongColor = input(
    name="squeezeLongColor",
    type="color",
    defaultValue="#00e676",
    label="Long Squeeze Color",
    group="Colors"
)
var squeezeShortColor = input(
    name="squeezeShortColor",
    type="color",
    defaultValue="#ff1744",
    label="Short Squeeze Color",
    group="Colors"
)
var neutralColor = input(
    name="neutralColor",
    type="color",
    defaultValue="#9e9e9e",
    label="Neutral Color",
    group="Colors"
)

// -----------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// -----------------------------------------------------------------------------
timeseries lsrSrc = long_short_ratio(symbol=src, exchange=exc)
timeseries oiSrc = open_interest(symbol=src, exchange=exc)
timeseries priceSrc = ohlcv(symbol=src, exchange=exc)

// Robust availability check — prevents NaN/undefined propagation
var dataAvailable = !isnan(lsrSrc.close[0]) && !isnan(oiSrc.close[0]) && !isnan(priceSrc.close[0])

if (!dataAvailable) {
    return
}

// -----------------------------------------------------------------------------
// 3. COMPUTATION — Net Positioning
// -----------------------------------------------------------------------------
// Normalize open interest by price to create a dimensionless positioning metric,
// then derive long and short counts from the long/short ratio.

timeseries oiPrice = oiSrc.close / math.max(priceSrc.close, 0.0001)

// Fallback ratio extraction: prefer total_account, then close[1], then 1.0
timeseries ratio = isnum(lsrSrc.total_account) ? lsrSrc.total_account
    : (isnum(lsrSrc.close[1]) ? lsrSrc.close[1] : 1.0)

// Long and short positioning
timeseries longs = ratio * oiPrice / (ratio + 1.0)
timeseries shorts = oiPrice / (ratio + 1.0)

// Smoothed series
timeseries longsSmooth = sma(longs, smoothLen)
timeseries shortsSmooth = sma(shorts, smoothLen)
timeseries netSmooth = longsSmooth - shortsSmooth

// Net as a percentage of total positioning (bounded metric)
timeseries totalSmooth = longsSmooth + shortsSmooth
timeseries netPct = totalSmooth > 0 ? (longsSmooth - shortsSmooth) / totalSmooth * 100.0 : 0.0

// Long percentage (contrarian threshold reference)
timeseries longPct = totalSmooth > 0 ? longsSmooth / totalSmooth * 100.0 : 50.0

// -----------------------------------------------------------------------------
// 4. Z-SCORE NORMALIZATION
// -----------------------------------------------------------------------------
// Per Zhao & Palomar (2018): z = (X − μ) / σ over a rolling window.
// Transforms raw net positioning into a regime-relative statistical measure.

timeseries netMean = sma(netSmooth, zLen)
timeseries netStd = stdev(netSmooth, zLen)
timeseries netZ = (netSmooth - netMean) / math.max(netStd, 0.0001)

timeseries netPctMean = sma(netPct, zLen)
timeseries netPctStd = stdev(netPct, zLen)
timeseries netPctZ = (netPct - netPctMean) / math.max(netPctStd, 0.0001)

// -----------------------------------------------------------------------------
// 5. REGIME DETECTION — Bull Squeeze / Bear Squeeze / Neutral
// -----------------------------------------------------------------------------
// Contrarian at extremes (z > ±2 or long% > 70/<30), trend-following at
// moderate levels. Three regimes: neutral, long squeeze (crowded longs →
// potential reversal), short squeeze (crowded shorts → potential reversal).

var squeezeLong = false
var squeezeShort = false
var squeezeLongExtreme = false
var squeezeShortExtreme = false
var regime = 0    // 0 = neutral, 1 = long squeeze, -1 = short squeeze

var dynSqHigh = squeezeThresh
var dynSqLow = -squeezeThresh
var dynExtHigh = squeezeThresh + 1.0
var dynExtLow = -(squeezeThresh + 1.0)

if (useDynamic) {
    var zVol = stddev(netZ, zLen)
    dynSqHigh = squeezeThresh + zVol * 0.5
    dynSqLow = -(squeezeThresh + zVol * 0.5)
    dynExtHigh = dynSqHigh + 1.0
    dynExtLow = dynSqLow - 1.0
    dynSqHigh = math.min(dynSqHigh, 3.0)
    dynSqLow = math.max(dynSqLow, -3.0)
    dynExtHigh = math.min(dynExtHigh, 4.0)
    dynExtLow = math.max(dynExtLow, -4.0)
}

// Z-score-based squeeze detection
if (netZ >= dynSqHigh) {
    squeezeLong = true
    regime = 1
} else if (netZ <= dynSqLow) {
    squeezeShort = true
    regime = -1
} else {
    regime = 0
}

if (netZ >= dynExtHigh) {
    squeezeLongExtreme = true
}
if (netZ <= dynExtLow) {
    squeezeShortExtreme = true
}

// Percentage-based confirmation (Forex Mechanics 2026 contrarian thresholds)
var pctLongSqueeze = longPct >= extremeRatio
var pctShortSqueeze = longPct <= (100.0 - extremeRatio)

var regimeColor = (regime == 1) ? squeezeLongColor
    : (regime == -1) ? squeezeShortColor
    : neutralColor

// -----------------------------------------------------------------------------
// 6. STATIC STATE TRACKING
// -----------------------------------------------------------------------------
static lastRegime = 0
static regimeChangeCount = 0
static squeezeLongCount = 0
static squeezeShortCount = 0
static sessionHighNet = -999999.0
static sessionLowNet = 999999.0
static sessionHighLongPct = 0.0
static sessionLowLongPct = 100.0
static lastBarIndex = 0
static totalSqueezeBars = 0

var currentBarIndex = bar_index[0]

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

    // Net positioning extremes
    if (netSmooth > sessionHighNet) {
        sessionHighNet = netSmooth
    }
    if (netSmooth < sessionLowNet) {
        sessionLowNet = netSmooth
    }

    // Long percentage extremes
    if (longPct > sessionHighLongPct) {
        sessionHighLongPct = longPct
    }
    if (longPct < sessionLowLongPct) {
        sessionLowLongPct = longPct
    }

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

    // Squeeze event counting
    if (squeezeLong) {
        squeezeLongCount = squeezeLongCount + 1
        totalSqueezeBars = totalSqueezeBars + 1
    }
    if (squeezeShort) {
        squeezeShortCount = squeezeShortCount + 1
        totalSqueezeBars = totalSqueezeBars + 1
    }
}

// Initialize on first bar
if (sessionHighNet < -900000) {
    sessionHighNet = netSmooth
    sessionLowNet = netSmooth
    sessionHighLongPct = longPct
    sessionLowLongPct = longPct
    lastRegime = regime
}

// -----------------------------------------------------------------------------
// 7. ALERT CONDITIONS
// -----------------------------------------------------------------------------
// Squeeze penetrations (entering squeeze zone)
var squeezeLongEnter = squeezeLong && !isnan(netZ[1]) && netZ[1] < dynSqHigh
var squeezeShortEnter = squeezeShort && !isnan(netZ[1]) && netZ[1] > dynSqLow
var squeezeLongExit = !squeezeLong && !isnan(netZ[1]) && netZ[1] >= dynSqHigh
var squeezeShortExit = !squeezeShort && !isnan(netZ[1]) && netZ[1] <= dynSqLow

// Extreme penetrations
var extremeLongEnter = squeezeLongExtreme && !isnan(netZ[1]) && netZ[1] < dynExtHigh
var extremeShortEnter = squeezeShortExtreme && !isnan(netZ[1]) && netZ[1] > dynExtLow

// Zero-line cross for net positioning
var netCrossUp = netSmooth > 0 && !isnan(netSmooth[1]) && netSmooth[1] <= 0
var netCrossDn = netSmooth < 0 && !isnan(netSmooth[1]) && netSmooth[1] >= 0

// -----------------------------------------------------------------------------
// 8. PLOTTING
// -----------------------------------------------------------------------------

// --- Guide lines ---
hline(value=0, color="#ffffff20", width=1)

if (showGuides) {
    hline(value=dynSqHigh, color=transparency(squeezeLongColor, 40), width=1)
    hline(value=dynSqLow, color=transparency(squeezeShortColor, 40), width=1)
    hline(value=dynExtHigh, color=transparency(squeezeLongColor, 25), width=1)
    hline(value=dynExtLow, color=transparency(squeezeShortColor, 25), width=1)
}

// --- Longs & Shorts Lines ---
if (showLongs && showShorts) {
    plotLine(
        value=longsSmooth,
        width=2,
        colors=[longColor],
        label=["Longs"],
        desc=["Smoothed long positions (" + smoothLen + "-period SMA)"]
    )
    plotLine(
        value=shortsSmooth,
        width=2,
        colors=[shortColor],
        label=["Shorts"],
        desc=["Smoothed short positions (" + smoothLen + "-period SMA)"]
    )

    // Fill between longs and shorts (net positioning ribbon)
    plotLine(
        value=[longsSmooth, shortsSmooth],
        width=1,
        colors=[transparency(longColor, 20), transparency(shortColor, 20)],
        colorIndex=0,
        fill=true,
        label=["Longs", "Shorts"],
        desc=["Fill between long and short positioning lines"]
    )
}

// --- Net Histogram (color-coded by regime) ---
if (showNet) {
    var netBull = netSmooth >= 0
    var histColor = (regime == 1) ? squeezeLongColor
        : (regime == -1) ? squeezeShortColor
        : (netBull ? longColor : shortColor)
    plotBar(
        value=netSmooth,
        colors=[histColor, histColor],
        colorIndex=0,
        width=1,
        label=["Net Exposure"],
        desc=["Net long minus short exposure (regime-colored)"]
    )
}

// --- Z-Score Line ---
if (showZScore) {
    plotLine(
        value=netZ,
        width=2,
        colors=[netColor],
        label=["Net Z-Score"],
        desc=["Z-score of net positioning (" + zLen + "-period window)"]
    )
}

// --- Regime Fill (net vs zero) ---
if (showRegimeFill) {
    var fillBull = netSmooth > 0
    var fillColor = (regime == 1) ? squeezeLongColor
        : (regime == -1) ? squeezeShortColor
        : (fillBull ? longColor : shortColor)
    plotLine(
        value=[netSmooth, 0],
        width=1,
        colors=[transparency(fillColor, 15), transparency(fillColor, 15)],
        colorIndex=0,
        fill=true,
        label=["Net", "Zero"],
        desc=["Regime fill between net positioning and zero line"]
    )
}

// --- Squeeze Shapes ---
if (showShapes) {
    if (squeezeLongEnter) {
        plotShape(
            value=netSmooth,
            shape="triangleup",
            color=squeezeLongColor,
            width=3,
            label=["Long Squeeze"],
            desc=["Net positioning entered LONG SQUEEZE zone (z > " + dynSqHigh + ") — crowded longs, potential contrarian signal"]
        )
    }
    if (squeezeShortEnter) {
        plotShape(
            value=netSmooth,
            shape="triangledown",
            color=squeezeShortColor,
            width=3,
            label=["Short Squeeze"],
            desc=["Net positioning entered SHORT SQUEEZE zone (z < " + dynSqLow + ") — crowded shorts, potential contrarian signal"]
        )
    }
    if (extremeLongEnter) {
        plotShape(
            value=netSmooth,
            shape="diamond",
            color=squeezeLongColor,
            width=4,
            label=["Extreme Long"],
            desc=["EXTREME long squeeze detected (z > " + dynExtHigh + ") — highly crowded positioning"]
        )
    }
    if (extremeShortEnter) {
        plotShape(
            value=netSmooth,
            shape="diamond",
            color=squeezeShortColor,
            width=4,
            label=["Extreme Short"],
            desc=["EXTREME short squeeze detected (z < " + dynExtLow + ") — highly crowded positioning"]
        )
    }
    if (squeezeLongExit) {
        plotShape(
            value=netSmooth,
            shape="arrowdown",
            color=squeezeLongColor,
            width=2,
            label=["Squeeze Exit"],
            desc=["Long squeeze exited — positioning normalized"]
        )
    }
    if (squeezeShortExit) {
        plotShape(
            value=netSmooth,
            shape="arrowup",
            color=squeezeShortColor,
            width=2,
            label=["Squeeze Exit"],
            desc=["Short squeeze exited — positioning normalized"]
        )
    }
    if (netCrossUp) {
        plotShape(
            value=0,
            shape="circle",
            color=longColor,
            width=2,
            label=["Net Zero Up"],
            desc=["Net positioning crossed above zero (longs > shorts)"]
        )
    }
    if (netCrossDn) {
        plotShape(
            value=0,
            shape="circle",
            color=shortColor,
            width=2,
            label=["Net Zero Down"],
            desc=["Net positioning crossed below zero (shorts > longs)"]
        )
    }
}

// -----------------------------------------------------------------------------
// 9. REGIME TABLE (last bar only)
// -----------------------------------------------------------------------------
if (isLastBar && showTable) {
    var regimeText = (regime == 1) ? "LONG SQUEEZE"
        : (regime == -1) ? "SHORT SQUEEZE"
        : "NEUTRAL"
    var regimeTextColor = (regime == 1) ? squeezeLongColor
        : (regime == -1) ? squeezeShortColor
        : neutralColor

    var longPctStr = longPct
    var shortPctStr = 100.0 - longPct

    plotTable(
        data=[
            ["Net L/S (Yigito) — Perfected", regimeText],
            ["Symbol", src],
            ["Exchange", exc],
            ["Long %", longPctStr],
            ["Short %", shortPctStr],
            ["Net Position", netSmooth],
            ["Net Z-Score", netZ],
            ["Longs", longsSmooth],
            ["Shorts", shortsSmooth],
            ["Session High Net", sessionHighNet],
            ["Session Low Net", sessionLowNet],
            ["Session High Long %", sessionHighLongPct],
            ["Session Low Long %", sessionLowLongPct],
            ["Long Squeezes", squeezeLongCount],
            ["Short Squeezes", squeezeShortCount],
            ["Regime Changes", regimeChangeCount]
        ],
        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=9,
        cellPadding=3
    )
}