OPEN-SOURCE SCRIPT

Market State Analyzer

550
What The Indicator Does

the market state analyzer classifies price action into one of eight mutually exclusive regimes:

Trending Up: strong directional movement to the upside with aligned momentum and price structure. adx above trend threshold with positive directional index dominance. price typically above key moving averages with bullish alignment.
snapshot
Trending Down: strong directional movement to the downside with aligned momentum and price structure. adx above trend threshold with negative directional index dominance. price typically below key moving averages with bearish alignment.
snapshot
Ranging: sideways price action within a defined range. low adx indicating absence of trend. price oscillating around moving averages without clear directional bias. suitable for mean reversion strategies.
snapshot
Choppy: erratic, unpredictable price movement with no discernible pattern. high choppiness index combined with low efficiency ratio. multiple failed breakout attempts. best avoided or traded with minimal size.
snapshot
Squeeze: volatility compression phase where bollinger bands contract inside keltner channels. often precedes significant directional moves. the indicator tracks squeeze duration to filter false signals.
snapshot
Volatility expansion: rapid increase in price range following compression. often accompanies breakouts and trend initiations. characterized by expanding atr and potential volume surge.
snapshot
Low Volatility: extended period of compressed price movement. atr in lower percentile of historical range. may precede significant moves but timing is uncertain.
snapshot
High Volatility chaos: extreme price swings with no directional consistency. often occurs during news events or market dislocations. highest risk environment requiring defensive positioning.

How It Works

the indicator uses a multi-factor scoring engine that evaluates five core components simultaneously:

snapshot

Directional Movement Analysis
calculates adx (average directional index) to measure trend strength. the adx value is compared against two thresholds: a trend threshold (default 20) that confirms strong trends, and a weak threshold (default 12) that identifies ranging conditions. The directional indicators (+di and -di) determine trend direction.

Volatility Percentile Ranking
measures current atr (average true range) against its historical distribution over a configurable lookback period. This percentile ranking identifies whether current volatility is historically low, normal, or elevated. Volatility spikes are detected when atr exceeds a multiple of its moving average.

Choppiness Index
quantifies market choppiness using the relationship between the sum of atr values and the total price range over a period. higher values indicate choppy, non-trending conditions. the default threshold of 61.8 (derived from fibonacci) separates trending from choppy regimes.

Efficiency Ratio
measures the efficiency of price movement by comparing net price change to total path traveled. Values near 1.0 indicate efficient trending movement; values near 0 indicate inefficient choppy movement. This helps distinguish between true trends and ranging markets with noise.

Squeeze Detection
identifies volatility compression by comparing bollinger band width to keltner channel width. When bollinger bands trade completely inside keltner channels for a minimum number of bars, a squeeze is confirmed. Squeeze release often signals impending volatility expansion.

Scoring Engine
each regime receives a score from 0 to 100 based on how many conditions it satisfies. The winning regime must exceed the second-best score by a configurable margin (default 7.5 points) and persist for a minimum number of bars (default 3) before being confirmed. This dual-confirmation mechanism reduces regime whipsaws and false transitions.

Confidence Calculation
regime confidence combines the winning score magnitude with the score gap over second place. Higher confidence indicates stronger regime identification with less ambiguity.

Additional Analysis Features

Regime Stability Assessment
tracks how consistently the winning regime maintains its score advantage over time. High stability indicates the current regime is well-established. Low stability warns of potential imminent transition.

Price Structure Analysis
identifies swing highs and lows to detect higher-high/higher-low (bullish) or lower-high/lower-low (bearish) structure. This provides additional confirmation for trend regimes.

Multi-Timeframe Alignment
optionally analyzes the higher timeframe regime to identify when timeframes are aligned (higher probability setups) or conflicting (increased uncertainty).

Transition Probability
tracks historical regime transitions using a markov-style matrix. Calculates the probability of transitioning from the current regime to each other regime based on observed frequency.

Session Statistics
monitors regime distribution across asian, london, and new york trading sessions. Shows what percentage of time each session spends in trending versus non-trending regimes.

Risk Engine
provides regime-adaptive position sizing guidance. Suggests risk percentage and stop-loss atr multiplier based on current regime characteristics. Trending regimes allow larger positions; chaotic regimes require defensive sizing.

How To Use It

For Trending Up Or Trending Down Regimes
focus on trend-following strategies. Look for pullbacks to enter in trend direction. Avoid counter-trend positions. Use wider stops to accommodate trend continuation. The suggested strategy is "trend following" and what to avoid is "counter-trend" entries.

For Ranging Regime
apply mean reversion techniques. Buy at range support, sell at range resistance. Use tighter stops as breakouts can occur. Consider oscillator-based entries. The suggested strategy is "mean reversion" and what to avoid is "breakout entries" until confirmed.

For Choppy Regime
reduce position size significantly or stay flat entirely. If trading, use very tight stops and quick profit targets. do not expect follow-through on any move. The suggested strategy is "stay out or scalp only" and what to avoid is "swing positions."

For Squeeze Regime
prepare for an imminent breakout but do not predict direction. Watch for squeeze release signal. consider straddle-style approaches or wait for directional confirmation after release. The suggested strategy is "prepare breakout" and what to avoid is "large positions" until direction confirmed.

For Volatility Expansion Regime
this often follows squeeze release. momentum strategies work well. trail stops rather than using fixed targets. be prepared for extended moves. the suggested strategy is "momentum ride" and what to avoid is "fixed targets."

For Low Volatility Regime
patience required. Volatility will eventually expand but timing is uncertain. Smaller positions appropriate. avoid wide stops as they may be inefficient. The suggested strategy is "reduce size" and what to avoid is "wide stops."

For High Volatility Chaos Regime
maximum caution required. This often occurs during news or unexpected events. Significantly reduce size or exit entirely. If trading, use wide stops and expect random movement. The suggested strategy is "reduce size significantly" and what to avoid is "tight stops" which will be repeatedly triggered.

Settings Guide

for scalping (1m to 5m timeframes)
adx length: 10
adx trend threshold: 22, weak threshold: 12
atr length: 10, lookback: 80
choppiness length: 10, threshold: 58
efficiency length: 8, threshold: 0.25
bb/kc length: 16
squeeze min bars: 4
min regime bars: 4
switch margin: 10.0
note: faster response but more noise

for day trading (15m to 1h timeframes)
adx length: 14
adx trend threshold: 25, weak threshold: 15
atr length: 14, lookback: 120
choppiness length: 14, threshold: 61.8
efficiency length: 10, threshold: 0.30
bb/kc length: 20
squeeze min bars: 6
min regime bars: 3
switch margin: 7.5
note: balanced settings for most traders

for position trading (4h to daily timeframes)
adx length: 20
adx trend threshold: 27, weak threshold: 18
atr length: 20, lookback: 200
choppiness length: 21, threshold: 64
efficiency length: 20, threshold: 0.35
bb/kc length: 30
squeeze min bars: 8
min regime bars: 3
switch margin: 6.0
note: smoother signals with more lag

What Makes It Original

Multi-Dimensional Classification
unlike single-indicator approaches, this system evaluates trend strength, volatility magnitude, volatility direction, price efficiency, and compression state simultaneously to produce a holistic market characterization.

Dual-Confirmation Regime Switching
requires both score margin superiority and temporal persistence before confirming regime changes. this dramatically reduces false regime transitions compared to instantaneous classification methods.

Regime Stability Quantification
provides real-time assessment of how stable the current regime is by analyzing score gap variance. traders receive early warning when regime stability deteriorates.
Integrated Risk Adaptation
built-in risk engine adjusts suggested position sizing and stop placement based on regime characteristics, promoting consistent risk management across different market conditions.

Session-Aware Statistics
tracks regime distribution by trading session, helping traders understand which sessions tend to produce trending conditions versus choppy conditions for their chosen instrument.

Transition Probability Tracking
maintains historical record of regime transitions and calculates forward-looking probabilities, providing insight into likely next states from current conditions.

Available Alerts:

Regime Change Alerts
generic regime change alert
specific alert for each of the eight regimes when entered
alert includes previous regime context for understanding the transition

Squeeze Alerts
squeeze started (compression detected)
squeeze released (breakout initiated)
Confidence And Quality Alerts

High confidence regime detected (above 80%)
confidence dropped below threshold
regime quality degraded

Stability Alerts
transition imminent (stability low)
regime stabilized (stability high)
stability critical (very low)

Volatility Alerts
volatility spike detected
volatility expanding
volatility contracting

Structure Alerts
bullish structure formed (higher high and higher low)
bearish structure formed (lower high and lower low)
multi-timeframe alerts
timeframe regimes aligned
timeframe regimes conflicting

Duration Alerts
regime duration exceeded 20 bars
regime duration exceeded 50 bars

Score Gap Alert
score gap narrowing (regime becoming unstable)

Market Applicability

this indicator is suitable for any liquid market including forex pairs, cryptocurrencies, stocks, indices, commodities, and futures.

For Scalping (sub-5 minute charts): use faster settings as shown in the settings guide. focus on trending, ranging, and choppy regime identification. avoid trading during choppy and high volatility chaos regimes.

For Day Trading (5 minute to 1 hour charts): default settings work well. all regime classifications are relevant. pay attention to session statistics for your preferred trading session.

For Swing Trading (1 hour to daily charts): use slower settings. focus on trending and squeeze regimes for entries. ranging regime useful for identifying consolidation before continuation.

For Position Trading (daily and above): slowest settings recommended. primary focus on trending regime identification. squeeze detection useful for timing entries on pullbacks.

Non-Repainting Behavior

When "wait for bar close" is enabled (default), all regime calculations and signals are confirmed only after the current bar closes. This ensures that historical signals remain stable and do not change after the fact. For real-time analysis without waiting for bar close, this option can be disabled, but users should understand that regime classification may change during bar formation.

Disclaimer

This indicator is a technical analysis tool designed to help identify market conditions. It does not provide financial advice and should not be used as the sole basis for trading decisions. Past performance of any regime classification does not guarantee future results. Markets can change behavior without warning, and no indicator can predict future price movement with certainty.
Always use proper risk management. The suggested risk percentages and stop-loss multipliers are general guidelines that should be adjusted based on individual risk tolerance, account size, and trading experience. Consider combining this indicator with other forms of analysis including price action, fundamental analysis, and market context.
Trading involves substantial risk of loss and is not suitable for all investors. Only trade with capital you can afford to lose.



Aviso legal

As informações e publicações não se destinam a ser, e não constituem, conselhos ou recomendações financeiras, de investimento, comerciais ou de outro tipo fornecidos ou endossados pela TradingView. Leia mais nos Termos de Uso.