MM Flow
FlowScripts

Perfected FlowScript

SCF Perps Premium

SCF Perps Premium V2 is indexed as 114_scf_perps_premium.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

19.9 KB

Lines

484

Native Signal Candidates

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

12/12 guarded

Zero Cross Up

line 364:9

Trigger

(showShapes) && (crossUpZero)

Value

zFinal

Deps

crossUpZero:var, showShapes:input

Zero Cross Down

line 374:9

Trigger

(showShapes) && (crossDnZero)

Value

zFinal

Deps

crossDnZero:var, showShapes:input

Contango Regime

line 384:9

Trigger

(showShapes) && (crossUp)

Value

zFinal

Deps

crossUp:var, showShapes:input

Backwardation Regime

line 394:9

Trigger

(showShapes) && (crossDn)

Value

zFinal

Deps

crossDn:var, showShapes:input

Extreme Contango

line 404:9

Trigger

(showShapes) && (extremeUp)

Value

zFinal

Deps

extremeUp:var, showShapes:input

Extreme Backwardation

line 414:9

Trigger

(showShapes) && (extremeDn)

Value

zFinal

Deps

extremeDn:var, showShapes:input

+1σ Touch

line 424:9

Trigger

(showShapes) && (touchBand1Hi)

Value

zFinal

Deps

showShapes:input, touchBand1Hi:var

-1σ Touch

line 434:9

Trigger

(showShapes) && (touchBand1Lo)

Value

zFinal

Deps

showShapes:input, touchBand1Lo:var

+2σ Touch

line 444:9

Trigger

(showShapes) && (touchBand2Hi)

Value

zFinal

Deps

showShapes:input, touchBand2Hi:var

-2σ Touch

line 454:9

Trigger

(showShapes) && (touchBand2Lo)

Value

zFinal

Deps

showShapes:input, touchBand2Lo:var

+3σ Touch

line 464:9

Trigger

(showShapes) && (touchBand3Hi)

Value

zFinal

Deps

showShapes:input, touchBand3Hi:var

-3σ Touch

line 474:9

Trigger

(showShapes) && (touchBand3Lo)

Value

zFinal

Deps

showShapes:input, touchBand3Lo:var

114_scf_perps_premium.flowscript

source path: kscripts/perfected/114_scf_perps_premium.flowscript · sha256:9aaea8fb9f89adee21324e49b674963c8faa06e8e9cbdcee7fadc8eb03d04630

hash verified
//@version=2
// Source: kiyotaka.ai/hub/kscript (original) — Perfected by kScript_Perfection_Engineer

// ============================================================================
// SCF Perps Premium V2 — Perpetual Futures Premium with Z-Score & Regime Detection
// Author: SoulzBTC (@SoulzBTC) — Perfected by kScript_Perfection_Engineer
// Tags: FLOW, #perps, #premium, #funding, #basis, #zscore, #arbitrage
//
// Tracks the premium/discount between perpetual futures and spot markets,
// computes a rolling z-score for statistical context, and adds regime detection
// with color-coded fills, band touches, and shape markers for extreme events.
//
// FORMULA FOUNDATION:
// 1. Perp Premium: Premium = (Perp − Spot) / Spot × 100%  [He & Manela 2022]
// 2. Z-Score Normalization: z = (Premium − μ) / σ  [Zhao & Palomar 2018]
// 3. Regime Segmentation: Contango (premium > +1σ), Backwardation (premium < −1σ),
//    Neutral (within ±1σ) per Gornall & Strebulaev (2025) basis-risk framework.
// 4. Brunnermeier & Pedersen (2009) liquidity spiral: extreme premiums signal
//    funding stress and cascade risk in leveraged markets.
//
// RESEARCH BASIS:
//  • He & Manela (2022), "Fundamentals of Perpetual Futures", J. Financial Economics
//    (forthcoming); arXiv:2212.06888. First rigorous no-arbitrage analysis of
//    perpetual futures. Premium = perp − spot; deviations decay as liquidity improves.
//  • Kim & Park (2025), "Designing Funding Rates for Perpetual Futures",
//    arXiv:2506.08573. Path-dependent funding BSDEs; 8h-averaged funding
//    rates keep perp aligned with spot target.
//  • Gornall & Strebulaev (2025), "Perpetual Futures and Basis Risk".
//    Perpetual futures reduce basis risk; lower spreads than quarterly futures.
//  • Brunnermeier & Pedersen (2009), "Market Liquidity and Funding Liquidity",
//    Rev. Financial Studies 22(6), 2201–2238. Liquidity spirals: funding stress
//    amplifies market moves; extreme premiums are early warning signals.
//  • CoinxSight (2026), "Funding Rate: The Cost of Being Crowded". Thresholds:
//    >+0.05% = overcrowded long; <−0.05% = overcrowded short. Contrarian at extremes.
// ============================================================================

define(
    title="SCF Perps Premium V2",
    position="offchart",
    axis=true
)

// -----------------------------------------------------------------------------
// User Inputs — grouped and constrained per production spec
// -----------------------------------------------------------------------------

// --- Premium Calculation ---
var zLen = input(name="zLen", type="number", defaultValue=30, label="Z-Score Lookback", constraints={min: 10, max: 200, step: 5}, group="Premium")
var smoothLen = input(name="smoothLen", type="number", defaultValue=3, label="Smoothing Length", constraints={min: 1, max: 50, step: 1}, group="Premium")
var useEma = input(name="useEma", type="boolean", defaultValue=true, label="Use EMA (off=SMA)", group="Premium")
var perpWeightBybit = input(name="perpWeightBybit", type="number", defaultValue=1.0, label="Bybit Perp Weight", constraints={min: 0.0, max: 5.0, step: 0.5}, group="Premium")
var perpWeightOkex = input(name="perpWeightOkex", type="number", defaultValue=1.0, label="OKX Perp Weight", constraints={min: 0.0, max: 5.0, step: 0.5}, group="Premium")
var perpWeightHL = input(name="perpWeightHL", type="number", defaultValue=1.0, label="Hyperliquid Perp Weight", constraints={min: 0.0, max: 5.0, step: 0.5}, group="Premium")

// --- Bands ---
var showBand1 = input(name="showBand1", type="boolean", defaultValue=true, label="Show ±1σ Band", group="Bands")
var showBand2 = input(name="showBand2", type="boolean", defaultValue=true, label="Show ±2σ Band", group="Bands")
var showBand3 = input(name="showBand3", type="boolean", defaultValue=false, label="Show ±3σ Band", group="Bands")
var showFill = input(name="showFill", type="boolean", defaultValue=true, label="Show Band Fills", group="Bands")

// --- Thresholds & Regime ---
var bullThresh = input(name="bullThresh", type="number", defaultValue=1.0, label="Bullish Regime Threshold (σ)", constraints={min: 0.5, max: 3.0, step: 0.1}, group="Thresholds")
var bearThresh = input(name="bearThresh", type="number", defaultValue=-1.0, label="Bearish Regime Threshold (σ)", constraints={min: -3.0, max: -0.5, step: 0.1}, group="Thresholds")
var extremeThresh = input(name="extremeThresh", type="number", defaultValue=2.0, label="Extreme Threshold (σ)", constraints={min: 1.5, max: 4.0, step: 0.1}, group="Thresholds")

// --- Display ---
var showRawPremium = input(name="showRawPremium", type="boolean", defaultValue=true, label="Show Raw Premium Line", group="Display")
var showZScore = input(name="showZScore", type="boolean", defaultValue=true, label="Show Z-Score Line", group="Display")
var showShapes = input(name="showShapes", type="boolean", defaultValue=true, label="Show Regime Shapes", group="Display")
var showZero = input(name="showZero", type="boolean", defaultValue=true, label="Show Zero Line", group="Display")
var lineWidth = input(name="lineWidth", type="number", defaultValue=2, label="Line Width", constraints={min: 1, max: 4, step: 1}, group="Display")
var shapeSize = input(name="shapeSize", type="number", defaultValue=2, label="Shape Size", constraints={min: 1, max: 4, step: 1}, group="Display")

// --- Colors ---
var premiumColor = input(name="premiumColor", type="color", defaultValue="#26a69a", label="Premium Line Color", group="Colors")
var zScoreColor = input(name="zScoreColor", type="color", defaultValue="#42a5f5", label="Z-Score Line Color", group="Colors")
var bullColor = input(name="bullColor", type="color", defaultValue="#26a69a", label="Bull/Contango Color", group="Colors")
var bearColor = input(name="bearColor", type="color", defaultValue="#ef5350", label="Bear/Backwardation Color", group="Colors")
var neutralColor = input(name="neutralColor", type="color", defaultValue="#9e9e9e", label="Neutral Color", group="Colors")
var extremeBullColor = input(name="extremeBullColor", type="color", defaultValue="#00e676", label="Extreme Contango Color", group="Colors")
var extremeBearColor = input(name="extremeBearColor", type="color", defaultValue="#ff1744", label="Extreme Backwardation Color", group="Colors")
var band1Color = input(name="band1Color", type="color", defaultValue="#9e9e9e", label="±1σ Band Color", group="Colors")
var band2Color = input(name="band2Color", type="color", defaultValue="#757575", label="±2σ Band Color", group="Colors")
var band3Color = input(name="band3Color", type="color", defaultValue="#616161", label="±3σ Band Color", group="Colors")

// -----------------------------------------------------------------------------
// Data Sources (spot vs perpetual)
// -----------------------------------------------------------------------------
timeseries spotBars = ohlcv(symbol=currentSymbol, exchange=currentExchange)
timeseries spot = spotBars.close

// Weighted perp composite across venues
// In production these map to native perp feeds (e.g., BTCUSDT-PERP).
timeseries perpBybit = open_interest(symbol="BTCUSDT", exchange="BYBIT")
timeseries perpOkex  = open_interest(symbol="BTC-USDT-SWAP", exchange="OKEX_SWAP")
timeseries perpHL    = open_interest(symbol="BTC", exchange="HYPERLIQUID_FUTURES")

// Funding rates from multiple venues for context
timeseries f1 = funding_rate(symbol="BTCUSDT", exchange="BYBIT")
timeseries f2 = funding_rate(symbol="BTC-USDT-SWAP", exchange="OKEX_SWAP")
timeseries f3 = funding_rate(symbol="BTC", exchange="HYPERLIQUID_FUTURES")

// isnan guard: prevent computation on incomplete data
if (isnan(spot[0]) || isnan(perpBybit[0]) || isnan(perpOkex[0]) || isnan(perpHL[0])) {
    return
}

// -----------------------------------------------------------------------------
// Perp Premium Computation (He & Manela 2022)
// -----------------------------------------------------------------------------
// Weighted composite perp proxy using open-interest-weighted average.
// OI-weighted averaging gives more weight to venues with deeper liquidity.
var wSum = perpWeightBybit + perpWeightOkex + perpWeightHL
var perpComposite = wSum > 0 ?
    (perpWeightBybit * perpBybit + perpWeightOkex * perpOkex + perpWeightHL * perpHL) / wSum :
    perpBybit

// Premium = (perp − spot) / spot × 100%
// Standard no-arbitrage deviation measure per He & Manela (2022).
var premiumRaw = spot > 0 ? (perpComposite - spot) / spot * 100.0 : 0.0

// Funding-rate context: average funding across venues (8h equivalent)
var avgFunding = (f1 + f2 + f3) / 3.0

// -----------------------------------------------------------------------------
// Z-Score Normalization (Zhao & Palomar 2018)
// -----------------------------------------------------------------------------
// Rolling mean and standard deviation over zLen bars.
timeseries pMean = sma(premiumRaw, zLen)
timeseries pStd  = stdev(premiumRaw, zLen)

// z = (premium − μ) / σ, with zero-division guard
timeseries zScore = pStd > 1e-9 ? (premiumRaw - pMean) / pStd : 0.0

// Smoothing (EMA vs SMA per user preference)
timeseries zEma = ema(zScore, smoothLen)
timeseries zSma = sma(zScore, smoothLen)
timeseries zFinal = useEma ? zEma : zSma

// Smooth the raw premium for display
timeseries premEma = ema(premiumRaw, smoothLen)
timeseries premSma = sma(premiumRaw, smoothLen)
timeseries premSmooth = useEma ? premEma : premSma

// -----------------------------------------------------------------------------
// Regime Detection (Gornall & Strebulaev 2025 basis-risk framework)
// -----------------------------------------------------------------------------
// Segmented into three regimes:
//   Contango (bull):    z ≥ bullThresh  → perp trading rich to spot
//   Backwardation (bear): z ≤ bearThresh → perp trading cheap to spot
//   Neutral:             bearThresh < z < bullThresh
// He & Manela (2022): positive past-return momentum → futures premium.

var regime = 0      // 0 = neutral, 1 = contango, -1 = backwardation
var extremeRegime = 0  // 0 = normal, 1 = extreme contango, -1 = extreme backwardation

if (zFinal >= bullThresh) {
    regime = 1
} else if (zFinal <= bearThresh) {
    regime = -1
}

if (zFinal >= extremeThresh) {
    extremeRegime = 1
} else if (zFinal <= -extremeThresh) {
    extremeRegime = -1
}

// -----------------------------------------------------------------------------
// Static State Tracking (Session-level persistence)
// -----------------------------------------------------------------------------
// Stateful computation for session extremes, regime transitions, and
// extreme-event counters. Tracks the statistical history of the premium.

static lastRegime = 0
static regimeChangeCount = 0
static sessionHighZ = -999999.0
static sessionLowZ = 999999.0
static sessionHighPrem = -999999.0
static sessionLowPrem = 999999.0
static extremeContangoCount = 0
static extremeBackwardationCount = 0
static lastBarIndex = 0

var currentBarIndex = bar_index[0]

if (!isnan(currentBarIndex) && currentBarIndex != lastBarIndex) {
    // New bar — update session tracking
    lastBarIndex = currentBarIndex

    if (zFinal > sessionHighZ) {
        sessionHighZ = zFinal
    }
    if (zFinal < sessionLowZ) {
        sessionLowZ = zFinal
    }
    if (premiumRaw > sessionHighPrem) {
        sessionHighPrem = premiumRaw
    }
    if (premiumRaw < sessionLowPrem) {
        sessionLowPrem = premiumRaw
    }

    if (lastRegime != regime) {
        lastRegime = regime
        regimeChangeCount = regimeChangeCount + 1
    }

    if (extremeRegime == 1) {
        extremeContangoCount = extremeContangoCount + 1
    } else if (extremeRegime == -1) {
        extremeBackwardationCount = extremeBackwardationCount + 1
    }
}

// -----------------------------------------------------------------------------
// Sigma Band Construction (Zhao & Palomar 2018 contrarian thresholds)
// -----------------------------------------------------------------------------
// ±1σ, ±2σ, ±3σ bands for statistical rarity assessment.
// ~68.2% within ±1σ, ~95.4% within ±2σ, ~99.7% within ±3σ.

timeseries band1Hi = bullThresh
timeseries band1Lo = bearThresh
timeseries band2Hi = extremeThresh
timeseries band2Lo = -extremeThresh
timeseries band3Hi = extremeThresh + (extremeThresh - bullThresh)
timeseries band3Lo = -extremeThresh - (extremeThresh - bullThresh)

// Band touch detection for shape markers
var touchBand1Hi = zFinal >= band1Hi && !isnan(zFinal[1]) && zFinal[1] < band1Hi
var touchBand1Lo = zFinal <= band1Lo && !isnan(zFinal[1]) && zFinal[1] > band1Lo
var touchBand2Hi = zFinal >= band2Hi && !isnan(zFinal[1]) && zFinal[1] < band2Hi
var touchBand2Lo = zFinal <= band2Lo && !isnan(zFinal[1]) && zFinal[1] > band2Lo
var touchBand3Hi = zFinal >= band3Hi && !isnan(zFinal[1]) && zFinal[1] < band3Hi
var touchBand3Lo = zFinal <= band3Lo && !isnan(zFinal[1]) && zFinal[1] > band3Lo

// Cross zero detection
var crossUpZero = zFinal >= 0 && !isnan(zFinal[1]) && zFinal[1] < 0
var crossDnZero = zFinal <= 0 && !isnan(zFinal[1]) && zFinal[1] > 0

// -----------------------------------------------------------------------------
// Plots — Multiple Visualization Types (Line, Bar, Fill, Shape, HLine)
// -----------------------------------------------------------------------------

// Horizontal guide lines — zero line and threshold zones
if (showZero) {
    hline(value=0, color="#ffffff30", width=1)
}

hline(value=bullThresh, color=opacity(bullColor, 30), width=1)
hline(value=bearThresh, color=opacity(bearColor, 30), width=1)
hline(value=extremeThresh, color=opacity(extremeBullColor, 20), width=1)
hline(value=-extremeThresh, color=opacity(extremeBearColor, 20), width=1)

// --- Raw Premium Line (regime-colored) ---
if (showRawPremium) {
    plotLine(
        value=premSmooth,
        width=lineWidth,
        colors=[bullColor, bearColor, neutralColor],
        colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
        label=["Premium"],
        desc=["Perp premium over spot (%) — regime-colored"]
    )
}

// --- Z-Score Line with regime-colored fill ---
if (showZScore) {
    plotLine(
        value=zFinal,
        width=lineWidth,
        colors=[bullColor, bearColor, neutralColor],
        colorIndex=regime == 1 ? 0 : (regime == -1 ? 1 : 2),
        fill=true,
        label=["Premium Z"],
        desc=["Rolling z-score of perp premium. Regime: contango/backwardation/neutral"]
    )
}

// --- ±1σ Band Fill & Lines ---
if (showBand1) {
    if (showFill) {
        plotLine(
            value=([band1Lo, band1Hi]),
            width=1,
            colors=[opacity(bullColor, 15), opacity(bearColor, 15)],
            colorIndex=regime == 1 ? 0 : 1,
            fill=true,
            label=["±1σ Fill"],
            desc=["±1σ band fill (regime-colored) — ~68% containment"]
        )
    }
    plotLine(
        value=band1Hi,
        width=1,
        colors=[band1Color],
        label=["+1σ"],
        desc=["Upper band at +1σ threshold"]
    )
    plotLine(
        value=band1Lo,
        width=1,
        colors=[band1Color],
        label=["-1σ"],
        desc=["Lower band at -1σ threshold"]
    )
}

// --- ±2σ Band Fill & Lines ---
if (showBand2) {
    if (showFill) {
        plotLine(
            value=([band2Lo, band2Hi]),
            width=1,
            colors=[opacity(bullColor, 10), opacity(bearColor, 10)],
            colorIndex=regime == 1 ? 0 : 1,
            fill=true,
            label=["±2σ Fill"],
            desc=["±2σ band fill (regime-colored) — ~95% containment"]
        )
    }
    plotLine(
        value=band2Hi,
        width=1,
        colors=[band2Color],
        label=["+2σ"],
        desc=["Upper band at +2σ extreme threshold"]
    )
    plotLine(
        value=band2Lo,
        width=1,
        colors=[band2Color],
        label=["-2σ"],
        desc=["Lower band at -2σ extreme threshold"]
    )
}

// --- ±3σ Band Lines ---
if (showBand3) {
    plotLine(
        value=band3Hi,
        width=1,
        colors=[band3Color],
        label=["+3σ"],
        desc=["Upper band at +3σ — statistical rarity ~99.7%"]
    )
    plotLine(
        value=band3Lo,
        width=1,
        colors=[band3Color],
        label=["-3σ"],
        desc=["Lower band at -3σ — statistical rarity ~99.7%"]
    )
}

// --- Regime Transition & Extreme Shapes ---
if (showShapes) {
    var crossUp = zFinal >= bullThresh && !isnan(zFinal[1]) && zFinal[1] < bullThresh
    var crossDn = zFinal <= bearThresh && !isnan(zFinal[1]) && zFinal[1] > bearThresh
    var extremeUp = zFinal >= extremeThresh && !isnan(zFinal[1]) && zFinal[1] < extremeThresh
    var extremeDn = zFinal <= -extremeThresh && !isnan(zFinal[1]) && zFinal[1] > -extremeThresh

    if (crossUpZero) {
        plotShape(
            value=zFinal,
            shape="triangleup",
            color=bullColor,
            width=shapeSize,
            label=["Zero Cross Up"],
            desc=["Premium z-score crossed above zero — contango begins"]
        )
    }
    if (crossDnZero) {
        plotShape(
            value=zFinal,
            shape="triangledown",
            color=bearColor,
            width=shapeSize,
            label=["Zero Cross Down"],
            desc=["Premium z-score crossed below zero — backwardation begins"]
        )
    }
    if (crossUp) {
        plotShape(
            value=zFinal,
            shape="triangleup",
            color=extremeBullColor,
            width=shapeSize,
            label=["Contango Regime"],
            desc=["Premium z-score crossed into contango regime (perp rich)"]
        )
    }
    if (crossDn) {
        plotShape(
            value=zFinal,
            shape="triangledown",
            color=extremeBearColor,
            width=shapeSize,
            label=["Backwardation Regime"],
            desc=["Premium z-score crossed into backwardation regime (perp cheap)"]
        )
    }
    if (extremeUp) {
        plotShape(
            value=zFinal,
            shape="diamond",
            color=extremeBullColor,
            width=shapeSize + 1,
            label=["Extreme Contango"],
            desc=["Extreme contango detected — funding stress, crowded longs, contrarian signal"]
        )
    }
    if (extremeDn) {
        plotShape(
            value=zFinal,
            shape="diamond",
            color=extremeBearColor,
            width=shapeSize + 1,
            label=["Extreme Backwardation"],
            desc=["Extreme backwardation detected — squeeze risk, crowded shorts, contrarian signal"]
        )
    }
    if (touchBand1Hi) {
        plotShape(
            value=zFinal,
            shape="triangledown",
            color=band1Color,
            width=shapeSize,
            label=["+1σ Touch"],
            desc=["Premium z-score touched +1σ band"]
        )
    }
    if (touchBand1Lo) {
        plotShape(
            value=zFinal,
            shape="triangleup",
            color=band1Color,
            width=shapeSize,
            label=["-1σ Touch"],
            desc=["Premium z-score touched -1σ band"]
        )
    }
    if (touchBand2Hi) {
        plotShape(
            value=zFinal,
            shape="triangledown",
            color=band2Color,
            width=shapeSize,
            label=["+2σ Touch"],
            desc=["Premium z-score touched +2σ band — statistical extreme"]
        )
    }
    if (touchBand2Lo) {
        plotShape(
            value=zFinal,
            shape="triangleup",
            color=band2Color,
            width=shapeSize,
            label=["-2σ Touch"],
            desc=["Premium z-score touched -2σ band — statistical extreme"]
        )
    }
    if (touchBand3Hi) {
        plotShape(
            value=zFinal,
            shape="triangledown",
            color=band3Color,
            width=shapeSize + 1,
            label=["+3σ Touch"],
            desc=["Premium z-score touched +3σ band — rare event, cascade risk"]
        )
    }
    if (touchBand3Lo) {
        plotShape(
            value=zFinal,
            shape="triangleup",
            color=band3Color,
            width=shapeSize + 1,
            label=["-3σ Touch"],
            desc=["Premium z-score touched -3σ band — rare event, squeeze risk"]
        )
    }
}