MM Flow
FlowScripts

Perfected FlowScript

Net long Yigitobull indicator

Net Long YigitoBull Indicator V2 is indexed as 224_net_long_yigitobull_indicator.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

340

Native Signal Candidates

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

4/4 guarded

Crowded Long

line 267:9

Trigger

(showShapes) && (crossUp)

Value

smoothed

Deps

crossUp:var, showShapes:input

Crowded Short

line 277:9

Trigger

(showShapes) && (crossDn)

Value

smoothed

Deps

crossDn:var, showShapes:input

Squeeze Risk

line 287:9

Trigger

(showShapes) && (squeezeUp)

Value

smoothed

Deps

showShapes:input, squeezeUp:var

Short Squeeze Setup

line 297:9

Trigger

(showShapes) && (crowdedShortDn)

Value

smoothed

Deps

crowdedShortDn:var, showShapes:input

224_net_long_yigitobull_indicator.flowscript

source path: kscripts/perfected/224_net_long_yigitobull_indicator.flowscript · sha256:6ccb978aee977dd8bc7946cbe69d088aa55e54c3f7a7d4f35cd1df738cf155e0

hash verified
//@version=2
// ============================================================================
// Net Long YigitoBull Indicator V2 — Production-Quality Sentiment Oscillator
// Author: Y (@yigit)  |  Perfected by: kScript Perfection Engineer
// Tags: CORE, ADVANCED, #net, #long, #sentiment, #contrarian, #positioning
//
// Net-long positioning sentiment indicator with z-score normalization,
// squeeze/crowded regime detection, color-coded histogram, fill, and shape
// markers for contrarian signal extraction. Reads long/short ratio from
// supported exchanges and converts it into a normalized oscillator.
//
// FORMULA FOUNDATION:
// 1. Net Long %: NetLong = Long / (Long + Short) × 100  per Forex Mechanics (2026).
// 2. Z-Score Normalization: z = (NetLong − μ) / σ over rolling window
//    per Zhao & Palomar (2018) mean-reversion signal framework.
// 3. Regime Segmentation (Crowded/Crowded Short/Neutral/Moderate):
//    > 70% = crowded long (squeeze risk) per Forex Mechanics (2026).
//    < 30% = crowded short (contrarian buy) per Traders.MBA (2025).
//    45–55% = neutral equilibrium.
// 4. Contrarian Signal Strength: grows nonlinearly as positioning diverges
//    from 50/50 per Traders.MBA (2025).
// 5. Squeeze Dynamics: extreme short positioning (>70% short) creates
//    vulnerability to predatory price action per Brunnermeier & Pedersen (2005).
//
// RESEARCH BASIS:
//  • Forex Mechanics (2026), "Retail Positioning as a Contrarian Indicator".
//    Extreme net-long readings (>70%) signal crowded positioning and function
//    as contrarian signals because retail traders statistically take positions
//    against the trend.
//  • Traders.MBA (2025), "Sentiment and Positioning Strategy". Two primary
//    strategies: (1) Contrarian at extremes; (2) Trend-confirmation when moderate.
//    Signal strength grows nonlinearly as positioning diverges from 50/50.
//  • Brunnermeier & Pedersen (2005), "Predatory Trading", J. Finance 60(4),
//    1825–1863. Models how traders deliberately trade against others to force
//    distress. Extreme short positioning creates squeeze vulnerability.
//  • Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity",
//    RFS 22(6):2201–2238. Liquidity spirals explain cascade mechanics when
//    positioning is one-sided and funding tightens.
//  • Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint",
//    IEEE TSP. Z-score event triggers at ±2σ for statistical significance.
//  • Baker & Wurgler (2006), "Investor Sentiment and the Cross-Section of Stock
//    Returns", JF 61(4):1645–1680. Composite sentiment construction methodology.
// ============================================================================

define(
    title="Net Long YigitoBull Indicator 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=5, label="EMA Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Smoothing")
var signalLen = input(name="signalLen", type="number", defaultValue=20, label="Signal SMA Length", constraints={min: 2, max: 100, step: 1}, group="Smoothing")

// --- Z-Score ---
var zLookback = input(name="zLookback", type="number", defaultValue=100, label="Z-Score Lookback (bars)", constraints={min: 10, max: 500, step: 5}, group="Z-Score")
var useZScore = input(name="useZScore", type="boolean", defaultValue=true, label="Enable Z-Score Normalization", group="Z-Score")

// --- Thresholds & Regime ---
var extremeLong = input(name="extremeLong", type="number", defaultValue=70.0, label="Extreme Long Threshold (%)", constraints={min: 55.0, max: 95.0, step: 1.0}, group="Thresholds")
var extremeShort = input(name="extremeShort", type="number", defaultValue=30.0, label="Extreme Short Threshold (%)", constraints={min: 5.0, max: 45.0, step: 1.0}, group="Thresholds")
var squeezeBand = input(name="squeezeBand", type="number", defaultValue=80.0, label="Squeeze Risk Threshold (%)", constraints={min: 60.0, max: 98.0, step: 1.0}, group="Thresholds")
var crowdedShortBand = input(name="crowdedShortBand", type="number", defaultValue=20.0, label="Crowded Short Threshold (%)", constraints={min: 2.0, max: 40.0, step: 1.0}, group="Thresholds")

// --- Display ---
var showLine = input(name="showLine", type="boolean", defaultValue=true, label="Show Net Long Line", group="Display")
var showSignal = input(name="showSignal", type="boolean", defaultValue=true, label="Show Signal SMA", group="Display")
var showRibbon = input(name="showRibbon", type="boolean", defaultValue=true, label="Show Line-Signal Fill", group="Display")
var showHistogram = input(name="showHistogram", type="boolean", defaultValue=true, label="Show Histogram", group="Display")
var showZLine = input(name="showZLine", type="boolean", defaultValue=false, label="Show Z-Score Line", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")

// --- Colors ---
var longColor = input(name="longColor", type="color", defaultValue="#26a69a", label="Long Pressure Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var shortColor = input(name="shortColor", type="color", defaultValue="#ef5350", label="Short Pressure Color", group="Colors")
var squeezeColor = input(name="squeezeColor", type="color", defaultValue="#ff1744", label="Squeeze Risk Color", group="Colors")
var crowdedShortColor = input(name="crowdedShortColor", type="color", defaultValue="#00e676", label="Crowded Short Color", group="Colors")
var signalColor = input(name="signalColor", type="color", defaultValue="#ffffff", label="Signal Line Color", group="Colors")
var zLineColor = input(name="zLineColor", type="color", defaultValue="#ffd54f", label="Z-Score Line Color", group="Colors")

// ------------------------------------------------------------------------------
// Data Sources & NaN Guard
// ------------------------------------------------------------------------------
timeseries lsr = long_short_ratio(symbol=symbol, exchange=exchange)
timeseries ratio = isnum(lsr.total_account) ? lsr.total_account : (isnan(lsr[1]) ? 1.0 : lsr[1])

if (isnan(ratio[0])) {
    return
}

// Net Long % = Long / (Long + Short) × 100
timeseries netLong = (ratio / (ratio + 1.0)) * 100.0

// ------------------------------------------------------------------------------
// Smoothing & Signal
// ------------------------------------------------------------------------------
timeseries smoothed = ema(source=netLong, period=smoothLen)
timeseries signal = sma(source=smoothed, period=signalLen)

// Momentum histogram (netLong deviation from signal)
timeseries hist = smoothed - signal

// ------------------------------------------------------------------------------
// Z-Score Normalization (Zhao & Palomar 2018)
// ------------------------------------------------------------------------------
// z = (NetLong − μ) / σ over rolling window.

var meanNetLong = sma(source=smoothed, period=zLookback)
var stdNetLong = stddev(source=smoothed, period=zLookback)
var safeStdNetLong = stdNetLong > 0 ? stdNetLong : 1.0
var zScore = useZScore ? (smoothed - meanNetLong) / safeStdNetLong : smoothed

// ------------------------------------------------------------------------------
// Regime Detection (Squeeze / Crowded / Neutral / Moderate)
// ------------------------------------------------------------------------------
// Regime classification:
//   Squeeze risk:      smoothed >= squeezeBand         (extreme long crowding)
//   Crowded long:      smoothed >= extremeLong         (contrarian sell signal)
//   Crowded short:     smoothed <= crowdedShortBand    (contrarian buy signal)
//   Extreme short:     smoothed <= extremeShort        (squeeze risk to shorts)
//   Neutral:           between extremeShort and extremeLong

var regimeSqueeze = smoothed >= squeezeBand
var regimeCrowdedLong = smoothed >= extremeLong && smoothed < squeezeBand
var regimeExtremeShort = smoothed <= extremeShort
var regimeCrowdedShort = smoothed <= crowdedShortBand && smoothed > extremeShort
var regimeNeutral = !regimeSqueeze && !regimeCrowdedLong && !regimeExtremeShort && !regimeCrowdedShort

var regimeColor = regimeSqueeze ? squeezeColor : (regimeCrowdedLong ? longColor : (regimeExtremeShort ? squeezeColor : (regimeCrowdedShort ? crowdedShortColor : neutralColor)))

// Determine color index: 0 = long/squeeze, 1 = neutral, 2 = short/crowded short
var colIdx = 0
colIdx = regimeNeutral ? 1 : colIdx
colIdx = (regimeExtremeShort || regimeCrowdedShort) ? 2 : colIdx

// ------------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ------------------------------------------------------------------------------
// Tracks regime transitions, session extremes, and extreme-event counts.

static lastRegime = 0
static regimeChangeCount = 0
static sessionHighNetLong = -999999.0
static sessionLowNetLong = 999999.0
static squeezeCount = 0
static crowdedShortCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

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

    if (netLong > sessionHighNetLong) {
        sessionHighNetLong = netLong
    }
    if (netLong < sessionLowNetLong) {
        sessionLowNetLong = netLong
    }

    var currentRegime = regimeSqueeze ? 4 : (regimeCrowdedLong ? 3 : (regimeExtremeShort ? -4 : (regimeCrowdedShort ? -3 : 0)))
    if (lastRegime != currentRegime) {
        lastRegime = currentRegime
        regimeChangeCount = regimeChangeCount + 1
    }

    if (regimeSqueeze) {
        squeezeCount = squeezeCount + 1
    }
    if (regimeExtremeShort || regimeCrowdedShort) {
        crowdedShortCount = crowdedShortCount + 1
    }
}

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

// --- Midline (50% equilibrium) ---
hline(value=50, color="#ffffff20", width=1)

// --- Threshold guides ---
hline(value=extremeLong, color=transparency(longColor, 50), width=1)
hline(value=extremeShort, color=transparency(shortColor, 50), width=1)
hline(value=squeezeBand, color=transparency(squeezeColor, 30), width=1)
hline(value=crowdedShortBand, color=transparency(crowdedShortColor, 30), width=1)

// --- Net Long Line (regime-colored) ---
if (showLine) {
    plotLine(
        value=smoothed,
        width=2,
        colors=[regimeColor],
        label=["Net Long %"],
        desc=["Percentage of accounts positioned long (EMA-smoothed). Regime-colored."]
    )
}

// --- Signal SMA ---
if (showSignal) {
    plotLine(
        value=signal,
        width=1,
        colors=[signalColor],
        label=["Signal SMA"],
        desc=["SMA of smoothed net-long percentage (" + signalLen + ")"]
    )
}

// --- Line-Signal Ribbon Fill ---
if (showRibbon) {
    var ribbonBull = smoothed > signal
    plotLine(
        value=[smoothed, signal],
        width=1,
        colors=[transparency(longColor, 20), transparency(shortColor, 20)],
        colorIndex=ribbonBull ? 0 : 1,
        fill=true,
        label=["Net Long", "Signal"],
        desc=["Fill between net-long line and signal SMA"]
    )
}

// --- Histogram (color-coded by regime) ---
if (showHistogram) {
    var histColor = regimeSqueeze ? squeezeColor : (regimeCrowdedLong ? longColor : (regimeExtremeShort ? squeezeColor : (regimeCrowdedShort ? crowdedShortColor : neutralColor)))
    plotBar(
        value=hist,
        colors=[histColor],
        width=1,
        label=["Net Long Momentum"],
        desc=["Histogram of net-long deviation from signal SMA"]
    )
}

// --- Z-Score Line ---
if (showZLine && useZScore) {
    plotLine(
        value=zScore,
        width=1,
        colors=[zLineColor],
        label=["Z-Score"],
        desc=["Z-score of smoothed net-long percentage (" + zLookback + "-bar lookback)"]
    )
}

// --- Regime transition shapes ---
if (showShapes) {
    var crossUp = smoothed >= extremeLong && !isnan(smoothed[1]) && smoothed[1] < extremeLong
    var crossDn = smoothed <= extremeShort && !isnan(smoothed[1]) && smoothed[1] > extremeShort
    var squeezeUp = smoothed >= squeezeBand && !isnan(smoothed[1]) && smoothed[1] < squeezeBand
    var crowdedShortDn = smoothed <= crowdedShortBand && !isnan(smoothed[1]) && smoothed[1] > crowdedShortBand

    if (crossUp) {
        plotShape(
            value=smoothed,
            shape="triangleup",
            color=longColor,
            width=3,
            label=["Crowded Long"],
            desc=["Net long crossed above extreme threshold — contrarian caution (squeeze risk)"]
        )
    }
    if (crossDn) {
        plotShape(
            value=smoothed,
            shape="triangledown",
            color=shortColor,
            width=3,
            label=["Crowded Short"],
            desc=["Net long crossed below extreme threshold — contrarian opportunity (potential squeeze)"]
        )
    }
    if (squeezeUp) {
        plotShape(
            value=smoothed,
            shape="diamond",
            color=squeezeColor,
            width=4,
            label=["Squeeze Risk"],
            desc=["Extreme long crowding detected — elevated short-squeeze risk"]
        )
    }
    if (crowdedShortDn) {
        plotShape(
            value=smoothed,
            shape="diamond",
            color=crowdedShortColor,
            width=4,
            label=["Short Squeeze Setup"],
            desc=["Extreme short crowding detected — potential long-squeeze / short-covering setup"]
        )
    }
}

// ------------------------------------------------------------------------------
// Regime Table (last bar only)
// ------------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeSqueeze ? "SQUEEZE RISK" : (regimeCrowdedLong ? "CROWDED LONG" : (regimeExtremeShort ? "EXTREME SHORT" : (regimeCrowdedShort ? "CROWDED SHORT" : "NEUTRAL")))
    var regimeTextColor = regimeSqueeze ? squeezeColor : (regimeCrowdedLong ? longColor : (regimeExtremeShort ? squeezeColor : (regimeCrowdedShort ? crowdedShortColor : neutralColor)))

    plotTable(
        data=[
            ["Net Long V2", regimeText],
            ["Net Long %", smoothed[0]],
            ["Signal", signal[0]],
            ["Momentum", hist[0]],
            ["Z-Score", zScore[0]],
            ["Session High", sessionHighNetLong],
            ["Session Low", sessionLowNetLong],
            ["Squeeze Events", squeezeCount],
            ["Crowded Short Events", crowdedShortCount]
        ],
        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
    )
}