Systemic Credit Market Pressure IndexSystemic Credit Market Pressure Index (SCMPI): A Composite Indicator for Credit Cycle Analysis
The Systemic Credit Market Pressure Index (SCMPI) represents a novel composite indicator designed to quantify systemic stress within credit markets through the integration of multiple macroeconomic variables. This indicator employs advanced statistical normalization techniques, adaptive threshold mechanisms, and intelligent visualization systems to provide real-time assessment of credit market conditions across expansion, neutral, and stress regimes. The methodology combines credit spread analysis, labor market indicators, consumer credit conditions, and household debt metrics into a unified framework for systemic risk assessment, featuring dynamic Bollinger Band-style thresholds and theme-adaptive visualization capabilities.
## 1. Introduction
Credit cycles represent fundamental drivers of economic fluctuations, with their dynamics significantly influencing financial stability and macroeconomic outcomes (Bernanke, Gertler & Gilchrist, 1999). The identification and measurement of credit market stress has become increasingly critical following the 2008 financial crisis, which highlighted the need for comprehensive early warning systems (Adrian & Brunnermeier, 2016). Traditional single-variable approaches often fail to capture the multidimensional nature of credit market dynamics, necessitating the development of composite indicators that integrate multiple information sources.
The SCMPI addresses this gap by constructing a weighted composite index that synthesizes four key dimensions of credit market conditions: corporate credit spreads, labor market stress, consumer credit accessibility, and household leverage ratios. This approach aligns with the theoretical framework established by Minsky (1986) regarding financial instability hypothesis and builds upon empirical work by Gilchrist & Zakrajšek (2012) on credit market sentiment.
## 2. Theoretical Framework
### 2.1 Credit Cycle Theory
The theoretical foundation of the SCMPI rests on the credit cycle literature, which posits that credit availability fluctuates in predictable patterns that amplify business cycle dynamics (Kiyotaki & Moore, 1997). During expansion phases, credit becomes increasingly available as risk perceptions decline and collateral values rise. Conversely, stress phases are characterized by credit contraction, elevated risk premiums, and deteriorating borrower conditions.
The indicator incorporates Kindleberger's (1978) framework of financial crises, which identifies key stages in credit cycles: displacement, boom, euphoria, profit-taking, and panic. By monitoring multiple variables simultaneously, the SCMPI aims to capture transitions between these phases before they become apparent in individual metrics.
### 2.2 Systemic Risk Measurement
Systemic risk, defined as the risk of collapse of an entire financial system or entire market (Kaufman & Scott, 2003), requires measurement approaches that capture interconnectedness and spillover effects. The SCMPI follows the methodology established by Bisias et al. (2012) in constructing composite measures that aggregate individual risk indicators into system-wide assessments.
The index employs the concept of "financial stress" as defined by Illing & Liu (2006), encompassing increased uncertainty about fundamental asset values, increased uncertainty about other investors' behavior, increased flight to quality, and increased flight to liquidity.
## 3. Methodology
### 3.1 Component Variables
The SCMPI integrates four primary components, each representing distinct aspects of credit market conditions:
#### 3.1.1 Credit Spreads (BAA-10Y Treasury)
Corporate credit spreads serve as the primary indicator of credit market stress, reflecting risk premiums demanded by investors for corporate debt relative to risk-free government securities (Gilchrist & Zakrajšek, 2012). The BAA-10Y spread specifically captures investment-grade corporate credit conditions, providing insight into broad credit market sentiment.
#### 3.1.2 Unemployment Rate
Labor market conditions directly influence credit quality through their impact on borrower repayment capacity (Bernanke & Gertler, 1995). Rising unemployment typically precedes credit deterioration, making it a valuable leading indicator for credit stress.
#### 3.1.3 Consumer Credit Rates
Consumer credit accessibility reflects the transmission of monetary policy and credit market conditions to household borrowing (Mishkin, 1995). Elevated consumer credit rates indicate tightening credit conditions and reduced credit availability for households.
#### 3.1.4 Household Debt Service Ratio
Household leverage ratios capture the debt burden relative to income, providing insight into household financial stress and potential credit losses (Mian & Sufi, 2014). High debt service ratios indicate vulnerable household sectors that may contribute to credit market instability.
### 3.2 Statistical Methodology
#### 3.2.1 Z-Score Normalization
Each component variable undergoes robust z-score normalization to ensure comparability across different scales and units:
Z_i,t = (X_i,t - μ_i) / σ_i
Where X_i,t represents the value of variable i at time t, μ_i is the historical mean, and σ_i is the historical standard deviation. The normalization period employs a rolling 252-day window to capture annual cyclical patterns while maintaining sensitivity to regime changes.
#### 3.2.2 Adaptive Smoothing
To reduce noise while preserving signal quality, the indicator employs exponential moving average (EMA) smoothing with adaptive parameters:
EMA_t = α × Z_t + (1-α) × EMA_{t-1}
Where α = 2/(n+1) and n represents the smoothing period (default: 63 days).
#### 3.2.3 Weighted Aggregation
The composite index combines normalized components using theoretically motivated weights:
SCMPI_t = w_1×Z_spread,t + w_2×Z_unemployment,t + w_3×Z_consumer,t + w_4×Z_debt,t
Default weights reflect the relative importance of each component based on empirical literature: credit spreads (35%), unemployment (25%), consumer credit (25%), and household debt (15%).
### 3.3 Dynamic Threshold Mechanism
Unlike static threshold approaches, the SCMPI employs adaptive Bollinger Band-style thresholds that automatically adjust to changing market volatility and conditions (Bollinger, 2001):
Expansion Threshold = μ_SCMPI - k × σ_SCMPI
Stress Threshold = μ_SCMPI + k × σ_SCMPI
Neutral Line = μ_SCMPI
Where μ_SCMPI and σ_SCMPI represent the rolling mean and standard deviation of the composite index calculated over a configurable period (default: 126 days), and k is the threshold multiplier (default: 1.0). This approach ensures that thresholds remain relevant across different market regimes and volatility environments, providing more robust regime classification than fixed thresholds.
### 3.4 Visualization and User Interface
The SCMPI incorporates advanced visualization capabilities designed for professional trading environments:
#### 3.4.1 Adaptive Theme System
The indicator features an intelligent dual-theme system that automatically optimizes colors and transparency levels for both dark and bright chart backgrounds. This ensures optimal readability across different trading platforms and user preferences.
#### 3.4.2 Customizable Visual Elements
Users can customize all visual aspects including:
- Color Schemes: Automatic theme adaptation with optional custom color overrides
- Line Styles: Configurable widths for main index, trend lines, and threshold boundaries
- Transparency Optimization: Automatic adjustment based on selected theme for optimal contrast
- Dynamic Zones: Color-coded regime areas with adaptive transparency
#### 3.4.3 Professional Data Table
A comprehensive 13-row data table provides real-time component analysis including:
- Composite index value and regime classification
- Individual component z-scores with color-coded stress indicators
- Trend direction and signal strength assessment
- Dynamic threshold status and volatility metrics
- Component weight distribution for transparency
## 4. Regime Classification
The SCMPI classifies credit market conditions into three distinct regimes:
### 4.1 Expansion Regime (SCMPI < Expansion Threshold)
Characterized by favorable credit conditions, low risk premiums, and accommodative lending standards. This regime typically corresponds to economic expansion phases with low default rates and increasing credit availability.
### 4.2 Neutral Regime (Expansion Threshold ≤ SCMPI ≤ Stress Threshold)
Represents balanced credit market conditions with moderate risk premiums and stable lending standards. This regime indicates neither significant stress nor excessive exuberance in credit markets.
### 4.3 Stress Regime (SCMPI > Stress Threshold)
Indicates elevated credit market stress with high risk premiums, tightening lending standards, and deteriorating borrower conditions. This regime often precedes or coincides with economic contractions and financial market volatility.
## 5. Technical Implementation and Features
### 5.1 Alert System
The SCMPI includes a comprehensive alert framework with seven distinct conditions:
- Regime Transitions: Expansion, Neutral, and Stress phase entries
- Extreme Conditions: Values exceeding ±2.0 standard deviations
- Trend Reversals: Directional changes in the underlying trend component
### 5.2 Performance Optimization
The indicator employs several optimization techniques:
- Efficient Calculations: Pre-computed statistical measures to minimize computational overhead
- Memory Management: Optimized variable declarations for real-time performance
- Error Handling: Robust data validation and fallback mechanisms for missing data
## 6. Empirical Validation
### 6.1 Historical Performance
Backtesting analysis demonstrates the SCMPI's ability to identify major credit stress episodes, including:
- The 2008 Financial Crisis
- The 2020 COVID-19 pandemic market disruption
- Various regional banking crises
- European sovereign debt crisis (2010-2012)
### 6.2 Leading Indicator Properties
The composite nature and dynamic threshold system of the SCMPI provides enhanced leading indicator properties, typically signaling regime changes 1-3 months before they become apparent in individual components or market indices. The adaptive threshold mechanism reduces false signals during high-volatility periods while maintaining sensitivity during regime transitions.
## 7. Applications and Limitations
### 7.1 Applications
- Risk Management: Portfolio managers can use SCMPI signals to adjust credit exposure and risk positioning
- Academic Research: Researchers can employ the index for credit cycle analysis and systemic risk studies
- Trading Systems: The comprehensive alert system enables automated trading strategy implementation
- Financial Education: The transparent methodology and visual design facilitate understanding of credit market dynamics
### 7.2 Limitations
- Data Dependency: The indicator relies on timely and accurate macroeconomic data from FRED sources
- Regime Persistence: Dynamic thresholds may exhibit brief lag during extremely rapid regime transitions
- Model Risk: Component weights and parameters require periodic recalibration based on evolving market structures
- Computational Requirements: Real-time calculations may require adequate processing power for optimal performance
## References
Adrian, T. & Brunnermeier, M.K. (2016). CoVaR. *American Economic Review*, 106(7), 1705-1741.
Bernanke, B. & Gertler, M. (1995). Inside the black box: the credit channel of monetary policy transmission. *Journal of Economic Perspectives*, 9(4), 27-48.
Bernanke, B., Gertler, M. & Gilchrist, S. (1999). The financial accelerator in a quantitative business cycle framework. *Handbook of Macroeconomics*, 1, 1341-1393.
Bisias, D., Flood, M., Lo, A.W. & Valavanis, S. (2012). A survey of systemic risk analytics. *Annual Review of Financial Economics*, 4(1), 255-296.
Bollinger, J. (2001). *Bollinger on Bollinger Bands*. McGraw-Hill Education.
Gilchrist, S. & Zakrajšek, E. (2012). Credit spreads and business cycle fluctuations. *American Economic Review*, 102(4), 1692-1720.
Illing, M. & Liu, Y. (2006). Measuring financial stress in a developed country: An application to Canada. *Journal of Financial Stability*, 2(3), 243-265.
Kaufman, G.G. & Scott, K.E. (2003). What is systemic risk, and do bank regulators retard or contribute to it? *The Independent Review*, 7(3), 371-391.
Kindleberger, C.P. (1978). *Manias, Panics and Crashes: A History of Financial Crises*. Basic Books.
Kiyotaki, N. & Moore, J. (1997). Credit cycles. *Journal of Political Economy*, 105(2), 211-248.
Mian, A. & Sufi, A. (2014). What explains the 2007–2009 drop in employment? *Econometrica*, 82(6), 2197-2223.
Minsky, H.P. (1986). *Stabilizing an Unstable Economy*. Yale University Press.
Mishkin, F.S. (1995). Symposium on the monetary transmission mechanism. *Journal of Economic Perspectives*, 9(4), 3-10.
Indicators and strategies
ES OHLC BASED ON 9:301. RTH Price Levels
YC (Yesterday's Close): Previous day's RTH closing price at 4:00 PM ET
0DTE-O (Today's Open): Current day's RTH opening price at 9:30 AM ET
T-E-M (Today's Europe-Asia Midpoint): Midpoint of overnight session high/low
T-E-R (Today's Europe-Asia Resistance): Overnight session high
T-E-S (Today's Europe-Asia Support): Overnight session low
Y-T-M (Yesterday-Today Midpoint): Midpoint between YC and 0DTE-O
2. Previous Bar Percentage Levels
Displays 50% retracement level for all bars
Shows 70% level for bullish bars (close > open)
Shows 30% level for bearish bars (close < open)
Lines automatically update with each new bar
3. Custom Support/Resistance Lines
Up to 4 customizable horizontal levels (2 resistance, 2 support)
Useful for marking key psychological levels or pivot points
4. VIX-Based Options Strategy Suggestions
Real-time VIX value display
Time Zone Handling
The indicator is configured for Central Time (CT) as Pine Script's default:
RTH Open: 8:30 AM CT (9:30 AM ET)
RTH Close: 3:00 PM CT (4:00 PM ET)
Overnight session: 7:00 PM CT to 8:30 AM CT next day
Usage Notes
Chart Requirement: This indicator only works on 5-minute timeframe charts
Auto-refresh: All lines and labels automatically refresh at each new trading day's RTH open
24-hour Market: Designed for ES futures which trade nearly 24 hours
Visual Clarity: Different line styles and colors for easy identification
Ideal For
Day traders focusing on ES futures
0DTE options traders needing key reference levels
Traders using overnight gaps and previous day's levels
Those incorporating VIX-based strategies in their trading
Directionality OscillatorDirectionality Oscillator is a simple momentum tool that measures net price displacement against total price activity over a chosen look-back period. It takes today’s closing price minus the close from “len” bars ago and divides that by the sum of all absolute bar-to-bar moves across the same span. The result is a value between –1 and +1, where positive values show that upward moves dominated and negative values show that downward moves prevailed.
To smooth out short-term noise, the indicator applies a five-bar simple moving average to the normalized value. A color gradient—from red at –1, through gray at 0, to green at +1—paints the line, making it easy to see whether bearish or bullish pressure is strongest. Two horizontal lines at the user-defined threshold and its negative mark zones of extreme directional strength. Readings above the positive threshold signal strong bullish momentum, and readings below the negative threshold signal strong bearish momentum.
Traders can watch for crossings above or below these threshold lines as trend confirmations or potential reversal warnings. A cross of the zero line indicates a shift in net directional control and can serve as an early trend-change alert when supported by price action or volume. Because it filters out sideways noise by normalizing against total activity, it highlights sustained directional thrust more clearly than a raw price-change measure.
Eigenvector Centrality Drift (ECD) - Market State Network What is Eigenvector Centrality Drift (ECD)?
Eigenvector Centrality Drift (ECD) is a groundbreaking indicator that applies concepts from network science to financial markets. Instead of viewing price as a simple series, ECD models the market as a dynamic network of “micro-states”—distinct combinations of price, volatility, and volume. By tracking how the influence of these states changes over time, ECD helps you spot regime shifts and transitions in market character before they become obvious in price.
This is not another moving average or momentum oscillator. ECD is inspired by eigenvector centrality—a measure of influence in network theory—and adapts it to the world of price action, volatility, and volume. It’s about understanding which market states are “in control” and when that control is about to change.
Theoretical Foundation
Network Science: In complex systems, nodes (states) and edges (transitions) form a network. Eigenvector centrality measures how influential a node is, not just by its direct connections, but by the influence of the nodes it connects to.
Market Micro-States: Each bar is classified into a “state” based on price change, volatility, and volume. The market transitions between these states, forming a network of possible regimes.
Centrality Drift: By tracking the centrality (influence) of the current state, and how it changes (drifts) over time, ECD highlights when the market’s “center of gravity” is shifting—often a precursor to major moves or regime changes.
How ECD Works
State Classification: Each bar is assigned to one of N market micro-states, based on a weighted combination of normalized price change, volatility, and volume.
Transition Matrix: Over a rolling window, ECD tracks how often the market transitions from each state to every other state, forming a transition probability matrix.
Centrality Calculation: Using a simplified eigenvector approach, ECD calculates the “influence” score for each state, reflecting how central it is to the network of recent market behavior.
Centrality Drift: The indicator tracks the Z-score of the change in centrality for the current state. Rapid increases or decreases, or a shift in the dominant state, signal a potential regime shift.
Dominant State: ECD also highlights which state currently has the highest influence, providing insight into the prevailing market character.
Inputs:
🌐 Market State Configuration
Number of Market States (n_states, default 6): Number of distinct micro-states to track.
3–4: Simple (Up/Down/Sideways)
5–6: Balanced (recommended)
7–9: Complex, more nuanced
Price Change Weight (price_weight, default 0.4):
How much price movement defines a state. Higher = more directional.
Volatility Weight (vol_weight, default 0.3):
How much volatility defines a state. Higher = more regime focus.
Volume Weight (volume_weight, default 0.3):
How much volume defines a state. Higher = more participation focus.
🔗 Network Analysis
Transition Matrix Window (transition_window, default 50): Lookback for building the state transition matrix.
Shorter: Adapts quickly
Longer: More stable
Influence Decay Factor (influence_decay, default 0.85): How much influence propagates through the network.
Higher: Distant transitions matter more
Lower: Only immediate transitions matter
Drift Detection Sensitivity (drift_sensitivity, default 1.5): Z-score threshold for significant centrality drift.
Lower: More signals
Higher: Only major shifts
🎨 Visualization
Show Network Visualization (show_network, default true): Background color and effects based on network structure.
Show Centrality Score (show_centrality, default true): Plots the current state’s centrality measure.
Show Drift Indicator (show_drift, default true): Plots the centrality drift Z-score.
Show State Map (show_state_map, default true): Dashboard showing all state centralities and which is dominant.
Color Scheme (color_scheme, default "Quantum"):
“Quantum”: Cyan/Magenta
“Neural”: Green/Blue
“Plasma”: Yellow/Pink
“Matrix”: Green/Black
Color Schemes
Dynamic gradients reflect the current state’s centrality and drift, using your chosen color palette.
Background network effect: The more central the current state, the more intense the background.
Centrality and drift lines: Color-coded for clarity and regime shift detection.
Visual Logic
Centrality Score Line: Plots the influence of the current state, with glow for emphasis.
Drift Indicator: Histogram of centrality drift Z-score, green for positive, red for negative.
Threshold Lines: Dotted lines mark the drift sensitivity threshold for regime shift alerts.
State Map Dashboard: Top-right panel shows all state centralities, highlights the current and dominant state, and visualizes influence with bars.
Information Panel: Bottom-left panel summarizes current state, centrality, dominant state, drift Z-score, and regime shift status.
How to Use ECD
Centrality Score: High = current state is highly influential; low = state is peripheral.
Drift Z-Score:
Large positive/negative = rapid change in influence, regime shift likely.
Near zero = stable network, no major shift.
Dominant State: The state with the highest centrality is “in control” of the market’s transitions.
State Map: Use to see which states are rising or falling in influence.
Tips:
Use fewer states for simple markets, more for nuanced analysis.
Watch for drift Z-score crossing the threshold—these are your regime shift signals.
Combine with your own system for confirmation.
Alerts:
ECD Regime Shift: Significant centrality drift detected—potential regime change.
ECD State Change: Market state transition occurred.
ECD Dominance Shift: Dominant market state has changed.
Originality & Usefulness
ECD is not a mashup or rehash of standard indicators. It is a novel application of network science and eigenvector centrality to market microstructure, providing a new lens for understanding regime shifts and market transitions. The state network, centrality drift, and dashboard are unique to this script. ECD is designed for anticipation, not confirmation—helping you see the market’s “center of gravity” shift before price action makes it obvious.
Chart Info
Script Name: Eigenvector Centrality Drift (ECD) – Market State Network
Recommended Use: Any asset, any timeframe. Tune parameters to your style.
Disclaimer
This script is for research and educational purposes only. It does not provide financial advice or direct buy/sell signals. Always use proper risk management and combine with your own strategy. Past performance is not indicative of future results.
See the market as a network. Anticipate the shift in influence.
— Dskyz , for DAFE Trading Systems
H4 Swing Grade Checklist English V.1✅ H4 Swing Grade Checklist – Auto Grading for Smart Money Setups
This script helps manual traders assess the quality of a Smart Money swing trade setup by checking 7 key criteria. The system assigns a grade (A+, A, A−, or B) based on how many and which checklist items are met.
📋 Checklist Items (7 total):
✅ Sweep occurs within 4 candles
✅ MSS (strong break candle)
✅ Entry is placed outside the wick of the sweep
✅ FVG is fresh (not previously used)
✅ FVG overlaps Fibonacci 0.705 level
✅ FVG lies within Premium or Discount zone
✅ Entry is placed at 0.705 Fibonacci retracement
🏅 Grading Criteria:
A+ → All 7 checklist items are satisfied
A → Only missing #5 (FVG Overlap with 0.705)
A− → Only missing #4 (FVG Fresh)
B → Only missing #2 (MSS – clear break of structure)
– → Any other combinations / fewer than 6 conditions met
⚙️ Features:
Toggle visibility with one click
Fixed display in top-right or bottom-right of the chart
Color-coded grading logic (Green, Yellow, Orange, Blue)
Clear checklist feedback for trade journaling or evaluation
🚀 Ideal For:
ICT / Smart Money traders
Prop firm evaluations
Swing trade quality control
Information Asymmetry Gradient (IAG) What is the Information Asymmetry Gradient (IAG)?
The Information Asymmetry Gradient (IAG) is a unique market regime and imbalance detector that quantifies the subtle, directional “information flow” in price and volume. Inspired by information theory and market microstructure, IAG is designed to help traders spot the early buildup of conviction or surprise—the kind of hidden imbalance that often precedes major price moves.
Unlike traditional volume or momentum indicators, IAG focuses on the efficiency and directionality of information transfer: how much “informational energy” is being revealed by up-moves versus down-moves, normalized by price movement. It’s not just about net flow, but about the quality and asymmetry of that flow.
Theoretical Foundation
Information Asymmetry: Markets move when new information is revealed. If one side (buyers or sellers) is consistently more “informationally efficient” per unit of price change, an imbalance is building—even if price hasn’t moved much yet.
Gradient: By tracking the rate of change (gradient) between fast and slow information flows, IAG highlights when a subtle imbalance is accelerating.
Volatility of Asymmetry: Sudden spikes in the volatility of information asymmetry often signal regime uncertainty or the approach of a “surprise” move.
How IAG Works
Directional Information Content: For each bar, IAG estimates the “information per unit of price change” for both up-moves and down-moves, using volume and price action.
Asymmetry Calculation: Computes the difference (or ratio) between up and down information content, revealing directional bias.
Gradient Detection: Calculates both a fast and slow EMA of the asymmetry, then measures their difference (the “gradient”), normalized as a Z-score.
Volatility of Asymmetry: Tracks the standard deviation of asymmetry over a rolling window, with Z-score normalization to spot “information shocks.”
Flow Strength: Quantifies the conviction of the current information flow on a 0–100 scale.
Regime Detection: Flags “extreme” asymmetry, “building” flow, and “high volatility” states.
Inputs:
🌌 Core Asymmetry Parameters
Fast Information Period (short_len, default 8): EMA period for detecting immediate information flow changes.
5–8: Scalping (1–5min)
8–12: Day trading (15min–1hr)
12–20: Swing trading (4hr+)
Slow Information Period (long_len, default 34): EMA period for baseline information context. Should be 3–5x fast period.
Default (34): Fibonacci number, stable for most assets.
Gradient Smoothing (gradient_smooth, default 3): Smooths the gradient calculation.
1–2: Raw, responsive
3–5: Balanced
6–10: Very smooth
📊 Asymmetry Method
Calculation Mode (calc_mode, default "Weighted"):
“Simple”: Basic volume split by direction
“Weighted”: Volume × price movement (default, most robust)
“Logarithmic”: Log-scaled for large moves
Use Ratio (show_ratio, default false):
“Difference”: UpInfo – DownInfo (additive)
“Ratio”: UpInfo / DownInfo (multiplicative, better for comparing volatility regimes)
🌊 Volatility Analysis
Volatility Window (stdev_len, default 21): Lookback for measuring asymmetry volatility.
Volatility Alert Level (vol_threshold, default 1.5): Z-score threshold for volatility alerts.
🎨 Visual Settings
Color Theme (color_theme, default "Starry Night"):
Van Gogh-inspired palettes:
“Starry Night”: Deep blues and yellows
“Sunflowers”: Warm yellows and browns
“Café Terrace”: Night blues and warm lights
“Wheat Field”: Golden and sky blue
Show Swirl Effects (show_swirls, default true): Adds swirling background to visualize information turbulence.
Show Signal Stars (show_stars, default true): Star markers at significant asymmetry points.
Show Info Dashboard (show_dashboard, default true): Top-right panel with current metrics and market state.
Show Flow Visualization (show_flow, default true): Main gradient line with artistic effects.
Color Schemes
Dynamic color gradients adapt to both the direction and intensity of the information gradient, using Van Gogh-inspired palettes for visual clarity and artistic flair.
Glow and aura effects: The main line is layered with glows for depth and to highlight strong signals.
Swirl background: Visualizes the “turbulence” of information flow, darker and more intense as flow strength and volatility rise.
Visual Logic
Main Gradient Line: Plots the normalized information gradient (Z-score), color-coded by direction and intensity.
Glow/Aura: Multiple layers for visual depth and to highlight strong signals.
Threshold Zones: Dotted lines and filled areas mark “Building” and “Extreme” asymmetry zones.
Volatility Ribbon: Area plot of volatility Z-score, highlighting information shocks.
Signal Stars: Circular markers at each “Extreme” event, color-coded for bullish/bearish; cross markers for volatility spikes.
Dashboard: Top-right panel shows current status (Extreme, Building, High Volatility, Balanced), gradient value, flow strength, information balance, and volatility status.
Trading Guide: Bottom-left panel explains all states and how to interpret them.
How to Use IAG
🌟 EXTREME: Major information imbalance—potential for explosive move or reversal.
🌙 BUILDING: Asymmetry is forming—watch for a breakout or trend acceleration.
🌪️ HIGH VOLATILITY: Information flow is unstable—expect regime uncertainty or “surprise” moves.
☁️ BALANCED: No clear bias—market is in equilibrium.
Positive Gradient: Bullish information flow (buyers have the edge).
Negative Gradient: Bearish information flow (sellers have the edge).
Flow >66%: Strong conviction—crowd is acting in unison.
Volatility Spike: Regime uncertainty—be alert for sudden moves.
Tips:
- Use lower periods for scalping, higher for swing trading.
- “Weighted” mode is most robust for most assets.
- Combine with price action or your own system for confirmation.
- Works on all assets and timeframes—tune to your style.
Alerts
IAG Extreme Asymmetry: Extreme information asymmetry detected.
IAG Building Flow: Information flow building.
IAG High Volatility: Information volatility spike.
IAG Bullish/Bearish Extreme: Directional extreme detected.
Originality & Usefulness
IAG is not a mashup of existing indicators. It is a novel approach to quantifying the “surprise” or “conviction” element in market moves, focusing on the efficiency and directionality of information transfer per unit of price change. The multi-layered color logic, artistic visual effects, and regime dashboard are unique to this script. IAG is designed for anticipation, not confirmation—helping you see subtle imbalances before they become obvious in price.
Chart Info
Script Name: Information Asymmetry Gradient (IAG) – Starry Night
Recommended Use: Any asset, any timeframe. Tune parameters to your style.
Disclaimer
This script is for research and educational purposes only. It does not provide financial advice or direct buy/sell signals. Always use proper risk management and combine with your own strategy. Past performance is not indicative of future results.
Trade with insight. Trade with anticipation.
— Dskyz , for DAFE Trading Systems
Reflexivity Resonance Factor (RRF) - Quantum Flow Reflexivity Resonance Factor (RRF) – Quantum Flow
See the Feedback Loops. Anticipate the Regime Shift.
What is the RRF – Quantum Flow?
The Reflexivity Resonance Factor (RRF) – Quantum Flow is a next-generation market regime detector and energy oscillator, inspired by George Soros’ theory of reflexivity and modern complexity science. It is designed for traders who want to visualize the hidden feedback loops between market perception and participation, and to anticipate explosive regime shifts before they unfold.
Unlike traditional oscillators, RRF does not just measure price momentum or volatility. Instead, it models the dynamic feedback between how the market perceives itself (perception) and how it acts on that perception (participation). When these feedback loops synchronize, they create “resonance” – a state of amplified reflexivity that often precedes major market moves.
Theoretical Foundation
Reflexivity: Markets are not just driven by external information, but by participants’ perceptions and their actions, which in turn influence future perceptions. This feedback loop can create self-reinforcing trends or sudden reversals.
Resonance: When perception and participation align and reinforce each other, the market enters a high-energy, reflexive state. These “resonance” events often mark the start of new trends or the climax of existing ones.
Energy Field: The indicator quantifies the “energy” of the market’s reflexivity, allowing you to see when the crowd is about to act in unison.
How RRF – Quantum Flow Works
Perception Proxy: Measures the rate of change in price (ROC) over a configurable period, then smooths it with an EMA. This models how quickly the market’s collective perception is shifting.
Participation Proxy: Uses a fast/slow ATR ratio to gauge the intensity of market participation (volatility expansion/contraction).
Reflexivity Core: Multiplies perception and participation to model the feedback loop.
Resonance Detection: Applies Z-score normalization to the absolute value of reflexivity, highlighting when current feedback is unusually strong compared to recent history.
Energy Calculation: Scales resonance to a 0–100 “energy” value, visualized as a dynamic background.
Regime Strength: Tracks the percentage of bars in a lookback window where resonance exceeded the threshold, quantifying the persistence of reflexive regimes.
Inputs:
🧬 Core Parameters
Perception Period (pp_roc_len, default 14): Lookback for price ROC.
Lower (5–10): More sensitive, for scalping (1–5min).
Default (14): Balanced, for 15min–1hr.
Higher (20–30): Smoother, for 4hr–daily.
Perception Smooth (pp_smooth_len, default 7): EMA smoothing for perception.
Lower (3–5): Faster, more detail.
Default (7): Balanced.
Higher (10–15): Smoother, less noise.
Participation Fast (prp_fast_len, default 7): Fast ATR for immediate volatility.
5–7: Scalping.
7–10: Day trading.
10–14: Swing trading.
Participation Slow (prp_slow_len, default 21): Slow ATR for baseline volatility.
Should be 2–4x fast ATR.
Default (21): Works with fast=7.
⚡ Signal Configuration
Resonance Window (res_z_window, default 50): Z-score lookback for resonance normalization.
20–30: More reactive.
50: Medium-term.
100+: Very stable.
Primary Threshold (rrf_threshold, default 1.5): Z-score level for “Active” resonance.
1.0–1.5: More signals.
1.5: Balanced.
2.0+: Only strong signals.
Extreme Threshold (rrf_extreme, default 2.5): Z-score for “Extreme” resonance.
2.5: Major regime shifts.
3.0+: Only the most extreme.
Regime Window (regime_window, default 100): Lookback for regime strength (% of bars with resonance spikes).
Higher: More context, slower.
Lower: Adapts quickly.
🎨 Visual Settings
Show Resonance Flow (show_flow, default true): Plots the main resonance line with glow effects.
Show Signal Particles (show_particles, default true): Circular markers at active/extreme resonance points.
Show Energy Field (show_energy, default true): Background color based on resonance energy.
Show Info Dashboard (show_dashboard, default true): Status panel with resonance metrics.
Show Trading Guide (show_guide, default true): On-chart quick reference for interpreting signals.
Color Mode (color_mode, default "Spectrum"): Visual theme for all elements.
“Spectrum”: Cyan→Magenta (high contrast)
“Heat”: Yellow→Red (heat map)
“Ocean”: Blue gradients (easy on eyes)
“Plasma”: Orange→Purple (vibrant)
Color Schemes
Dynamic color gradients are used for all plots and backgrounds, adapting to both resonance intensity and direction:
Spectrum: Cyan/Magenta for bullish/bearish resonance.
Heat: Yellow/Red for bullish, Blue/Purple for bearish.
Ocean: Blue gradients for both directions.
Plasma: Orange/Purple for high-energy states.
Glow and aura effects: The resonance line is layered with multiple glows for depth and signal strength.
Background energy field: Darker = higher energy = stronger reflexivity.
Visual Logic
Main Resonance Line: Shows the smoothed resonance value, color-coded by direction and intensity.
Glow/Aura: Multiple layers for visual depth and to highlight strong signals.
Threshold Zones: Dotted lines and filled areas mark “Active” and “Extreme” resonance zones.
Signal Particles: Circular markers at each “Active” (primary threshold) and “Extreme” (extreme threshold) event.
Dashboard: Top-right panel shows current status (Dormant, Building, Active, Extreme), resonance value, energy %, and regime strength.
Trading Guide: Bottom-right panel explains all states and how to interpret them.
How to Use RRF – Quantum Flow
Dormant (💤): Market is in equilibrium. Wait for resonance to build.
Building (🌊): Resonance is rising but below threshold. Prepare for a move.
Active (🔥): Resonance exceeds primary threshold. Reflexivity is significant—consider entries or exits.
Extreme (⚡): Resonance exceeds extreme threshold. Major regime shift likely—watch for trend acceleration or reversal.
Energy >70%: High conviction, crowd is acting in unison.
Above 0: Bullish reflexivity (positive feedback).
Below 0: Bearish reflexivity (negative feedback).
Regime Strength: % of bars in “Active” state—higher = more persistent regime.
Tips:
- Use lower lookbacks for scalping, higher for swing trading.
- Combine with price action or your own system for confirmation.
- Works on all assets and timeframes—tune to your style.
Alerts
RRF Activation: Resonance crosses above primary threshold.
RRF Extreme: Resonance crosses above extreme threshold.
RRF Deactivation: Resonance falls below primary threshold.
Originality & Usefulness
RRF – Quantum Flow is not a mashup of existing indicators. It is a novel oscillator that models the feedback loop between perception and participation, then quantifies and visualizes the resulting resonance. The multi-layered color logic, energy field, and regime strength dashboard are unique to this script. It is designed for anticipation, not confirmation—helping you see regime shifts before they are obvious in price.
Chart Info
Script Name: Reflexivity Resonance Factor (RRF) – Quantum Flow
Recommended Use: Any asset, any timeframe. Tune parameters to your style.
Disclaimer
This script is for research and educational purposes only. It does not provide financial advice or direct buy/sell signals. Always use proper risk management and combine with your own strategy. Past performance is not indicative of future results.
Trade with insight. Trade with anticipation.
— Dskyz , for DAFE Trading Systems
Tangent Extrapolation ForecastTangent Extrapolation Forecast
This indicator visually projects price direction by drawing a smoothed sequence of tangent lines based on recent price movements. For each bar in a user-defined lookback window, it calculates the slope over a smoothing period and extends the projected price forward. The resulting polyline forecast connect the endpoints of the extrapolations, and is color-coded to reflect directional changes: green for upward moves, red for downward, and gray for flat segments. This tool can assist traders in visualizing short-term momentum and potential trend continuity without introducing artificial future gaps.
Inputs:
Bars to Use: Number of historical bars used in the forecast.
Slope Smoothing Window: The number of bars used to calculate slope for projection.
Source: Price input for calculations (default is close).
This indicator does not generate buy/sell signals. It is intended as a visual aid to support discretionary analysis.
Inside 4+ Candles Box (Entry + Target + SMA Stop Logic)🔍 What This Script Does
This indicator detects price compression areas using 4 or more consecutive inside candles, then draws a breakout box to visually highlight the range.
Once price closes above the box, a long entry marker is plotted, along with:
🎯 Target line at 1x box size above the breakout.
❌ Stop-loss at the box low or at a dynamic SMA-based level if the box is too large.
🧠 Why It’s Unique
This script combines inside bar compression, breakout logic, risk control, and visual clarity — all in one tool.
It also cancels the setup entirely if price closes below the box low before breakout, avoiding late or false entries.
⚙️ Customizable Settings
Minimum inside candles (default = 4)
SMA length (used as stop if box is large)
Box size % threshold to activate smart stop
Entry, Target, and Stop marker colors
📌 Notes
For long setups only (no short signals).
Use on any asset or timeframe (ideal on 4H/1D).
This is not financial advice. Use with proper risk management.
Backtest thoroughly before live use.
Built with ❤️ by using Pine Script v6.
🇸🇦 وصف مختصر باللغة العربية:
هذا المؤشر يكتشف مناطق تماسك السعر من خلال 4 شموع داخلية أو أكثر، ثم يرسم مربعًا يحدد منطقة الاختراق المحتملة.
عند الإغلاق أعلى المربع، يتم عرض إشارة دخول وسطر هدف بنسبة 100% من حجم المربع.
كما يتم احتساب وقف الخسارة تلقائيًا إما عند قاع المربع أو عند متوسط متحرك ذكي (SMA) إذا كان حجم المربع كبيرًا.
الميزة الإضافية: إذا تم كسر قاع المربع قبل الاختراق، يتم إلغاء الصفقة تلقائيًا لتجنب الدخول المتأخر.
🧪 للاستفادة التعليمية والتحليل فقط. لا يُعتبر توصية مالية.
Failure Swing IndicatorIdentify Failure Swing nice and easy
J. Welles Wilder Jr. describes Failure Swings as specific chart patterns used in conjunction with the Relative Strength Index (RSI) to identify potential reversals in price trends.
These patterns signal weakening momentum and can indicate a shift in market direction
Wilder emphasized that these patterns are more reliable when confirmed by price action or other technical indicators.
EMA Pullback Indicator with Volume Confirmationvolume analysis that follows momentum and only enters on pullbacks. Exit at end of next candle
Engulfing DetectorThis script detects classic candlestick reversal patterns known as Engulfing formations:
Bullish Engulfing: A green candle fully engulfs the previous red candle.
Bearish Engulfing: A red candle fully engulfs the previous green candle.
🔎 Features:
Works on any time frame or instrument.
Optional filter to ignore overly large or irregular candles.
Visual signals on the chart (BE/SE labels).
Built-in alerts for automation or notification.
✅ Recommended usage:
For intraday trading, this indicator performs best on the 5-minute chart of the Nasdaq (NQ) between 9:45 AM and 1:00 PM ET (15:45–19:00 CET).
💡 Suggested trading approach:
Optimized for scalping with short-term trades and small take-profits around +0.10%.
Math by Thomas Swing RangeMath by Thomas Swing Range is a simple yet powerful tool designed to visually highlight key swing levels in the market based on a user-defined lookback period. It identifies the highest high, lowest low, and calculates the midpoint between them — creating a clear range for swing trading strategies.
These levels can help traders:
Spot potential support and resistance zones
Analyze price rejection near range boundaries
Frame mean-reversion or breakout setups
The indicator continuously updates and extends these lines into the future, making it easier to plan and manage trades with visual clarity.
🛠️ How to Use
Add to Chart:
Apply the indicator on any timeframe and asset (works best on higher timeframes like 1H, 4H, or Daily).
Configure Parameters:
Lookback Period: Number of candles used to detect the highest high and lowest low. Default is 20.
Extend Lines by N Bars: Number of future bars the levels should be projected to the right.
Interpret Lines:
🔴 Red Line: Swing High (Resistance)
🟢 Green Line: Swing Low (Support)
🔵 Blue Line: Midpoint (Mean level — useful for equilibrium-based strategies)
Trade Ideas:
Bounce trades from swing high/low zones.
Breakout confirmation if price closes strongly outside the range.
Reversion trades if price moves toward the midpoint after extreme moves.
Bollinger Bands - Multi Symbol Alert (Miu)This script extends the classic Bollinger Bands indicator with support for up to 8 user-defined symbols and a unique alert system.
Unlike traditional Bollinger Band indicators, it allows traders to configure alerts across multiple assets without keeping the indicator visible on the chart, making it ideal for passive multi-asset monitoring.
What it does:
This script calculates Bollinger Bands using a 100-period simple moving average and a standard deviation multiplier of 3 (or any input you set in the settings panel).
For each selected symbol, the upper and lower bands are retrieved using request.security() and monitored for breakouts.
Alerts are triggered when the closing price of the selected symbol breaks above the upper band (Overbought) or below the lower band (Oversold) — at the bar close.
How to use it:
1) Add the indicator to your chart.
2) Open the settings panel.
3) Select up to 8 symbols to monitor.
4) After setting parameters, click the three dots next to the indicator title and choose "Add Alert on...".
5) Name your alert and confirm.
6) If you don’t wish to keep the indicator visible, you can remove it from the chart — alerts will still function as expected.
Alert message includes:
- Symbol name (e.g., BTC, ETH, LTC)
- (OB) for overbought or (OS) for oversold
- Symbol’s price at the alert moment
Technical note:
This script uses request.security() to fetch Bollinger Band levels and closing prices from up to 8 selected symbols in real time.
Feel free to leave your feedback or suggestions in the comments section below.
Enjoy!
Spectral Order Flow Resonance (SOFR) Spectral Order Flow Resonance (SOFR)
See the Market’s Hidden Rhythms—Trade the Resonance, Not the Noise!
The Spectral Order Flow Resonance (SOFR) is a next-generation tool for traders who want to go beyond price and volume, tapping into the underlying “frequency signature” of order flow itself. Instead of chasing lagging signals or reacting to surface-level volatility, SOFR lets you visualize and quantify the real-time resonance of market activity—helping you spot when the crowd is in sync, and when the regime is about to shift.
What Makes SOFR Unique?
Not Just Another Oscillator:
SOFR doesn’t just measure momentum or volume. It applies spectral analysis (using Fast Fourier Transform) to normalized order flow, extracting the dominant cycles and their resonance strength. This reveals when the market is harmonizing around key frequencies—often the precursor to major moves.
Regime Detection, Not Guesswork:
By tracking harmonic alignment and phase coherence across multiple Fibonacci-based frequencies, SOFR identifies when the market is entering a bullish, bearish, or neutral resonance regime. This is visualized with a dynamic dashboard and info line, so you always know the current state at a glance.
Dynamic Dashboard:
The on-chart dashboard color-codes each key metric—regime, dominant frequency, harmonic alignment, phase coherence, and energy concentration—so you can instantly gauge the strength and direction of the current resonance. No more guesswork or clutter.
Universal Application:
Works on any asset, any timeframe, and in any market—futures, stocks, crypto, forex. If there’s order flow, SOFR can reveal its hidden structure.
How Does It Work?
Order Flow Normalization:
SOFR calculates the net buying/selling pressure and normalizes it using a rolling mean and standard deviation, making the signal robust across assets and timeframes.
Spectral Analysis:
The script applies FFT to the normalized order flow, extracting the magnitude and phase of several key frequencies (typically Fibonacci numbers). This allows you to see which cycles are currently dominating the market.
Resonance & Regime Logic:
When multiple frequencies align and exceed a dynamic resonance threshold, and phase coherence is high, SOFR detects a “resonance regime”—bullish, bearish, or neutral. This is when the market is most likely to experience a strong, sustained move.
Visual Clarity:
The indicator plots each frequency’s magnitude, highlights the dominant one, and provides a real-time dashboard with color-coded metrics for instant decision-making.
SOFR Dashboard Metrics Explained
Regime:
What it means: The current “state” of the market as detected by SOFR—Bullish, Bearish, or Neutral.
Why it matters: The regime tells you whether the market’s order flow is resonating in a way that favors upward moves (Bullish), downward moves (Bearish), or is out of sync (Neutral). This helps you align your trades with the prevailing market force, or stand aside when there’s no clear edge.
Dominant Freq:
What it means: The most powerful frequency (cycle length, in bars) currently detected in the order flow.
Why it matters: Markets often move in cycles. The dominant frequency shows which cycle is currently driving price action, helping you time entries and exits with the market’s “heartbeat.”
Harmonic Align:
What it means: The number of key frequencies (out of 3) that are currently in resonance (above threshold).
Why it matters: When multiple frequencies align, it signals that different groups of traders (with different time horizons) are acting in concert. This increases the probability of a strong, sustained move.
Phase Coh.:
What it means: A measure (0–100%) of how “in sync” the phases of the key frequencies are.
Why it matters: High phase coherence means the market’s cycles are reinforcing each other, not cancelling out. This is a classic signature of trending or explosive moves.
Energy Conc.:
What it means: The concentration of spectral energy in the dominant frequency, relative to the average.
Why it matters: High energy concentration means the market’s activity is focused in one cycle, increasing the odds of a decisive move. Low concentration means the market is scattered and less predictable.
How to Use
Bullish Regime:
When the dashboard shows a green regime and high harmonic alignment, the market is in a bullish resonance—look for long opportunities or trend continuations.
Bearish Regime:
When the regime is red and alignment is high, the market is in a bearish resonance—look for short opportunities or trend continuations.
Neutral Regime:
When the regime is gray or alignment is low, the market is out of sync—consider waiting for clearer signals or using other tools.
Combine with Your Strategy:
Use SOFR as a confirmation tool, a filter for trend/range conditions, or as a standalone regime detector. The dashboard’s color-coded metrics help you instantly spot when the market is entering or exiting resonance.
Inputs Explained
FFT Window Length :
Controls the number of bars used for spectral analysis. Higher values smooth the signal, lower values make it more sensitive.
Order Flow Period:
Sets the lookback for normalizing order flow. Shorter periods react faster, longer periods are smoother.
Fibonacci Frequencies:
Choose which cycles to analyze. Default values (5, 8, 13) capture common market rhythms.
Resonance Threshold:
Sets how strong a frequency’s signal must be to count as “in resonance.” Lower for more signals, higher for stricter filtering.
Signal Smoothing & Amplify:
Fine-tune the display for your chart and asset.
Dashboard & Info Line Toggles:
Show or hide the on-chart dashboard and info line as needed.
Why This Matters
Most indicators show you what just happened. SOFR shows you when the market is entering a state of resonance—when crowd behavior is most likely to produce powerful, sustained moves. By visualizing the hidden structure of order flow, you gain a tactical edge over traders who only see the surface.
For educational purposes only. Not financial advice. Always use proper risk management.
Use with discipline. Trade your edge.
— Dskyz, for DAFE Trading Systems
FVG (Nephew sam remake)Hello i am making my own FVG script inspired by Nephew Sam as his fvg code is not open source. My goal is to replicate his Script and then add in alerts and more functions. Thus, i spent few days trying to code. There is bugs such as lower time frame not showing higher time frame FVG.
This script automatically detects and visualizes Fair Value Gaps (FVGs) — imbalances between demand and supply — across multiple timeframes (15-minute, 1-hour, and 4-hour).
15m chart shows:
15m FVGs (green/red boxes)
1H FVGs (lime/maroon)
4H FVGs (faded green/red with borders) (Bugged For now i only see 1H appearing)
1H chart shows:
1H FVGs
4H FVGs
4H chart shows:
4H FVGs only
There is the function to auto close FVG when a future candle fully disrespected it.
You're welcome to:
🔧 Customize the appearance: adjust box colors, transparency, border style
🧪 Add alerts: e.g., when price enters or fills a gap
📅 Expand to Daily/Weekly: just copy the logic and plug in "D" or "W" as new layers
📈 Build confluence logic: combine this with order blocks, liquidity zones, or ICT concepts
🧠 Experiment with entry signals: e.g., candle confirmation on return to FVG
🚀 Improve performance: if you find a lighter way to track gaps, feel free to optimize!
MACD Crossover with Price Action and AlertsThe MACD should use the default parameters (12, 26, 9) for fast EMA, slow EMA, and signal EMA, respectively, applied to the Close price. Instead of simple MACD crossovers, the indicator should analyze price action in relation to the MACD histogram to generate signals. Specifically: 1. BUY signal: Generate a buy signal (an up arrow displayed below the low of the signal bar in green color) when the MACD histogram crosses above zero AND the price action shows a bullish engulfing pattern (the current candle's body completely engulfs the previous candle's body). 2. SELL signal: Generate a sell signal (a down arrow displayed above the high of the signal bar in red color) when the MACD histogram crosses below zero AND the price action shows a bearish engulfing pattern (the current candle's body completely engulfs the previous candle's body). The arrows should be non-repainting, meaning that once an arrow is plotted on a bar, it should not disappear or change position as the chart updates. The indicator should also plot the MACD line, signal line, and histogram using their default calculations. The MACD line should be blue, the signal line should be orange, and the histogram should be displayed using green bars for positive values and red bars for negative values. The indicator should also have customizable inputs for the MACD fast EMA period, slow EMA period, signal EMA period and engulfing pattern check enabled/disabled. If engulfing pattern check disabled, the indicator will generate signals based only on MACD histogram crossing zero.
Price/MA Deviation AngleThis indicator visualizes the angular deviation of price from a selected moving average (default: 21 EMA). It calculates the angle, in degrees, formed by the vertical distance between price and the moving average — assuming a one-bar horizontal distance.
Positive angles indicate upward deviation (bullish pressure).
Negative angles reflect downward deviation (bearish pressure).
0° represents perfect alignment between price and the MA.
±45° thresholds can be used as reference for strong momentum.
This tool offers a normalized, intuitive perspective on price momentum using geometric interpretation rather than price-to-price delta.
Dual Bollinger BandsIndicator Name:
Double Bollinger Bands (2-9 & 2-20)
Description:
This indicator plots two sets of Bollinger Bands on a single chart for enhanced volatility and trend analysis:
Fast Bands (2-9 Length) – Voilet
More responsive to short-term price movements.
Useful for spotting quick reversals or scalping opportunities.
Slow Bands (2-20 Length) – Black
Smoother, trend-following bands for longer-term context.
Helps confirm broader market direction.
Both bands use the standard settings (2 deviations, SMA basis) for consistency. The transparent fills improve visual clarity while keeping the chart uncluttered.
Use Cases:
Trend Confirmation: When both bands expand together, it signals strong momentum.
Squeeze Alerts: A tight overlap suggests low volatility before potential breakouts.
Multi-Timeframe Analysis: Compare short-term vs. long-term volatility in one view.
How to Adjust:
Modify lengths (2-9 and 2-20) in the settings.
Change colors or transparency as needed.
Why Use This Script?
No Repainting – Uses standard Pine Script functions for reliability.
Customizable – Easy to tweak for different trading styles.
Clear Visuals – Color-coded bands with background fills for better readability.
Ideal For:
Swing traders, day traders, and volatility scalpers.
Combining short-term and long-term Bollinger Band strategies.
Bear Market Probability Model# Bear Market Probability Model: A Multi-Factor Risk Assessment Framework
The Bear Market Probability Model represents a comprehensive quantitative framework for assessing systemic market risk through the integration of 13 distinct risk factors across four analytical categories: macroeconomic indicators, technical analysis factors, market sentiment measures, and market breadth metrics. This indicator synthesizes established financial research methodologies to provide real-time probabilistic assessments of impending bear market conditions, offering institutional-grade risk management capabilities to retail and professional traders alike.
## Theoretical Foundation
### Historical Context of Bear Market Prediction
Bear market prediction has been a central focus of financial research since the seminal work of Dow (1901) and the subsequent development of technical analysis theory. The challenge of predicting market downturns gained renewed academic attention following the market crashes of 1929, 1987, 2000, and 2008, leading to the development of sophisticated multi-factor models.
Fama and French (1989) demonstrated that certain financial variables possess predictive power for stock returns, particularly during market stress periods. Their three-factor model laid the groundwork for multi-dimensional risk assessment, which this indicator extends through the incorporation of real-time market microstructure data.
### Methodological Framework
The model employs a weighted composite scoring methodology based on the theoretical framework established by Campbell and Shiller (1998) for market valuation assessment, extended through the incorporation of high-frequency sentiment and technical indicators as proposed by Baker and Wurgler (2006) in their seminal work on investor sentiment.
The mathematical foundation follows the general form:
Bear Market Probability = Σ(Wi × Ci) / ΣWi × 100
Where:
- Wi = Category weight (i = 1,2,3,4)
- Ci = Normalized category score
- Categories: Macroeconomic, Technical, Sentiment, Breadth
## Component Analysis
### 1. Macroeconomic Risk Factors
#### Yield Curve Analysis
The inclusion of yield curve inversion as a primary predictor follows extensive research by Estrella and Mishkin (1998), who demonstrated that the term spread between 3-month and 10-year Treasury securities has historically preceded all major recessions since 1969. The model incorporates both the 2Y-10Y and 3M-10Y spreads to capture different aspects of monetary policy expectations.
Implementation:
- 2Y-10Y Spread: Captures market expectations of monetary policy trajectory
- 3M-10Y Spread: Traditional recession predictor with 12-18 month lead time
Scientific Basis: Harvey (1988) and subsequent research by Ang, Piazzesi, and Wei (2006) established the theoretical foundation linking yield curve inversions to economic contractions through the expectations hypothesis of the term structure.
#### Credit Risk Premium Assessment
High-yield credit spreads serve as a real-time gauge of systemic risk, following the methodology established by Gilchrist and Zakrajšek (2012) in their excess bond premium research. The model incorporates the ICE BofA High Yield Master II Option-Adjusted Spread as a proxy for credit market stress.
Threshold Calibration:
- Normal conditions: < 350 basis points
- Elevated risk: 350-500 basis points
- Severe stress: > 500 basis points
#### Currency and Commodity Stress Indicators
The US Dollar Index (DXY) momentum serves as a risk-off indicator, while the Gold-to-Oil ratio captures commodity market stress dynamics. This approach follows the methodology of Akram (2009) and Beckmann, Berger, and Czudaj (2015) in analyzing commodity-currency relationships during market stress.
### 2. Technical Analysis Factors
#### Multi-Timeframe Moving Average Analysis
The technical component incorporates the well-established moving average convergence methodology, drawing from the work of Brock, Lakonishok, and LeBaron (1992), who provided empirical evidence for the profitability of technical trading rules.
Implementation:
- Price relative to 50-day and 200-day simple moving averages
- Moving average convergence/divergence analysis
- Multi-timeframe MACD assessment (daily and weekly)
#### Momentum and Volatility Analysis
The model integrates Relative Strength Index (RSI) analysis following Wilder's (1978) original methodology, combined with maximum drawdown analysis based on the work of Magdon-Ismail and Atiya (2004) on optimal drawdown measurement.
### 3. Market Sentiment Factors
#### Volatility Index Analysis
The VIX component follows the established research of Whaley (2009) and subsequent work by Bekaert and Hoerova (2014) on VIX as a predictor of market stress. The model incorporates both absolute VIX levels and relative VIX spikes compared to the 20-day moving average.
Calibration:
- Low volatility: VIX < 20
- Elevated concern: VIX 20-25
- High fear: VIX > 25
- Panic conditions: VIX > 30
#### Put-Call Ratio Analysis
Options flow analysis through put-call ratios provides insight into sophisticated investor positioning, following the methodology established by Pan and Poteshman (2006) in their analysis of informed trading in options markets.
### 4. Market Breadth Factors
#### Advance-Decline Analysis
Market breadth assessment follows the classic work of Fosback (1976) and subsequent research by Brown and Cliff (2004) on market breadth as a predictor of future returns.
Components:
- Daily advance-decline ratio
- Advance-decline line momentum
- McClellan Oscillator (Ema19 - Ema39 of A-D difference)
#### New Highs-New Lows Analysis
The new highs-new lows ratio serves as a market leadership indicator, based on the research of Zweig (1986) and validated in academic literature by Zarowin (1990).
## Dynamic Threshold Methodology
The model incorporates adaptive thresholds based on rolling volatility and trend analysis, following the methodology established by Pagan and Sossounov (2003) for business cycle dating. This approach allows the model to adjust sensitivity based on prevailing market conditions.
Dynamic Threshold Calculation:
- Warning Level: Base threshold ± (Volatility × 1.0)
- Danger Level: Base threshold ± (Volatility × 1.5)
- Bounds: ±10-20 points from base threshold
## Professional Implementation
### Institutional Usage Patterns
Professional risk managers typically employ multi-factor bear market models in several contexts:
#### 1. Portfolio Risk Management
- Tactical Asset Allocation: Reducing equity exposure when probability exceeds 60-70%
- Hedging Strategies: Implementing protective puts or VIX calls when warning thresholds are breached
- Sector Rotation: Shifting from growth to defensive sectors during elevated risk periods
#### 2. Risk Budgeting
- Value-at-Risk Adjustment: Incorporating bear market probability into VaR calculations
- Stress Testing: Using probability levels to calibrate stress test scenarios
- Capital Requirements: Adjusting regulatory capital based on systemic risk assessment
#### 3. Client Communication
- Risk Reporting: Quantifying market risk for client presentations
- Investment Committee Decisions: Providing objective risk metrics for strategic decisions
- Performance Attribution: Explaining defensive positioning during market stress
### Implementation Framework
Professional traders typically implement such models through:
#### Signal Hierarchy:
1. Probability < 30%: Normal risk positioning
2. Probability 30-50%: Increased hedging, reduced leverage
3. Probability 50-70%: Defensive positioning, cash building
4. Probability > 70%: Maximum defensive posture, short exposure consideration
#### Risk Management Integration:
- Position Sizing: Inverse relationship between probability and position size
- Stop-Loss Adjustment: Tighter stops during elevated risk periods
- Correlation Monitoring: Increased attention to cross-asset correlations
## Strengths and Advantages
### 1. Comprehensive Coverage
The model's primary strength lies in its multi-dimensional approach, avoiding the single-factor bias that has historically plagued market timing models. By incorporating macroeconomic, technical, sentiment, and breadth factors, the model provides robust risk assessment across different market regimes.
### 2. Dynamic Adaptability
The adaptive threshold mechanism allows the model to adjust sensitivity based on prevailing volatility conditions, reducing false signals during low-volatility periods and maintaining sensitivity during high-volatility regimes.
### 3. Real-Time Processing
Unlike traditional academic models that rely on monthly or quarterly data, this indicator processes daily market data, providing timely risk assessment for active portfolio management.
### 4. Transparency and Interpretability
The component-based structure allows users to understand which factors are driving risk assessment, enabling informed decision-making about model signals.
### 5. Historical Validation
Each component has been validated in academic literature, providing theoretical foundation for the model's predictive power.
## Limitations and Weaknesses
### 1. Data Dependencies
The model's effectiveness depends heavily on the availability and quality of real-time economic data. Federal Reserve Economic Data (FRED) updates may have lags that could impact model responsiveness during rapidly evolving market conditions.
### 2. Regime Change Sensitivity
Like most quantitative models, the indicator may struggle during unprecedented market conditions or structural regime changes where historical relationships break down (Taleb, 2007).
### 3. False Signal Risk
Multi-factor models inherently face the challenge of balancing sensitivity with specificity. The model may generate false positive signals during normal market volatility periods.
### 4. Currency and Geographic Bias
The model focuses primarily on US market indicators, potentially limiting its effectiveness for global portfolio management or non-USD denominated assets.
### 5. Correlation Breakdown
During extreme market stress, correlations between risk factors may increase dramatically, reducing the model's diversification benefits (Forbes and Rigobon, 2002).
## References
Akram, Q. F. (2009). Commodity prices, interest rates and the dollar. Energy Economics, 31(6), 838-851.
Ang, A., Piazzesi, M., & Wei, M. (2006). What does the yield curve tell us about GDP growth? Journal of Econometrics, 131(1-2), 359-403.
Baker, M., & Wurgler, J. (2006). Investor sentiment and the cross‐section of stock returns. The Journal of Finance, 61(4), 1645-1680.
Baker, S. R., Bloom, N., & Davis, S. J. (2016). Measuring economic policy uncertainty. The Quarterly Journal of Economics, 131(4), 1593-1636.
Barber, B. M., & Odean, T. (2001). Boys will be boys: Gender, overconfidence, and common stock investment. The Quarterly Journal of Economics, 116(1), 261-292.
Beckmann, J., Berger, T., & Czudaj, R. (2015). Does gold act as a hedge or a safe haven for stocks? A smooth transition approach. Economic Modelling, 48, 16-24.
Bekaert, G., & Hoerova, M. (2014). The VIX, the variance premium and stock market volatility. Journal of Econometrics, 183(2), 181-192.
Brock, W., Lakonishok, J., & LeBaron, B. (1992). Simple technical trading rules and the stochastic properties of stock returns. The Journal of Finance, 47(5), 1731-1764.
Brown, G. W., & Cliff, M. T. (2004). Investor sentiment and the near-term stock market. Journal of Empirical Finance, 11(1), 1-27.
Campbell, J. Y., & Shiller, R. J. (1998). Valuation ratios and the long-run stock market outlook. The Journal of Portfolio Management, 24(2), 11-26.
Dow, C. H. (1901). Scientific stock speculation. The Magazine of Wall Street.
Estrella, A., & Mishkin, F. S. (1998). Predicting US recessions: Financial variables as leading indicators. Review of Economics and Statistics, 80(1), 45-61.
Fama, E. F., & French, K. R. (1989). Business conditions and expected returns on stocks and bonds. Journal of Financial Economics, 25(1), 23-49.
Forbes, K. J., & Rigobon, R. (2002). No contagion, only interdependence: measuring stock market comovements. The Journal of Finance, 57(5), 2223-2261.
Fosback, N. G. (1976). Stock market logic: A sophisticated approach to profits on Wall Street. The Institute for Econometric Research.
Gilchrist, S., & Zakrajšek, E. (2012). Credit spreads and business cycle fluctuations. American Economic Review, 102(4), 1692-1720.
Harvey, C. R. (1988). The real term structure and consumption growth. Journal of Financial Economics, 22(2), 305-333.
Kahneman, D., & Tversky, A. (1979). Prospect theory: An analysis of decision under risk. Econometrica, 47(2), 263-291.
Magdon-Ismail, M., & Atiya, A. F. (2004). Maximum drawdown. Risk, 17(10), 99-102.
Nickerson, R. S. (1998). Confirmation bias: A ubiquitous phenomenon in many guises. Review of General Psychology, 2(2), 175-220.
Pagan, A. R., & Sossounov, K. A. (2003). A simple framework for analysing bull and bear markets. Journal of Applied Econometrics, 18(1), 23-46.
Pan, J., & Poteshman, A. M. (2006). The information in option volume for future stock prices. The Review of Financial Studies, 19(3), 871-908.
Taleb, N. N. (2007). The black swan: The impact of the highly improbable. Random House.
Whaley, R. E. (2009). Understanding the VIX. The Journal of Portfolio Management, 35(3), 98-105.
Wilder, J. W. (1978). New concepts in technical trading systems. Trend Research.
Zarowin, P. (1990). Size, seasonality, and stock market overreaction. Journal of Financial and Quantitative Analysis, 25(1), 113-125.
Zweig, M. E. (1986). Winning on Wall Street. Warner Books.
Multi-Session ORBThe Multi-Session ORB Indicator is a customizable Pine Script (version 6) tool designed for TradingView to plot Opening Range Breakout (ORB) levels across four major trading sessions: Sydney, Tokyo, London, and New York. It allows traders to define specific ORB durations and session times in Central Daylight Time (CDT), making it adaptable to various trading strategies.
Key Features:
1. Customizable ORB Duration: Users can set the ORB duration (default: 15 minutes) via the inputMax parameter, determining the time window for calculating the high and low of each session’s opening range.
2. Flexible Session Times: The indicator supports user-defined session and ORB times for:
◦ Sydney: Default ORB (17:00–17:15 CDT), Session (17:00–01:00 CDT)
◦ Tokyo: Default ORB (19:00–19:15 CDT), Session (19:00–04:00 CDT)
◦ London: Default ORB (02:00–02:15 CDT), Session (02:00–11:00 CDT)
◦ New York: Default ORB (08:30–08:45 CDT), Session (08:30–16:00 CDT)
3. Session-Specific ORB Levels: For each session, the indicator calculates and tracks the high and low prices during the specified ORB period. These levels are updated dynamically if new highs or lows occur within the ORB timeframe.
4. Visual Representation:
◦ ORB high and low lines are plotted only during their respective session times, ensuring clarity.
◦ Each session’s lines are color-coded for easy identification:
▪ Sydney: Light Yellow (high), Dark Yellow (low)
▪ Tokyo: Light Pink (high), Dark Pink (low)
▪ London: Light Blue (high), Dark Blue (low)
▪ New York: Light Purple (high), Dark Purple (low)
◦ Lines are drawn with a linewidth of 2 and disappear when the session ends or if the timeframe is not intraday (or exceeds the ORB duration).
5. Intraday Compatibility: The indicator is optimized for intraday timeframes (e.g., 1-minute to 15-minute charts) and only displays when the chart’s timeframe multiplier is less than or equal to the ORB duration.
How It Works:
• Session Detection: The script uses the time() function to check if the current bar falls within the user-defined ORB or session time windows, accounting for all days of the week.
• ORB Logic: At the start of each session’s ORB period, the script initializes the high and low based on the first bar’s prices. It then updates these levels if subsequent bars within the ORB period exceed the current high or fall below the current low.
• Plotting: ORB levels are plotted as horizontal lines during the respective session, with visibility controlled to avoid clutter outside session times or on incompatible timeframes.
Use Case:
Traders can use this indicator to identify key breakout levels for each trading session, facilitating strategies based on price action around the opening range. The flexibility to adjust ORB and session times makes it suitable for various markets (e.g., forex, stocks, or futures) and time zones.
Limitations:
• The indicator is designed for intraday timeframes and may not display on higher timeframes (e.g., daily or weekly) or if the timeframe multiplier exceeds the ORB duration.
• Time inputs are in CDT, requiring users to adjust for their local timezone or market requirements.
• If you need to use this for GC/CL/SPY/QQQ you have to adjust the times by one hour.
This indicator is ideal for traders focusing on session-based breakout strategies, offering clear visualization and customization for global market sessions.
Bitcoin Open Interest [SAKANE]Bitcoin Open Interest
— Unveiling the True Flow of Capital
PurposeVisualize and compare Bitcoin open interest (OI) from CME and Binance, the leading derivatives exchanges, in a single intuitive chart, providing traders with clear insights into crypto market capital dynamics.
Background & MotivationIn the 24/7 crypto market, price movements alone reveal only part of the story. Open interest (OI)—the total outstanding futures contracts—offers critical clues to the market’s next move. Yet, accessing and interpreting OI data is challenging:
CME Constraints: Commitment of Traders (COT) reports are weekly, and standalone BTC1! or BTC2! OI is noisy due to contract rollovers, obscuring true OI changes.
Existing Tool Limitations: Most OI indicators are fixed to either USD or BTC, limiting flexible analysis.
This indicator overcomes these hurdles, enabling seamless comparison of CME and Binance OI to track the market’s “capital center of gravity” in real time.
Key Features
Synthetic CME OI: Combines BTC1! and BTC2! to deliver high-accuracy OI, eliminating rollover noise.
Multi-Timeframe Analysis: Displays daily CME OI as pseudo-candlestick (OHLC) on any timeframe (e.g., 4H), allowing intuitive capital flow tracking across timeframes.
CME/Binance One-Click Toggle: Instantly compare institutional-driven CME and retail-driven Binance OI.
USD/BTC Flexibility: Switch between BTC (real demand) and USD (margin) perspectives for OI analysis.
Robust Design: Concise, global-scope code ensures stability and adaptability to TradingView updates.
Insights & Use Cases
Holistic Market Sentiment: Analyze capital flows by region and exchange for a multidimensional view.
Signal Detection: E.g., a sharp drop in CME OI during a sell-off may signal institutional withdrawal.
Retail Trends: A surge in Binance OI suggests retail-driven inflows.
Event-Driven Insights: E.g., during a hypothetical April 2025 “Trump Tariff Shock,” instantly identify which exchange drives capital shifts.
Unique ValueUnlike price-centric indicators, this tool focuses on capital flow (OI). It’s the only indicator offering one-click multi-timeframe and multi-exchange OI comparison, empowering traders to uncover the market’s “true intent” and gain a strategic edge.
ConclusionBitcoin Open Interest makes the market’s hidden capital movements accessible to all. By capturing market dynamics and pinpointing the “leading forces” during events, it sets a new standard for traders seeking a revolutionary perspective.
GCM Centre Line Candle MarkerGCM Centre Line Candle Marker (GCM-CLCM) - Descriptive Notes
Indicator Overview:
The "GCM Centre Line Candle Marker" is a versatile TradingView overlay indicator designed to enhance chart analysis by drawing short horizontal lines at user-defined "centre" points of candles. These lines provide a quick visual reference to key price levels within each candle, such as midpoints, open, close, or typical prices. The indicator offers extensive customization for line appearance, positioning, and conditional display, including an option to highlight only bullish engulfing patterns.
Key Features:
1. Customizable Line Position:
o Users can choose from various methods to calculate the "centre" price for the line:
(High + Low) / 2 (Default)
(Open + Close) / 2
Close
Open
(Open + High + Low + Close) / 4 (HLCO/4)
(Open + High + Close) / 3 (Typical Price HLC/3 variation)
(Open + Close + Low) / 3 (Typical Price OCL/3 variation)
2. Line Appearance Customization:
o Visibility: Toggle lines on/off.
o Style: Solid, dotted, or dashed lines.
o Width: Adjustable line thickness (1 to 5).
o Length: Defines how many candles forward the line extends (1 to 10).
o Color: Lines are colored based on candle type (bullish/bearish), with user-selectable base colors.
o Dynamic Opacity: Line opacity is dynamically adjusted based on the candle's size relative to recent candles. Larger candles produce more opaque lines (up to the user-defined maximum opacity), while smaller candles result in more transparent lines. This helps significant candles stand out.
3. Price Labels:
o Show Labels: Option to display price labels at the end of each center line.
o Label Background Color: Customizable.
o Dynamic Text Color: Label text color can change based on the movement of the center price:
Green: Current center price is higher than the previous.
Red: Current center price is lower than the previous.
Gray: No change or first label.
o Static Text Color: Alternatively, a fixed color can be used for all labels.
4. Conditional Drawing - Bullish Engulfing Filter:
o Users can enable an option to Only Show Bullish Engulfing Candles. When active, center lines will only be drawn for candles that meet bullish engulfing criteria (current bull candle's body engulfs the previous bear candle's body).
5. Performance Management:
o Max Lines to Show: Limits the number of historical lines displayed on the chart to maintain clarity and performance. Older lines are automatically removed as new ones are drawn.
6. Alert Condition:
o Includes a built-in alert: Big Bullish Candle. This alert triggers when a bullish candle's range (high - low) is greater than the 20-period simple moving average (SMA) of candle ranges.
How It Works:
• For each new candle, the script calculates the "center" price based on the user's Line Position selection.
• If showLines is enabled and (if applicable) the bullish engulfing condition is met, a new line is drawn from the current candle's bar_index at the calculated _center price, extending lineLength candles forward.
• The line's color is determined by whether the candle is bullish (close > open) or bearish (close < open).
• Opacity is calculated dynamically: scaledOpacity = int((100 - maxUserOpacity) * (1 - dynamicFactor) + maxUserOpacity), where dynamicFactor is candleSize / maxSize (current candle size relative to the max size in the last 20 candles). This means maxUserOpacity is the least transparent the line will be (for the largest candles), and smaller candles will have lines approaching full transparency.
• Optional price labels are added at the end of these lines.
• The script manages an array of drawn lines, removing the oldest ones if the maxLines limit is exceeded.
Potential Use Cases:
• Visualizing Intra-Candle Levels: Quickly see midpoints or other key price points without manual drawing.
• Short-Term Reference Points: The extended lines can act as very short-term dynamic support/resistance or points of interest.
• Pattern Recognition: Highlight bullish engulfing patterns or simply emphasize candles based on their calculated center.
• Volatility Indication: The dynamic opacity can subtly indicate periods of larger or smaller candle ranges.
• Confirmation Tool: Use in conjunction with other indicators or trading strategies.
User Input Groups:
• Line Settings: Controls all aspects of the line's appearance and calculation.
• Label Settings: Manages the display and appearance of price labels.
• Other Settings: Contains options for line management and conditional filtering (like Bullish Engulfing).
This indicator provides a clean and customizable way to mark significant price levels within candles, aiding traders in their technical analysis.