Perfected FlowScript
Open Interest RSI
Open Interest RSI [Perfected] is indexed as 062_open_interest_rsi.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
12.4 KB
Lines
310
Native Signal Candidates
6 source-level chart marker triggers extracted from guarded FlowScript v2 blocks.
OB Entry
line 246:9
Trigger
(showShapes) && (crossOb)
Value
oiRsi
Deps
crossOb:var, showShapes:input
OS Entry
line 256:9
Trigger
(showShapes) && (crossOs)
Value
oiRsi
Deps
crossOs:var, showShapes:input
Extreme OB
line 266:9
Trigger
(showShapes) && (extremeOb)
Value
oiRsi
Deps
extremeOb:var, showShapes:input
Extreme OS
line 276:9
Trigger
(showShapes) && (extremeOs)
Value
oiRsi
Deps
extremeOs:var, showShapes:input
Bull Div
line 290:9
Trigger
(showDivergence && showShapes) && (bullDiv)
Value
oiRsi
Deps
bullDiv:var, showDivergence:input, showShapes:input
Bear Div
line 300:9
Trigger
(showDivergence && showShapes) && (bearDiv)
Value
oiRsi
Deps
bearDiv:var, showDivergence:input, showShapes:input
062_open_interest_rsi.flowscript
source path: kscripts/perfected/062_open_interest_rsi.flowscript · sha256:b451f078cfed1d5e2e01aa4b25ab778776f8de4447a317042907bae3a681c88e
//@version=2
// Source: kiyotaka.ai/hub/kscript (original) — Perfected by kScript_Perfection_Engineer
// ============================================================================
// Open Interest RSI [BackQuant Perfected]
// Author: BackQuant (@BackQuant) — Perfected by kScript_Perfection_Engineer
// Tags: ADVANCED, CORE, #oi, #rsi, #momentum, #divergence, #wilder
//
// Wilder's RSI applied to Open Interest (not price) with signal-line
// divergence detection, fill between RSI and signal, overbought/oversold zone
// shading, and extreme-event shape markers. Rising OI-RSI = leverage and
// participation building; falling OI-RSI = de-risking. Extremes precede squeezes.
//
// FORMULA FOUNDATION:
// 1. Wilder RSI: RSI = 100 − 100 / (1 + RS) where RS = RMA(gain) / RMA(loss)
// per Wilder (1978). Applied to OI changes instead of price changes.
// 2. Signal Line: EMA or SMA of OI-RSI for cross-confirmation.
// 3. Divergence Detection: Bullish divergence = price makes lower low while
// OI-RSI makes higher low; Bearish divergence = price makes higher high while
// OI-RSI makes lower high (Wilder 1978 original methodology).
// 4. Overbought/Oversold Zones: 70/30 thresholds (Wilder 1978); extremes >70
// signal overbought leverage, <30 signal oversold de-risking.
//
// RESEARCH BASIS:
// • Wilder (1978), "New Concepts in Technical Trading Systems". Original RSI
// formula with 14-period smoothing. Explicitly described bullish/bearish
// divergences as tools to foreshadow reversals.
// • Chen, Cuny & Haugen (1995), "Stock Volatility and the Levels of the Basis
// and Open Interest in Futures Contracts", J. Finance 50(1), 281–300.
// Higher OI associated with greater information flow and price discovery.
// • Ponnusamy & Manual (2016), "A Study on Financial Indicators' Reliability in
// Technical Analysis". RSI performed better than MACD and Stochastic; multi-
// indicator confirmation recommended.
// • 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 — OI-RSI extremes flag "unexpected" shifts.
// • "Open Interest Delta - By Leviathan" (LeviathanCapital 2024). OI Delta maps
// net change in OI at each price level; positive delta = new positions opened.
// ============================================================================
define(
title="Open Interest RSI [Perfected]",
position="offchart",
axis=true
)
// ---------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// ---------------------------------------------------------------------------
// --- RSI Parameters ---
var rsiLen = input(name="rsiLen", type="number", defaultValue=14, label="RSI Length", constraints={min: 2, max: 100, step: 1}, group="RSI Parameters")
var useWilder = input(name="useWilder", type="boolean", defaultValue=true, label="Use Wilder RMA (off=SMA)", group="RSI Parameters")
// --- Signal Line ---
var sigLen = input(name="sigLen", type="number", defaultValue=9, label="Signal Length", constraints={min: 1, max: 100, step: 1}, group="Signal Line")
var useEmaSig = input(name="useEmaSig", type="boolean", defaultValue=true, label="Signal = EMA (off=SMA)", group="Signal Line")
// --- Zones ---
var thrHi = input(name="thrHi", type="number", defaultValue=70, label="Overbought Threshold", constraints={min: 50, max: 95, step: 1}, group="Zones")
var thrLo = input(name="thrLo", type="number", defaultValue=30, label="Oversold Threshold", constraints={min: 5, max: 50, step: 1}, group="Zones")
var showZones = input(name="showZones", type="boolean", defaultValue=true, label="Show OB/OS Zone Shading", group="Zones")
// --- Divergence ---
var showDivergence = input(name="showDivergence", type="boolean", defaultValue=true, label="Show Divergence Signals", group="Divergence")
var divLookback = input(name="divLookback", type="number", defaultValue=14, label="Divergence Lookback", constraints={min: 5, max: 50, step: 1}, group="Divergence")
// --- Display ---
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show RSI/Signal Fill", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Extreme Shapes", group="Display")
var showSignal = input(name="showSignal", type="boolean", defaultValue=true, label="Show Signal Line", group="Display")
// --- Colors ---
var rsiColor = input(name="rsiColor", type="color", defaultValue="#9c27b0", label="RSI Line Color", group="Colors")
var sigColor = input(name="sigColor", type="color", defaultValue="#ff9800", label="Signal Line Color", group="Colors")
var obColor = input(name="obColor", type="color", defaultValue="#ef5350", label="Overbought Zone Color", group="Colors")
var osColor = input(name="osColor", type="color", defaultValue="#26a69a", label="Oversold Zone Color", group="Colors")
// ---------------------------------------------------------------------------
// Data Sources
// ---------------------------------------------------------------------------
timeseries oiTS = open_interest(symbol=currentSymbol, exchange=currentExchange)
timeseries oi = oiTS.close
timeseries pxTS = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries c = pxTS.close
// isnan guard: prevent execution before data is loaded
if (isnan(oi[0]) || isnan(c[0])) {
return
}
// ---------------------------------------------------------------------------
// RSI (Wilder) Applied to OI
// ---------------------------------------------------------------------------
// Wilder RSI on OI changes: rising OI-RSI = leverage/participation building;
// falling OI-RSI = de-risking. Extremes (70/30) precede squeezes.
timeseries dOI = oi - oi[1]
timeseries gain = math.max(dOI, 0.0)
timeseries loss = math.max(-dOI, 0.0)
// Wilder's RMA (smoothed moving average) or plain SMA
timeseries avgG = useWilder ? rma(gain, rsiLen) : sma(gain, rsiLen)
timeseries avgL = useWilder ? rma(loss, rsiLen) : sma(loss, rsiLen)
// Zero-division guard: if avgL == 0, RSI = 100 (no losses = pure gains)
timeseries rs = avgL > 0 ? avgG / avgL : 100.0
timeseries oiRsi = 100.0 - (100.0 / (1.0 + rs))
// ---------------------------------------------------------------------------
// Signal Line
// ---------------------------------------------------------------------------
timeseries sig = useEmaSig ? ema(oiRsi, sigLen) : sma(oiRsi, sigLen)
// ---------------------------------------------------------------------------
// Regime Detection (OB/OS/neutral)
// ---------------------------------------------------------------------------
var isOverbought = oiRsi >= thrHi
var isOversold = oiRsi <= thrLo
var isNeutral = !isOverbought && !isOversold
var regimeColorIdx = isOverbought ? 0 : (isOversold ? 1 : 2)
// ---------------------------------------------------------------------------
// Divergence Detection (Wilder 1978 original methodology)
// ---------------------------------------------------------------------------
// Bullish divergence: price makes lower low, OI-RSI makes higher low
// Bearish divergence: price makes higher high, OI-RSI makes lower high
timeseries priceLL = lowest(c, divLookback)
timeseries priceHH = highest(c, divLookback)
timeseries rsiLL = lowest(oiRsi, divLookback)
timeseries rsiHH = highest(oiRsi, divLookback)
var bullDiv = c == priceLL && oiRsi > rsiLL && oiRsi < thrLo
var bearDiv = c == priceHH && oiRsi < rsiHH && oiRsi > thrHi
// ---------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// ---------------------------------------------------------------------------
static lastRegime = 2 // 0=OB, 1=OS, 2=neutral
static regimeChangeCount = 0
static sessionHighRsi = 0.0
static sessionLowRsi = 100.0
static obCount = 0
static osCount = 0
static lastBarIndex = 0
var currentBarIndex = bar_index[0]
if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
lastBarIndex = currentBarIndex
if (oiRsi > sessionHighRsi) {
sessionHighRsi = oiRsi
}
if (oiRsi < sessionLowRsi) {
sessionLowRsi = oiRsi
}
var currentRegime = isOverbought ? 0 : (isOversold ? 1 : 2)
if (lastRegime != currentRegime) {
lastRegime = currentRegime
regimeChangeCount = regimeChangeCount + 1
}
if (isOverbought) {
obCount = obCount + 1
} else if (isOversold) {
osCount = osCount + 1
}
}
// ---------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Fill, Shape, HLine, Zone)
// ---------------------------------------------------------------------------
// Horizontal reference lines
hline(value=thrHi, color=opacity(obColor, 30), width=1)
hline(value=50, color="#88888840", width=1)
hline(value=thrLo, color=opacity(osColor, 30), width=1)
// Overbought/Oversold zone shading (background bands)
if (showZones) {
plotLine(
value=([thrHi, 100]),
width=1,
colors=[opacity(obColor, 10)],
fill=true,
label=["OB Zone"],
desc=["Overbought zone (70–100) — elevated leverage, squeeze risk ahead"]
)
plotLine(
value=([0, thrLo]),
width=1,
colors=[opacity(osColor, 10)],
fill=true,
label=["OS Zone"],
desc=["Oversold zone (0–30) — de-risking, potential accumulation zone"]
)
}
// OI-RSI line with regime color coding
plotLine(
value=oiRsi,
width=2,
colors=[obColor, osColor, rsiColor],
colorIndex=regimeColorIdx,
label=["OI-RSI"],
desc=["Wilder RSI on OI; >70 overbought leverage, <30 oversold de-risking"]
)
// Signal line
if (showSignal) {
plotLine(
value=sig,
width=1,
colors=[sigColor],
label=["Signal"],
desc=["EMA/SMA of OI-RSI for cross confirmation and momentum smoothing"]
)
}
// Fill between RSI and signal line
if (showFill && showSignal) {
plotLine(
value=([math.min(oiRsi, sig), math.max(oiRsi, sig)]),
width=1,
colors=[opacity(rsiColor, 15), opacity(sigColor, 15)],
colorIndex=oiRsi > sig ? 0 : 1,
fill=true,
label=["RSI/Signal Fill"],
desc=["Fill between OI-RSI and signal line — momentum divergence shading"]
)
}
// Extreme-event shape markers
if (showShapes) {
var crossOb = oiRsi >= thrHi && !isnan(oiRsi[1]) && oiRsi[1] < thrHi
var crossOs = oiRsi <= thrLo && !isnan(oiRsi[1]) && oiRsi[1] > thrLo
var extremeOb = oiRsi >= 85 && !isnan(oiRsi[1]) && oiRsi[1] < 85
var extremeOs = oiRsi <= 15 && !isnan(oiRsi[1]) && oiRsi[1] > 15
if (crossOb) {
plotShape(
value=oiRsi,
shape="triangledown",
color=obColor,
width=3,
label=["OB Entry"],
desc=["OI-RSI crossed into overbought zone (>70) — leverage building, squeeze risk"]
)
}
if (crossOs) {
plotShape(
value=oiRsi,
shape="triangleup",
color=osColor,
width=3,
label=["OS Entry"],
desc=["OI-RSI crossed into oversold zone (<30) — de-risking, potential accumulation"]
)
}
if (extremeOb) {
plotShape(
value=oiRsi,
shape="diamond",
color=obColor,
width=4,
label=["Extreme OB"],
desc=["OI-RSI extreme overbought (>85) — maximum leverage, highest squeeze probability"]
)
}
if (extremeOs) {
plotShape(
value=oiRsi,
shape="diamond",
color=osColor,
width=4,
label=["Extreme OS"],
desc=["OI-RSI extreme oversold (<15) — maximum de-risking, potential capitulation bottom"]
)
}
}
// Divergence shape markers (Wilder 1978 methodology)
if (showDivergence && showShapes) {
if (bullDiv) {
plotShape(
value=oiRsi,
shape="triangleup",
color="#42a5f5",
width=4,
label=["Bull Div"],
desc=["Bullish divergence: price lower low, OI-RSI higher low — hidden accumulation"]
)
}
if (bearDiv) {
plotShape(
value=oiRsi,
shape="triangledown",
color="#ff7043",
width=4,
label=["Bear Div"],
desc=["Bearish divergence: price higher high, OI-RSI lower high — hidden distribution"]
)
}
}