Indicator · Pine Script v6 · Own pane

Deleveraging Detection Score

by realanthonyc

This indicator measures market deleveraging and liquidation stress on a 0 to 100 scale, plotted in a separate pane.

View on GitHub

GitHub stars2on the repository
Pine versionv6current
Lines of code106
Settings5inputs
LicenceMPL-2.0
Last update8 months ago3 Mar 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

106 lines of Pine Script v6 from dds.pine, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.

dds.pine
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © realanthonyc https://www.tradingview.com/u/realanthonyc

//@version=6
// ----------------------------------------------------------------------
//  Deleveraging Detection Score (DDS)
//  On GitHub: https://github.com/realanthonyc/Deleveraging-Detection-Score
//  v1.1.2
// ----------------------------------------------------------------------
indicator("Deleveraging Detection Score", shorttitle="DDS", overlay=false, precision=2)

// ==========================================
// 1. LOGIC INPUTS & GUIDANCE
// ==========================================
i_proxy_sym = input.symbol("NASDAQ:QQQ", "Liquidation Proxy", tooltip="Choose a liquidity proxy to monitor its correlation. Examples:\n- Metals: NQ1! / QQQ / SPY\n- Crypto: DXY (preferred) / QQQ\n- NQ1! / QQQ: DXY (preferred) / US10Y")
sigmaThr    = input.float(3.00, "Crash Sigma Threshold", step=0.25, tooltip="Extreme drop threshold.\n- Gold: 3.0\n- Silver: 3.5 - 4.0\n- Copper: 3.5\n- Crypto: 4.0+")
atrZThr     = input.float(2.00, "ATR Z-Score Threshold", step=0.25, tooltip="Volatility spikes.\n2 = 2 standard deviations above mean")
lb          = input.int(10, "Stress Lookback (Bars)", minval=3, tooltip="Memory of the market (for Stress Cascade Count).")
corrLen     = input.int(20, "Sync Corr Length", minval=10, maxval=60, tooltip="Higher = more stable sync signal. Metals often look cleaner at 20-40.")

// ==========================================
// 2. CORE PHYSICS (Liquidation Engine)
// ==========================================
f_sec(sym, expr) => request.security(sym, timeframe.period, expr, gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_off)

// A. Price Velocity (Standardized Log Returns)
logRet      = math.log(close / close[1])
retSD       = ta.stdev(logRet, 60)
// Explicit zero-dispersion check
retSig      = (retSD == 0 or na(retSD)) ? 0.0 : logRet / retSD

// B. Volatility Intensity (ATR Z-Score)
atr_v       = ta.atr(14)
atrSMA      = ta.sma(atr_v, 100)
atrSD       = ta.stdev(atr_v, 100)
// Ensure Z-score calculation is stable
atrZ        = (atrSD == 0 or na(atrSD)) ? 0.0 : (atr_v - atrSMA) / atrSD

// C. Global Synchronicity (Correlation with Liquidity Proxy)
proxy_logRet = f_sec(i_proxy_sym, math.log(close / close[1]))
market_corr  = nz(ta.correlation(logRet, proxy_logRet, corrLen), 0.0)

// D. Stress Identifiers
is_crash    = retSig < -sigmaThr
is_vol      = atrZ > atrZThr and logRet < 0
stressBar   = is_crash or (retSig < -2.0 and atrZ > 1.0)

// E. Cascade Logic (Dynamic Thresholding)
stressCount = 0
for i = 0 to lb - 1
    if stressBar[i] == true
        stressCount += 1

// Dynamic threshold logic
casMin      = math.max(2, math.floor(lb / 4))
is_cascade  = stressCount >= casMin

// ==========================================
// 3. SCORING & COLOR SYSTEM
// ==========================================
baseScore   = is_crash ? 75 : is_vol ? 45 : is_cascade ? 25 : 0

// Support both positive and inverse correlation
sync_positive = (market_corr > 0.5) and (logRet < 0) and (proxy_logRet < 0)
sync_inverse  = (market_corr < -0.5) and (logRet < 0) and (proxy_logRet > 0)
syncBonus     = sync_positive or sync_inverse

score       = math.min(100, baseScore + (syncBonus ? 10 : 0))

c_stable    = color.new(color.green, 0)
c_recovery  = color.new(color.orange, 0)
c_stress    = color.new(color.red, 0)
c_liq       = color.new(color.purple, 0)

regime_col  = score >= 70 ? c_liq : score >= 40 ? c_stress : score >= 20 ? c_recovery : c_stable

// ==========================================
// 4. VISUALS
// ==========================================
plot(score, "Risk Level %", color=regime_col, linewidth=2)
bgcolor(score >= 20 ? color.new(regime_col, 92) : na)

// ==========================================
// 5. TACTICAL DASHBOARD
// ==========================================
var table panel = table.new(position.top_right, 2, 5, border_width=1, border_color=color.white)

f_row(r, l, v, bg) =>
    table.cell(panel, 0, r, l, bgcolor=color.new(color.black, 0), text_color=color.white, text_size=size.small)
    table.cell(panel, 1, r, v, bgcolor=bg, text_color=color.white, text_size=size.small)

if barstate.islast
    state_txt = score >= 70 ? "FORCED LIQUIDATION" : score >= 40 ? "HIGH STRESS" : score >= 20 ? "RECOVERY" : "NORMAL"
    strat_txt = score >= 40 ? "DEFEND / EXIT" : score >= 20 ? "WATCH" : "ATTACK"

    f_row(0, "Market Status", state_txt, regime_col)
    f_row(1, "Risk Level", str.tostring(score) + "%", regime_col)

    // Palette-consistent sync coloring (support strong negative correlation)
    corr_col = math.abs(market_corr) > 0.5 ? c_stress : math.abs(market_corr) > 0.3 ? c_recovery : c_stable
    f_row(2, "Liquidity Proxy Sync", str.tostring(market_corr, "#.##"), corr_col)

    cas_col = stressCount >= casMin ? (score >= 40 ? c_stress : c_recovery) : c_stable
    f_row(3, "Stress Cascade Count", str.tostring(stressCount) + " / " + str.tostring(casMin), cas_col)

    f_row(4, "Strategic Action", strat_txt, regime_col)

Overview

Deleveraging Detection Score evaluates extreme downside price velocity via standardized log returns, volatility expansion using an ATR Z-score, a rolling stress bar cascade count, and market synchronicity with a user-selected liquidity proxy. Scores categorize conditions from normal to forced liquidation. Configurable parameters include the proxy symbol, crash sigma threshold, ATR Z-score threshold, stress lookback, and correlation length.

Details

Published by

realanthonyc on GitHub

Draws

Separate pane below the chart

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.

Topics

indicatorpinescripttradingview

Settings

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

SettingTypeDefaultVariable
Liquidation ProxysymbolNASDAQ:QQQi_proxy_sym
Crash Sigma Thresholdfloat3.00sigmaThr
ATR Z-Score Thresholdfloat2.00atrZThr
Stress Lookback (Bars)int10lb
Sync Corr Lengthint20corrLen
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 scans a pasted list of symbols and shows matching long and short setups in a table in a separate pane. It uses a Supertrend crossover, then applies an ATR or fixed-point volatility range so quiet, sideways conditions can be skipped. Optional fil

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

Test 009 Stat Mining

by ricardosantos79
261 stars

This statistical analysis tool mines historical relationships between RSI values and candle volatility. It calculates a 14-period RSI from the previous bar and normalizes absolute price change using a 14-period Average True Range (ATR). Based on the normalized

Indicator v4 Oscillators & momentumVolatility & bands
Updated 4 years ago · None stated GitHub repository of Test 009 Stat Mining

Market Speedometer

by TradersPost
228 stars

Market Speedometer plots a 0-100 market speed reading in a separate pane. It measures movement by bar-to-bar change, true range, or a short average of recent bars, then ranks that movement against ATR and a percentile lookback. An EMA smooths the reading, and

Indicator v6 Volatility & bandsOscillators & momentum
Updated 3 months ago · None stated GitHub repository of Market Speedometer
46 stars

This indicator summarizes higher-timeframe candle range statistics by time of day and shows them in a table in a separate pane. It groups candles into slots for 5-minute, 15-minute, 1-hour, 4-hour, 8-hour, or 12-hour periods over a chosen lookback in days, and

Indicator v5 Screeners & dashboardsSessions & time Repaints
Updated 8 weeks ago · None stated GitHub repository of HTF Candle Stats by Time of Day
41 stars

This indicator transforms standard RSI calculations into logit space, estimating rolling distributions to derive empirical z-scores mapped back to the 0–100 RSI scale. Plotted in a separate pane, it features multi-horizon central lines—fast and structural cent

Indicator v6 Oscillators & momentumVolatility & bands
Updated 4 days ago · None stated GitHub repository of Calibrated RSI Position Zones

More Volatility & bands scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers