Indicator · Pine Script v5 · Own pane

CASA v2 Cross-Asset Risk Gauge

by AssetWhisper

An indicator in a separate pane that builds a 0 to 100 gauge of market risk from several other markets rather than the chart symbol: an equity ETF, the VIX, the dollar index, the 10-year yield and a high-yield credit ETF.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code123
Settings21inputs
LicenceMPL-2.0
Last update7 weeks ago10 Sep 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

123 lines of Pine Script v5 from indicators/CASA_Cross_Asset_Risk_Gauge.pine, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.

CASA_Cross_Asset_Risk_Gauge.pine
//@version=5
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © AssetWhisper — https://assetwhisper.com/indicators/
// ============================================================================
//  CASA v2 — Cross-Asset Risk Gauge
//  Idea: el riesgo sistémico se lee mejor en el conjunto de activos macro que en
//  el gráfico de un solo ticker. Se combinan z-scores de: retorno de renta
//  variable, cambio del VIX, dólar, tipos a 10 años y crédito high-yield en un
//  score único, que se convierte en un gauge 0-100 (percentil histórico). Sirve
//  como filtro de régimen para cualquier otra estrategia: en RISK OFF se apagan
//  las señales agresivas, en RISK ON se habilitan rupturas.
//  Mejoras v2: símbolos válidos, crédito HY, gauge por percentil, histéresis,
//  detector de "shock" cross-asset, timeframe macro configurable y salida exportable.
// ============================================================================
indicator("CASA v2 — Cross-Asset Risk Gauge", shorttitle="CASA v2", overlay=false)

grpA = "Activos"
eqSym   = input.symbol("AMEX:SPY", "Equity index", group=grpA)
vixSym  = input.symbol("TVC:VIX", "Volatility index", group=grpA)
dxySym  = input.symbol("TVC:DXY", "Dollar index", group=grpA)
rateSym = input.symbol("TVC:US10Y", "10Y yield", group=grpA)
crSym   = input.symbol("AMEX:HYG", "High-yield credit ETF", group=grpA)
useChartTF = input.bool(true, "Use chart timeframe for macro data", group=grpA)
macroTF    = input.timeframe("D", "Macro timeframe (if not chart TF)", group=grpA)
grpW = "Pesos (signo = dirección que AUMENTA el riesgo)"
wEq   = input.float(-1.0, "Equity return", step=0.1, group=grpW)
wVix  = input.float(1.5, "VIX change", step=0.1, group=grpW)
wDxy  = input.float(0.5, "Dollar change", step=0.1, group=grpW)
wRate = input.float(0.5, "Yield change", step=0.1, group=grpW)
wCr   = input.float(-1.0, "HY credit return", step=0.1, group=grpW)
grpP = "Parámetros"
retLen     = input.int(5, "Return window (bars)", minval=1, maxval=20, group=grpP)
zLen       = input.int(60, "Z-score lookback", minval=20, maxval=250, group=grpP)
rankLen    = input.int(252, "Gauge percentile lookback", minval=50, maxval=1000, group=grpP)
smoothLen  = input.int(3, "Smoothing", minval=1, maxval=10, group=grpP)
riskOffLvl = input.int(70, "RISK OFF level (gauge)", minval=50, maxval=95, group=grpP)
riskOnLvl  = input.int(30, "RISK ON level (gauge)", minval=5, maxval=50, group=grpP)
hystLvl    = input.int(10, "Hysteresis (gauge points)", minval=0, maxval=30, group=grpP)
shockTh    = input.float(0.75, "Shock threshold (score jump in 1 bar)", minval=0.2, maxval=3.0, step=0.05, group=grpP)
showComp   = input.bool(true, "Show components", group=grpP)

// === DATOS ===
// Si el TF macro es inferior al del gráfico se usa el del gráfico (request.security
// no debe pedir un TF inferior). Nota: con TF macro superior al del gráfico el valor
// intradía se actualiza en tiempo real (comportamiento estándar de request.security).
tfUse = useChartTF ? timeframe.period : (timeframe.in_seconds(macroTF) < timeframe.in_seconds(timeframe.period) ? timeframe.period : macroTF)

zOf(src, len) =>
    sd = ta.stdev(src, len)
    sd > 0 ? (src - ta.sma(src, len)) / sd : 0.0

// Cada componente se calcula en el TF macro dentro de request.security
zEq   = nz(request.security(eqSym,   tfUse, zOf(ta.roc(close, retLen), zLen), ignore_invalid_symbol=true))
zVix  = nz(request.security(vixSym,  tfUse, zOf(ta.roc(close, retLen), zLen), ignore_invalid_symbol=true))
zDxy  = nz(request.security(dxySym,  tfUse, zOf(ta.roc(close, retLen), zLen), ignore_invalid_symbol=true))
zRate = nz(request.security(rateSym, tfUse, zOf(ta.change(close, retLen), zLen), ignore_invalid_symbol=true))
zCr   = nz(request.security(crSym,   tfUse, zOf(ta.roc(close, retLen), zLen), ignore_invalid_symbol=true))

// === SCORE COMPUESTO Y GAUGE ===
wSum     = math.abs(wEq) + math.abs(wVix) + math.abs(wDxy) + math.abs(wRate) + math.abs(wCr)
rawScore = wSum > 0 ? (wEq * zEq + wVix * zVix + wDxy * zDxy + wRate * zRate + wCr * zCr) / wSum : 0.0
score    = ta.ema(rawScore, smoothLen)
gauge    = ta.percentrank(score, rankLen)          // 0-100: estrés actual vs. historia reciente

// Régimen con histéresis: 1 = RISK ON, -1 = RISK OFF, 0 = NEUTRAL
var int regime = 0
if regime != -1 and gauge >= riskOffLvl
    regime := -1
else if regime == -1 and gauge < riskOffLvl - hystLvl
    regime := 0
if regime != 1 and gauge <= riskOnLvl
    regime := 1
else if regime == 1 and gauge > riskOnLvl + hystLvl
    regime := 0

// Shock cross-asset: salto brusco del score en una barra
shock = rawScore - rawScore[1] >= shockTh and rawScore > 0

regimeLabel = regime == -1 ? "RISK OFF" : regime == 1 ? "RISK ON" : "NEUTRAL"
regimeColor = regime == -1 ? color.red : regime == 1 ? color.green : color.orange
modeHint    = regime == -1 ? "Defensive: no breakouts" : regime == 1 ? "Breakouts enabled" : "Reduced size"

// === VISUAL ===
hline(riskOffLvl, "RISK OFF", color=color.new(color.red, 50), linestyle=hline.style_dashed)
hline(50, "Mid", color=color.new(color.gray, 70), linestyle=hline.style_dotted)
hline(riskOnLvl, "RISK ON", color=color.new(color.green, 50), linestyle=hline.style_dashed)
plot(gauge, "Risk gauge (0-100)", color=regimeColor, linewidth=3)
plot(showComp and wSum > 0 ? 50 + wEq * zEq / wSum * 25 : na, "Equity contrib", color=color.new(color.blue, 60), linewidth=1)
plot(showComp and wSum > 0 ? 50 + wVix * zVix / wSum * 25 : na, "VIX contrib", color=color.new(color.red, 60), linewidth=1)
plot(showComp and wSum > 0 ? 50 + wDxy * zDxy / wSum * 25 : na, "Dollar contrib", color=color.new(color.teal, 60), linewidth=1)
plot(showComp and wSum > 0 ? 50 + wRate * zRate / wSum * 25 : na, "Yield contrib", color=color.new(color.purple, 60), linewidth=1)
plot(showComp and wSum > 0 ? 50 + wCr * zCr / wSum * 25 : na, "Credit contrib", color=color.new(color.orange, 60), linewidth=1)
bgcolor(color.new(regimeColor, 92), title="Regime")
plotshape(shock, "Cross-asset shock", style=shape.xcross, location=location.top, color=color.red, size=size.small, text="SHOCK")

// Series exportables (usar como input.source en otros scripts)
plot(regime, "CASA regime (export: 1 on / -1 off)", display=display.none)

// === TABLA ===
var table t = table.new(position.top_right, 2, 9, bgcolor=color.new(color.black, 60))
cellZ(row, name, z, w) =>
    contrib = w * z
    table.cell(t, 0, row, name, text_color=color.white, text_size=size.small)
    table.cell(t, 1, row, (z >= 0 ? "+" : "") + str.tostring(z, "#.##") + " z", text_color=contrib > 0.3 ? color.red : contrib < -0.3 ? color.lime : color.gray, text_size=size.small)
table.cell(t, 0, 0, "REGIME", text_color=color.white, text_size=size.small)
table.cell(t, 1, 0, regimeLabel, bgcolor=color.new(regimeColor, 30), text_color=color.white, text_size=size.small)
table.cell(t, 0, 1, "Gauge", text_color=color.white, text_size=size.small)
table.cell(t, 1, 1, str.tostring(gauge, "#") + " / 100", text_color=regimeColor, text_size=size.small)
table.cell(t, 0, 2, "Score", text_color=color.white, text_size=size.small)
table.cell(t, 1, 2, str.tostring(score, "#.##"), text_color=color.white, text_size=size.small)
cellZ(3, "Equity", zEq, wEq)
cellZ(4, "VIX", zVix, wVix)
cellZ(5, "Dollar", zDxy, wDxy)
cellZ(6, "10Y yield", zRate, wRate)
cellZ(7, "HY credit", zCr, wCr)
table.cell(t, 0, 8, "Mode", text_color=color.white, text_size=size.small)
table.cell(t, 1, 8, modeHint, text_color=regimeColor, text_size=size.small)

// === ALERTAS ===
alertcondition(regime == -1 and regime[1] != -1, "CASA RISK OFF", "CASA v2: entering RISK OFF regime")
alertcondition(regime == 1 and regime[1] != 1, "CASA RISK ON", "CASA v2: entering RISK ON regime")
alertcondition(regime == 0 and regime[1] != 0, "CASA NEUTRAL", "CASA v2: regime back to NEUTRAL")
alertcondition(shock, "CASA Shock", "CASA v2: cross-asset shock detected")

Overview

Their returns or changes are turned into z-scores, weighted, smoothed and ranked against history. Risk-off and risk-on levels use hysteresis, and a shock flag marks sudden jumps. Symbols, weights and timeframe are inputs.

Details

Published by

AssetWhisper on GitHub

Type

Indicator, Pine Script v5

Draws

Separate pane below the chart

Category

Volatility & bands

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Equity indexsymbolAMEX:SPYeqSym
Volatility indexsymbolTVC:VIXvixSym
Dollar indexsymbolTVC:DXYdxySym
10Y yieldsymbolTVC:US10YrateSym
High-yield credit ETFsymbolAMEX:HYGcrSym
Use chart timeframe for macro databooltrueuseChartTF
Macro timeframe (if not chart TF)timeframeDmacroTF
Equity returnfloat-1.0wEq
VIX changefloat1.5wVix
Dollar changefloat0.5wDxy
Yield changefloat0.5wRate
HY credit returnfloat-1.0wCr
Show all 21 settings
SettingTypeDefaultVariable
Return window (bars)int5retLen
Z-score lookbackint60zLen
Gauge percentile lookbackint252rankLen
Smoothingint3smoothLen
RISK OFF level (gauge)int70riskOffLvl
RISK ON level (gauge)int30riskOnLvl
Hysteresis (gauge points)int10hystLvl
Shock threshold (score jump in 1 bar)float0.75shockTh
Show componentsbooltrueshowComp
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

This indicator calculates the distribution of close-to-close percentage changes using rate of change on closing prices. It bins percentage changes into intervals of 0.25 percent increments from negative to positive values and plots a normalized cumulative hist

Indicator v4 Volatility & bands
Updated 11 days ago · GPL-3.0 GitHub repository of Close-to-Close % Change Distribution

This indicator plots a Supertrend-based trend-following setup in a separate pane and skips conditions it treats as a sideways market. A volatility range is built from an ATR value, with RMA, SMA, EMA, or WMA smoothing, or from a fixed point distance. Optional

Indicator v5 TrendVolatility & bands
Updated 1 year ago · MPL-2.0 GitHub repository of Trend Following Setup - Sideways Market Skipper
330 stars

This indicator plots candle range and open-to-close movement as percentages in a separate pane. Range is the high-low difference divided by the low, and change is the close-open difference divided by the open. Both series draw as columns. Teal columns show ran

Indicator v5 Volatility & bands
Updated 2 months ago · None stated GitHub repository of Percent & Volatility [Alorse]

Mojito v3 Strategy

by namuan
318 stars

The Mojito v3 Strategy indicator evaluates volatility term structure by calculating the ratio between front-month and second-month VIX futures contracts. It smooths this ratio using a configurable median filter and compares the result against user-defined uppe

Indicator v5 Volatility & bands
Updated 2 months ago · MIT GitHub repository of Mojito v3 Strategy

Function - Logistic Equation

by ricardosantos79
261 stars

Calculates dynamic modeling values by applying a mathematical logistic differential equation to price change over a specified lookback length. It measures price momentum relative to the recent high-low price range. The script plots positive and negative logist

Indicator v5 Oscillators & momentumVolatility & bands
Updated 4 years ago · None stated GitHub repository of Function - Logistic Equation

MACD-V

by harryguiacorn
219 stars

MACD-V is a volatility-normalized momentum indicator based on research by Alex Spiroglou. It calculates the standard MACD histogram and normalizes it by dividing by the Average True Range (ATR). Plotted in a separate pane as a colored histogram, it includes us

Indicator v5 Oscillators & momentumVolatility & bands
Updated 1 year ago · None stated GitHub repository of MACD-V

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers