OPEN-SOURCE SCRIPT

Volatility Regime Engine [JOAT]

803
Volatility Regime Engine

Introduction

The Volatility Regime Engine is a sophisticated volatility analysis tool designed to identify market cycles through expansion and contraction patterns. This indicator goes beyond simple volatility measurement by classifying volatility into distinct regimes, detecting squeeze patterns, and forecasting potential volatility shifts. It's built for traders who understand that volatility is not just noise but a predictable cycle that creates trading opportunities when properly understood.

Volatility is the lifeblood of markets - it creates opportunities, determines risk, and influences strategy selection. This engine provides institutional-grade volatility analysis that helps traders adapt their approach to current market conditions. Whether you're a day trader adjusting stop distances, a swing trader timing entries after volatility contractions, or a position trader sizing positions based on volatility forecasts, this tool provides the critical volatility intelligence needed for superior decision-making.

스냅샷

Why This Indicator Exists

Most traders treat volatility as a single number (like ATR) without understanding its cyclical nature and predictive properties. This indicator addresses that limitation by:

  • Regime Classification: Identifies whether volatility is expanding, contracting, or normal, allowing strategy adaptation
  • Squeeze Detection: Pinpoints volatility compression patterns that often precede significant price moves
  • Cycle Analysis: Tracks volatility cycles to identify optimal entry and exit timing
  • Forecasting Capability: Uses mean reversion principles to predict likely volatility shifts
  • Adaptive Multipliers: Provides dynamic stop loss and target multipliers based on current volatility
  • Historical Context: Places current volatility in percentile context for better decision making


The engine solves the critical problem of using static risk management in dynamic volatility environments. By understanding where you are in the volatility cycle, you can anticipate market behavior and position yourself accordingly.

Core Components Explained

1. Multi-Layer ATR Analysis

The indicator uses three ATR timeframes to capture volatility across different horizons:

Pine Script®
// Multiple ATR timeframes float atr_fast = ta.atr(i_atr_fast) float atr_slow = ta.atr(i_atr_slow) float atr_baseline = ta.sma(ta.atr(i_atr_slow), i_atr_baseline) // ATR ratios float atr_ratio = atr_baseline > 0 ? atr_slow / atr_baseline : 1.0 float atr_momentum = atr_fast / atr_slow


ATR layers:
  • Fast ATR (7 periods): Captures immediate volatility changes
  • Slow ATR (21 periods): Medium-term volatility trend
  • Baseline ATR (50 periods smoothed): Long-term volatility average
  • ATR Ratio: Current volatility relative to baseline (key for regime detection)
  • ATR Momentum: Short-term volatility acceleration/deceleration


The ATR ratio is the primary driver of regime classification - values above 1.4 indicate expansion, below 0.6 indicate contraction.

2. Squeeze Detection System

The indicator uses the classic TTM Squeeze concept with enhanced features:

Pine Script®
// Squeeze state bool squeeze_on = bb_lower > kc_lower and bb_upper < kc_upper bool squeeze_off = bb_lower < kc_lower and bb_upper > kc_upper // Squeeze duration tracking var int squeeze_duration = 0 if squeeze_on squeeze_duration := squeeze_duration + 1 else squeeze_duration := 0 // Squeeze intensity (longer squeeze = more explosive release) float squeeze_intensity = math.min(float(squeeze_duration) / 20.0 * 100, 100)


Squeeze components:
  • Bollinger Bands: Measure volatility through standard deviation
  • Keltner Channels: Measure volatility through ATR
  • Squeeze On: BB inside KC indicates volatility compression
  • Squeeze Duration: Time in compression - longer durations build more energy
  • Squeeze Intensity: Percentage score of compression buildup
  • Squeeze Release: Transition from compression to expansion


Squeeze releases are among the most reliable volatility signals - they often precede significant price moves.

3. Historical Volatility Analysis

For additional confirmation, the indicator calculates statistical volatility:

Pine Script®
f_historical_vol(int period, int annual_days) => float log_return = math.log(close / close[1]) float hv = ta.stdev(log_return, period) * math.sqrt(annual_days) * 100 hv float hv_current = i_use_hv ? f_historical_vol(i_hv_len, i_hv_annual) : 0 float hv_avg = i_use_hv ? ta.sma(hv_current, i_hv_len * 2) : 0 float hv_ratio = hv_avg > 0 ? hv_current / hv_avg : 1.0


HV features:
  • Log Returns Calculation: Statistically sound volatility measurement
  • Annualization: Converts to annualized volatility percentage
  • HV Ratio: Current volatility relative to historical average
  • HV Regime: High/low volatility classification
  • Confirmation Layer: Validates ATR-based regime detection


Historical volatility adds a statistical layer that confirms what the ATR analysis is showing.

4. Volatility Regime Classification

The indicator classifies volatility into four distinct states:

Pine Script®
// Raw regime based on ATR ratio int raw_vol_regime = 0 if atr_ratio >= i_exp_thresh raw_vol_regime := 1 // Expansion else if atr_ratio <= i_con_thresh raw_vol_regime := -1 // Contraction // Confirmed regime with bar count filter var int regime_counter = 0 var int confirmed_vol_regime = 0 if raw_vol_regime == raw_vol_regime[1] and raw_vol_regime != 0 regime_counter := math.min(regime_counter + 1, i_regime_confirm + 1) else if raw_vol_regime != raw_vol_regime[1] regime_counter := 1 if regime_counter >= i_regime_confirm confirmed_vol_regime := raw_vol_regime


Regime types:
  • Expansion (ATR ratio > 1.4): High volatility, wide ranges, increased risk
  • Contraction (ATR ratio < 0.6): Low volatility, narrow ranges, preparing for breakouts
  • Normal (0.6 < ATR ratio < 1.4): Balanced volatility, normal market conditions
  • Transitioning: Regime changes requiring confirmation before acting


Regime confirmation prevents whipsaws by requiring multiple bars in the same regime before classification.

5. Volatility Cycle Phases

Beyond simple regimes, the indicator identifies where you are in the volatility cycle:

Pine Script®
// Cycle phases: 0=neutral, 1=building, 2=peak, 3=declining, 4=trough var int vol_cycle_phase = 0 float atr_slope = atr_slow - atr_slow[5] float atr_accel = atr_slope - nz(atr_slope[5]) if confirmed_vol_regime == 1 if atr_accel > 0 vol_cycle_phase := 1 // Building expansion else vol_cycle_phase := 2 // Peak expansion else if confirmed_vol_regime == -1 if atr_accel < 0 vol_cycle_phase := 3 // Declining to contraction else vol_cycle_phase := 4 // Trough contraction


Cycle phases:
  • Building Expansion: Volatility increasing, acceleration positive
  • Peak Expansion: High volatility but decelerating
  • Declining to Contraction: Volatility decreasing rapidly
  • Trough Contraction: Low volatility stabilizing
  • Neutral: Transition periods between phases


Cycle analysis helps anticipate the next phase and prepare strategy adjustments.

6. Adaptive Multipliers

The indicator provides dynamic multipliers for risk management:

Pine Script®
// Dynamic stop multiplier based on regime float adaptive_stop_mult = switch confirmed_vol_regime 1 => 1.5 // Wider stops in expansion -1 => 0.8 // Tighter stops in contraction => 1.0 // Normal // Dynamic target multiplier float adaptive_target_mult = switch confirmed_vol_regime 1 => 2.0 // Larger targets in expansion -1 => 1.2 // Smaller targets in contraction => 1.5 // Normal


Adaptive features:
  • Stop Multiplier: Adjusts stop distance based on volatility regime
  • Target Multiplier: Scales profit targets to volatility conditions
  • Risk Adjustment: Helps maintain consistent risk across volatility regimes
  • Export Functions: Available for integration with trading systems


These multipliers help maintain consistent risk-to-reward ratios across different volatility environments.

Visual Elements

  • Multi-Layer Histogram: Core volatility ratio with gradient coloring
  • Glow Effects: Intensity-based glow around extreme volatility
  • Squeeze Momentum: Separate plot showing squeeze building/release
  • Cycle Momentum: Volatility cycle acceleration/deceleration
  • Background Shading: Regime-based background colors
  • Signal Markers: Premium volatility signals with labels
  • Dashboard: Real-time volatility metrics and forecasts


The dashboard displays:
1. Current volatility regime and strength
2. Cycle phase and momentum
3. ATR ratio and percentage
4. Percentile ranking of current volatility
5. Squeeze status and duration
6. Quality score of current setup
7. Volatility forecast (expansion/contraction)
8. Adaptive multipliers for risk management

Input Parameters

ATR Settings:
  • Fast ATR Period: Short-term volatility (default: 7)
  • Slow ATR Period: Medium-term volatility (default: 21)
  • Baseline Period: Long-term volatility average (default: 50)


Regime Thresholds:
  • Expansion Threshold: ATR ratio for expansion regime (default: 1.4)
  • Contraction Threshold: ATR ratio for contraction regime (default: 0.6)
  • Regime Confirmation: Bars for regime confirmation (default: 3)


Squeeze Detection:
  • Bollinger Period: BB calculation period (default: 20)
  • Bollinger Multiplier: BB standard deviation (default: 2.0)
  • Keltner Period: KC calculation period (default: 20)
  • Keltner Multiplier: KC ATR multiplier (default: 1.5)


Visual Settings:
  • Color Scheme: Customizable colors for each regime
  • Glow Effects: Enable/disable visual enhancements
  • Dashboard Display: Show/hide metrics panel
  • Signal Labels: Control signal label frequency


How to Use This Indicator

Step 1: Identify Current Regime
Check the dashboard for the current volatility regime. In expansion (red), expect larger ranges and adjust stops wider. In contraction (blue), prepare for potential breakouts. Normal conditions (purple) allow standard trading approaches.

Step 2: Monitor Squeeze Patterns
Watch for squeeze onset (compression) and duration. Longer squeezes (high intensity) often lead to more explosive releases. The squeeze release signal is one of the most reliable volatility breakout patterns.

Step 3: Analyze Cycle Phase
Understanding the cycle phase helps anticipate the next move. Building expansion suggests continued volatility, while peak expansion warns of potential contraction ahead.

Step 4: Use Percentile Context
The ATR percentile shows how current volatility compares to historical levels. Extremely high percentiles (>90) suggest mean reversion to lower volatility, while low percentiles (<10) suggest expansion is likely.

Step 5: Apply Adaptive Multipliers
Use the provided stop and target multipliers to adjust your risk management to current conditions. This maintains consistent risk across different volatility environments.

Step 6: Watch for Premium Signals
Premium expansion signals (squeeze release + high volatility + HV confirmation) offer high-probability breakout opportunities. Premium contraction signals (early contraction + low HV) suggest optimal entry points before breakouts.

Best Practices

  • Use the indicator to adapt your strategy to volatility conditions rather than fighting them
  • Squeeze releases are most reliable when they occur after long compression periods (>10 bars)
  • Volatility expansion often follows news events - be aware of economic calendars
  • In low volatility environments, reduce position size but increase stop distance proportionally
  • High volatility periods offer larger profit potential but require wider stops and smaller position sizes
  • The volatility forecast is mean-reversion based - extreme volatility tends to revert to normal
  • Combine with trend analysis for best results - volatility expansion in the direction of trend is powerful
  • Use the adaptive multipliers in your automated strategies for dynamic risk management
  • Monitor the cycle phase to anticipate regime changes before they occur
  • Keep a volatility journal to track how different instruments behave in various regimes


Strategy Integration

This indicator is designed to integrate seamlessly with other trading systems:

  • Export plots provide volatility data for strategy consumption
  • Adaptive multipliers can be imported for dynamic risk management
  • Regime classification can filter trades based on volatility conditions
  • Squeeze signals can trigger breakout strategies
  • Cycle analysis can optimize entry/exit timing
  • Quality scores can weight signal strength in composite systems


The indicator includes 12 export functions for integration:
  • ATR Ratio Export: Normalized volatility level
  • Vol Regime Export: Current regime classification (-1, 0, 1)
  • ATR Percentile Export: Historical volatility context
  • Adaptive ATR Export: Volatility-adjusted ATR value
  • Stop Multiplier Export: Dynamic stop adjustment factor
  • Target Multiplier Export: Dynamic target adjustment factor
  • Squeeze State Export: Binary squeeze on/off signal
  • Squeeze Momentum Export: Squeeze building/release momentum
  • Vol Score Export: Normalized volatility score (-100 to +100)


Technical Implementation

Built with Pine Script v6 featuring:
  • Multi-timeframe volatility analysis across three ATR periods
  • Statistical historical volatility calculation with log returns
  • Advanced squeeze detection with duration and intensity tracking
  • Regime classification with confirmation logic to prevent whipsaws
  • Cycle phase analysis using slope and acceleration
  • Adaptive multiplier system for dynamic risk management
  • Comprehensive visualization with multi-layer glow effects
  • Real-time dashboard with 11 key volatility metrics
  • Alert conditions for all major volatility events
  • Export functions for strategy integration


The code uses confirmed bars for all calculations to prevent repainting and ensure reliable signals.

Originality Statement

This indicator is original in its comprehensive approach to volatility analysis and regime classification. While individual components (ATR, Bollinger Bands, Keltner Channels) are established tools, this indicator is justified because:

  • It synthesizes multiple volatility measurement approaches into a unified framework
  • The regime classification system provides actionable market state information
  • Cycle phase analysis adds predictive capability beyond simple volatility measurement
  • The squeeze detection system includes duration and intensity scoring for signal quality
  • Adaptive multipliers provide practical risk management adjustments based on volatility
  • Historical volatility adds statistical confirmation to price-based volatility measures
  • The forecasting system uses mean reversion principles for volatility prediction
  • Comprehensive visualization makes complex volatility concepts accessible and actionable
  • Export functions enable integration with other trading systems
  • Each component contributes unique insights: ATR shows current volatility, squeeze shows compression, HV shows statistical volatility, cycles show direction, and multipliers provide practical application


The indicator's value lies in transforming volatility from a single number into a rich, multi-dimensional analysis that helps traders understand not just how volatile the market is, but where it is in the volatility cycle and what that means for trading opportunities.

Disclaimer

This indicator is provided for educational and informational purposes only. It is not financial advice or a recommendation to buy or sell any financial instrument. Volatility analysis is a tool for understanding market conditions, not a prediction system.

Volatility patterns can change suddenly due to market events, news, or changes in market structure. Past volatility patterns do not guarantee future behavior. The indicator's signals are mathematical calculations based on historical patterns and should be used in conjunction with other forms of analysis.

Always use proper risk management, including stop losses and position sizing appropriate for current volatility conditions. High volatility periods require smaller position sizes due to increased risk, while low volatility periods may require wider stops to avoid premature exits.

The author is not responsible for any losses incurred from using this indicator. Users assume full responsibility for all trading decisions made using this system.

-Made with passion by officialjackofalltrades

면책사항

해당 정보와 게시물은 금융, 투자, 트레이딩 또는 기타 유형의 조언이나 권장 사항으로 간주되지 않으며, 트레이딩뷰에서 제공하거나 보증하는 것이 아닙니다. 자세한 내용은 이용 약관을 참조하세요.