OPEN-SOURCE SCRIPT

Chaos Regime Detection Engine [JOAT]

2 046
Chaos Regime Detection Engine [JOAT]

Introduction

The Chaos Regime Detection Engine is an advanced open-source market microstructure indicator that classifies market conditions into distinct regimes using multi-dimensional volatility analysis, directional conviction measurement, and institutional flow detection. This indicator transforms raw market data into actionable regime intelligence, helping traders identify when markets are trending, ranging, chaotic, or experiencing volatility shocks.

Unlike single-dimension volatility indicators that only measure price movement magnitude, this engine analyzes market structure through four independent scoring systems that combine into a unified regime classification framework. The indicator is designed for traders who understand that different market regimes require different trading approaches and that regime identification is the foundation of adaptive strategy selection.

Why This Indicator Exists

This indicator addresses a fundamental challenge in trading: markets constantly shift between different behavioral regimes, and strategies that work in one regime often fail in another. The core innovation lies in synthesizing multiple market microstructure measurements into a probabilistic regime classification system:

  • Directional Flow Regime: Markets exhibiting high price efficiency, low choppiness, and strong ADX conviction - ideal for trend-following strategies
  • Equilibrium Regime: Markets showing balanced conditions with moderate volatility and weak directional bias - suitable for mean-reversion approaches
  • Chaotic Turbulence Regime: Markets displaying high choppiness, low efficiency, and conflicting signals - best avoided or traded with tight stops
  • Volatility Shock Regime: Markets experiencing extreme volatility expansion with high volume - requires defensive positioning or volatility strategies


Each regime classification is derived from normalized scores across multiple dimensions, ensuring that regime identification remains robust across different instruments, timeframes, and market conditions. The system provides not just regime labels but confidence levels and intensity measurements that quantify regime strength.

Snapshot

Core Components Explained

1. ATR and Volatility Percentile Analysis

The indicator calculates Average True Range (ATR) over a customizable period (default 14) and expresses it as a percentage of current price. This normalization allows cross-instrument comparison and removes price-level bias.

ATR percentile ranking over 100 bars provides context for current volatility relative to recent history. High percentile rankings (>70) indicate elevated volatility, while low rankings (<30) suggest compressed volatility. This percentile approach is superior to raw ATR because it adapts to each instrument's unique volatility characteristics.

The volatility percentile feeds into multiple regime scores, particularly the Volatility Shock score, which combines ATR percentile with standard deviation percentile and volume surge detection to identify extreme volatility events.

2. Kaufman Efficiency Ratio

The Efficiency Ratio measures how efficiently price moves from point A to point B by comparing net price change to total path length:

Efficiency = Net Price Change / Sum of Absolute Bar-to-Bar Changes

Values near 1.0 indicate highly efficient, directional movement (trending). Values near 0.0 indicate inefficient, choppy movement (ranging). The indicator uses a customizable lookback period (default 20) to calculate efficiency.

High efficiency feeds into the Directional Flow score, while low efficiency contributes to both Equilibrium and Chaotic Turbulence scores. This dual contribution ensures that the regime classification captures the full spectrum of market behavior.

3. Choppiness Index

The Choppiness Index quantifies market choppiness using logarithmic calculations:

Choppiness = 100 * log10(Sum of ATR / (Highest High - Lowest Low)) / log10(Length)

Values above 61.8 indicate choppy, range-bound markets. Values below 38.2 indicate trending markets. The indicator uses a customizable period (default 14) for this calculation.

The Choppiness Index is inverted when contributing to the Directional Flow score (100 - Choppiness) because low choppiness indicates high directional clarity. High choppiness directly contributes to the Chaotic Turbulence score, identifying markets where price action lacks clear direction.

4. ADX Directional Conviction System

The indicator implements a complete ADX (Average Directional Index) calculation including +DI and -DI components:

+DI measures upward directional movement strength
-DI measures downward directional movement strength
ADX measures the strength of directional movement regardless of direction

ADX values above the trend threshold (default 25) indicate emerging directional conviction. Values above the strong threshold (default 40) indicate dominant directional conviction. The indicator uses customizable lengths for both DI calculation (default 14) and ADX smoothing (default 14).

ADX contributes bonus points to the Directional Flow score when above threshold and to the Equilibrium score when below threshold. The difference between +DI and -DI provides directional bias (long vs short) and conviction strength measurements.

5. Standard Deviation and RVI Analysis

Standard deviation of close prices over 20 bars provides an alternative volatility measurement that captures price dispersion rather than range. The indicator calculates standard deviation as a percentage of price and ranks it using percentile analysis.

The Relative Volatility Index (RVI) applies standard deviation concepts to directional movement:

RVI = 100 * StdDev(Up Moves) / (StdDev(Up Moves) + StdDev(Down Moves))

RVI values above 50 indicate upward volatility dominance, below 50 indicates downward volatility dominance. This provides directional context to volatility measurements that raw standard deviation lacks.

Both metrics contribute to the Volatility Shock score, helping identify when markets are experiencing not just high volatility but directionally biased volatility expansion.

6. Volume Delta Integration

The indicator estimates buying and selling pressure using volume and candle structure:

Buy Volume = Volume when close > open
Sell Volume = Volume when close < open

Volume surge detection compares current volume to 20-period average using a customizable threshold (default 1.5x). Volume surges add bonus points to the Volatility Shock score, confirming that volatility expansion is accompanied by genuine institutional participation rather than thin-market noise.

This volume integration ensures that regime classifications reflect actual market activity rather than just price movement patterns.

7. Regime Scoring and Classification Engine

The indicator calculates four independent regime scores (0-100 scale):

Directional Score = (Efficiency * 100 + (100 - Choppiness) + ADX Bonus) / 2.2
Equilibrium Score = (100 - ATR Percentile + (100 - Efficiency * 100) + ADX Penalty) / 2.2
Turbulence Score = (Choppiness + (100 - Efficiency * 100)) / 2
Shock Score = (ATR Percentile + StdDev Percentile + Volume Surge Bonus) / 2.3

These scores are then normalized to sum to 100%, creating a probability distribution across the four regimes. The dominant regime is determined by the highest normalized score, with confidence level equal to that score's magnitude.

Regime intensity is classified as Nascent (score 35-45), Established (score 45-60), or Dominant (score >60), providing additional context about regime strength and stability.

8. Fractal Divergence Detection

The indicator implements fractal-based divergence detection using a composite volatility index that combines:

30% ATR Percentile
20% Efficiency Ratio
20% Inverted Choppiness
15% StdDev Percentile
15% RVI

This composite index is smoothed with a 5-period EMA and analyzed for fractal tops and bottoms using a 5-bar pattern recognition system. Divergences are detected when price makes new highs/lows but the composite volatility index fails to confirm, suggesting hidden institutional positioning or liquidity asymmetries.

Regular divergences signal potential reversals, while hidden divergences suggest trend continuation after pullbacks. The indicator plots these divergences with color-coded markers and draws connecting lines for visual clarity.

Visual Elements

  • Composite Volatility Line: Main plot showing the smoothed composite volatility index with dynamic gradient coloring based on regime confidence
  • Regime Intensity Histogram: Histogram showing regime-specific intensity with transparency based on confidence level
  • Microstructure Indicators: Subtle circle plots showing ATR percentile, efficiency ratio, and directional clarity for detailed analysis
  • Conviction Overlay: Stepline plot showing ADX with gradient coloring based on conviction strength
  • Fractal Divergence Markers: Circle plots at fractal tops/bottoms with color-coded divergence identification
  • Regime Threshold Lines: Horizontal lines at key regime transition levels (50, 60, 40, 75, 25)
  • Probability Zone Fill: Subtle background fill showing current regime probability field
  • Signal Shapes: Triangle shapes on price chart for high-confidence regime transitions and divergences
  • Comprehensive Dashboard: 12-row intelligence panel showing regime state, certainty, bias, probability scores, conviction, confluence, and all key metrics


The dashboard provides at-a-glance regime assessment with color-coded values, status indicators, and confidence measurements for all regime dimensions simultaneously.

Snapshot

Input Parameters

Signal Architecture:
  • Regime Shift Signals: Toggle chaos-to-order transition detection (default enabled)
  • Regime Persistence Signals: Toggle regime stability confirmations (default enabled)
  • Fractal Divergence Detection: Toggle hidden liquidity flow asymmetries (default enabled)
  • Minimum Confluence Threshold: Multi-factor validation requirement (1-5, default 3)


Volatility Microstructure:
  • Volatility Expansion Period: ATR calculation length (5-50, default 14)
  • Volatility Percentile Window: Percentile ranking lookback (20-500, default 100)
  • Price Efficiency Horizon: Efficiency ratio calculation period (5-100, default 20)
  • Chaos Measurement Period: Choppiness index length (5-50, default 14)


Directional Conviction:
  • Conviction Measurement Length: DI calculation period (5-50, default 14)
  • Conviction Smoothing Factor: ADX smoothing length (1-50, default 14)
  • Conviction Emergence Level: ADX trend threshold (15-40, default 25)
  • Conviction Dominance Level: ADX strong threshold (30-60, default 40)


Institutional Flow:
  • Enable Flow Asymmetry Detection: Toggle volume delta analysis (default enabled)
  • Flow Surge Multiplier: Volume threshold for surge detection (1.0-5.0, default 1.5)


Regime Parameters:
  • Directional Regime Threshold: Score required for directional classification (50-90, default 60)
  • Chaotic Regime Threshold: Score required for chaos classification (10-50, default 40)
  • Volatility Shock Threshold: Score required for shock classification (25-50, default 35)


Visualization:
  • Regime Intelligence Panel: Toggle dashboard display (default enabled)
  • Microstructure Indicators: Toggle detailed metric plots (default enabled)
  • Regime Probability Zones: Toggle background probability field (default enabled)
  • Intelligence Panel Scale: Small/Normal/Large dashboard sizing (default Normal)


Colors:
All colors are fully customizable including directional expansion (neon cyan), volatility shock (neon pink), equilibrium state (gold), and chaotic turbulence (sunset orange).

How to Use This Indicator

Step 1: Identify Current Regime
Check the dashboard "STATE" field to see current regime classification. Note the intensity level (Nascent/Established/Dominant) and certainty percentage. Dominant regimes with high certainty (>80%) are most reliable for strategy selection.

Step 2: Assess Regime Certainty
Monitor the "CERTAINTY" metric. High certainty (>60%) indicates clear regime conditions where strategies aligned with that regime should perform well. Low certainty (<40%) suggests transitional conditions where defensive positioning is appropriate.

Step 3: Check Directional Bias
Review the "BIAS" field showing Long Flow, Short Flow, or Neutral. This indicates whether directional conviction favors long or short positioning within the current regime. The numerical value shows conviction strength.

Step 4: Analyze Regime Probability Scores
Examine the four regime probability scores (Directional, Equilibrium, Turbulence, Shock). These show the relative likelihood of each regime. When one score dominates (>60%), regime classification is clear. When scores are balanced, market is transitional.

Step 5: Monitor Conviction Metrics
Check "CONVICTION" showing ADX value and status (Dominant/Emerging/Absent). Dominant conviction (>40) confirms that directional regimes have strong follow-through potential. Absent conviction (<25) suggests equilibrium or chaotic conditions.

Step 6: Evaluate Confluence Matrix
Review the "CONFLUENCE" score (0-5) showing how many confirmation factors align. Maximum confluence (5/5) indicates all factors agree, providing highest-confidence regime classification. Low confluence (1-2/5) suggests conflicting signals requiring caution.

Step 7: Watch for Regime Transitions
Regime transition signals (triangles on price chart) mark shifts between regimes. These are critical moments for strategy adjustment. Transitions from Chaos to Directional often mark the start of new trends. Transitions to Shock regimes warn of elevated risk.

Step 8: Use Divergence Signals
Fractal divergence markers (labeled "DIV") identify price-volatility asymmetries that often precede regime changes. Bullish divergences in Equilibrium regimes may signal upcoming Directional regimes. Bearish divergences in Directional regimes may warn of regime exhaustion.


Best Practices

  • Use Directional Flow regimes for trend-following strategies with trailing stops
  • Use Equilibrium regimes for mean-reversion strategies with defined profit targets
  • Avoid new positions during Chaotic Turbulence regimes or use very tight stops
  • Reduce position size or hedge during Volatility Shock regimes
  • Regime transitions with high confluence (4-5/5) offer highest-probability strategy shift opportunities
  • Dominant intensity regimes (>60% certainty) are most reliable for strategy execution
  • Nascent intensity regimes (<45% certainty) require defensive positioning until regime establishes
  • Monitor conviction metrics - Directional regimes without conviction (ADX <25) often fail
  • Fractal divergences are most reliable when they occur at regime extremes
  • Use the probability scores to anticipate regime transitions before they're officially classified
  • Equilibrium regimes with rising Directional scores suggest impending breakouts
  • Directional regimes with rising Turbulence scores warn of trend exhaustion


Indicator Limitations

  • Regime classification is probabilistic, not deterministic - no regime guarantees specific outcomes
  • The indicator identifies current regime but cannot predict regime duration
  • Regime transitions can be whipsaw-prone during genuinely transitional market conditions
  • Volume-based components require accurate volume data - some instruments have unreliable volume
  • The indicator works best on liquid instruments with consistent trading patterns
  • Newly listed instruments may lack sufficient history for reliable percentile calculations
  • Extreme market events (flash crashes, circuit breakers) can temporarily distort regime classification
  • The indicator shows what regime exists, not why - fundamental catalysts can override regime signals
  • Confluence scoring requires all factors to be relevant - some factors may be less meaningful on certain instruments
  • Fractal divergence detection requires clear fractal formation - choppy markets may produce false divergences
  • Regime intensity classifications are relative to recent history, not absolute across all market conditions


Technical Implementation

Built with Pine Script v6 using:
  • Complete ADX calculation with +DI/-DI components and customizable smoothing
  • Kaufman Efficiency Ratio using net change vs path length methodology
  • Choppiness Index with logarithmic normalization
  • Multi-component composite volatility index with weighted factor contributions
  • Percentile ranking calculations for ATR, standard deviation, and composite volatility
  • Fractal pattern recognition using 5-bar pivot detection
  • Divergence detection comparing price fractals to volatility fractals
  • Four-dimensional regime scoring system with normalization to probability distribution
  • Confluence factor calculation combining conviction, flow, clarity, certainty, and efficiency
  • Dynamic color gradients based on regime confidence and intensity
  • Comprehensive dashboard with 12 metrics and color-coded status indicators
  • Alert system for regime transitions, divergences, and conviction surges


The code is fully open-source with extensive comments explaining each calculation and regime classification logic.

Originality Statement

This indicator is original in its multi-dimensional regime classification approach. While individual components (ATR, Efficiency Ratio, Choppiness, ADX) are established concepts, this indicator is justified because:

  • It synthesizes four independent regime scoring systems into a unified probabilistic classification framework
  • The composite volatility index combines five distinct measurements with optimized weighting
  • Regime intensity classification (Nascent/Established/Dominant) provides confidence context beyond simple regime labels
  • Confluence scoring validates regime classification through multi-factor confirmation
  • Fractal divergence detection identifies hidden institutional positioning through volatility-price asymmetries
  • The normalization of regime scores to probability distribution ensures consistent interpretation across instruments
  • Integration of volume surge detection confirms that regime classifications reflect genuine market activity
  • The dashboard synthesizes 12 distinct metrics into a unified regime intelligence panel
  • Regime transition signals with confluence filtering provide high-confidence strategy adjustment points
  • The system adapts to each instrument's unique characteristics through percentile-based calculations


Each component contributes unique intelligence: ATR measures volatility magnitude, Efficiency measures directional clarity, Choppiness measures range-bound behavior, ADX measures conviction, volume confirms participation, and divergences reveal hidden positioning. The indicator's value lies in combining these complementary perspectives into a cohesive regime classification system that guides strategy selection.

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. Trading involves substantial risk of loss and is not suitable for all investors.

Regime classification is probabilistic analysis that identifies current market conditions but does not predict future regime duration or transitions. Regime signals do not guarantee profitable trades. Past regime patterns do not guarantee future regime patterns. Market conditions change, and strategies that worked in historical regimes may not work in future regimes.

The metrics displayed are mathematical calculations based on current market data, not predictions of future price movement. Regime transitions, divergences, and confluence scores do not guarantee profitable trades. Users must conduct their own analysis and risk assessment before making trading decisions.

Always use proper risk management, including stop losses and position sizing appropriate for your account size and risk tolerance. Never risk more than you can afford to lose. Consider consulting with a qualified financial advisor before making investment decisions.

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

-Made with passion by officialjackofalltrades

Haftungsausschluss

Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.