MM Flow
FlowScripts

Perfected FlowScript

Silver Gold Ratio

Silver Gold Ratio — Perfected Edition is indexed as 318_silver_gold_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

17.8 KB

Lines

441

Native Signal Candidates

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

8/8 guarded

Extreme High

line 319:9

Trigger

(showShapes) && (highPenetrate)

Value

dynUpper

Deps

highPenetrate:var, showShapes:input

Extreme Low

line 329:9

Trigger

(showShapes) && (lowPenetrate)

Value

dynLower

Deps

lowPenetrate:var, showShapes:input

Bull Div

line 343:9

Trigger

(showShapes) && (bullDiv)

Value

zSmooth

Deps

bullDiv:var, showShapes:input

Bear Div

line 353:9

Trigger

(showShapes) && (bearDiv)

Value

zSmooth

Deps

bearDiv:var, showShapes:input

Cross Up

line 367:9

Trigger

(showAlerts) && (crossUp)

Value

dynLower

Deps

crossUp:var, showAlerts:input

Cross Down

line 377:9

Trigger

(showAlerts) && (crossDown)

Value

dynUpper

Deps

crossDown:var, showAlerts:input

High Revert

line 387:9

Trigger

(showAlerts) && (highRevert)

Value

dynUpper

Deps

highRevert:var, showAlerts:input

Low Revert

line 397:9

Trigger

(showAlerts) && (lowRevert)

Value

dynLower

Deps

lowRevert:var, showAlerts:input

318_silver_gold_ratio.flowscript

source path: kscripts/perfected/318_silver_gold_ratio.flowscript · sha256:08f9f78bf677b57342443aaeaeba07bdf2f56c6b7e27959bcfd251ae60fec059

hash verified
//@version=2
// ============================================================================
// Silver Gold Ratio — Perfected Edition
// Author: D (@Diagnostics Roche) | Enhanced by kScript_Perfection_Engineer
// Tags: CORE, #silver, #gold, #ratio, #zscore, #regime, #pairs, #meanreversion
//
// Production-quality inter-commodity relative-value indicator. Computes the
// gold-to-silver price ratio, normalizes via rolling z-score, detects regime
// extremes with dynamic thresholds, and visualizes mean-reversion opportunities
// through color-coded fills, shape alerts, and a comprehensive regime table.
//
// The gold-silver ratio is among the oldest continuously tracked financial
// metrics, used by Greek and Roman traders. Modern quantitative analysis treats
// it as a mean-reverting spread anchored by shared monetary/inflation-hedge
// demand, divergent industrial use (silver), and central-bank gold preference.
//
// Research papers underpinning this design:
//  1. Mittal (2025), "Gold-Silver Pair Trading: Mean Reversion Strategy Using
//     ML": integrates classical cointegration with ML regime filters. Z-score
//     normalization with volatility, macro, and sentiment features outperforms
//     static statistical arbitrage during high-volatility regimes.
//     URL: https://www.academia.edu/145275839/
//  2. Gatev, Goetzmann & Rouwenhorst (2006), "Pairs Trading: Performance of a
//     Relative-Value Arbitrage Rule", Review of Financial Studies, 19(3), 797–827.
//     Seminal empirical study: average annualized excess returns of 11% for
//     US CRSP securities (1962–2002). Distance/cointegration methodology.
//     DOI: https://doi.org/10.1093/rfs/hhj020
//  3. Poterba & Summers (1988), "Mean Reversion in Stock Prices: Evidence and
//     Implications", JFE, 22(1), 27–59. Negative autocorrelation at medium horizons
//     supports dynamic threshold calibration for mean-reversion signals.
//     DOI: https://doi.org/10.1016/0304-405X(88)90021-9
//  4. Krauss (2017), "Statistical Arbitrage Pairs Trading Strategies: Review
//     and Outlook", J. Economic Surveys, 31(2), 513–545. Comprehensive taxonomy
//     of five pairs-trading streams: distance, cointegration, OU process,
//     stochastic spread, and ML approaches.
//     DOI: https://doi.org/10.1111/joes.12182
//  5. Zhao & Palomar (2018), "Mean-Reverting Portfolio With Budget Constraint",
//     IEEE Trans. Signal Processing. Formalizes z-score event triggers with
//     entry thresholds at Δ = d × σ_z (typically d = 1 or 2).
//     URL: https://palomar.home.ece.ust.hk/papers/2018/ZhaoPalomar-TSP2018.pdf
//  6. Vidyamurthy (2004), "Pairs Trading: Quantitative Methods and Analysis",
//     Wiley. Foundational textbook for cointegration-based spread modeling.
// ============================================================================

define(
    title="Silver Gold Ratio — Perfected Edition",
    position="offchart",
    axis=true
)

// ---------------------------------------------------------------------------
// 1. USER INPUTS — All grouped, all numeric inputs carry constraints
// ---------------------------------------------------------------------------

// -- Data Sources --
var goldSym   = input(name="goldSym",   type="string",  defaultValue="XAUUSD", label="Gold Symbol",   group="Data Sources")
var silverSym = input(name="silverSym", type="string",  defaultValue="XAGUSD", label="Silver Symbol", group="Data Sources")
var ex        = input(name="ex",        type="select",  defaultValue="FOREX",  label="Exchange",      options=["FOREX", "BINANCE", "BYBIT"], group="Data Sources")

// -- Ratio Computation --
var maLen     = input(name="maLen",     type="number",  defaultValue=50,  label="Mean Ratio MA Length",      constraints={min: 10, max: 200, step: 5},  group="Ratio Computation")
var zLen      = input(name="zLen",      type="number",  defaultValue=100, label="Z-Score Lookback",          constraints={min: 20, max: 500, step: 10}, group="Ratio Computation")
var smoothLen = input(name="smoothLen", type="number",  defaultValue=3,   label="Z-Score EMA Smooth",        constraints={min: 1, max: 20, step: 1},    group="Ratio Computation")

// -- Thresholds --
var zUpper    = input(name="zUpper",    type="number",  defaultValue=2.0,  label="Z Upper Threshold (σ)",    constraints={min: 0.5, max: 5.0, step: 0.1}, group="Thresholds")
var zLower    = input(name="zLower",    type="number",  defaultValue=-2.0, label="Z Lower Threshold (σ)",    constraints={min: -5.0, max: -0.5, step: 0.1}, group="Thresholds")
var useDynamic = input(name="useDynamic", type="boolean", defaultValue=false, label="Dynamic Thresholds (vol-adjusted)", group="Thresholds")
var volMultiplier = input(name="volMultiplier", type="number", defaultValue=1.0, label="Volatility Multiplier", constraints={min: 0.5, max: 3.0, step: 0.1}, group="Thresholds")

// -- Display --
var showRatio   = input(name="showRatio",   type="boolean", defaultValue=true,  label="Show Ratio Line",      group="Display")
var showMa      = input(name="showMa",      type="boolean", defaultValue=true,  label="Show Mean MA",         group="Display")
var showZ       = input(name="showZ",       type="boolean", defaultValue=true,  label="Show Z-Score",         group="Display")
var showZFill   = input(name="showZFill",   type="boolean", defaultValue=true,  label="Show Z-Score Fill",    group="Display")
var showShapes  = input(name="showShapes",  type="boolean", defaultValue=true,  label="Show Extreme Shapes",  group="Display")
var showAlerts  = input(name="showAlerts",  type="boolean", defaultValue=true,  label="Show Alert Shapes",    group="Display")

// -- Colors --
var lineColor   = input(name="lineColor",   type="color", defaultValue="#2962ff", label="Ratio Line Color",        group="Colors")
var maColor     = input(name="maColor",     type="color", defaultValue="#ff9800", label="Mean MA Color",           group="Colors")
var upColor     = input(name="upColor",     type="color", defaultValue="#ef5350", label="Overvalued (High Z) Color", group="Colors")
var dnColor     = input(name="dnColor",     type="color", defaultValue="#26a69a", label="Undervalued (Low Z) Color", group="Colors")
var neutralColor= input(name="neutralColor",type="color", defaultValue="#9e9e9e", label="Neutral Color",           group="Colors")
var bullDivColor= input(name="bullDivColor",type="color", defaultValue="#00e676", label="Bullish Divergence Color", group="Colors")
var bearDivColor= input(name="bearDivColor",type="color", defaultValue="#ff5252", label="Bearish Divergence Color", group="Colors")

// ---------------------------------------------------------------------------
// 2. DATA SOURCES & NaN GUARD
// ---------------------------------------------------------------------------
timeseries goldBars   = ohlcv(symbol=goldSym,   exchange=ex)
timeseries silverBars = ohlcv(symbol=silverSym, exchange=ex)
timeseries goldPx     = goldBars.close
timeseries silverPx   = silverBars.close

// Guard: halt until both feeds have loaded to avoid NaN propagation
if (isnan(goldPx[0]) || isnan(silverPx[0])) {
    return
}

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

// -- 3.1 Ratio calculation (guarded against zero silver price) --
// Classical gold-silver ratio = gold price / silver price.
// Historically ranged ~15:1 (ancient) to ~100:1 (modern).
timeseries ratio = silverPx > 0 ? goldPx / silverPx : 0.0

// -- 3.2 Mean and standard deviation (rolling window) --
timeseries ratioMa   = sma(ratio, maLen)
timeseries ratioMean = sma(ratio, zLen)
timeseries ratioSd   = stddev(ratio, zLen)

// -- 3.3 Z-score normalisation (all denominators guarded against zero) --
// Z_t = (Ratio_t − μ_t) / σ_t
// Per Zhao & Palomar (2018), entry thresholds at Δ = d × σ_z.
timeseries zScore = (ratioSd > 0) ? (ratio - ratioMean) / ratioSd : 0.0
timeseries zSmooth = ema(zScore, smoothLen)

// -- 3.4 Dynamic thresholds (volatility-adjusted) --
// Per Poterba & Summers (1988), mean-reversion intensity varies with volatility.
// We adjust z-score bands by rolling standard deviation of the z-score itself.
timeseries zVol = stddev(zSmooth, zLen)
var dynUpper = useDynamic ? zUpper + zVol * volMultiplier : zUpper
var dynLower = useDynamic ? zLower - zVol * volMultiplier : zLower

// Guard: ensure dynamic bands never invert
if (dynUpper <= dynLower) {
    dynUpper = 2.0
    dynLower = -2.0
}

// -- 3.5 Ratio deviation from MA (for divergence detection) --
timeseries ratioDev = ratioMa > 0 ? (ratio - ratioMa) / ratioMa * 100 : 0.0

// -- 3.6 Regime detection --
// Extreme high z: ratio overvalued → gold expensive vs silver → revert short gold / long silver
// Extreme low z:  ratio undervalued → gold cheap vs silver   → revert long gold / short silver
var extremeHigh = zSmooth > dynUpper
var extremeLow  = zSmooth < dynLower
var neutralRegime = !extremeHigh && !extremeLow
var bullishRegime = zSmooth < dynLower   // ratio low → gold cheap relative to silver
var bearishRegime = zSmooth > dynUpper   // ratio high → gold expensive relative to silver

var regimeColor = bullishRegime ? dnColor : (bearishRegime ? upColor : neutralColor)

// ---------------------------------------------------------------------------
// 4. DIVERGENCE DETECTION (stateful via static variables)
// ---------------------------------------------------------------------------
// Regular divergence: ratio makes higher high / lower low, z-score disagrees.
// We track pivot high/low state across bars using static variables.

static prevRatioHigh = -1.0
static prevZHigh = -1.0
static prevRatioLow = -1.0
static prevZLow = -1.0

var bearDiv = false
var bullDiv = false

// Initialize on first real bar after NaN guard
if (prevRatioHigh < 0) {
    prevRatioHigh = ratio[0]
    prevZHigh = zSmooth[0]
    prevRatioLow = ratio[0]
    prevZLow = zSmooth[0]
}

if (!isLiveUpdate) {
    // --- Regular Bearish Divergence ---
    // Ratio makes a higher high; z-score makes a lower high → hidden weakness
    if (ratio[0] > prevRatioHigh) {
        if (zSmooth[0] < prevZHigh) {
            bearDiv = true
        }
        prevRatioHigh = ratio[0]
        prevZHigh = zSmooth[0]
    }

    // --- Regular Bullish Divergence ---
    // Ratio makes a lower low; z-score makes a higher low → hidden strength
    if (ratio[0] < prevRatioLow) {
        if (zSmooth[0] > prevZLow) {
            bullDiv = true
        }
        prevRatioLow = ratio[0]
        prevZLow = zSmooth[0]
    }
}

// ---------------------------------------------------------------------------
// 5. STATIC REGIME TRACKING
// ---------------------------------------------------------------------------
// Track consecutive bars in each extreme regime for context-aware alerting.
static lastRegime = 0
static highBars = 0
static lowBars = 0

if (extremeHigh) {
    highBars = highBars + 1
    lowBars = 0
    lastRegime = 1
} else if (extremeLow) {
    lowBars = lowBars + 1
    highBars = 0
    lastRegime = -1
} else {
    highBars = 0
    lowBars = 0
    lastRegime = 0
}

// ---------------------------------------------------------------------------
// 6. ALERT CONDITIONS
// ---------------------------------------------------------------------------
// Z-score crossovers of dynamic thresholds
var crossUp   = zSmooth > dynLower && zSmooth[1] <= dynLower[1]
var crossDown = zSmooth < dynUpper && zSmooth[1] >= dynUpper[1]

// Extreme penetrations (first bar into extreme zone)
var highPenetrate = zSmooth > dynUpper && zSmooth[1] <= dynUpper[1]
var lowPenetrate  = zSmooth < dynLower && zSmooth[1] >= dynLower[1]

// Mean reversion (exit from extreme zone back toward neutral)
var highRevert = zSmooth < dynUpper && zSmooth[1] >= dynUpper[1]
var lowRevert  = zSmooth > dynLower && zSmooth[1] <= dynLower[1]

// ---------------------------------------------------------------------------
// 7. VISUALIZATION
// ---------------------------------------------------------------------------

// 7.1 Zero line
hline(value=0, color="#ffffff20", width=1)

// 7.2 Z-score reference lines
if (showZ) {
    hline(value=dynUpper, color=transparency(upColor, 60), width=1)
    hline(value=dynLower, color=transparency(dnColor, 60), width=1)
}

// 7.3 Ratio line (regime-colored)
if (showRatio) {
    plotLine(
        value=ratio,
        width=2,
        colors=[regimeColor],
        label=["Gold/Silver Ratio"],
        desc=["Gold price divided by silver price (regime-colored)"]
    )
}

// 7.4 Mean MA
if (showMa) {
    plotLine(
        value=ratioMa,
        width=2,
        colors=[maColor],
        label=["Mean Ratio MA"],
        desc=[str(maLen) + "-period SMA of ratio (long-term mean anchor)"]
    )
}

// 7.5 Ratio fill (ratio vs MA)
if (showRatio && showMa) {
    var ratioBull = ratio > ratioMa
    plotLine(
        value=[ratio, ratioMa],
        width=1,
        colors=[transparency(dnColor, 25), transparency(upColor, 25)],
        colorIndex=ratioBull ? 0 : 1,
        fill=true,
        label=["Ratio", "MA"],
        desc=["Fill between ratio and mean MA"]
    )
}

// 7.6 Z-score line (smoothed, regime-colored)
if (showZ) {
    plotLine(
        value=zSmooth,
        width=2,
        colors=[regimeColor],
        label=["Z-Score (Smoothed)"],
        desc=["Z-score of ratio vs " + zLen + "-period historical distribution (EMA-smoothed)"]
    )
}

// 7.7 Z-score fill (z-score vs zero line, color-coded by regime)
if (showZ && showZFill) {
    var zColorIdx = bullishRegime ? 0 : (bearishRegime ? 1 : 2)
    plotLine(
        value=[zSmooth, 0],
        width=1,
        colors=[transparency(dnColor, 30), transparency(upColor, 30), transparency(neutralColor, 20)],
        colorIndex=zColorIdx,
        fill=true,
        label=["Z-Score", "Zero"],
        desc=["Fill between smoothed z-score and zero line (color-coded by regime)"]
    )
}

// 7.8 Z-score histogram (bar chart)
if (showZ) {
    var zHistBull = zSmooth >= 0
    plotBar(
        value=zSmooth,
        colors=[transparency(dnColor, 50), transparency(upColor, 50)],
        colorIndex=zHistBull ? 0 : 1,
        width=1,
        label=["Z-Score Histogram"],
        desc=["Smoothed z-score as histogram"]
    )
}

// 7.9 Extreme divergence shapes
if (showShapes) {
    if (highPenetrate) {
        plotShape(
            value=dynUpper,
            shape="triangledown",
            colorIndex=bearDivColor,
            width=3,
            label=["Extreme High"],
            desc=["Ratio entered extreme overvalued zone (z > " + dynUpper + ") — gold expensive vs silver"]
        )
    }
    if (lowPenetrate) {
        plotShape(
            value=dynLower,
            shape="triangleup",
            colorIndex=bullDivColor,
            width=3,
            label=["Extreme Low"],
            desc=["Ratio entered extreme undervalued zone (z < " + dynLower + ") — gold cheap vs silver"]
        )
    }
}

// 7.10 Divergence shapes
if (showShapes) {
    if (bullDiv) {
        plotShape(
            value=zSmooth,
            shape="arrowup",
            colorIndex=bullDivColor,
            width=2,
            label=["Bull Div"],
            desc=["Bullish divergence: ratio lower low, z-score higher low — mean-reversion buy signal"]
        )
    }
    if (bearDiv) {
        plotShape(
            value=zSmooth,
            shape="arrowdown",
            colorIndex=bearDivColor,
            width=2,
            label=["Bear Div"],
            desc=["Bearish divergence: ratio higher high, z-score lower high — mean-reversion sell signal"]
        )
    }
}

// 7.11 Alert shapes (crossovers, reversion)
if (showAlerts) {
    if (crossUp) {
        plotShape(
            value=dynLower,
            shape="circle",
            colorIndex=bullDivColor,
            width=2,
            label=["Cross Up"],
            desc=["Z-score crossed above lower threshold — potential long gold / short silver"]
        )
    }
    if (crossDown) {
        plotShape(
            value=dynUpper,
            shape="circle",
            colorIndex=bearDivColor,
            width=2,
            label=["Cross Down"],
            desc=["Z-score crossed below upper threshold — potential short gold / long silver"]
        )
    }
    if (highRevert) {
        plotShape(
            value=dynUpper,
            shape="xcross",
            colorIndex=dnColor,
            width=2,
            label=["High Revert"],
            desc=["Z-score exited extreme high zone — mean reversion toward neutral underway"]
        )
    }
    if (lowRevert) {
        plotShape(
            value=dynLower,
            shape="xcross",
            colorIndex=upColor,
            width=2,
            label=["Low Revert"],
            desc=["Z-score exited extreme low zone — mean reversion toward neutral underway"]
        )
    }
}

// ---------------------------------------------------------------------------
// 8. REGIME TABLE (last bar only)
// ---------------------------------------------------------------------------
if (isLastBar) {
    var regimeText = bullishRegime ? "BULLISH (GOLD CHEAP)" : (bearishRegime ? "BEARISH (GOLD EXPENSIVE)" : "NEUTRAL")
    var regimeTextColor = bullishRegime ? dnColor : (bearishRegime ? upColor : neutralColor)
    var upperText = useDynamic ? "Dynamic Upper: " + dynUpper : "Static Upper: " + zUpper
    var lowerText = useDynamic ? "Dynamic Lower: " + dynLower : "Static Lower: " + zLower

    plotTable(
        data=[
            ["Silver Gold Ratio — Perfected", regimeText],
            ["Ratio", ratio[0]],
            ["Mean MA", ratioMa[0]],
            ["Z-Score", zSmooth[0]],
            ["Deviation %", ratioDev[0]],
            [upperText, lowerText],
            ["High Bars", highBars],
            ["Low Bars", lowBars]
        ],
        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
    )
}