MM Flow
FlowScripts

Perfected FlowScript

Longs and sorts

Longs and Shorts — Perfected Edition is indexed as 165_longs_and_shorts.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.5 KB

Lines

462

Native Signal Candidates

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

6/6 guarded

Long Extreme

line 365:9

Trigger

(showShapes) && (zScoreExtremePos)

Value

longsSm

Deps

showShapes:input, zScoreExtremePos:var

Short Extreme

line 375:9

Trigger

(showShapes) && (zScoreExtremeNeg)

Value

shortsSm

Deps

showShapes:input, zScoreExtremeNeg:var

Net Flip Bull

line 387:9

Trigger

(showShapes) && (netCrossUp)

Value

0

Deps

netCrossUp:var, showShapes:input

Net Flip Bear

line 397:9

Trigger

(showShapes) && (netCrossDown)

Value

0

Deps

netCrossDown:var, showShapes:input

Long Regime

line 409:9

Trigger

(showShapes) && (neutralToLong)

Value

longsSm

Deps

neutralToLong:var, showShapes:input

Short Regime

line 419:9

Trigger

(showShapes) && (neutralToShort)

Value

shortsSm

Deps

neutralToShort:var, showShapes:input

165_longs_and_shorts.flowscript

source path: kscripts/perfected/165_longs_and_shorts.flowscript · sha256:8482f8436a885f30a63df8c9a3fac12c6ffdec7df7a0c3bde1be8dc9f77d930d

hash verified
//@version=2
// ============================================================================
// Longs and Shorts — Perfected Edition
// Author: V (@victoryvt) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #longs, #shorts, #positioning, #zscore, #regime, #sentiment
//
// Production-quality futures positioning indicator with dual-sided exposure
// tracking, z-score normalization, multi-regime detection, and comprehensive
// color-coded histogram/shape visualization.
//
// Research papers underpinning this design:
//  1. Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the
//     Basis and Open Interest in Futures Contracts": foundational relationship
//     between OI, futures basis, and volatility. Higher OI = greater information
//     flow and price discovery.
//  2. He & Manela (2022), "Fundamentals of Perpetual Futures": no-arbitrage
//     perpetual futures pricing; past return momentum explains futures-spot
//     gap with R² > 50%. Validates momentum-anchored positioning analysis.
//  3. Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity":
//     liquidity spirals in leveraged markets. Directly supports liquidation
//     cascade mechanics and OI-driven volatility forecasting.
//  4. Baker & Wurgler (2006), "Investor Sentiment and the Cross-Section of
//     Stock Returns": composite sentiment index construction. Supports
//     multi-factor positioning sentiment aggregation.
//  5. Amberdata (2026), "Leverage & Liquidations: The $31B Deleveraging":
//     concrete liquidation thresholds. 5% of OI liquidation intensity as cascade
//     trigger; 15% APR funding as overheating signal.
//  6. Forex Mechanics (2026), "Retail Positioning as a Contrarian Indicator":
//     long/short ratios > 70/30 are extreme contrarian signals.
// ============================================================================

define(
    title="Longs and Shorts — 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="BINANCE_FUTURES",
    label="Exchange",
    options=["BINANCE_FUTURES", "BYBIT", "OKEX_SWAP"],
    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 zScoreLen = input(
    name="zScoreLen",
    type="number",
    defaultValue=20,
    label="Z-Score Lookback",
    constraints={min: 5, max: 100, step: 1},
    group="Smoothing"
)

// --- 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 Exposure Histogram",
    group="Display"
)
var showZScore = input(
    name="showZScore",
    type="boolean",
    defaultValue=true,
    label="Show Z-Score Oscillator",
    group="Display"
)
var showShapes = input(
    name="showShapes",
    type="boolean",
    defaultValue=true,
    label="Show Alert Shapes",
    group="Display"
)
var showTable = input(
    name="showTable",
    type="boolean",
    defaultValue=true,
    label="Show Summary Table",
    group="Display"
)

// --- Regime Thresholds ---
var longDomThreshold = input(
    name="longDomThreshold",
    type="number",
    defaultValue=0.6,
    label="Long Dominant Ratio",
    constraints={min: 0.51, max: 0.95, step: 0.01},
    group="Regime Thresholds"
)
var shortDomThreshold = input(
    name="shortDomThreshold",
    type="number",
    defaultValue=0.4,
    label="Short Dominant Ratio",
    constraints={min: 0.05, max: 0.49, step: 0.01},
    group="Regime Thresholds"
)
var zScoreExtreme = input(
    name="zScoreExtreme",
    type="number",
    defaultValue=2.0,
    label="Z-Score Extreme Threshold",
    constraints={min: 1.0, max: 4.0, step: 0.1},
    group="Regime Thresholds"
)

// --- 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 netBullColor = input(
    name="netBullColor",
    type="color",
    defaultValue="#00e676",
    label="Net Bull Color",
    group="Colors"
)
var netBearColor = input(
    name="netBearColor",
    type="color",
    defaultValue="#ff5252",
    label="Net Bear Color",
    group="Colors"
)
var zScoreColor = input(
    name="zScoreColor",
    type="color",
    defaultValue="#42a5f5",
    label="Z-Score 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)

timeseries price = priceSrc.close

if (isnan(price[0]) || isnan(oiSrc.close[0]) || isnan(lsrSrc.total_account[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. CORE COMPUTATION
// ---------------------------------------------------------------------------
// OI in coin terms (divide by price to get coin count)
timeseries oiCoins = oiSrc.close / math.max(price, 0.0001)

// Long/short ratio (total_account if available, fallback to close series)
timeseries ratio = isnum(lsrSrc.total_account) ? lsrSrc.total_account
    : (isnum(lsrSrc.close[1]) ? lsrSrc.close[1] : 1.0)

// Raw long and short position counts derived from OI and ratio
// ratio = longs / shorts, therefore longs = ratio * shorts
// OI = longs + shorts = ratio * shorts + shorts = shorts * (ratio + 1)
timeseries longs = ratio * oiCoins / (ratio + 1.0)
timeseries shorts = oiCoins / (ratio + 1.0)

// Smoothed position lines
timeseries longsSm = sma(longs, smoothLen)
timeseries shortsSm = sma(shorts, smoothLen)

// Net exposure (positive = longs dominate, negative = shorts dominate)
timeseries netExposure = longsSm - shortsSm

// Position ratio (long dominance metric)
timeseries posRatio = (longsSm + shortsSm) > 0 ? longsSm / (longsSm + shortsSm) : 0.5

// ---------------------------------------------------------------------------
// 4. Z-SCORE NORMALIZATION
// ---------------------------------------------------------------------------
// Z-score of net exposure: measures how unusual current positioning is
// relative to recent history. Standardizes across instruments.

timeseries netMean = sma(netExposure, zScoreLen)
timeseries netStd = stddev(netExposure, zScoreLen)
timeseries netZScore = netStd > 0 ? (netExposure - netMean) / netStd : 0

// Z-score of long/short ratio (sentiment extremity)
timeseries ratioMean = sma(ratio, zScoreLen)
timeseries ratioStd = stddev(ratio, zScoreLen)
timeseries ratioZScore = ratioStd > 0 ? (ratio - ratioMean) / ratioStd : 0

// ---------------------------------------------------------------------------
// 5. REGIME DETECTION
// ---------------------------------------------------------------------------
// Regime classification based on position ratio:
//   Long Dominant: posRatio > longDomThreshold (e.g., 0.60)
//   Short Dominant: posRatio < shortDomThreshold (e.g., 0.40)
//   Neutral: everything between

var regimeLongDom = posRatio > longDomThreshold
var regimeShortDom = posRatio < shortDomThreshold
var regimeNeutral = !regimeLongDom && !regimeShortDom

var regimeColor = regimeLongDom ? longColor : (regimeShortDom ? shortColor : neutralColor)

// ---------------------------------------------------------------------------
// 6. ALERT CONDITIONS
// ---------------------------------------------------------------------------
// Z-score extremes (contrarian signals at ±2σ)
var zScoreExtremePos = netZScore > zScoreExtreme && netZScore[1] <= zScoreExtreme
var zScoreExtremeNeg = netZScore < -zScoreExtreme && netZScore[1] >= -zScoreExtreme

// Regime transitions
var longToNeutral = regimeLongDom && !regimeLongDom[1]
var shortToNeutral = regimeShortDom && !regimeShortDom[1]
var neutralToLong = regimeLongDom && !regimeLongDom[1]
var neutralToShort = regimeShortDom && !regimeShortDom[1]

// Zero-line cross of net exposure
var netCrossUp = netExposure > 0 && netExposure[1] <= 0
var netCrossDown = netExposure < 0 && netExposure[1] >= 0

// ---------------------------------------------------------------------------
// 7. STATIC TRACKING (stateful bar-to-bar)
// ---------------------------------------------------------------------------
static lastLongPeak = 0.0
static lastShortPeak = 0.0
static lastNetPeak = 0.0
static lastNetTrough = 0.0

if (lastLongPeak < 0) {
    lastLongPeak = longsSm[0]
    lastShortPeak = shortsSm[0]
    lastNetPeak = netExposure[0]
    lastNetTrough = netExposure[0]
} else {
    if (longsSm[0] > lastLongPeak) {
        lastLongPeak = longsSm[0]
    }
    if (shortsSm[0] > lastShortPeak) {
        lastShortPeak = shortsSm[0]
    }
    if (netExposure[0] > lastNetPeak) {
        lastNetPeak = netExposure[0]
    }
    if (netExposure[0] < lastNetTrough) {
        lastNetTrough = netExposure[0]
    }
}

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

// --- Zero line ---
hline(value=0, color="#ffffff20", width=1)

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

// --- Net Exposure Histogram (regime-colored) ---
if (showNet) {
    var netBull = netExposure >= 0
    plotBar(
        value=netExposure,
        colors=[transparency(netBullColor, 70), transparency(netBearColor, 70)],
        colorIndex=netBull ? 0 : 1,
        width=1,
        label=["Net Exposure"],
        desc=["Net long minus short exposure (regime-colored)"]
    )
}

// --- Z-Score Oscillator ---
if (showZScore) {
    plotLine(
        value=netZScore,
        width=2,
        colors=[zScoreColor],
        label=["Z-Score"],
        desc=["Z-score of net exposure (" + zScoreLen + " lookback)"]
    )
    // Z-score reference bands
    hline(value=zScoreExtreme, color=transparency(shortColor, 60), width=1)
    hline(value=-zScoreExtreme, color=transparency(longColor, 60), width=1)
    hline(value=1, color=transparency(neutralColor, 40), width=1)
    hline(value=-1, color=transparency(neutralColor, 40), width=1)
}

// --- Shape Markers (regime transitions & z-score extremes) ---
if (showShapes) {
    // Z-score extreme contrarian signals
    if (zScoreExtremePos) {
        plotShape(
            value=longsSm,
            shape="triangledown",
            colorIndex=shortColor,
            width=2,
            label=["Long Extreme"],
            desc=["Extreme long dominance (z-score > +" + zScoreExtreme + ") — contrarian warning"]
        )
    }
    if (zScoreExtremeNeg) {
        plotShape(
            value=shortsSm,
            shape="triangleup",
            colorIndex=longColor,
            width=2,
            label=["Short Extreme"],
            desc=["Extreme short dominance (z-score < -" + zScoreExtreme + ") — contrarian warning"]
        )
    }

    // Zero-line cross of net exposure
    if (netCrossUp) {
        plotShape(
            value=0,
            shape="triangleup",
            colorIndex=netBullColor,
            width=2,
            label=["Net Flip Bull"],
            desc=["Net exposure crossed above zero — longs now dominant"]
        )
    }
    if (netCrossDown) {
        plotShape(
            value=0,
            shape="triangledown",
            colorIndex=netBearColor,
            width=2,
            label=["Net Flip Bear"],
            desc=["Net exposure crossed below zero — shorts now dominant"]
        )
    }

    // Regime transition markers
    if (neutralToLong) {
        plotShape(
            value=longsSm,
            shape="circle",
            colorIndex=longColor,
            width=2,
            label=["Long Regime"],
            desc=["Positioning shifted to long-dominant regime"]
        )
    }
    if (neutralToShort) {
        plotShape(
            value=shortsSm,
            shape="circle",
            colorIndex=shortColor,
            width=2,
            label=["Short Regime"],
            desc=["Positioning shifted to short-dominant regime"]
        )
    }
}

// ---------------------------------------------------------------------------
// 9. SUMMARY TABLE (last bar only)
// ---------------------------------------------------------------------------
if (showTable && isLastBar) {
    var regimeText = regimeLongDom ? "LONG DOMINANT" : (regimeShortDom ? "SHORT DOMINANT" : "NEUTRAL")
    var regimeTextColor = regimeLongDom ? longColor : (regimeShortDom ? shortColor : neutralColor)

    plotTable(
        data=[
            ["Longs & Shorts — Perfected", regimeText],
            ["Longs (coins)", longsSm[0]],
            ["Shorts (coins)", shortsSm[0]],
            ["Net Exposure", netExposure[0]],
            ["Long Ratio", posRatio[0]],
            ["Net Z-Score", netZScore[0]],
            ["Ratio Z-Score", ratioZScore[0]],
            ["Long Peak", lastLongPeak],
            ["Short Peak", lastShortPeak]
        ],
        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
    )
}