Perfected FlowScript
BTC Net Long Position Indicator
BTC Net Long Position — Perfected is indexed as 183_btc_net_long_position.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.3 KB
Lines
302
Native Signal Candidates
2 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
Extreme Long
line 241:5
Trigger
(showShapes && extremeLong)
Value
extremeDiv
Deps
extremeLong:var, showShapes:input
Extreme Short
line 251:5
Trigger
(showShapes && extremeShort)
Value
-extremeDiv
Deps
extremeShort:var, showShapes:input
183_btc_net_long_position.flowscript
source path: kscripts/perfected/183_btc_net_long_position.flowscript · sha256:3364ac0091d7a1d63e21f6ead95235b3ba9138c9b01d1a966f6c2d5dd2c3aa14
//@version=2
// ============================================================================
// BTC Net Long Position — Perfected Edition
// Author: L (@leader56) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, FLOW, #btc, #netlong, #positioning, #zscore, #regime
//
// Aggregates net long positioning from OI and long/short ratio across multiple
// perpetual futures exchanges, then standardizes the aggregate via rolling-window
// z-score to surface regime extremes. Color-coded histograms, filled areas,
// and shape alerts flag when positioning reaches statistically rare levels
// — often marking crowded-long tops or crowded-short bottoms.
//
// Academic foundation (exact papers & formulas):
// 1. Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the
// Basis and Open Interest in Futures Contracts", Journal of Financial
// and Quantitative Analysis, 30(3), 407–432.
// [Formula] OI levels ∝ information flow; higher OI predicts greater
// future price volatility. DOI: https://doi.org/10.2307/2331349
//
// 2. He & Manela (2022), "Fundamentals of Perpetual Futures".
// Past-return momentum significantly explains the futures-spot gap
// (R² > 50%). Supports cross-exchange OI aggregation: the gap is
// driven by funding-cost momentum and positioning pressure.
//
// 3. Aleti & Mizrach (2021), "Bitcoin Spot and Futures Market
// Microstructure". CME leads price discovery; trade-size divergence
// between spot and futures supports multi-venue positioning analysis.
//
// 4. "Retail Positioning as a Contrarian Indicator" — Forex Mechanics (2026)
// Extreme retail positioning (>70% long or <30% long) is a contrarian
// reversal signal. Net-long z-scores beyond +2 flag crowded longs.
//
// 5. "Sentiment and Positioning Strategy" — Traders.MBA (2025)
// Two strategies: (1) contrarian at extremes, (2) trend-following
// at moderate levels. The z-score threshold design directly implements
// this dual-regime framework.
//
// 6. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint".
// [Formula] z̄ₜ = (zₜ − μ) / σ with entry/exit thresholds at ±1σ, ±2σ.
// Directly motivates the z-score normalization and band design.
// ============================================================================
define(title="BTC Net Long Position — Perfected", position="offchart", axis=true)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// -- Data Sources --
var incBybit = input(name="incBybit", type="boolean", defaultValue=true, label="Include Bybit", group="Data Sources")
var incBinance = input(name="incBinance", type="boolean", defaultValue=true, label="Include Binance", group="Data Sources")
var incOKX = input(name="incOKX", type="boolean", defaultValue=true, label="Include OKX", group="Data Sources")
var incDeribit = input(name="incDeribit", type="boolean", defaultValue=false, label="Include Deribit", group="Data Sources")
// -- Computation --
var smoothLen = input(name="smoothLen", type="number", defaultValue=7, label="Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Computation")
var zWindow = input(name="zWindow", type="number", defaultValue=50, label="Z-Score Window", constraints={min: 20, max: 200, step: 5}, group="Computation")
var zSmooth = input(name="zSmooth", type="number", defaultValue=3, label="Z EMA Smooth", constraints={min: 1, max: 20, step: 1}, group="Computation")
var divThreshold = input(name="divThreshold", type="number", defaultValue=1.0, label="Regime Threshold (σ)", constraints={min: 0.5, max: 3.0, step: 0.5}, group="Computation")
var extremeDiv = input(name="extremeDiv", type="number", defaultValue=2.0, label="Extreme Threshold (σ)", constraints={min: 1.5, max: 4.0, step: 0.5}, group="Computation")
// -- Display --
var showNetLine = input(name="showNetLine", type="boolean", defaultValue=true, label="Show Net Position Line", group="Display")
var showNetBars = input(name="showNetBars", type="boolean", defaultValue=true, label="Show Net Position Bars", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showZHistogram = input(name="showZHistogram", type="boolean", defaultValue=true, label="Show Z Histogram", group="Display")
var showZFill = input(name="showZFill", type="boolean", defaultValue=true, label="Show Z Fill Area", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showRawOI = input(name="showRawOI", type="boolean", defaultValue=false, label="Show Raw OI Lines", group="Display")
// -- Colors --
var longColor = input(name="longColor", type="color", defaultValue="#00c853", label="Long Dominant Color", group="Colors")
var shortColor = input(name="shortColor", type="color", defaultValue="#d50000", label="Short Dominant Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#78909c", label="Neutral Color", group="Colors")
var lineColor = input(name="lineColor", type="color", defaultValue="#42a5f5", label="Net Line Color", group="Colors")
var zLineColor = input(name="zLineColor", type="color", defaultValue="#ffffff", label="Z-Score Line Color", group="Colors")
// ---------------------------------------------------------------------------
// 2. DATA SOURCES — with isnan() guard on first external access
// ---------------------------------------------------------------------------
timeseries lsrBybit = long_short_ratio(symbol="BTCUSDT", exchange="BYBIT")
timeseries oiBybit = open_interest(symbol="BTCUSDT", exchange="BYBIT")
timeseries pxBybit = ohlcv(symbol="BTCUSDT", exchange="BYBIT")
timeseries lsrBin = long_short_ratio(symbol="BTCUSDT", exchange="BINANCE_FUTURES")
timeseries oiBin = open_interest(symbol="BTCUSDT", exchange="BINANCE_FUTURES")
timeseries pxBin = ohlcv(symbol="BTCUSDT", exchange="BINANCE_FUTURES")
timeseries lsrOKX = long_short_ratio(symbol="BTC-USDT-SWAP", exchange="OKEX_SWAP")
timeseries oiOKX = open_interest(symbol="BTC-USDT-SWAP", exchange="OKEX_SWAP")
timeseries pxOKX = ohlcv(symbol="BTC-USDT-SWAP", exchange="OKEX_SWAP")
timeseries lsrDeribit = long_short_ratio(symbol="BTC-PERPETUAL", exchange="DERIBIT")
timeseries oiDeribit = open_interest(symbol="BTC-PERPETUAL", exchange="DERIBIT")
timeseries pxDeribit = ohlcv(symbol="BTC-PERPETUAL", exchange="DERIBIT")
// Guard: halt until all included feeds have loaded to avoid NaN propagation
if (isnan(pxBybit.close[0]) || isnan(pxBin.close[0]) || isnan(pxOKX.close[0]) || isnan(pxDeribit.close[0])) {
return
}
// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------
// -- 3.1 Per-venue net position (longs − shorts) in coin terms --
// Net = (ratio × OI_coins / (ratio + 1)) − (OI_coins / (ratio + 1))
// = OI_coins × (ratio − 1) / (ratio + 1)
timeseries oiBybitCoins = oiBybit.close / math.max(pxBybit.close, 0.0001)
timeseries ratioBybit = isnum(lsrBybit.total_account) ? lsrBybit.total_account : 1.0
timeseries netBybit = incBybit ? (ratioBybit * oiBybitCoins / (ratioBybit + 1.0)) - (oiBybitCoins / (ratioBybit + 1.0)) : 0
timeseries oiBinCoins = oiBin.close / math.max(pxBin.close, 0.0001)
timeseries ratioBin = isnum(lsrBin.total_account) ? lsrBin.total_account : 1.0
timeseries netBin = incBinance ? (ratioBin * oiBinCoins / (ratioBin + 1.0)) - (oiBinCoins / (ratioBin + 1.0)) : 0
timeseries oiOKXCoins = oiOKX.close / math.max(pxOKX.close, 0.0001)
timeseries ratioOKX = isnum(lsrOKX.total_account) ? lsrOKX.total_account : 1.0
timeseries netOKX = incOKX ? (ratioOKX * oiOKXCoins / (ratioOKX + 1.0)) - (oiOKXCoins / (ratioOKX + 1.0)) : 0
timeseries oiDeribitCoins = oiDeribit.close / math.max(pxDeribit.close, 0.0001)
timeseries ratioDeribit = isnum(lsrDeribit.total_account) ? lsrDeribit.total_account : 1.0
timeseries netDeribit = incDeribit ? (ratioDeribit * oiDeribitCoins / (ratioDeribit + 1.0)) - (oiDeribitCoins / (ratioDeribit + 1.0)) : 0
// -- 3.2 Aggregate net position --
timeseries aggregateNet = netBybit + netBin + netOKX + netDeribit
timeseries netSmooth = sma(aggregateNet, smoothLen)
// -- 3.3 Z-score normalization (all denominators guarded against zero) --
// Z_t = (Net_t − μ_t) / σ_t, where μ_t = SMA(Net, W), σ_t = StDev(Net, W).
timeseries netMean = sma(aggregateNet, zWindow)
timeseries netStd = stdev(aggregateNet, zWindow)
timeseries rawZ = (netStd > 0) ? (aggregateNet - netMean) / netStd : 0
timeseries zScore = ema(rawZ, zSmooth)
// -- 3.4 Regime detection (configurable thresholds, no magic numbers) --
var longDominant = zScore > divThreshold
var shortDominant = zScore < -divThreshold
var extremeLong = zScore > extremeDiv
var extremeShort = zScore < -extremeDiv
var neutralRegime = !longDominant && !shortDominant
// -- 3.5 Regime state tracking via static variables --
// Tracks consecutive bars in each regime for context-aware alerting.
static lastRegime = 0
static longBars = 0
static shortBars = 0
if (longDominant) {
longBars = longBars + 1
shortBars = 0
lastRegime = 1
} else if (shortDominant) {
shortBars = shortBars + 1
longBars = 0
lastRegime = -1
} else {
longBars = 0
shortBars = 0
lastRegime = 0
}
// -- 3.6 Zero-line helper for fill areas --
timeseries zeroLine = 0
// ---------------------------------------------------------------------------
// 4. VISUALIZATION — Multiple types: plotLine, plotShape, plotBar, fill, histogram
// ---------------------------------------------------------------------------
// 4.1 Net position line (regime-colored fill)
if (showNetLine) {
var isNetLong = netSmooth > 0
plotLine(
value=[netSmooth, zeroLine],
width=2,
colors=[lineColor, transparency(longColor, 40), transparency(shortColor, 40)],
colorIndex=isNetLong ? 1 : 2,
fill=true,
label=["Aggregate Net Long"],
desc=["Sum of (longs − shorts) across included venues; fill green when net long, red when net short"]
)
}
// 4.2 Net position bars (sign-based colouring)
if (showNetBars) {
var netBull = netSmooth > 0
plotBar(
value=netSmooth,
colors=[longColor, shortColor],
colorIndex=netBull ? 0 : 1,
width=1,
label=["Net Position Bars"],
desc=["Aggregate net position as bars; green = long dominant, red = short dominant"]
)
}
// 4.3 Z-Score line (regime-colored)
if (showZScore) {
var zColor = longDominant ? longColor : (shortDominant ? shortColor : neutralColor)
plotLine(
value=zScore,
width=2,
colors=[zColor],
label=["Net Long Z-Score"],
desc=["Rolling-window z-score of aggregate net position; mean-reverting around 0"]
)
}
// 4.4 Z-Score fill area (colorIndex regime coding)
// colorIndex maps: 0 = long dominant, 1 = short dominant, 2 = neutral
if (showZFill) {
timeseries zColorIdx = longDominant ? 0 : (shortDominant ? 1 : 2)
plotLine(
value=[zScore, zeroLine],
width=2,
colors=[longColor, shortColor, neutralColor],
colorIndex=zColorIdx,
fill=true,
label=["Z-Score Regime"],
desc=["Filled area between z-score and zero, color-coded by regime"]
)
}
// 4.5 Z-Score histogram (regime-colored bars)
if (showZHistogram) {
var histBull = zScore > 0
plotBar(
value=zScore,
colors=[transparency(longColor, 60), transparency(shortColor, 60)],
colorIndex=histBull ? 0 : 1,
width=1,
label=["Z Histogram"],
desc=["Z-score as histogram bars; positive = long pressure, negative = short pressure"]
)
}
// 4.6 Extreme divergence shapes (plotShape)
if (showShapes && extremeLong) {
plotShape(
value=extremeDiv,
shape="triangleup",
colorIndex=longColor,
width=3,
label=["Extreme Long"],
desc=["Aggregate net long z-score exceeds +" + extremeDiv + "σ; crowded long warning / potential top"]
)
}
if (showShapes && extremeShort) {
plotShape(
value=-extremeDiv,
shape="triangledown",
colorIndex=shortColor,
width=3,
label=["Extreme Short"],
desc=["Aggregate net short z-score exceeds −" + extremeDiv + "σ; crowded short warning / potential bottom"]
)
}
// 4.7 Optional raw OI lines (context)
if (showRawOI) {
plotLine(value=oiBybit.close, width=1, colors=["#2962ff"], label=["Bybit OI"], desc=["Bybit open interest (context)"])
plotLine(value=oiBin.close, width=1, colors=["#ff6d00"], label=["Binance OI"], desc=["Binance Futures open interest (context)"])
}
// 4.8 Reference thresholds (hline)
hline(value=0, color="#ffffff30", width=1)
hline(value=divThreshold, color="#ffffff20", width=1)
hline(value=-divThreshold, color="#ffffff20", width=1)
hline(value=extremeDiv, color="#ffffff15", width=1)
hline(value=-extremeDiv, color="#ffffff15", width=1)
// ---------------------------------------------------------------------------
// 5. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
var regimeText = longDominant ? "LONG DOMINANT" : (shortDominant ? "SHORT DOMINANT" : "NEUTRAL")
var regimeTextColor = longDominant ? longColor : (shortDominant ? shortColor : neutralColor)
plotTable(
data=[
["BTC Net Long — Perfected", regimeText],
["Aggregate Net (coins)", netSmooth[0]],
["Z-Score", zScore[0]],
["Regime Bars", lastRegime > 0 ? longBars : (lastRegime < 0 ? shortBars : 0)],
["Venues Active", (incBybit ? 1 : 0) + (incBinance ? 1 : 0) + (incOKX ? 1 : 0) + (incDeribit ? 1 : 0)]
],
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
)
}