Recession Warning Model [BackQuant]Recession Warning Model
Overview
The Recession Warning Model (RWM) is a Pine Script® indicator designed to estimate the probability of an economic recession by integrating multiple macroeconomic, market sentiment, and labor market indicators. It combines over a dozen data series into a transparent, adaptive, and actionable tool for traders, portfolio managers, and researchers. The model provides customizable complexity levels, display modes, and data processing options to accommodate various analytical requirements while ensuring robustness through dynamic weighting and regime-aware adjustments.
Purpose
The RWM fulfills the need for a concise yet comprehensive tool to monitor recession risk. Unlike approaches relying on a single metric, such as yield-curve inversion, or extensive economic reports, it consolidates multiple data sources into a single probability output. The model identifies active indicators, their confidence levels, and the current economic regime, enabling users to anticipate downturns and adjust strategies accordingly.
Core Features
- Indicator Families : Incorporates 13 indicators across five categories: Yield, Labor, Sentiment, Production, and Financial Stress.
- Dynamic Weighting : Adjusts indicator weights based on recent predictive accuracy, constrained within user-defined boundaries.
- Leading and Coincident Split : Separates early-warning (leading) and confirmatory (coincident) signals, with adjustable weighting (default 60/40 mix).
- Economic Regime Sensitivity : Modulates output sensitivity based on market conditions (Expansion, Late-Cycle, Stress, Crisis), using a composite of VIX, yield-curve, financial conditions, and credit spreads.
- Display Options : Supports four modes—Probability (0-100%), Binary (four risk bins), Lead/Coincident, and Ensemble (blended probability).
- Confidence Intervals : Reflects model stability, widening during high volatility or conflicting signals.
- Alerts : Configurable thresholds (Watch, Caution, Warning, Alert) with persistence filters to minimize false signals.
- Data Export : Enables CSV output for probabilities, signals, and regimes, facilitating external analysis in Python or R.
Model Complexity Levels
Users can select from four tiers to balance simplicity and depth:
1. Essential : Focuses on three core indicators—yield-curve spread, jobless claims, and unemployment change—for minimalistic monitoring.
2. Standard : Expands to nine indicators, adding consumer confidence, PMI, VIX, S&P 500 trend, money supply vs. GDP, and the Sahm Rule.
3. Professional : Includes all 13 indicators, incorporating financial conditions, credit spreads, JOLTS vacancies, and wage growth.
4. Research : Unlocks all indicators plus experimental settings for advanced users.
Key Indicators
Below is a summary of the 13 indicators, their data sources, and economic significance:
- Yield-Curve Spread : Difference between 10-year and 3-month Treasury yields. Negative spreads signal banking sector stress.
- Jobless Claims : Four-week moving average of unemployment claims. Sustained increases indicate rising layoffs.
- Unemployment Change : Three-month change in unemployment rate. Sharp rises often precede recessions.
- Sahm Rule : Triggers when unemployment rises 0.5% above its 12-month low, a reliable recession indicator.
- Consumer Confidence : University of Michigan survey. Declines reflect household pessimism, impacting spending.
- PMI : Purchasing Managers’ Index. Values below 50 indicate manufacturing contraction.
- VIX : CBOE Volatility Index. Elevated levels suggest market anticipation of economic distress.
- S&P 500 Growth : Weekly moving average trend. Declines reduce wealth effects, curbing consumption.
- M2 + GDP Trend : Monitors money supply and real GDP. Simultaneous declines signal credit contraction.
- NFCI : Chicago Fed’s National Financial Conditions Index. Positive values indicate tighter conditions.
- Credit Spreads : Proxy for corporate bond spreads using 10-year vs. 2-year Treasury yields. Widening spreads reflect stress.
- JOLTS Vacancies : Job openings data. Significant drops precede hiring slowdowns.
- Wage Growth : Year-over-year change in average hourly earnings. Late-cycle spikes often signal economic overheating.
Data Processing
- Rate of Change (ROC) : Optionally applied to capture momentum in data series (default: 21-bar period).
- Z-Score Normalization : Standardizes indicators to a common scale (default: 252-bar lookback).
- Smoothing : Applies a short moving average to final signals (default: 5-bar period) to reduce noise.
- Binary Signals : Generated for each indicator (e.g., yield-curve inverted or PMI below 50) based on thresholds or Z-score deviations.
Probability Calculation
1. Each indicator’s binary signal is weighted according to user settings or dynamic performance.
2. Weights are normalized to sum to 100% across active indicators.
3. Leading and coincident signals are aggregated separately (if split mode is enabled) and combined using the specified mix.
4. The probability is adjusted by a regime multiplier, amplifying risk during Stress or Crisis regimes.
5. Optional smoothing ensures stable outputs.
Display and Visualization
- Probability Mode : Plots a continuous 0-100% recession probability with color gradients and confidence bands.
- Binary Mode : Categorizes risk into four levels (Minimal, Watch, Caution, Alert) for simplified dashboards.
- Lead/Coincident Mode : Displays leading and coincident probabilities separately to track signal divergence.
- Ensemble Mode : Averages traditional and split probabilities for a balanced view.
- Regime Background : Color-coded overlays (green for Expansion, orange for Late-Cycle, amber for Stress, red for Crisis).
- Analytics Table : Optional dashboard showing probability, confidence, regime, and top indicator statuses.
Practical Applications
- Asset Allocation : Adjust equity or bond exposures based on sustained probability increases.
- Risk Management : Hedge portfolios with VIX futures or options during regime shifts to Stress or Crisis.
- Sector Rotation : Shift toward defensive sectors when coincident signals rise above 50%.
- Trading Filters : Disable short-term strategies during high-risk regimes.
- Event Timing : Scale positions ahead of high-impact data releases when probability and VIX are elevated.
Configuration Guidelines
- Enable ROC and Z-score for consistent indicator comparison unless raw data is preferred.
- Use dynamic weighting with at least one economic cycle of data for optimal performance.
- Monitor stress composite scores above 80 alongside probabilities above 70 for critical risk signals.
- Adjust adaptation speed (default: 0.1) to 0.2 during Crisis regimes for faster indicator prioritization.
- Combine RWM with complementary tools (e.g., liquidity metrics) for intraday or short-term trading.
Limitations
- Macro indicators lag intraday market moves, making RWM better suited for strategic rather than tactical trading.
- Historical data availability may constrain dynamic weighting on shorter timeframes.
- Model accuracy depends on the quality and timeliness of economic data feeds.
Final Note
The Recession Warning Model provides a disciplined framework for monitoring economic downturn risks. By integrating diverse indicators with transparent weighting and regime-aware adjustments, it empowers users to make informed decisions in portfolio management, risk hedging, or macroeconomic research. Regular review of model outputs alongside market-specific tools ensures its effective application across varying market conditions.
Fundamental Analysis
Global Liquidity Sentiment (US / Europe / Asia) # Global Liquidity Sentiment Dashboard (US / Europe / Asia) with Alerts
## Summary
Aggregates broad liquidity (M2 or proxies) from the **U.S., Europe, and Asia** into a normalized global index, compares it to Bitcoin price, and derives a heuristic **market sentiment** (Optimistic / Neutral / Pessimistic). Highlights imbalances via divergence detection and surfaces regime shifts with visual cues and alerts.
## Key Features
- Weighted composite **Global Liquidity Index** (US M2 + Europe + Asia).
- **BTC / Liquidity ratio** showing how stretched Bitcoin is relative to available liquidity.
- **Sentiment signal** combining liquidity trend and price-to-liquidity momentum.
- **Divergence detection** when BTC moves disproportionately vs liquidity.
- Colored summary table with metrics, regional weight breakdown, and trend emphasis.
- Alert conditions for sentiment flips and strong divergence events.
## Visual Output
- **Top-right table** displaying:
- Global Liquidity Index (normalized)
- BTC / Liquidity ratio
- Ratio momentum
- Divergence (%) from recent baseline
- Sentiment (Optimistic / Neutral / Pessimistic) with translucent color background
- Regional weights (US / EU / Asia)
- **Line plots**:
- Blue: Global Liquidity Index
- Orange: BTC / Liquidity
- Gray: Smoothed ratio baseline for divergence context
## Inputs
- **US M2 Money Stock:** Real US broad money (via `FRED:WM2NS`).
- **Europe / Asia:** Optionally use live symbol proxies (if available) or manual values.
- **FX rates:** Convert non-USD regional series into USD for aggregation.
- **Weights:** Adjust the relative contribution of US, Europe, and Asia to the composite index.
- **Liquidity SMA length:** Short-term smoothing for trend detection on liquidity.
- **Price/Liquidity momentum length:** Lookback for momentum of BTC-to-liquidity relationship.
- **Divergence SMA & threshold:** Baseline and sensitivity for flagging strong deviations.
## Interpretation
- **Optimistic:** Liquidity expanding and BTC gaining relative strength—risk-friendly environment.
- **Pessimistic:** Liquidity contracting while BTC weakens vs liquidity—potential fragility or correction risk.
- **Neutral:** Mixed or inconclusive signals.
- **High BTC / Liquidity ratio:** Bitcoin may be overextended relative to global liquidity support.
- **Strong Divergence:** Significant dislocation between BTC price and liquidity trend—possible precursor to mean reversion or continuation depending on context.
## Alerts
Built-in alert conditions:
- **Sentiment to Optimistic / Pessimistic / Neutral** — triggers when regime shifts.
- **Strong Divergence** — triggers when BTC/liquidity ratio deviates beyond the configured threshold from its recent smoothed average.
Suggested alert messages (preconfigured):
- “Sentiment changed to Optimistic”
- “Sentiment changed to Pessimistic”
- “Sentiment changed to Neutral”
- “Strong divergence between BTC and global liquidity detected”
## Usage Tips
- Use the sentiment as a macro liquidity backdrop to contextualize BTC moves.
- Monitor divergence to catch overextensions or early signs of trend exhaustion.
- Tweak regional weights to reflect evolving global liquidity influence (e.g., give more weight to Asia as its footprint grows).
- If regional proxies aren’t available, regularly update manual values from official sources (ECB, BOJ, PBOC) to keep the index relevant.
## Limitations
- Europe/Asia liquidity may rely on manual inputs or imperfect proxies (TradingView may not expose official M2 for all regions).
- Heuristic sentiment and divergence are not standalone trade signals—validate with price structure / other confirmations.
- Does not replace high-fidelity on-chain, order book, or institutional flow data.
## Example Scenario
Bitcoin rallies sharply while the Global Liquidity Index flattens. The BTC / Liquidity ratio spikes, divergence crosses threshold, and sentiment shifts toward **Pessimistic**—indicating the move may be running ahead of underlying liquidity support, signaling caution or a possible retracement.
Simple Trading ChecklistCustomisable Simple Trading Checklist
This script overlays a fully customizable trading checklist directly onto your chart, providing an at-a-glance reminder of key trading steps and conditions before entering a position.
It is especially useful for discretionary or rule-based traders who want a consistent on-screen process to follow.
High/Low Premarket & Previous Day This scripts adds lines for previous day and premarket high/low with labels that you can toggle on and off. The lines extend through current premarket and trading session
TrailingPE//@version=6
indicator("TrailingPE", shorttitle="TPE", overlay=true)
// === USER INPUTS ===
pos_x = input.string("Right", "Horizontal Position", options= )
pos_y = input.string("Top", "Vertical Position", options= )
text_color = input.color(color.white, "Text Color")
bg_color = input.color(color.new(color.blue, 80), "Background Color")
text_size = input.string("Normal", "Font Size", options= )
// === POSITION MAPPING ===
get_position_y() =>
switch pos_y
"Top" =>
switch pos_x
"Left" => position.top_left
"Center" => position.top_center
"Right" => position.top_right
"Middle" =>
switch pos_x
"Left" => position.middle_left
"Center" => position.middle_center
"Right" => position.middle_right
"Bottom" =>
switch pos_x
"Left" => position.bottom_left
"Center" => position.bottom_center
"Right" => position.bottom_right
get_text_size() =>
switch text_size
"Tiny" => size.tiny
"Small" => size.small
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
// === PE CALCULATION ===
eps_ttm = request.financial(syminfo.tickerid, "EARNINGS_PER_SHARE_DILUTED", "TTM")
if na(eps_ttm)
eps_ttm := request.financial(syminfo.tickerid, "EARNINGS_PER_SHARE_BASIC", "TTM")
current_price = close
pe_ratio = eps_ttm > 0 ? current_price / eps_ttm : na
is_data_valid = not na(pe_ratio) and eps_ttm > 0
// === COMPACT SINGLE-LINE DISPLAY ===
if barstate.islast
var table pe_table = table.new(get_position_y(), 1, 1,
bgcolor=bg_color,
border_width=1,
border_color=color.gray)
table.clear(pe_table, 0, 0, 0, 0)
if is_data_valid
// Single line: "PE : Value" - removed text_style parameter
pe_rounded = math.ceil(pe_ratio)
pe_text = "PE : " + str.tostring(pe_rounded)
table.cell(pe_table, 0, 0, pe_text,
text_color=text_color,
text_size=get_text_size(),
bgcolor=bg_color)
else
table.cell(pe_table, 0, 0, "PE : N/A",
text_color=color.red,
text_size=get_text_size(),
bgcolor=bg_color)
EPS+Sales+Net Profit+MCap+Sector & Industry📄 Full Description
This script displays a comprehensive financial data panel directly on your TradingView chart, helping long-term investors and swing traders make informed decisions based on fundamental trends. It consolidates key financial metrics and business classification data into a single, visually clear table.
🔍 Key Features:
🧾 Financial Metrics (Auto-Fetched via request.financial):
EPS (Earnings Per Share) – Displayed with trend direction (QoQ or YoY).
Sales / Revenue – In ₹ Crores (for Indian stocks), trend change also included.
Net Profit – Also in ₹ Crores, along with percentage change.
Market Cap – Automatically calculated using outstanding shares × price, shown in ₹ Cr.
Free Float Market Cap – Based on float shares × price, also in ₹ Cr.
🏷️ Sector & Industry Info:
Automatically identifies and displays the Sector and Industry of the stock using syminfo.sector and syminfo.industry.
Displayed inline with metrics, making it easy to know what business the stock belongs to.
📊 Table View:
Compact and responsive table shown on your chart.
Columns: Date | EPS | QoQ | Sales | QoQ | Net Profit | QoQ | Metrics
Metrics column dynamically shows:
Market Cap
Free Float
Sector (Row 4)
Industry (Row 5)
🌗 Appearance:
Supports Dark Mode and Mini Mode toggle.
You can also customize:
Number of data points (last 4+ quarters or years)
Table position and size
🎯 Use Case:
This script is ideal for:
Fundamental-focused traders who use EPS/Sales trends to identify momentum.
Swing traders who combine price action with fundamental tailwinds.
Portfolio builders who want to see sector/industry alignment quickly.
It works best with fundamentally sound stocks where earnings and profitability are a major factor in price movements.
✅ Important Notes:
Script uses request.financial which only works with supported symbols (mostly stocks).
Market Cap and Free Float are calculated in ₹ Crores.
All financial values are rounded and formatted for readability (e.g., 1,234 Cr).
🙏 Credits:
Developed and published by Sameer Thorappa
Built with a clean, minimalist approach for high readability and functionality.
FEDFUNDS Rate Divergence Oscillator [BackQuant]FEDFUNDS Rate Divergence Oscillator
1. Concept and Rationale
The United States Federal Funds Rate is the anchor around which global dollar liquidity and risk-free yield expectations revolve. When the Fed hikes, borrowing costs rise, liquidity tightens and most risk assets encounter head-winds. When it cuts, liquidity expands, speculative appetite often recovers. Bitcoin, a 24-hour permissionless asset sometimes described as “digital gold with venture-capital-like convexity,” is particularly sensitive to macro-liquidity swings.
The FED Divergence Oscillator quantifies the behavioural gap between short-term monetary policy (proxied by the effective Fed Funds Rate) and Bitcoin’s own percentage price change. By converting each series into identical rate-of-change units, subtracting them, then optionally smoothing the result, the script produces a single bounded-yet-dynamic line that tells you, at a glance, whether Bitcoin is outperforming or underperforming the policy backdrop—and by how much.
2. Data Pipeline
• Fed Funds Rate – Pulled directly from the FRED database via the ticker “FRED:FEDFUNDS,” sampled at daily frequency to synchronise with crypto closes.
• Bitcoin Price – By default the script forces a daily timeframe so that both series share time alignment, although you can disable that and plot the oscillator on intraday charts if you prefer.
• User Source Flexibility – The BTC series is not hard-wired; you can select any exchange-specific symbol or even swap BTC for another crypto or risk asset whose interaction with the Fed rate you wish to study.
3. Math under the Hood
(1) Rate of Change (ROC) – Both the Fed rate and BTC close are converted to percent return over a user-chosen lookback (default 30 bars). This means a cut from 5.25 percent to 5.00 percent feeds in as –4.76 percent, while a climb from 25 000 to 30 000 USD in BTC over the same window converts to +20 percent.
(2) Divergence Construction – The script subtracts the Fed ROC from the BTC ROC. Positive values show BTC appreciating faster than policy is tightening (or falling slower than the rate is cutting); negative values show the opposite.
(3) Optional Smoothing – Macro series are noisy. Toggle “Apply Smoothing” to calm the line with your preferred moving-average flavour: SMA, EMA, DEMA, TEMA, RMA, WMA or Hull. The default EMA-25 removes day-to-day whips while keeping turning points alive.
(4) Dynamic Colour Mapping – Rather than using a single hue, the oscillator line employs a gradient where deep greens represent strong bullish divergence and dark reds flag sharp bearish divergence. This heat-map approach lets you gauge intensity without squinting at numbers.
(5) Threshold Grid – Five horizontal guides create a structured regime map:
• Lower Extreme (–50 pct) and Upper Extreme (+50 pct) identify panic capitulations and euphoria blow-offs.
• Oversold (–20 pct) and Overbought (+20 pct) act as early warning alarms.
• Zero Line demarcates neutral alignment.
4. Chart Furniture and User Interface
• Oscillator fill with a secondary DEMA-30 “shader” offers depth perception: fat ribbons often precede high-volatility macro shifts.
• Optional bar-colouring paints candles green when the oscillator is above zero and red below, handy for visual correlation.
• Background tints when the line breaches extreme zones, making macro inflection weeks pop out in the replay bar.
• Everything—line width, thresholds, colours—can be customised so the indicator blends into any template.
5. Interpretation Guide
Macro Liquidity Pulse
• When the oscillator spends weeks above +20 while the Fed is still raising rates, Bitcoin is signalling liquidity tolerance or an anticipatory pivot view. That condition often marks the embryonic phase of major bull cycles (e.g., March 2020 rebound).
• Sustained prints below –20 while the Fed is already dovish indicate risk aversion or idiosyncratic crypto stress—think exchange scandals or broad flight to safety.
Regime Transition Signals
• Bullish cross through zero after a long sub-zero stint shows Bitcoin regaining upward escape velocity versus policy.
• Bearish cross under zero during a hiking cycle tells you monetary tightening has finally started to bite.
Momentum Exhaustion and Mean-Reversion
• Touches of +50 (or –50) come rarely; they are statistically stretched events. Fade strategies either taking profits or hedging have historically enjoyed positive expectancy.
• Inside-bar candlestick patterns or lower-timeframe bearish engulfings simultaneously with an extreme overbought print make high-probability short scalp setups, especially near weekly resistance. The same logic mirrors for oversold.
Pair Trading / Relative Value
• Combine the oscillator with spreads like BTC versus Nasdaq 100. When both the FED Divergence oscillator and the BTC–NDQ relative-strength line roll south together, the cross-asset confirmation amplifies conviction in a mean-reversion short.
• Swap BTC for miners, altcoins or high-beta equities to test who is the divergence leader.
Event-Driven Tactics
• FOMC days: plot the oscillator on an hourly chart (disable ‘Force Daily TF’). Watch for micro-structural spikes that resolve in the first hour after the statement; rapid flips across zero can front-run post-FOMC swings.
• CPI and NFP prints: extremes reached into the release often mean positioning is one-sided. A reversion toward neutral in the first 24 hours is common.
6. Alerts Suite
Pre-bundled conditions let you automate workflows:
• Bullish / Bearish zero crosses – queue spot or futures entries.
• Standard OB / OS – notify for first contact with actionable zones.
• Extreme OB / OS – prime time to review hedges, take profits or build contrarian swing positions.
7. Parameter Playground
• Shorten ROC Lookback to 14 for tactical traders; lengthen to 90 for macro investors.
• Raise extreme thresholds (for example ±80) when plotting on altcoins that exhibit higher volatility than BTC.
• Try HMA smoothing for responsive yet smooth curves on intraday charts.
• Colour-blind users can easily swap bull and bear palette selections for preferred contrasts.
8. Limitations and Best Practices
• The Fed Funds series is step-wise; it only changes on meeting days. Rapid BTC oscillations in between may dominate the calculation. Keep that perspective when interpreting very high-frequency signals.
• Divergence does not equal causation. Crypto-native catalysts (ETF approvals, hack headlines) can overwhelm macro links temporarily.
• Use in conjunction with classical confirmation tools—order-flow footprints, market-profile ledges, or simple price action to avoid “pure-indicator” traps.
9. Final Thoughts
The FEDFUNDS Rate Divergence Oscillator distills an entire macro narrative monetary policy versus risk sentiment into a single colourful heartbeat. It will not magically predict every pivot, yet it excels at framing market context, spotting stretches and timing regime changes. Treat it as a strategic compass rather than a tactical sniper scope, combine it with sound risk management and multi-factor confirmation, and you will possess a robust edge anchored in the world’s most influential interest-rate benchmark.
Trade consciously, stay adaptive, and let the policy-price tension guide your roadmap.
EMA Trend Confirmation with Alerts此脚本是基于EMA 200周期 50周期 20周期加以合并并进行改进的一个脚本指标,主要作用是用于观察趋势走向,其中有上升下降和震荡趋势,经过多数测试,此指标适用于短线交易,推荐周期为20或15,大周期和长线交易详见RSI+EMA结合指标
This script is an improved script indicator based on the EMA 200 period, 50 period, and 20 period. Its main function is to observe the trend direction, including up, down, and oscillating trends. After many tests, this indicator is suitable for short-term trading, and the recommended period is 20 or 15. For large-cycle and long-term trading, please refer to the RSI+EMA combination indicator.
SulLaLuna M2 Hull DetectorAbsolutely — here's a polished **TradingView script description/article** you can publish with your indicator. It blends clarity, inspiration, respect, and community wisdom — SulLaLuna style.
---
## 🌕 SulLaLuna M2 Hull Detector 💵
### 🧠 Track Global Liquidity. Time Your Trades with Confidence.
This indicator lets you visualize shifts in global liquidity by analyzing the **aggregate Global M2 Money Supply** (adjusted by FX rates) and applying the legendary **Hull Moving Average** to detect clean trend pivots.
When **money flows in**, markets often rise.
When **liquidity contracts**, caution is wise.
> **This tool helps you detect those pivots—visually, simply, and powerfully.**
---
### 📈 How It Works
* ✅ Pulls M2 money supply from over 20 economies (adjusted to USD using FX)
* ✅ Normalizes to your current chart so you can visually track macro liquidity
* ✅ Applies **Hull MA** to smooth the trend and reduce lag
* ✅ Flags **bullish and bearish flips** with M2 markers on chart
* ✅ Optional color-coded background for macro awareness
* ✅ Fully customizable: control colors, opacity, and visibility
---
### ⚡ How to Use It
1. **Watch for a flip.**
A green "M2" label indicates rising liquidity → bullish conditions.
A red "M2" label indicates declining liquidity → caution.
2. **Look for confluence.**
Use this alongside your preferred system.
For example, we love combining it with the **Sushi Trend Indicator**.
> If **Sushi flips bullish**, and **M2 flips bullish** — strong case for a long.
> If **Sushi is bearish**, and **M2 flips bearish** — potential short setup.
> Both directions can earn, if you time it right.
3. **Apply sound risk management.**
Use stop-loss (SL), take-profit (TP), and position sizing that fits your system.
> 🔑 **"Scared money don't make no money."**
> — *Krown Chakra*
---
### 🙏 Acknowledgements
Massive thanks to:
* The **TradingView team** for the platform that empowers this kind of sharing
* The creators of public M2 and FX feeds
* The developers of the **Hull MA**, whose innovation this tool builds on
* Our fellow SulLaLuna traders — F.I.R.E. Decibels — who live and trade with purpose
---
### ⚠️ Disclaimer
This indicator is **not financial advice** and **no indicator is perfect**.
Always trade with logic, discipline, and confluence across systems.
---
If you find this helpful, please:
* ⭐ Add it to your favorites
* 💬 Drop a comment
* 🔁 Share it with a trader who needs a compass in macro chaos
Stay sharp. Stay sovereign.
— **Team SulLaLuna** 🌕
CGPT Golden Cross / Death Cross AlertThis custom indicator identifies Golden Cross (Gx) and Death Cross (Dx) events using either EMA or SMA moving averages. A Golden Cross occurs when a short-term MA (e.g., 50) crosses above a long-term MA (e.g., 200), signaling potential bullish momentum. A Death Cross signals potential bearish momentum, with the short-term MA crossing below the long-term MA.
It includes:
📈 Customizable MA types (EMA or SMA)
⚙️ Adjustable fast & slow MA lengths
🟢🔴 Chart labels for Gx (green) and Dx (red)
🎯 Background highlights for visual trend shifts
🔔 Built-in alert conditions for real-time notifications
Ideal for crypto, stocks, or forex swing and trend trading
Normalized Dist from 4H MA200 + Chart HighlightsNormalized Distance from 4H EMA200 + Highlighting Extremes
This indicator measures the distance between the current price and the 4-hour EMA200, normalized into a z-score to detect statistically significant deviations.
🔹 The lower pane shows the normalized z-score.
🔹 Green background = price far below EMA200 (z < -2).
🔹 Red background = price far above EMA200 (z > 3.1).
🔹 These thresholds are user-configurable.
🔹 On the main chart:
🟥 Red candles indicate overheated prices (z > upper threshold)
🟩 Green candles signal oversold conditions (z < lower threshold)
The EMA200 is always taken from a fixed 4H timeframe, regardless of your current chart resolution.
Drawdown Distribution Analysis (DDA) ACADEMIC FOUNDATION AND RESEARCH BACKGROUND
The Drawdown Distribution Analysis indicator implements quantitative risk management principles, drawing upon decades of academic research in portfolio theory, behavioral finance, and statistical risk modeling. This tool provides risk assessment capabilities for traders and portfolio managers seeking to understand their current position within historical drawdown patterns.
The theoretical foundation of this indicator rests on modern portfolio theory as established by Markowitz (1952), who introduced the fundamental concepts of risk-return optimization that continue to underpin contemporary portfolio management. Sharpe (1966) later expanded this framework by developing risk-adjusted performance measures, most notably the Sharpe ratio, which remains a cornerstone of performance evaluation in financial markets.
The specific focus on drawdown analysis builds upon the work of Chekhlov, Uryasev and Zabarankin (2005), who provided the mathematical framework for incorporating drawdown measures into portfolio optimization. Their research demonstrated that traditional mean-variance optimization often fails to capture the full risk profile of investment strategies, particularly regarding sequential losses. More recent work by Goldberg and Mahmoud (2017) has brought these theoretical concepts into practical application within institutional risk management frameworks.
Value at Risk methodology, as comprehensively outlined by Jorion (2007), provides the statistical foundation for the risk measurement components of this indicator. The coherent risk measures framework developed by Artzner et al. (1999) ensures that the risk metrics employed satisfy the mathematical properties required for sound risk management decisions. Additionally, the focus on downside risk follows the framework established by Sortino and Price (1994), while the drawdown-adjusted performance measures implement concepts introduced by Young (1991).
MATHEMATICAL METHODOLOGY
The core calculation methodology centers on a peak-tracking algorithm that continuously monitors the maximum price level achieved and calculates the percentage decline from this peak. The drawdown at any time t is defined as DD(t) = (P(t) - Peak(t)) / Peak(t) × 100, where P(t) represents the asset price at time t and Peak(t) represents the running maximum price observed up to time t.
Statistical distribution analysis forms the analytical backbone of the indicator. The system calculates key percentiles using the ta.percentile_nearest_rank() function to establish the 5th, 10th, 25th, 50th, 75th, 90th, and 95th percentiles of the historical drawdown distribution. This approach provides a complete picture of how the current drawdown compares to historical patterns.
Statistical significance assessment employs standard deviation bands at one, two, and three standard deviations from the mean, following the conventional approach where the upper band equals μ + nσ and the lower band equals μ - nσ. The Z-score calculation, defined as Z = (DD - μ) / σ, enables the identification of statistically extreme events, with thresholds set at |Z| > 2.5 for extreme drawdowns and |Z| > 3.0 for severe drawdowns, corresponding to confidence levels exceeding 99.4% and 99.7% respectively.
ADVANCED RISK METRICS
The indicator incorporates several risk-adjusted performance measures that extend beyond basic drawdown analysis. The Sharpe ratio calculation follows the standard formula Sharpe = (R - Rf) / σ, where R represents the annualized return, Rf represents the risk-free rate, and σ represents the annualized volatility. The system supports dynamic sourcing of the risk-free rate from the US 10-year Treasury yield or allows for manual specification.
The Sortino ratio addresses the limitation of the Sharpe ratio by focusing exclusively on downside risk, calculated as Sortino = (R - Rf) / σd, where σd represents the downside deviation computed using only negative returns. This measure provides a more accurate assessment of risk-adjusted performance for strategies that exhibit asymmetric return distributions.
The Calmar ratio, defined as Annual Return divided by the absolute value of Maximum Drawdown, offers a direct measure of return per unit of drawdown risk. This metric proves particularly valuable for comparing strategies or assets with different risk profiles, as it directly relates performance to the maximum historical loss experienced.
Value at Risk calculations provide quantitative estimates of potential losses at specified confidence levels. The 95% VaR corresponds to the 5th percentile of the drawdown distribution, while the 99% VaR corresponds to the 1st percentile. Conditional VaR, also known as Expected Shortfall, estimates the average loss in the worst 5% of scenarios, providing insight into tail risk that standard VaR measures may not capture.
To enable fair comparison across assets with different volatility characteristics, the indicator calculates volatility-adjusted drawdowns using the formula Adjusted DD = Raw DD / (Volatility / 20%). This normalization allows for meaningful comparison between high-volatility assets like cryptocurrencies and lower-volatility instruments like government bonds.
The Risk Efficiency Score represents a composite measure ranging from 0 to 100 that combines the Sharpe ratio and current percentile rank to provide a single metric for quick asset assessment. Higher scores indicate superior risk-adjusted performance relative to historical patterns.
COLOR SCHEMES AND VISUALIZATION
The indicator implements eight distinct color themes designed to accommodate different analytical preferences and market contexts. The EdgeTools theme employs a corporate blue palette that matches the design system used throughout the edgetools.org platform, ensuring visual consistency across analytical tools.
The Gold theme specifically targets precious metals analysis with warm tones that complement gold chart analysis, while the Quant theme provides a grayscale scheme suitable for analytical environments that prioritize clarity over aesthetic appeal. The Behavioral theme incorporates psychology-based color coding, using green to represent greed-driven market conditions and red to indicate fear-driven environments.
Additional themes include Ocean, Fire, Matrix, and Arctic schemes, each designed for specific market conditions or user preferences. All themes function effectively with both dark and light mode trading platforms, ensuring accessibility across different user interface configurations.
PRACTICAL APPLICATIONS
Asset allocation and portfolio construction represent primary use cases for this analytical framework. When comparing multiple assets such as Bitcoin, gold, and the S&P 500, traders can examine Risk Efficiency Scores to identify instruments offering superior risk-adjusted performance. The 95% VaR provides worst-case scenario comparisons, while volatility-adjusted drawdowns enable fair comparison despite varying volatility profiles.
The practical decision framework suggests that assets with Risk Efficiency Scores above 70 may be suitable for aggressive portfolio allocations, scores between 40 and 70 indicate moderate allocation potential, and scores below 40 suggest defensive positioning or avoidance. These thresholds should be adjusted based on individual risk tolerance and market conditions.
Risk management and position sizing applications utilize the current percentile rank to guide allocation decisions. When the current drawdown ranks above the 75th percentile of historical data, indicating that current conditions are better than 75% of historical periods, position increases may be warranted. Conversely, when percentile rankings fall below the 25th percentile, indicating elevated risk conditions, position reductions become advisable.
Institutional portfolio monitoring applications include hedge fund risk dashboard implementations where multiple strategies can be monitored simultaneously. Sharpe ratio tracking identifies deteriorating risk-adjusted performance across strategies, VaR monitoring ensures portfolios remain within established risk limits, and drawdown duration tracking provides valuable information for investor reporting requirements.
Market timing applications combine the statistical analysis with trend identification techniques. Strong buy signals may emerge when risk levels register as "Low" in conjunction with established uptrends, while extreme risk levels combined with downtrends may indicate exit or hedging opportunities. Z-scores exceeding 3.0 often signal statistically oversold conditions that may precede trend reversals.
STATISTICAL SIGNIFICANCE AND VALIDATION
The indicator provides 95% confidence intervals around current drawdown levels using the standard formula CI = μ ± 1.96σ. This statistical framework enables users to assess whether current conditions fall within normal market variation or represent statistically significant departures from historical patterns.
Risk level classification employs a dynamic assessment system based on percentile ranking within the historical distribution. Low risk designation applies when current drawdowns perform better than 50% of historical data, moderate risk encompasses the 25th to 50th percentile range, high risk covers the 10th to 25th percentile range, and extreme risk applies to the worst 10% of historical drawdowns.
Sample size considerations play a crucial role in statistical reliability. For daily data, the system requires a minimum of 252 trading days (approximately one year) but performs better with 500 or more observations. Weekly data analysis benefits from at least 104 weeks (two years) of history, while monthly data requires a minimum of 60 months (five years) for reliable statistical inference.
IMPLEMENTATION BEST PRACTICES
Parameter optimization should consider the specific characteristics of different asset classes. Equity analysis typically benefits from 500-day lookback periods with 21-day smoothing, while cryptocurrency analysis may employ 365-day lookback periods with 14-day smoothing to account for higher volatility patterns. Fixed income analysis often requires longer lookback periods of 756 days with 34-day smoothing to capture the lower volatility environment.
Multi-timeframe analysis provides hierarchical risk assessment capabilities. Daily timeframe analysis supports tactical risk management decisions, weekly analysis informs strategic positioning choices, and monthly analysis guides long-term allocation decisions. This hierarchical approach ensures that risk assessment occurs at appropriate temporal scales for different investment objectives.
Integration with complementary indicators enhances the analytical framework. Trend indicators such as RSI and moving averages provide directional bias context, volume analysis helps confirm the severity of drawdown conditions, and volatility measures like VIX or ATR assist in market regime identification.
ALERT SYSTEM AND AUTOMATION
The automated alert system monitors five distinct categories of risk events. Risk level changes trigger notifications when drawdowns move between risk categories, enabling proactive risk management responses. Statistical significance alerts activate when Z-scores exceed established threshold levels of 2.5 or 3.0 standard deviations.
New maximum drawdown alerts notify users when historical maximum levels are exceeded, indicating entry into uncharted risk territory. Poor risk efficiency alerts trigger when the composite risk efficiency score falls below 30, suggesting deteriorating risk-adjusted performance. Sharpe ratio decline alerts activate when risk-adjusted performance turns negative, indicating that returns no longer compensate for the risk undertaken.
TRADING STRATEGIES
Conservative risk parity strategies can be implemented by monitoring Risk Efficiency Scores across a diversified asset portfolio. Monthly rebalancing maintains equal risk contribution from each asset, with allocation reductions triggered when risk levels reach "High" status and complete exits executed when "Extreme" risk levels emerge. This approach typically results in lower overall portfolio volatility, improved risk-adjusted returns, and reduced maximum drawdown periods.
Tactical asset rotation strategies compare Risk Efficiency Scores across different asset classes to guide allocation decisions. Assets with scores exceeding 60 receive overweight allocations, while assets scoring below 40 receive underweight positions. Percentile rankings provide timing guidance for allocation adjustments, creating a systematic approach to asset allocation that responds to changing risk-return profiles.
Market timing strategies with statistical edges can be constructed by entering positions when Z-scores fall below -2.5, indicating statistically oversold conditions, and scaling out when Z-scores exceed 2.5, suggesting overbought conditions. The 95% VaR serves as a stop-loss reference point, while trend confirmation indicators provide additional validation for position entry and exit decisions.
LIMITATIONS AND CONSIDERATIONS
Several statistical limitations affect the interpretation and application of these risk measures. Historical bias represents a fundamental challenge, as past drawdown patterns may not accurately predict future risk characteristics, particularly during structural market changes or regime shifts. Sample dependence means that results can be sensitive to the selected lookback period, with shorter periods providing more responsive but potentially less stable estimates.
Market regime changes can significantly alter the statistical parameters underlying the analysis. During periods of structural market evolution, historical distributions may provide poor guidance for future expectations. Additionally, many financial assets exhibit return distributions with fat tails that deviate from normal distribution assumptions, potentially leading to underestimation of extreme event probabilities.
Practical limitations include execution risk, where theoretical signals may not translate directly into actual trading results due to factors such as slippage, timing delays, and market impact. Liquidity constraints mean that risk metrics assume perfect liquidity, which may not hold during stressed market conditions when risk management becomes most critical.
Transaction costs are not incorporated into risk-adjusted return calculations, potentially overstating the attractiveness of strategies that require frequent trading. Behavioral factors represent another limitation, as human psychology may override statistical signals, particularly during periods of extreme market stress when disciplined risk management becomes most challenging.
TECHNICAL IMPLEMENTATION
Performance optimization ensures reliable operation across different market conditions and timeframes. All technical analysis functions are extracted from conditional statements to maintain Pine Script compliance and ensure consistent execution. Memory efficiency is achieved through optimized variable scoping and array usage, while computational speed benefits from vectorized calculations where possible.
Data quality requirements include clean price data without gaps or errors that could distort distribution analysis. Sufficient historical data is essential, with a minimum of 100 bars required and 500 or more preferred for reliable statistical inference. Time alignment across related assets ensures meaningful comparison when conducting multi-asset analysis.
The configuration parameters are organized into logical groups to enhance usability. Core settings include the Distribution Analysis Period (100-2000 bars), Drawdown Smoothing Period (1-50 bars), and Price Source selection. Advanced metrics settings control risk-free rate sourcing, either from live market data or fixed rate specification, along with toggles for various risk-adjusted metric calculations.
Display options provide flexibility in visual presentation, including color theme selection from eight available schemes, automatic dark mode optimization, and control over table display, position lines, percentile bands, and standard deviation overlays. These options ensure that the indicator can be adapted to different analytical workflows and visual preferences.
CONCLUSION
The Drawdown Distribution Analysis indicator provides risk management tools for traders seeking to understand their current position within historical risk patterns. By combining established statistical methodology with practical usability features, the tool enables evidence-based risk assessment and portfolio optimization decisions.
The implementation draws upon established academic research while providing practical features that address real-world trading requirements. Dynamic risk-free rate integration ensures accurate risk-adjusted performance calculations, while multiple color schemes accommodate different analytical preferences and use cases.
Academic compliance is maintained through transparent methodology and acknowledgment of limitations. The tool implements peer-reviewed statistical techniques while clearly communicating the constraints and assumptions underlying the analysis. This approach ensures that users can make informed decisions about the appropriate application of the risk assessment framework within their broader trading and investment processes.
BIBLIOGRAPHY
Artzner, P., Delbaen, F., Eber, J.M. and Heath, D. (1999) 'Coherent Measures of Risk', Mathematical Finance, 9(3), pp. 203-228.
Chekhlov, A., Uryasev, S. and Zabarankin, M. (2005) 'Drawdown Measure in Portfolio Optimization', International Journal of Theoretical and Applied Finance, 8(1), pp. 13-58.
Goldberg, L.R. and Mahmoud, O. (2017) 'Drawdown: From Practice to Theory and Back Again', Journal of Risk Management in Financial Institutions, 10(2), pp. 140-152.
Jorion, P. (2007) Value at Risk: The New Benchmark for Managing Financial Risk. 3rd edn. New York: McGraw-Hill.
Markowitz, H. (1952) 'Portfolio Selection', Journal of Finance, 7(1), pp. 77-91.
Sharpe, W.F. (1966) 'Mutual Fund Performance', Journal of Business, 39(1), pp. 119-138.
Sortino, F.A. and Price, L.N. (1994) 'Performance Measurement in a Downside Risk Framework', Journal of Investing, 3(3), pp. 59-64.
Young, T.W. (1991) 'Calmar Ratio: A Smoother Tool', Futures, 20(1), pp. 40-42.
Valuation Tool + Williams %R by QDEEDValuation + Williams %R Indicator
This indicator combines relative valuation and momentum to help identify overvalued and undervalued conditions in key macro assets:
DXY (US Dollar Index)
GC1! (Gold Futures)
ZB1! (30-Year US Treasury Bond Futures)
Inspired by Larry Williams' techniques, this tool uses a rescaled comparison of asset prices and overlays the Williams %R momentum oscillator.
What it shows:
When the value line is above 0, the asset may be overvalued relative to the others.
When it's below 0, the asset may be undervalued.
The Williams %R adds a timing layer, indicating overbought/oversold momentum zones.
2 Asset Optimal PortfolioThis script calculates and plots either the Sharpe Ratio or Sortino Ratio for a two-asset portfolio using historical price data, allowing users to analyse how different allocations affect portfolio performance over a specified lookback period.
Features:
Determine the weights of 2 assets and how they affect the the Sharpe or Sortino ratio.
Adjust timeframe to suit your personal investment timeframe.
User Inputs:
1. Asset 1 and Asset 2: Choose any two symbols to evaluate (default is BTCUSD for both).
2. Look Back Length: Number of past bars (days) to use for calculations (default is 365).
3. Source: Price source for returns (default is close).
4. Ratio: Select which ratio to plot — Sharpe or Sortino.
5. % of Asset 1: Portfolio weight (from 0 to 1) for Asset 1.
FMX Trend Confirmation - No Reversals🔍 FMX Continuation Signal – No Reversals
Powered by the FMX Model (Fundamentals Meet Execution)
This indicator is designed to capture high-probability continuation trades only, avoiding risky reversals. It confirms buy or sell signals based on:
✅ 15-Minute Structure Shift Confirmation
✅ Liquidity Sweeps (stop hunts beyond recent highs/lows)
✅ Trend Validation using HTF SMA (default: 15min)
✅ Second Candle Close inside the sweep range — FMX-grade precision
📈 Green “Buy” labels appear when:
Liquidity is swept below recent lows
Price closes back inside the range
The higher timeframe trend is bullish
📉 Orange “Sell” labels appear when:
Liquidity is swept above recent highs
Price closes back inside the range
The higher timeframe trend is bearish
🛡️ No reversal signals are plotted. This tool is meant for traders who follow the trend with smart money logic, inspired by FMX principles.
Twin Range Filter – Buy/Sell SignalsThe Twin Range Filter is a trend-following indicator that combines two adaptive volatility filters to identify potential market reversals and trend continuations. It uses two configurable smoothing periods (fast and slow) to calculate a dynamic range around price, filtering out market noise and highlighting meaningful shifts in direction.
This indicator plots BUY and SELL signals based on price action in relation to the range filter, as well as internal trend conditions.
✅ How It Works:
Long Signal (BUY) is triggered when:
Price is above the filtered range (showing strength), and
Short-term upward momentum is confirmed.
Short Signal (SELL) is triggered when:
Price is below the filtered range (showing weakness), and
Short-term downward momentum is confirmed.
The signals are highlighted using green "Long" and red "Short" labels on the chart.
Background colors reinforce the current directional bias.
🔔 Alerts:
Long Signal – A new BUY condition has been detected.
Short Signal – A new SELL condition has been detected.
📌 Use Cases:
Entry timing for swing or intraday trades
Trend confirmation filter
Signal generator in automated strategies (when paired with a strategy script)
DAX Inducere Simplă v1.3 – Confirmare InducereDAX Inducere Simplă v1.3 – Confirmare Inducere ,signals before fvg mss and displacement
Volume vs Volatility Trend Signal1 is increasing volume decreasing volatility -1 is decreasing volume increasing volatility 0 is neither
Scalping Indicator v6This Script Show You Recent Scalping Trades u can get instantly we have use the knowledge we gain across the time we might be right or wrong do your own research and use this indicator on ur own risk
Fibonacci Range Detector ║ BullVision🔬 Overview
The Fibonacci Range Mapper is a dynamic technical tool designed to identify, track, and visualize price ranges using Fibonacci levels. Whether you're trading manually or prefer automated structure recognition, this indicator helps you contextualize market moves and locate key price zones with precision.
⚙️ Core Logic
🔍 Range Detection (Auto & Manual Modes)
In Auto mode, the indicator uses an advanced ZigZag system based on ATR or percentage thresholds to confirm market swings and construct Fibonacci-based ranges.
In Manual mode, traders can define their own swing low and high to generate precise custom ranges.
📐 Fibonacci Mapping
Each detected range is automatically plotted with key Fibonacci retracement levels — 0%, 25%, 50%, 75%, 100% — along with optional extensions (127.2% and 161.8%) to anticipate price continuations or reversals.
📋 Live Data Table
An integrated info panel dynamically displays crucial metrics:
• Range size
• Current price zone (Discount / Mid / Premium)
• Position within range (%)
• Distance to range extremes
• Range status (Pending or Confirmed)
🕰️ Historical Memory
Up to 20 past ranges can be stored and visualized simultaneously, helping traders recognize repeated price behaviors and contextual support/resistance levels.
🎨 Visual Highlights
Zones of interest (0–25% = Discount, 75–100% = Premium) are color-coded with custom transparency, and labels can be toggled for clarity. The current active range updates in real time as structure evolves.
🔧 User Customization
• Detection Method: Choose between ATR or % ZigZag for automated swing identification
• Confirmation Delay: Set how many bars to wait before confirming a new high
• Manual Overrides: Select exact price levels when you want full control
• Extensions & Labels: Toggle additional lines and info to suit your charting style
• Visual Table Position: Customize where the data table appears on screen
• Color Scheme: Define your own zone gradients for better visual interpretation
📈 Use Cases
This indicator is ideal for traders who want to:
• Identify value zones within local or macro price structures
• Plan trades around Fibonacci retracement and extension levels
• Detect shifts in market structure using an adaptive ZigZag logic
• Track recurring price ranges and historical reaction points
• Enhance technical confluence with clean, visual price mapping
⚠️ Important Notes
This tool is not a buy/sell signal generator — it is a visual framework for structure-based analysis.
Use it in conjunction with your existing strategy and risk management process.
Always confirm with broader context and multi-timeframe alignment.
Kent Directional Filter🧭 Kent Directional Filter
Author: GabrielAmadeusLau
Type: Filter
📖 What It Is
The Kent Directional Filter is a directionality-sensitive smoothing tool inspired by the Kent distribution, a probability model used to describe directional and elliptical shapes on a sphere. In this context, it's repurposed for analyzing the angular trajectory of price movements and smoothing them for actionable insights.
It’s ideal for:
Detecting directional bias with probabilistic weighting
Enhancing momentum or trend-following systems
Filtering non-linear price action
🔬 How It Works
Price Angle Estimation:
Computes a rough angular shift in price using atan(src - src ) to estimate direction.
Kent Distribution Weighting:
κ (kappa) controls concentration strength (how sharply it prefers a direction).
β (beta) controls ellipticity (bias toward curved vs. linear moves).
These parameters influence how strongly the indicator favors movements at ~45° angles, simulating a directional “lens.”
Smoothing:
A Simple Moving Average (SMA) is applied over the raw directional probabilities to reduce noise and highlight the underlying trend signal.
⚙️ Inputs
Source: Price series used for angle calculation (default: close)
Smoothing Length: Window size for the moving average
Pi Divisor: Pi / 4 would be 45 degrees, you can change the 4 to 3, 2, etc.
Kappa (κ): Controls how focused the directionality is (higher = sharper filter)
Beta (β): Adds curvature sensitivity; higher values accentuate asymmetrical moves
🧠 Tips for Best Results
Use κ = 1–2 for moderate directional filtering, and β = 0.3–0.7 for smooth elliptical bias.
Combine with volume-based indicators to confirm breakout strength.
Works best in higher timeframes (1h–1D) to capture macro directional structure.
I might revisit this.