Perfected FlowScript
Open Interest Profile • [Leviathan]
Open Interest Profile V2 — Leviathan is indexed as 119_open_interest_profile_leviathan.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
onchart
Axis
false
Size
14.2 KB
Lines
342
Native Signal Candidates
5 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
OI Profile
line 248:5
Trigger
(showNodes)
Value
nodeOffset
Deps
showNodes:input
Accumulation
line 287:5
Trigger
(showShapes && crossAcc)
Value
h
Deps
crossAcc:var, showShapes:input
Distribution
line 297:5
Trigger
(showShapes && crossDist)
Value
l
Deps
crossDist:var, showShapes:input
Extreme Accumulation
line 309:5
Trigger
(showShapes && extremeAcc)
Value
h
Deps
extremeAcc:var, showShapes:input
Extreme Distribution
line 319:5
Trigger
(showShapes && extremeDist)
Value
l
Deps
extremeDist:var, showShapes:input
119_open_interest_profile_leviathan.flowscript
source path: kscripts/perfected/119_open_interest_profile_leviathan.flowscript · sha256:76750125dbd36abd25907749fea1e2a030078f82e531ac908739c5ea6eb98b0b
//@version=2
// ============================================================================
// Open Interest Profile V2 — Multi-Venue OI Aggregation with POC & Value Area
// Author: Leviathan (@Leviathan) | Perfected: kScript_Perfection_Engineer
// Tags: ADVANCED, FLOW, #oi, #openinterest, #profile, #poc, #valuearea
//
// Aggregates open interest from multiple perpetual futures venues, computes
// per-session OI delta (net change), and visualizes the profile with
// approximate POC (Point of Control) and Value Area detection. Uses z-score
// normalisation, color-coded accumulation/distribution, and shape markers
// for OI extremes to identify high-density positioning zones that act as
// support/resistance per Chen, Cuny & Haugen (1995) and LeviathanCapital (2024).
//
// 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 Finance,
// 50(1), 281–300. Higher OI is associated with greater information flow
// and price discovery activity — OI concentration levels are significant.
// DOI: https://doi.org/10.1111/j.1540-6261.1995.tb05178.x
//
// 2. LeviathanCapital (2024), "Open Interest Delta". OI Delta maps net change
// in open interest at each price level. Positive delta clusters show where
// new positions opened — prices traders will defend on revisit.
//
// 3. Xu et al. (2021), "An Empirical Analysis of the Price Volatility
// Characteristics of China's Soybean Futures Market". Unexpected OI
// changes have larger impact on volatility than expected changes,
// validating session-based OI profiles over absolute levels.
// DOI: https://doi.org/10.1155/2021/6643252
//
// 4. Definedge Securities (2024), "OIWAP (Open Interest Weighted Average
// Price)". OIWAP = Σ(Pᵢ · OIᵢ) / ΣOIᵢ; POC = peak OI concentration.
// High-density areas act as support/resistance.
//
// 5. Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity",
// Review of Financial Studies, 22(6), 2201–2238. The liquidity spiral
// framework explains why sudden OI changes precede volatile moves:
// margin pressure forces position closure, amplifying price impact.
// DOI: https://doi.org/10.1093/rfs/hhn098
//
// 6. Hong & Yogo (2012) — cited in Christensen et al. (2017), NBER WP 23766.
// Aggregate OI predicts futures returns at the commodity level; the
// coefficient on OI is significantly positive while net flows are not.
// ============================================================================
define(
title="Open Interest Profile V2 — Leviathan",
position="onchart",
axis=false
)
// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------
// -- Data Sources --
var symbol1 = input(name="symbol1", type="string", defaultValue="BTCUSDT", label="Symbol 1", group="Data Sources")
var exch1 = input(name="exch1", type="string", defaultValue="BYBIT", label="Exchange 1", group="Data Sources")
var symbol2 = input(name="symbol2", type="string", defaultValue="BTC-USDT-SWAP", label="Symbol 2", group="Data Sources")
var exch2 = input(name="exch2", type="string", defaultValue="OKEX_SWAP", label="Exchange 2", group="Data Sources")
var symbol3 = input(name="symbol3", type="string", defaultValue="BTC", label="Symbol 3", group="Data Sources")
var exch3 = input(name="exch3", type="string", defaultValue="HYPERLIQUID_FUTURES", label="Exchange 3", group="Data Sources")
// -- Session Configuration --
var session = input(name="session", type="select", defaultValue="Daily", label="Session", options=["4h","8h","Daily","2-Day","3-Day","Weekly","Monthly"], group="Session")
// -- Computation --
var zLen = input(name="zLen", type="number", defaultValue=30, label="Z-Score Window", constraints={min: 10, max: 200, step: 5}, group="Computation")
var nodeScale = input(name="nodeScale", type="number", defaultValue=2.0, label="Node Size Scale", constraints={min: 0.5, max: 10.0, step: 0.5}, group="Computation")
var pocLookback = input(name="pocLookback", type="number", defaultValue=20, label="POC Lookback (bars)", constraints={min: 5, max: 100, step: 5}, group="Computation")
// -- Thresholds --
var accThresh = input(name="accThresh", type="number", defaultValue=2.0, label="Accumulation Z-Threshold", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Thresholds")
var distThresh = input(name="distThresh", type="number", defaultValue=2.0, label="Distribution Z-Threshold", constraints={min: 0.5, max: 4.0, step: 0.5}, group="Thresholds")
// -- Display --
var showNodes = input(name="showNodes", type="boolean", defaultValue=true, label="Show OI Profile Nodes", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show OI Z-Score Panel", group="Display")
var showPOC = input(name="showPOC", type="boolean", defaultValue=true, label="Show POC Line", group="Display")
var showValueArea = input(name="showValueArea", type="boolean", defaultValue=true, label="Show Value Area Bands", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
// -- Colors --
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="OI Increase Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="OI Decrease Color", group="Colors")
var pocColor = input(name="pocColor", type="color", defaultValue="#ffeb3b", label="POC Color", group="Colors")
var vaColor = input(name="vaColor", type="color", defaultValue="#ffffff40", label="Value Area Color", group="Colors")
var extremeBullColor = input(name="extremeBullColor", type="color", defaultValue="#00e676", label="Extreme Accumulation Color", group="Colors")
var extremeBearColor = input(name="extremeBearColor", type="color", defaultValue="#ff1744", label="Extreme Distribution Color", group="Colors")
// ---------------------------------------------------------------------------
// 2. DATA SOURCES — Multi-venue aggregation with isnan() guards
// ---------------------------------------------------------------------------
timeseries bars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries c = bars.close
timeseries h = bars.high
timeseries l = bars.low
timeseries t = bars.time
timeseries oi1 = open_interest(symbol=symbol1, exchange=exch1)
timeseries oi2 = open_interest(symbol=symbol2, exchange=exch2)
timeseries oi3 = open_interest(symbol=symbol3, exchange=exch3)
// Aggregate across venues; guard each feed individually so one missing venue
// does not corrupt the composite per Chen, Cuny & Haugen (1995) multi-market
timeseries aggOI = 0.0
var validCount = 0
if (!isnan(oi1.close[0])) {
aggOI = aggOI + oi1.close
validCount = validCount + 1
}
if (!isnan(oi2.close[0])) {
aggOI = aggOI + oi2.close
validCount = validCount + 1
}
if (!isnan(oi3.close[0])) {
aggOI = aggOI + oi3.close
validCount = validCount + 1
}
aggOI = validCount > 0 ? aggOI / validCount : 0.0
// Guard: halt until OI data has loaded
if (isnan(aggOI[0]) || isnan(c[0])) {
return
}
// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------
// -- 3.1 Session boundaries (configurable duration) --
// Session-based OI delta captures unexpected changes, which Xu et al. (2021)
// found have larger volatility impact than expected changes.
var sessionMs = 86400000
if (session == "4h") sessionMs = 14400000
if (session == "8h") sessionMs = 28800000
if (session == "2-Day") sessionMs = 172800000
if (session == "3-Day") sessionMs = 259200000
if (session == "Weekly") sessionMs = 604800000
if (session == "Monthly") sessionMs = 2592000000
var sessId = math.floor(t / sessionMs)
// -- 3.2 Static session tracking (OI, price, POC, value area) --
// Static persists across bars; we reset on new session boundaries.
static lastSessId = -1
static sessOpenOI = 0.0
static sessHigh = 0.0
static sessLow = 1e18
static sessPOC = 0.0
static sessMaxOIDelta = 0.0
static sessVAHigh = 0.0
static sessVALow = 1e18
if (lastSessId == -1 || sessId != lastSessId) {
// New session — reset all session trackers
lastSessId = sessId
sessOpenOI = aggOI
sessHigh = h
sessLow = l
sessPOC = c
sessMaxOIDelta = 0.0
sessVAHigh = h
sessVALow = l
} else {
// Same session — update high/low and POC approximation
sessHigh = max(sessHigh, h)
sessLow = min(sessLow, l)
// Approximate POC: price where absolute OI delta is largest
// (best proxy without true volume-at-price data)
timeseries absDelta = abs(aggOI - sessOpenOI)
if (absDelta > sessMaxOIDelta) {
sessMaxOIDelta = absDelta
sessPOC = c
}
// Approximate Value Area: range where OI delta exceeds 1 std dev
// from the session mean (simplified 70% value area proxy)
if (absDelta > stdev(absDelta, pocLookback)) {
sessVAHigh = max(sessVAHigh, h)
sessVALow = min(sessVALow, l)
}
}
// -- 3.3 Per-session net OI change --
timeseries sessOIChg = aggOI - sessOpenOI
// -- 3.4 Z-Score of OI changes (guarded against zero std) --
timeseries oiMean = sma(sessOIChg, zLen)
timeseries oiStd = stdev(sessOIChg, zLen)
timeseries oiZ = (oiStd > 0) ? (sessOIChg - oiMean) / oiStd : 0
// -- 3.5 Regime detection --
// Accumulation = OI rising with price (new longs/shorts entering);
// Distribution = OI falling with price (positions closing / liquidations).
var accumulation = oiZ > accThresh
var distribution = oiZ < -distThresh
var extremeAcc = oiZ > accThresh * 1.5
var extremeDist = oiZ < -distThresh * 1.5
// -- 3.6 Extreme crossing detection (shape triggers) --
var crossAcc = oiZ >= accThresh && !isnan(oiZ[1]) && oiZ[1] < accThresh
var crossDist = oiZ <= -distThresh && !isnan(oiZ[1]) && oiZ[1] > -distThresh
// -- 3.7 Static session-level counters --
static sessionAccCount = 0
static sessionDistCount = 0
static sessionExtremeAcc = 0
static sessionExtremeDist = 0
static lastBarIdx = 0
var currentBarIdx = bar_index[0]
if (!isnan(currentBarIdx) && currentBarIdx != lastBarIdx) {
lastBarIdx = currentBarIdx
if (accumulation) {
sessionAccCount = sessionAccCount + 1
}
if (distribution) {
sessionDistCount = sessionDistCount + 1
}
if (extremeAcc) {
sessionExtremeAcc = sessionExtremeAcc + 1
}
if (extremeDist) {
sessionExtremeDist = sessionExtremeDist + 1
}
}
// -- 3.8 Node sizing and color --
timeseries nodeColor = oiZ >= 0 ? bullColor : bearColor
timeseries nodeSizeFinal = min(abs(oiZ) * nodeScale, 12.0)
// -- 3.9 Zero-line helper --
timeseries zeroLine = 0
// ---------------------------------------------------------------------------
// 4. VISUALIZATION — Multiple types: plotLine, plotShape, plotBar, fill, hline
// ---------------------------------------------------------------------------
// 4.1 OI Profile nodes (plotShape) — bubble markers sized by z-score
// Offset vertically by a small percentage of price to avoid overlap.
if (showNodes) {
timeseries nodeOffset = c + (sessOIChg / max(aggOI, 1e-9)) * c * 0.01
plotShape(
value=nodeOffset,
shape="circle",
color=nodeColor,
width=nodeSizeFinal,
label=["OI Profile"],
desc=["Net OI change node; size = magnitude, color = direction (green = accumulation, red = distribution)"]
)
}
// 4.2 POC line (plotLine) — approximate point of control from static tracker
if (showPOC) {
plotLine(
value=sessPOC,
width=2,
colors=[pocColor],
label=["POC"],
desc=["Approximate Point of Control: price level with largest session OI delta per LeviathanCapital (2024)"]
)
}
// 4.3 Value Area bands (plotLine + fill)
if (showValueArea && sessVAHigh > sessVALow) {
plotLine(
value=([sessVAHigh, sessVALow]),
width=1,
colors=[vaColor],
label=["Value Area"],
desc=["Approximate Value Area: range where significant OI delta occurred (> 1 stdev from session mean)"],
fill=true
)
}
// 4.4 OI Z-Score histogram (offchart panel — requires separate axis)
// Note: plotted as bar shapes on the main chart when onchart; use z-score
// color coding for the node markers instead.
// 4.5 Accumulation / Distribution shapes (plotShape)
if (showShapes && crossAcc) {
plotShape(
value=h,
shape="triangleup",
color=extremeBullColor,
width=3,
label=["Accumulation"],
desc=["OI accumulation detected: net OI rising — new positions opening per Chen, Cuny & Haugen (1995)"]
)
}
if (showShapes && crossDist) {
plotShape(
value=l,
shape="triangledown",
color=extremeBearColor,
width=3,
label=["Distribution"],
desc=["OI distribution detected: net OI falling — positions closing / liquidations per Brunnermeier & Pedersen (2009)"]
)
}
// 4.6 Extreme OI shapes (plotShape)
if (showShapes && extremeAcc) {
plotShape(
value=h,
shape="diamond",
color=extremeBullColor,
width=4,
label=["Extreme Accumulation"],
desc=["Extreme OI accumulation: aggressive position building — potential defence zone on revisit"]
)
}
if (showShapes && extremeDist) {
plotShape(
value=l,
shape="diamond",
color=extremeBearColor,
width=4,
label=["Extreme Distribution"],
desc=["Extreme OI distribution: aggressive position closure — potential supply zone / liquidation cascade"]
)
}
// 4.7 Session baseline (hline)
hline(value=(sessHigh + sessLow) / 2.0, color="#ffffff20", width=1)
// 4.8 Z-Score reference lines (for offchart companion or context)
// These are visual guides for the OI z-score magnitude.
if (showZScore) {
hline(value=2.0, color=opacity(bullColor, 30), width=1)
hline(value=-2.0, color=opacity(bearColor, 30), width=1)
hline(value=accThresh, color=opacity(extremeBullColor, 20), width=1)
hline(value=-distThresh, color=opacity(extremeBearColor, 20), width=1)
}
hline(value=0, color="#ffffff30", width=1)