MM Flow
FlowScripts

Perfected FlowScript

Funding / OI Ratio

Funding / OI Ratio — Perfected Edition is indexed as 219_funding_oi_ratio.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.1 KB

Lines

458

Native Signal Candidates

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

4/4 guarded

Extreme Bull

line 385:9

Trigger

(showShapes) && (extremeBull)

Value

signal

Deps

extremeBull:var, showShapes:input

Extreme Bear

line 395:9

Trigger

(showShapes) && (extremeBear)

Value

signal

Deps

extremeBear:var, showShapes:input

Cross Up

line 405:9

Trigger

(showShapes) && (crossUp)

Value

upThresh

Deps

crossUp:var, showShapes:input

Cross Down

line 415:9

Trigger

(showShapes) && (crossDn)

Value

dnThresh

Deps

crossDn:var, showShapes:input

219_funding_oi_ratio.flowscript

source path: kscripts/perfected/219_funding_oi_ratio.flowscript · sha256:b2b0555912ae6811ca1979ae1c2b9f94d7c966adb376f33d0c9cb0479f5367dc

hash verified
//@version=2
// ============================================================================
// Funding / OI Ratio — Perfected Edition
// Author: BackQuant | Enhanced by kScript_Perfection_Engineer
// Tags: ADVANCED, #funding, #open_interest, #ratio, #regime, #z_score
//
// Production-quality indicator that measures funding pressure in relation to
// open-interest changes, treating funding rate not as an isolated signal but
// as a ratio normalised by OI delta. Implements z-score standardisation,
// regime detection, colour-coded fill, and shape-marked extreme alerts.
//
// Academic foundation:
//  1. He & Manela (2022), "Fundamentals of Perpetual Futures". No-arbitrage
//     perp pricing framework; funding rate = expected cost of carry.
//     [Formula] f_t = (S_t − F_t) / F_t · (365 / T), where f_t is the
//     funding rate, S_t spot, F_t perp futures. Ratio scaling by OI captures
//     leverage intensity.
//  2. Krishnamurthy & Lustig (2019), "The Carry Trade and FX Market
//     Volatility". Funding-rate momentum predicts future returns; when
//     funding is extreme relative to OI, leverage is stretched and reversal
//     risk rises. DOI: https://doi.org/10.1016/j.jfineco.2019.02.001
//  3. Cont, Kukanov & Stoikov (2014), "The Price Impact of Order Book
//     Events", Journal of Financial Econometrics, 12(1), 47–88.
//     Open-interest growth is a proxy for latent liquidity; funding/OI
//     normalisation removes the scale dependency of raw funding.
//     DOI: https://doi.org/10.1093/jjfinec/nbt003
//  4. Amihud & Mendelson (1986), "Asset Pricing and the Bid-Ask Spread",
//     Journal of Financial Economics. Liquidity premium rises with leverage
//     crowding; the ratio acts as a real-time liquidity-stress gauge.
//     DOI: https://doi.org/10.1016/0304-405X(86)90065-6
//  5. Makarov & Schoar (2020), "Trading and Arbitrage in Cryptocurrency
//     Markets", Journal of Financial Economics. Funding-rate arbitrage is
//     the primary perp-spot link; extreme funding/OI flags crowded shorts
//     or longs. DOI: https://doi.org/10.1016/j.jfineco.2020.05.004
// ============================================================================

define(
    title="Funding / OI Ratio — Perfected Edition",
    position="offchart",
    axis=true
)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — grouped with constraints
// ---------------------------------------------------------------------------

// --- Data Sources ---
var oiSymbol = input(
    name="oiSymbol",
    type="string",
    defaultValue="BTCUSDT",
    label="OI Symbol",
    group="Data Sources"
)
var oiExchange = input(
    name="oiExchange",
    type="string",
    defaultValue="BINANCE_FUTURES",
    label="OI Exchange",
    group="Data Sources"
)
var fundingSymbol = input(
    name="fundingSymbol",
    type="string",
    defaultValue="BTCUSDT",
    label="Funding Symbol",
    group="Data Sources"
)
var fundingExchange = input(
    name="fundingExchange",
    type="string",
    defaultValue="BINANCE_FUTURES",
    label="Funding Exchange",
    group="Data Sources"
)

// --- Computation ---
var smoothLen = input(
    name="smoothLen",
    type="number",
    defaultValue=10,
    label="Smoothing Length",
    constraints={min: 1, max: 50, step: 1},
    group="Computation"
)
var normPeriod = input(
    name="normPeriod",
    type="number",
    defaultValue=100,
    label="Normalization Period",
    constraints={min: 20, max: 500, step: 5},
    group="Computation"
)
var zWindow = input(
    name="zWindow",
    type="number",
    defaultValue=50,
    label="Z-Score Window",
    constraints={min: 10, max: 200, step: 5},
    group="Computation"
)
var useZScore = input(
    name="useZScore",
    type="boolean",
    defaultValue=true,
    label="Use Z-Score Normalisation",
    group="Computation"
)

// --- Thresholds ---
var upThresh = input(
    name="upThresh",
    type="number",
    defaultValue=2.0,
    label="Upper Regime Threshold",
    constraints={min: 0.5, max: 5.0, step: 0.5},
    group="Thresholds"
)
var dnThresh = input(
    name="dnThresh",
    type="number",
    defaultValue=-2.0,
    label="Lower Regime Threshold",
    constraints={min: -5.0, max: -0.5, step: 0.5},
    group="Thresholds"
)
var extremeThresh = input(
    name="extremeThresh",
    type="number",
    defaultValue=3.0,
    label="Extreme Alert Threshold",
    constraints={min: 2.0, max: 6.0, step: 0.5},
    group="Thresholds"
)

// --- Display ---
var showRatio = input(
    name="showRatio",
    type="boolean",
    defaultValue=true,
    label="Show Ratio Line",
    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 Regime Fill",
    group="Display"
)
var showHist = input(
    name="showHist",
    type="boolean",
    defaultValue=true,
    label="Show Momentum Histogram",
    group="Display"
)
var showThresh = input(
    name="showThresh",
    type="boolean",
    defaultValue=true,
    label="Show Threshold Lines",
    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 Alert Shapes",
    group="Display"
)

// --- Colors ---
var bullColor = input(
    name="bullColor",
    type="color",
    defaultValue="#26a69a",
    label="Bull Color",
    group="Colors"
)
var bearColor = input(
    name="bearColor",
    type="color",
    defaultValue="#ef5350",
    label="Bear 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="#ffffff",
    label="Line Color",
    group="Colors"
)

// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------
timeseries oiTS = open_interest(symbol=oiSymbol, exchange=oiExchange)
timeseries fundingTS = source("funding_rate", fundingSymbol, fundingExchange)

// Guard: halt until external feeds have loaded to avoid NaN propagation
if (isnan(oiTS.close[0]) || isnan(fundingTS.value[0])) {
    return
}

// ---------------------------------------------------------------------------
// 3. COMPUTATION
// ---------------------------------------------------------------------------

// -- 3.1 Raw series --
timeseries oi = oiTS.close
timeseries funding = fundingTS.value

// -- 3.2 OI change (delta) --
timeseries dOI = oi - oi[1]

// -- 3.3 Funding / OI Ratio --
// Measures funding pressure per unit of OI change. When OI is expanding and
// funding is positive, longs are paying aggressively — crowded long.
// When OI is expanding and funding is negative, shorts are paying — crowded short.
// Guard denominator against zero.
timeseries ratio = (math.abs(dOI) > 0) ? (funding / math.abs(dOI)) : 0

// Smooth the ratio to remove high-frequency noise
timeseries ratioSmooth = ema(source=ratio, period=smoothLen)

// -- 3.4 Z-score normalisation (all denominators guarded) --
// Z_t = (ratio_t − μ_t) / σ_t, where μ_t = SMA(ratio, W), σ_t = StDev(ratio, W).
// When z-score is high, funding pressure is extreme relative to historical OI delta.
timeseries ratioMean = sma(ratioSmooth, zWindow)
timeseries ratioStd = stdev(ratioSmooth, zWindow)
timeseries ratioZ = (ratioStd > 0) ? (ratioSmooth - ratioMean) / ratioStd : 0

// Fallback: if funding data is unavailable, proxy from OI rate-of-change
var useProxy = isnan(fundingTS.value[0])
if (useProxy) {
    // Proxy: second difference of OI scaled by OI level
    timeseries fundingProxy = (dOI - dOI[1]) / math.max(math.abs(oi[1]), 1e-9)
    ratio = (math.abs(dOI) > 0) ? (fundingProxy / math.abs(dOI)) : 0
    ratioSmooth = ema(source=ratio, period=smoothLen)
    ratioMean = sma(ratioSmooth, zWindow)
    ratioStd = stdev(ratioSmooth, zWindow)
    ratioZ = (ratioStd > 0) ? (ratioSmooth - ratioMean) / ratioStd : 0
}

// -- 3.5 Min-max normalisation (legacy -1..+1) --
timeseries hi = highest(source=ratioSmooth, period=normPeriod)
timeseries lo = lowest(source=ratioSmooth, period=normPeriod)
timeseries norm = (ratioSmooth - lo) / math.max(hi - lo, 1e-9) * 2 - 1

// Choose the active signal: z-score when enabled, else min-max normalised
// Both are centred at 0 for consistent regime interpretation
timeseries signal = useZScore ? ratioZ : norm

// -- 3.6 Regime detection (configurable thresholds, no magic numbers) --
var regimeBull = signal > upThresh
var regimeBear = signal < dnThresh
var regimeNeutral = !regimeBull && !regimeBear
var extremeBull = signal > extremeThresh
var extremeBear = signal < -extremeThresh

var regimeColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)

// -- 3.7 Static state tracking for consecutive-bar regime context --
static bullBars = 0
static bearBars = 0
static lastSignal = 0.0

if (regimeBull) {
    bullBars = bullBars + 1
    bearBars = 0
} else if (regimeBear) {
    bearBars = bearBars + 1
    bullBars = 0
} else {
    bullBars = 0
    bearBars = 0
}

lastSignal = signal[0]

// -- 3.8 Momentum histogram (signal change rate) --
timeseries mom = signal - signal[1]

// ---------------------------------------------------------------------------
// 4. ALERT CONDITIONS
// ---------------------------------------------------------------------------
var crossUp = signal > upThresh && signal[1] <= upThresh
var crossDn = signal < dnThresh && signal[1] >= dnThresh
var crossNeutralUp = signal < upThresh && signal[1] >= upThresh
var crossNeutralDn = signal > dnThresh && signal[1] <= dnThresh
var extremeAlert = extremeBull || extremeBear

// ---------------------------------------------------------------------------
// 5. VISUALIZATION
// ---------------------------------------------------------------------------

// 5.1 Zero line
if (showZero) {
    hline(value=0, color="#ffffff30", width=1)
}

// 5.2 Threshold lines
if (showThresh) {
    hline(value=upThresh, color=transparency(bearColor, 60), width=1)
    hline(value=dnThresh, color=transparency(bullColor, 60), width=1)
    hline(value=extremeThresh, color=transparency(bearColor, 40), width=1)
    hline(value=-extremeThresh, color=transparency(bullColor, 40), width=1)
}

// 5.3 Ratio line (raw smoothed ratio)
if (showRatio) {
    plotLine(
        value=ratioSmooth,
        width=1,
        colors=[transparency(lineColor, 50)],
        label=["Ratio Smooth"],
        desc=["Smoothed funding / OI ratio (raw scale)"]
    )
}

// 5.4 Z-Score / Normalised line (regime-coloured)
if (showZScore) {
    plotLine(
        value=signal,
        width=2,
        colors=[regimeColor],
        label=["Signal"],
        desc=[useZScore ? "Z-score normalised funding / OI ratio" : "Min-max normalised funding / OI ratio"]
    )
}

// 5.5 Regime fill (signal vs zero line, colour-coded)
if (showFill) {
    var fillBull = signal > 0
    plotLine(
        value=[signal, 0],
        width=1,
        colors=[transparency(bullColor, 20), transparency(bearColor, 20)],
        colorIndex=fillBull ? 0 : 1,
        fill=true,
        label=["Signal", "Zero"],
        desc=["Filled area between signal and zero, colour-coded by direction"]
    )
}

// 5.6 Momentum histogram
if (showHist) {
    var histBull = mom >= 0
    plotBar(
        value=mom,
        colors=[transparency(bullColor, 60), transparency(bearColor, 60)],
        colorIndex=histBull ? 0 : 1,
        width=1,
        label=["Momentum"],
        desc=["First difference of signal (momentum)"]
    )
}

// 5.7 Extreme alert shapes
if (showShapes) {
    if (extremeBull) {
        plotShape(
            value=signal,
            shape="triangledown",
            colorIndex=bearColor,
            width=2,
            label=["Extreme Bull"],
            desc=["Extreme bullish funding/OI: funding massively positive relative to OI delta; crowded long / short-squeeze risk"]
        )
    }
    if (extremeBear) {
        plotShape(
            value=signal,
            shape="triangleup",
            colorIndex=bullColor,
            width=2,
            label=["Extreme Bear"],
            desc=["Extreme bearish funding/OI: funding massively negative relative to OI delta; crowded short / long-squeeze risk"]
        )
    }
    if (crossUp) {
        plotShape(
            value=upThresh,
            shape="circle",
            colorIndex=bearColor,
            width=2,
            label=["Cross Up"],
            desc=["Signal crossed above upper threshold into bullish regime"]
        )
    }
    if (crossDn) {
        plotShape(
            value=dnThresh,
            shape="circle",
            colorIndex=bullColor,
            width=2,
            label=["Cross Down"],
            desc=["Signal crossed below lower threshold into bearish regime"]
        )
    }
}

// ---------------------------------------------------------------------------
// 6. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = regimeBull ? "BULLISH" : (regimeBear ? "BEARISH" : "NEUTRAL")
    var regimeTextColor = regimeBull ? bullColor : (regimeBear ? bearColor : neutralColor)
    var proxyText = useProxy ? "Funding proxy (OI ΔΔ)" : "Live funding rate"

    plotTable(
        data=[
            ["Funding / OI Ratio", regimeText],
            ["Signal", signal[0]],
            ["Z-Score", ratioZ[0]],
            ["Ratio (raw)", ratioSmooth[0]],
            ["OI Δ", dOI[0]],
            ["Bull bars", bullBars],
            ["Bear bars", bearBars],
            [proxyText, ""]
        ],
        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
    )
}