Perfected FlowScript
Net Shorts
Net Shorts — Perfected Edition is indexed as 143_net_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.9 KB
Lines
445
Native Signal Candidates
5 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Crowded Short
line 365:9
Trigger
(showShapes) && (zCrossUp)
Value
aggZ
Deps
showShapes:input, zCrossUp:var
Extreme Cover
line 375:9
Trigger
(showShapes) && (zCrossDown)
Value
aggZ
Deps
showShapes:input, zCrossDown:var
Shorts Rising
line 385:9
Trigger
(showShapes) && (zeroCrossUp)
Value
aggShort
Deps
showShapes:input, zeroCrossUp:var
Shorts Falling
line 395:9
Trigger
(showShapes) && (zeroCrossDown)
Value
aggShort
Deps
showShapes:input, zeroCrossDown:var
Squeeze Alert
line 405:9
Trigger
(showShapes) && (squeezeAlert)
Value
aggShort
Deps
showShapes:input, squeezeAlert:var
143_net_shorts.flowscript
source path: kscripts/perfected/143_net_shorts.flowscript · sha256:7dd35013f96c2dfe6180d5ca1236f7eeaaa4a79ed976bcecc85644978adad07b
//@version=2
// ============================================================================
// Net Shorts — Perfected Edition
// Author: BackQuant (@BackQuant) | Enhanced by kScript Perfection Engineer
// Tags: ADVANCED, SPECIALIZED, #net, #shorts, #positioning, #oi, #zscore,
// #regime, #histogram
//
// Production-grade net short positioning estimator with z-score normalization,
// regime detection, color-coded histogram, shape markers, and fill zones.
// Combines open-interest delta decomposition with price-based weighting and
// statistical standardization to identify short positioning extremes.
//
// Academic foundations:
// 1. Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the
// Basis and Open Interest in Futures Contracts" (Journal of Finance 50(1),
// 281–300). Establishes OI as containing information about future volatility
// and market expectations. Higher OI = greater information flow and price
// discovery activity. Underpins OI-based positioning decomposition.
// 2. Brunnermeier & Pedersen (2005), "Predatory Trading" (Journal of Finance
// 60(4), 1825–1863). Models how traders deliberately trade against others to
// force distress. Understanding net short positioning is critical for
// squeeze dynamics — when shorts are crowded, predatory buying can force
// short covering. Key concept: traders buy to push prices up, causing short
// positions to lose value and forcing cover.
// 3. Adrian & Shin (2010), "Liquidity and Leverage" (Journal of Financial
// Intermediation 19(3), 418–437). Shows leverage is procyclical —
// intermediaries expand leverage during booms and reduce during busts.
// Net short estimates help measure this procyclical positioning dynamic
// from the short side.
// 4. Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity"
// (Review of Financial Studies 22(6), 2201–2238). The liquidity spiral
// model explains why leveraged markets experience sudden, non-linear price
// moves when margin thresholds are breached. Directly supports liquidation
// cascade mechanics and extreme positioning detection.
// 5. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint"
// (IEEE TSP). z̄_t = (z_t − μ_z)/σ_z with entry thresholds at Δ = d×σ_z
// (typically d = 1 or 2). Underpins z-score normalization and regime
// classification used here.
// 6. He & Manela (2022), "Fundamentals of Perpetual Futures" (arXiv:2212.06888).
// First rigorous no-arbitrage analysis of perpetual futures pricing. Past
// return momentum significantly explains futures-spot gap (R² > 50%).
// Validates funding rate deviation as a sentiment/positioning signal.
// ============================================================================
define(
title="Net Shorts — Perfected Edition",
position="offchart",
axis=true
)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// ---------------------------------------------------------------------------
// --- Positioning Model ---
var anchor = input(
name="anchor",
type="select",
defaultValue="Daily",
label="Anchor Period",
options=["Hourly", "Daily", "Weekly", "Monthly", "Rolling", "Full"],
group="Positioning Model"
)
var smoothLen = input(
name="smoothLen",
type="number",
defaultValue=5,
label="Smoothing Length",
constraints={min: 1, max: 50, step: 1},
group="Positioning Model"
)
var oiLookback = input(
name="oiLookback",
type="number",
defaultValue=14,
label="OI Lookback",
constraints={min: 5, max: 100, step: 1},
group="Positioning Model"
)
var priceWeight = input(
name="priceWeight",
type="number",
defaultValue=0.6,
label="Price Weight (0–1)",
constraints={min: 0.0, max: 1.0, step: 0.1},
group="Positioning Model"
)
// --- Z-Score ---
var zLookback = input(
name="zLookback",
type="number",
defaultValue=20,
label="Z-Score Lookback",
constraints={min: 5, max: 100, step: 1},
group="Z-Score"
)
var zExtreme = input(
name="zExtreme",
type="number",
defaultValue=2.0,
label="Extreme Z-Score Threshold",
constraints={min: 1.0, max: 5.0, step: 0.5},
group="Z-Score"
)
// --- Display ---
var showLine = input(
name="showLine",
type="boolean",
defaultValue=true,
label="Show Net Short Line",
group="Display"
)
var showHistogram = input(
name="showHistogram",
type="boolean",
defaultValue=true,
label="Show Color-Coded Histogram",
group="Display"
)
var showZScore = input(
name="showZScore",
type="boolean",
defaultValue=true,
label="Show Z-Score Line",
group="Display"
)
var showFill = input(
name="showFill",
type="boolean",
defaultValue=true,
label="Show Fill Zone",
group="Display"
)
var showZero = input(
name="showZero",
type="boolean",
defaultValue=true,
label="Show Zero Line",
group="Display"
)
var showShapes = input(
name="showShapes",
type="boolean",
defaultValue=true,
label="Show Extreme Shape Markers",
group="Display"
)
var showTable = input(
name="showTable",
type="boolean",
defaultValue=true,
label="Show Summary Table (last bar)",
group="Display"
)
// --- Colors ---
var shortColor = input(
name="shortColor",
type="color",
defaultValue="#ef5350",
label="Short Expansion Color",
group="Colors"
)
var coverColor = input(
name="coverColor",
type="color",
defaultValue="#26a69a",
label="Short Covering Color",
group="Colors"
)
var zLineColor = input(
name="zLineColor",
type="color",
defaultValue="#ab47bc",
label="Z-Score Line Color",
group="Colors"
)
var squeezeColor = input(
name="squeezeColor",
type="color",
defaultValue="#ffd700",
label="Squeeze Warning Color",
group="Colors"
)
// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries c = bars.close
timeseries h = bars.high
timeseries l = bars.low
timeseries t = bars.time
if (isnan(c[0]) || isnan(h[0]) || isnan(l[0])) {
return
}
// Multi-exchange OI aggregation (best-effort; falls back to zero)
timeseries oiBybit = open_interest(symbol="BTCUSDT", exchange="BYBIT")
timeseries oiOkex = open_interest(symbol="BTC-USDT-SWAP", exchange="OKEX_SWAP")
timeseries oiRaw = (!isnan(oiBybit.close) && !isnan(oiOkex.close)) ? ((oiBybit.close + oiOkex.close) / 2.0) : (isnan(oiBybit.close) ? oiOkex.close : oiBybit.close)
timeseries oi = isnan(oiRaw) ? 0.0 : oiRaw
// ---------------------------------------------------------------------------
// 3. NET SHORT ESTIMATION
// ---------------------------------------------------------------------------
// OI Delta = net change in open interest
timeseries oiDelta = oi - nz(oi[1])
// Short allocation: inverse of long logic
// Price below midpoint → higher short allocation
timeseries midPx = (h + l) / 2.0
timeseries belowMid = (c < midPx) ? 1.0 : 0.0
timeseries shortWeight = belowMid * priceWeight + (1.0 - priceWeight) * 0.5
// Net short estimate: OI delta × (2×shortWeight − 1)
// When shortWeight > 0.5, netShort > 0 (short expansion)
// When shortWeight < 0.5, netShort < 0 (short covering / long expansion)
timeseries netShortRaw = oiDelta * (2.0 * shortWeight - 1.0)
timeseries netShort = ema(netShortRaw, smoothLen)
// ---------------------------------------------------------------------------
// 4. ANCHOR AGGREGATION (static tracking)
// ---------------------------------------------------------------------------
var anchorMs = 86400000
if (anchor == "Hourly") anchorMs = 3600000
if (anchor == "Weekly") anchorMs = 604800000
if (anchor == "Monthly") anchorMs = 2592000000
var anchorId = math.floor(t / anchorMs)
static aggShort = 0.0
static lastAnchor = -1
if (!isLiveUpdate) {
if (lastAnchor == -1 || anchorId != lastAnchor) {
if (anchor == "Full" || anchor == "Rolling") {
aggShort = nz(aggShort) + netShort
} else {
aggShort = netShort
}
lastAnchor = anchorId
} else {
if (anchor == "Full" || anchor == "Rolling") {
aggShort = nz(aggShort) + netShort
} else {
aggShort = nz(aggShort) + netShort
}
}
}
// ---------------------------------------------------------------------------
// 5. Z-SCORE NORMALIZATION
// ---------------------------------------------------------------------------
timeseries aggMean = sma(aggShort, zLookback)
timeseries aggStd = stddev(aggShort, zLookback)
timeseries aggZ = (aggStd > 0) ? (aggShort - aggMean) / aggStd : 0.0
// Z-score of raw netShort (for line coloring)
timeseries nsMean = sma(netShort, zLookback)
timeseries nsStd = stddev(netShort, zLookback)
timeseries nsZ = (nsStd > 0) ? (netShort - nsMean) / nsStd : 0.0
// ---------------------------------------------------------------------------
// 6. REGIME DETECTION
// ---------------------------------------------------------------------------
// Short Expansion: aggShort rising and positive, or z-score > 0.5
// Short Covering: aggShort falling and negative, or z-score < -0.5
// Squeeze Risk: aggShort > 0 and price rising (shorts underwater)
// Crowded Short: aggZ > 2 (extreme short positioning — squeeze risk)
var regimeShort = aggShort > 0 && nsZ > 0.5
var regimeCover = aggShort < 0 && nsZ < -0.5
var regimeSqueeze = aggShort > 0 && c > nz(c[1]) && nsZ > 1.0
var regimeCrowded = aggZ > zExtreme
var regimeNeutral = !regimeShort && !regimeCover && !regimeSqueeze && !regimeCrowded
var regimeColor = regimeCrowded ? squeezeColor : (regimeSqueeze ? squeezeColor : (regimeShort ? shortColor : (regimeCover ? coverColor : "#9e9e9e")))
// ---------------------------------------------------------------------------
// 7. STATIC TRACKING FOR SHAPE MARKERS
// ---------------------------------------------------------------------------
static lastAggZ = 0.0
static lastAggShort = 0.0
var zCrossUp = false
var zCrossDown = false
var zeroCrossUp = false
var zeroCrossDown = false
var squeezeAlert = false
if (!isLiveUpdate) {
zCrossUp = aggZ > zExtreme && lastAggZ <= zExtreme
zCrossDown = aggZ < -zExtreme && lastAggZ >= -zExtreme
zeroCrossUp = aggShort > 0 && lastAggShort <= 0
zeroCrossDown = aggShort < 0 && lastAggShort >= 0
squeezeAlert = regimeSqueeze && !regimeSqueeze[1]
lastAggZ = aggZ
lastAggShort = aggShort
}
// ---------------------------------------------------------------------------
// 8. PLOTTING
// ---------------------------------------------------------------------------
// --- Zero Line ---
if (showZero) {
hline(value=0, color="#ffffff20", width=1)
}
// --- Fill Zone (aggShort vs zero) ---
if (showFill) {
var fillColor = aggShort > 0 ? transparency(shortColor, 30) : transparency(coverColor, 30)
plotLine(
value=[aggShort, 0],
width=1,
colors=[transparency(shortColor, 30), transparency(coverColor, 30)],
colorIndex=aggShort > 0 ? 0 : 1,
fill=true,
label=["Net Shorts", "Zero"],
desc=["Fill between net short estimate and zero line", "Zero reference"]
)
}
// --- Net Short Line (regime-colored) ---
if (showLine) {
plotLine(
value=aggShort,
width=2,
colors=[regimeColor],
label=["Net Shorts"],
desc=["Aggregated net short estimate (anchor: " + anchor + "). Regime-colored."]
)
}
// --- Color-Coded Histogram ---
if (showHistogram) {
var histColor = regimeCrowded ? squeezeColor : (regimeSqueeze ? squeezeColor : (aggShort > 0 ? shortColor : coverColor))
plotBar(
value=aggShort,
colors=[transparency(histColor, 60)],
width=1,
label=["Net Short Hist"],
desc=["Color-coded histogram: red = short expansion, green = covering, gold = squeeze risk"]
)
}
// --- Z-Score Line ---
if (showZScore) {
plotLine(
value=aggZ,
width=1,
colors=[transparency(zLineColor, 50)],
label=["Z-Score"],
desc=["Net short z-score over " + zLookback + " bars. >" + zExtreme + " = extreme."]
)
}
// --- Extreme Shape Markers ---
if (showShapes) {
if (zCrossUp) {
plotShape(
value=aggZ,
shape="triangleup",
colorIndex=squeezeColor,
width=2,
label=["Crowded Short"],
desc=["Z-score crossed above +" + zExtreme + " — crowded short positioning, squeeze risk"]
)
}
if (zCrossDown) {
plotShape(
value=aggZ,
shape="triangledown",
colorIndex=coverColor,
width=2,
label=["Extreme Cover"],
desc=["Z-score crossed below -" + zExtreme + " — extreme short covering / long expansion"]
)
}
if (zeroCrossUp) {
plotShape(
value=aggShort,
shape="circle",
colorIndex=shortColor,
width=2,
label=["Shorts Rising"],
desc=["Net short estimate crossed above zero — short positioning expanding"]
)
}
if (zeroCrossDown) {
plotShape(
value=aggShort,
shape="circle",
colorIndex=coverColor,
width=2,
label=["Shorts Falling"],
desc=["Net short estimate crossed below zero — short positioning declining"]
)
}
if (squeezeAlert) {
plotShape(
value=aggShort,
shape="xcross",
colorIndex=squeezeColor,
width=2,
label=["Squeeze Alert"],
desc=["Short squeeze condition: positive net short + rising price + elevated z-score"]
)
}
}
// ---------------------------------------------------------------------------
// 9. SUMMARY TABLE (last bar only)
// ---------------------------------------------------------------------------
if (showTable && isLastBar) {
var regimeText = regimeCrowded ? "CROWDED SHORT" : (regimeSqueeze ? "SQUEEZE RISK" : (regimeShort ? "SHORT EXPANSION" : (regimeCover ? "SHORT COVERING" : "NEUTRAL")))
var regimeTextColor = regimeCrowded ? squeezeColor : (regimeSqueeze ? squeezeColor : (regimeShort ? shortColor : (regimeCover ? coverColor : "#9e9e9e")))
plotTable(
data=[
["Net Shorts — Perfected", regimeText],
["Net Short", aggShort[0]],
["Z-Score", aggZ[0]],
["OI Delta", oiDelta[0]],
["Short Weight", shortWeight[0]],
["Anchor", anchor]
],
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
)
}