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.
Fundamental Analysis
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.
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.
Dinamik Trend (EMA Ribbon)Dynamic Trend Identification (EMA Ribbon)
This script plots 20, 50, 100 and 200 period EMAs on the price chart and changes the color of the 20 EMA according to its slope.
Volatility Breakout with Auto Buy/Sell🔧 Features:
3 different volatility measurement methods combined.
It gives signals as Volatility Spike ("Break ↑") and Volatility Drop ("Drop ↓").
It works in the bottom panel because Overlay = false.
MSTR mNAV RatiomNav for MSTR
mNAV (Multiple-to-Net Asset Value): It's a colloquial term, often used as a ratio of MSTR's market capitalization to the market value of its Bitcoin holdings.
Implied ERP ApproximationDefinition of Equity Risk Premium (ERP):
The Equity Risk Premium (ERP) is the excess return that investors expect to earn from investing in stocks over a risk-free asset, typically represented by government bonds like the 10-year U.S. Treasury note.
Mathematically, it’s often approximated as:
ERP=Expected Stock Market Return−Risk-Free Rate\text{ERP} = \text{Expected Stock Market Return} - \text{Risk-Free Rate}\text{ERP} = \text{Expected Stock Market Return} - \text{Risk-Free Rate}
In practice, the expected stock market return can be approximated using the earnings yield of the S&P 500, which is the inverse of the Price-to-Earnings (P/E) ratio:
Earnings Yield=Earnings per SharePrice=1P/E Ratio\text{Earnings Yield} = \frac{\text{Earnings per Share}}{\text{Price}} = \frac{1}{\text{P/E Ratio}}\text{Earnings Yield} = \frac{\text{Earnings per Share}}{\text{Price}} = \frac{1}{\text{P/E Ratio}}
The risk-free rate is typically the yield on the 10-year U.S. Treasury note (symbol ^TNX on TradingView).
The Implied ERP Indicator:
The Implied ERP Indicator calculates the ERP by subtracting the 10-year Treasury yield from the S&P 500 earnings yield:
Implied ERP=S&P 500 Earnings Yield−10-Year Treasury Yield\text{Implied ERP} = \text{S\&P 500 Earnings Yield} - \text{10-Year Treasury Yield}\text{Implied ERP} = \text{S\&P 500 Earnings Yield} - \text{10-Year Treasury Yield}
Since Pine Script cannot directly fetch the P/E ratio or earnings data for SP:SPX (as discussed in the earlier error with ta.pe()), we approximate the P/E ratio using a static value (e.g., 25.0, which you can adjust based on the actual P/E ratio as of May 2025).
Normalized DXY+Custom USD Index (DXY+) – Normalized Dollar Strength with Bitcoin, Gold, and Yuan.
This custom USD strength index replicates the structure of the official U.S. Dollar Index (DXY), while expanding it to include modern financial assets such as Bitcoin (BTC), Ethereum (ETH), gold (XAU), and the Chinese yuan (CNY).
Weights for the core fiat currencies (EUR, JPY, GBP, CAD, SEK, CHF) follow the official ICE DXY methodology. Additional components are weighted proportionally based on their estimated global economic influence.
The index is normalized from its initial valid data point, meaning it starts at 100 on the first day all asset inputs are available. From that point forward, it tracks the relative strength of the U.S. dollar against this expanded basket.
This provides a more comprehensive and modernized view of the dollar's strength—not only against traditional fiat currencies, but also in the context of rising decentralized assets and non-Western trade power.
Refined Reversals (Stricter Bullish, RSI < 30)A Reversal indicator based on 3 confluences. Not yet back tested
H2-25 cuts (bp)This custom TradingView indicator tracks and visualizes the implied pricing of Federal Reserve rate cuts in the market, specifically for the second half of 2025. It does so by comparing the price differences between two specific Fed funds futures contracts: one for June 2025 and one for December 2025. These contracts are traded on the Chicago Board of Trade (CBOT) and are a widely-used market gauge of the expected path of U.S. interest rates.
The indicator calculates the difference between the implied rates for June and December 2025, and then multiplies the result by 100 to express it in basis points (bps). Each 0.01 change in the spread corresponds to a 1-basis point change in expectations for future rate cuts. A positive value indicates that the market is pricing in a higher likelihood of one or more rate cuts in 2025, while a negative value suggests that the market expects the Fed to hold rates steady or even raise them.
The plot represents the difference in implied rate cuts (in basis points) between the two contracts:
June 2025 (ZQM2025): A contract representing the implied Fed funds rate for June 2025.
December 2025 (ZQZ2025): A contract representing the implied Fed funds rate for December 2025.
Custom USD Index (DXY+)This is a modernized, expanded version of the U.S. Dollar Index (DXY), designed to provide a more accurate representation of the dollar’s global strength in today’s diversified economy.
Unlike the traditional DXY, which excludes major players like China and entirely omits real-world stores of value, this custom index (DXY+) includes:
Fiat Currencies (78.3% total weight):
EUR, JPY, GBP, CAD, AUD, CHF, and CNY — equally weighted to reflect the global currency landscape.
Gold (17.5%):
Gold (XAUUSD) is included as a traditional reserve asset and inflation hedge, acknowledging its continued monetary relevance.
Cryptocurrencies (2.8% total weight):
Bitcoin (BTC) and Ethereum (ETH) represent the emerging digital monetary layer.
The index rises when the U.S. dollar strengthens relative to this blended basket, and falls when the dollar weakens against it. This is ideal for traders, economists, and macro analysts seeking a more inclusive and up-to-date measure of dollar performance.
Custom USD IndexThis is a modernized, expanded version of the U.S. Dollar Index (DXY), designed to provide a more accurate representation of the dollar’s global strength in today’s diversified economy.
Unlike the traditional DXY, which excludes major players like China and entirely omits real-world stores of value, this custom index (DXY+) includes:
Fiat Currencies (78.3% total weight):
EUR, JPY, GBP, CAD, AUD, CHF, and CNY — equally weighted to reflect the global currency landscape.
Gold (17.5%):
Gold (XAUUSD) is included as a traditional reserve asset and inflation hedge, acknowledging its continued monetary relevance.
Cryptocurrencies (2.8% total weight):
Bitcoin (BTC) and Ethereum (ETH) represent the emerging digital monetary layer.
The index rises when the U.S. dollar strengthens relative to this blended basket, and falls when the dollar weakens against it. This is ideal for traders, economists, and macro analysts seeking a more inclusive and up-to-date measure of dollar performance.
Order Block Finderjust trying out some new stuff with some old stuff to speed up my charting process. so far things look good
Levels & Flow📌 Overview
Levels & Flow is a visual trading tool that combines daily pivot levels with a dynamic EMA ribbon to help traders identify structure, momentum, and key decision zones in the market.
This script is designed for discretionary traders who rely on clean visual cues for intraday and swing trading strategies.
⚙️ Key Features
Daily Pivot, Support, and Resistance Lines
Automatically plots the daily pivot level based on the previous day’s OHLC data, along with calculated support and resistance levels.
Fibonacci Retracement Levels
Two dashed lines above and below the pivot represent the retracement of the pivot-resistance and pivot-support range, forming the boundaries of the “no-trade zone.”
No-Trade Zone (Shaded Box)
A gray shaded box between the two Fibonacci levels to visually mark a high-chop/low-conviction zone.
Trend-Based Candle Coloring (Current Day Only)
Candles are colored green if the close is above the pivot, red if below (only on the current trading day).
Bullish/Bearish Trend Label
A small table in the bottom-right corner displays “Bullish” or “Bearish” depending on whether price is above or below the pivot.
20-EMA Gradient Ribbon
A stack of 20 EMAs, each smoothed and color-coded from blue to green to reflect short- to long-term trend alignment.
Cumulative EMA with Adaptive Weighting
An intelligent moving average line that adjusts weight distribution among the 20 EMAs based on recent predictive accuracy using a learning rate and lookback period.
🧠 How It Works
📍 Levels
The script calculates daily pivot, resistance, and support levels using standard formulas:
Pivot = (High + Low + Close) / 3
Resistance = (2 × Pivot) – Low
Support = (2 × Pivot) – High
These levels update each day and extend 143 bars to the right.
📏 Fib Lines
Fib Up = Pivot + (Resistance – Pivot) × 0.382
Fib Down = Pivot – (Pivot – Support) × 0.382
These lines form the “no-trade zone” box.
📈 EMA Ribbon
20 EMAs starting from the user-defined Base Length, each incremented by 1
Each EMA is smoothed using the Smoothing Period
Color-coded from blue to green for intuitive visual flow
Filled between EMAs to visualize trend strength and alignment
🧠 Cumulative EMA Learning
Each EMA’s historical error is calculated over a Lookback Period
Lower-error EMAs receive higher weight; weights are normalized to sum to 1
The result is a cumulative EMA that adapts based on historical predictive power
🔧 User Inputs
Input
Base EMA Length: Sets the period for the shortest EMA (default: 20)
Smoothing Period: Smooths all EMAs and the cumulative EMA
Lookback for Learning: Number of bars to evaluate EMA prediction accuracy
Learning Rate: Adjusts how quickly weights shift in favor of more accurate EMAs
✅ How to Use It
Use the pivot level to define directional bias.
Watch for price breakouts above resistance or breakdowns below support to consider entry.
Avoid trading inside the shaded zone, where direction is less reliable.
Use the EMA ribbon gradient to confirm short/long alignment.
The cumulative EMA helps define trend with noise reduction.
🧪 Best For
Intraday traders who want to blend structure with flow
Swing traders needing clean daily levels with dynamic confirmation
Anyone looking to avoid choppy zones and improve visual clarity
⚠️ Disclaimer
This script is for educational and informational purposes only. It does not constitute financial advice or a trading recommendation. Always test scripts in simulation or on demo accounts before live use. Use at your own risk.
Bloomberg Financial Conditions Index (Proxy)The Bloomberg Financial Conditions Index (BFCI): A Proxy Implementation
Financial conditions indices (FCIs) have become essential tools for economists, policymakers, and market participants seeking to quantify and monitor the overall state of financial markets. Among these measures, the Bloomberg Financial Conditions Index (BFCI) has emerged as a particularly influential metric. Originally developed by Bloomberg L.P., the BFCI provides a comprehensive assessment of stress or ease in financial markets by aggregating various market-based indicators into a single, standardized value (Hatzius et al., 2010).
The original Bloomberg Financial Conditions Index synthesizes approximately 50 different financial market variables, including money market indicators, bond market spreads, equity market valuations, and volatility measures. These variables are normalized using a Z-score methodology, weighted according to their relative importance to overall financial conditions, and then aggregated to produce a composite index (Carlson et al., 2014). The resulting measure is centered around zero, with positive values indicating accommodative financial conditions and negative values representing tighter conditions relative to historical norms.
As Angelopoulou et al. (2014) note, financial conditions indices like the BFCI serve as forward-looking indicators that can signal potential economic developments before they manifest in traditional macroeconomic data. Research by Adrian et al. (2019) demonstrates that deteriorating financial conditions, as measured by indices such as the BFCI, often precede economic downturns by several months, making these indices valuable tools for predicting changes in economic activity.
Proxy Implementation Approach
The implementation presented in this Pine Script indicator represents a proxy of the original Bloomberg Financial Conditions Index, attempting to capture its essential features while acknowledging several significant constraints. Most critically, while the original BFCI incorporates approximately 50 financial variables, this proxy version utilizes only six key market components due to data accessibility limitations within the TradingView platform.
These components include:
Equity market performance (using SPY as a proxy for S&P 500)
Bond market yields (using TLT as a proxy for 20+ year Treasury yields)
Credit spreads (using the ratio between LQD and HYG as a proxy for investment-grade to high-yield spreads)
Market volatility (using VIX directly)
Short-term liquidity conditions (using SHY relative to equity prices as a proxy)
Each component is transformed into a Z-score based on log returns, weighted according to approximated importance (with weights derived from literature on financial conditions indices by Brave and Butters, 2011), and aggregated into a composite measure.
Differences from the Original BFCI
The methodology employed in this proxy differs from the original BFCI in several important ways. First, the variable selection is necessarily limited compared to Bloomberg's comprehensive approach. Second, the proxy relies on ETFs and publicly available indices rather than direct market rates and spreads used in the original. Third, the weighting scheme, while informed by academic literature, is simplified compared to Bloomberg's proprietary methodology, which may employ more sophisticated statistical techniques such as principal component analysis (Kliesen et al., 2012).
These differences mean that while the proxy BFCI captures the general direction and magnitude of financial conditions, it may not perfectly replicate the precision or sensitivity of the original index. As Aramonte et al. (2013) suggest, simplified proxies of financial conditions indices typically capture broad movements in financial conditions but may miss nuanced shifts in specific market segments that more comprehensive indices detect.
Practical Applications and Limitations
Despite these limitations, research by Arregui et al. (2018) indicates that even simplified financial conditions indices constructed from a limited set of variables can provide valuable signals about market stress and future economic activity. The proxy BFCI implemented here still offers significant insight into the relative ease or tightness of financial conditions, particularly during periods of market stress when correlations among financial variables tend to increase (Rey, 2015).
In practical applications, users should interpret this proxy BFCI as a directional indicator rather than an exact replication of Bloomberg's proprietary index. When the index moves substantially into negative territory, it suggests deteriorating financial conditions that may precede economic weakness. Conversely, strongly positive readings indicate unusually accommodative financial conditions that might support economic expansion but potentially also signal excessive risk-taking behavior in markets (López-Salido et al., 2017).
The visual implementation employs a color gradient system that enhances interpretation, with blue representing neutral conditions, green indicating accommodative conditions, and red signaling tightening conditions—a design choice informed by research on optimal data visualization in financial contexts (Few, 2009).
References
Adrian, T., Boyarchenko, N. and Giannone, D. (2019) 'Vulnerable Growth', American Economic Review, 109(4), pp. 1263-1289.
Angelopoulou, E., Balfoussia, H. and Gibson, H. (2014) 'Building a financial conditions index for the euro area and selected euro area countries: what does it tell us about the crisis?', Economic Modelling, 38, pp. 392-403.
Aramonte, S., Rosen, S. and Schindler, J. (2013) 'Assessing and Combining Financial Conditions Indexes', Finance and Economics Discussion Series, Federal Reserve Board, Washington, D.C.
Arregui, N., Elekdag, S., Gelos, G., Lafarguette, R. and Seneviratne, D. (2018) 'Can Countries Manage Their Financial Conditions Amid Globalization?', IMF Working Paper No. 18/15.
Brave, S. and Butters, R. (2011) 'Monitoring financial stability: A financial conditions index approach', Economic Perspectives, Federal Reserve Bank of Chicago, 35(1), pp. 22-43.
Carlson, M., Lewis, K. and Nelson, W. (2014) 'Using policy intervention to identify financial stress', International Journal of Finance & Economics, 19(1), pp. 59-72.
Few, S. (2009) Now You See It: Simple Visualization Techniques for Quantitative Analysis. Analytics Press, Oakland, CA.
Hatzius, J., Hooper, P., Mishkin, F., Schoenholtz, K. and Watson, M. (2010) 'Financial Conditions Indexes: A Fresh Look after the Financial Crisis', NBER Working Paper No. 16150.
Kliesen, K., Owyang, M. and Vermann, E. (2012) 'Disentangling Diverse Measures: A Survey of Financial Stress Indexes', Federal Reserve Bank of St. Louis Review, 94(5), pp. 369-397.
López-Salido, D., Stein, J. and Zakrajšek, E. (2017) 'Credit-Market Sentiment and the Business Cycle', The Quarterly Journal of Economics, 132(3), pp. 1373-1426.
Rey, H. (2015) 'Dilemma not Trilemma: The Global Financial Cycle and Monetary Policy Independence', NBER Working Paper No. 21162.
Aggregated Perpetual Futures Open InterestPurpose
Aggregates perpetual futures open interest across Binance, Bybit, and OKX for the base currency of the asset loaded in your tradingview window.
How It Works
Symbol detection: The script grabs syminfo.basecurrency (e.g., “BTC”) from whatever market is on screen.
Ticker mapping: It constructs the three perp-OI feeds that TradingView publishes in the form EXCHANGE:USDT.P_OI
Data request: For each feed it fetches the full OHLC candle (request.security) on the chart’s timeframe. If a venue doesn’t list that perp, the request simply returns na.
Aggregation: The script adds the opens, highs, lows, and closes of all non-na feeds to produce a single aggregated OI candle.
General Notes
The status line shows each venue’s individual OI close.
FVG Candle HighlighterThis indicator highlights only the true Fair Value Gap (FVG) creator candle — the middle candle in a 3-bar FVG formation — with zero clutter.
🔹 Bullish FVG: Candle is colored if price gaps above the high two bars back
🔹 Bearish FVG: Candle is colored if price gaps below the low two bars back
✨ No boxes. No zones. Just pure, visual price-action accuracy.
🔧 Powered by Pine Script v6
🧠 Based on institutional-style FVG logic
🎯 Ideal for Smart Money / ICT / Order Block strategies
Coinbase Premium IndicatorPurpose
Indicates whether a crypto asset listed on a Coinbase spot market is trading at a premium or discount to other spot (Tether) markets.
How It Works
The script takes the base currency for the pair loaded in that TradingView window and searches for its Coinbase spot market. It also maps the base currency to the USDT (Tether) spot markets on Binance, Bybit, and OKX.
The Premium/ Discount is: (coin-btc-usd) - (sum(bnce-btc-usdt, bybt-btc-usdt, okx-btc-usdt))
General Notes
The status line of the Indicator displays the value of the premium/ discount and the market prices of the pair for each constituent exchange.
PER x RangeThis Pine Script calculates the target price of the Nikkei Average based on the EPS (Earnings Per Share) and different PER (Price-to-Earnings Ratio) multiples ranging from 17.5x to 12x, in increments of 0.5x. It then plots these target prices on the chart.
Key Features:
Input EPS: You can manually input the current EPS value of the Nikkei Average (the example uses 2380, but you can replace it with the actual EPS).
PER Multiples Calculation: The script calculates target prices for different PER multiples (17.5x, 17x, 16.5x, ..., down to 12x).
Plotting Target Prices: The calculated target prices (EPS * PER) are plotted on the chart as blue lines, showing you different target price scenarios based on varying PER multiples.
VOID Directional Spike MarkerThis indicator highlights significant directional moves on the $VOID chart (NYSE USI:UVOL − DERIBIT:DVOL ) using simple visual cues:
🔼 Green up arrows when the candle closes significantly higher than it opens
🔽 Red down arrows when the candle closes significantly lower than it opens
Threshold is fully customizable (default: 15,000,000)
Ideal for spotting explosive internal shifts on the 5-minute chart during key market moments
Alerts included for both up and down spikes
Use this to track aggressive buying or selling pressure across NYSE internals and time your entries on NQ, ES, or YM with stronger conviction.
Order Block with BoSHere’s a professional and concise description you can use for publishing your **TradingView script** titled **"Order Block with BoS"**:
---
### 📌 **Description for TradingView Publication:**
**"Order Block with Break of Structure (BoS)"** is a powerful price action-based indicator designed to identify potential reversal zones and momentum shifts using **Order Block** detection combined with **Break of Structure (BoS)** confirmation.
### 🔍 **Key Features:**
* **Order Block Detection**: Highlights bullish and bearish order blocks using precise candle structure logic.
* **Break of Structure (BoS)**: Confirms structural breaks above swing highs or below swing lows to validate potential trend continuation or reversal.
* **Dynamic ATR Filter**: Uses a 14-period ATR with dynamic thresholds to confirm significant moves, filtering out weak breakouts.
* **Visual Aids**:
* Color-coded **boxes** to mark detected Order Blocks.
* **Arrows** at BoS confirmation points when ATR confirms strong momentum.
* Optional **dashed BoS lines** to show where price broke structure.
### ⚙️ **Customizable Inputs**:
* `Swing Length`: Defines the sensitivity of swing high/low detection.
* `Show Break of Structure`: Toggle on/off BoS confirmation lines.
* `Candle Lookback`: Number of historical candles to consider.
This indicator is ideal for traders who incorporate **smart money concepts**, **market structure analysis**, or **institutional order flow** strategies.
---
Would you like me to help write the **strategy** version of this or translate the description into another language for international audiences?
Economic Event DatesThis TradingView indicator ("Economic Event Dates") plots significant economic event dates directly on your chart, helping you stay informed about potential market-moving announcements. It includes pre-configured dates for:
* **FOMC Meetings:** Key policy meetings of the Federal Open Market Committee.
* **CPI Releases:** Consumer Price Index data releases, a key measure of inflation.
* **Bitcoin Halvings:** Programmatic reductions in Bitcoin's new supply issuance.
**Features:**
* **Customizable Dates:** Easily input and manage dates for FOMC, CPI, and Halving events for current and future years (2025, 2026, and beyond for Halvings).
* **Visual Cues:** Displays vertical lines on the chart at the precise time of each event.
* **Event Labels:** Shows clear labels (e.g., "FOMC", "CPI", "Halving") for each event line.
* **Color Coding:** Distinct colors for FOMC (blue), CPI (orange), and Halving (purple) events for quick identification.
* **Future Events Focus:** Option to display only upcoming events relative to the current real time.
* **Morning Alerts:** (Optional) Triggers an alert on the morning of a scheduled event, providing a timely reminder.
* **Customizable Appearance:** Adjust line width and toggle label visibility.
**How to Use:**
1. Add the indicator to your TradingView chart.
2. Review and update the input dates for FOMC, CPI, and Halving events in the indicator settings. The script includes placeholders and notes for future dates that may require verification from official sources (e.g., federalreserve.gov, bls.gov).
3. Customize colors, line width, label visibility, and alert preferences as needed.
4. Observe the vertical lines on your chart indicating upcoming economic events.
This tool is designed for traders and investors who want to incorporate awareness of major economic events into their market analysis. Remember to verify future event dates as they are officially announced.
Created by YouNesta