OPEN-SOURCE SCRIPT

HMM Enhanced: Regime Probability

597
HMM Enhanced: Regime Probability

Most technical indicators tell you what price has already done. This one asks a different question entirely: what kind of market are we probably in right now?
The HMM Enhanced: Regime Probability indicator applies a Bayesian Hidden Markov Model to three independently constructed market features, producing a real-time probability estimate for three market regimes — Bullish, Bearish, and Chop. It runs directly on the price chart as an overlay, colours your bars by the dominant regime and its confidence, and plots the adaptive trend engine's basis and trailing level so you can see the model's inputs on the chart. A compact dashboard shows the live probability split at all times.

1. What Is a Hidden Markov Model?

A Hidden Markov Model is a statistical framework for reasoning about systems that switch between a small number of underlying states — states that can't be observed directly, but leave traces in the data we can observe.

The "hidden" part is the key insight. In financial markets, the true regime — whether the market is in a trending, ranging, or volatile state — is never directly visible. We can't look at a price bar and read off "this is a bull regime bar" the way we'd read a closing price. What we can observe are things like price's distance from a trend reference, the slope of a moving average, and the strength of directional movement. An HMM uses these observable signals to continuously estimate the probability that the hidden state is X versus Y versus Z.

The model has three core components:

States — the hidden regimes (here: Bull, Bear, Chop).
Emission distributions — for each state, a probability distribution over what the observable signals tend to look like when that state is active. In this indicator, those are Gaussian (normal) distributions parameterised by a mean and standard deviation for each of the three features.
Transition matrix — the probability of moving from one regime to another between bars. This encodes the "stickiness" of regimes: a trending market doesn't instantly flip to choppy on a single bad bar.

Each bar, the forward algorithm combines the previous regime probabilities (propagated through the transition matrix) with the likelihood of today's observations under each regime's emission model, and normalises to produce a fresh posterior probability for each state. This is sequential Bayesian inference: every bar is an update step.

Baum-Welch and Why This Indicator Takes a Different Approach

In a fully trained HMM, the emission parameters (the means and variances that define what each regime "looks like") would be estimated from historical data using the Baum-Welch algorithm — an Expectation-Maximisation procedure that iterates forward and backward passes over the full training set until the parameters converge to a locally optimal fit. Baum-Welch is the textbook solution, but it has a practical limitation in a live trading context: it requires a fixed training window, it's computationally heavy to run on every new bar, and it can produce a model that's well-fitted to its training period but struggles on new market conditions.

This indicator uses a different approach: online dominant-state EM. The emission parameters start from carefully designed prior values (described below) and then update incrementally each bar — but only for whichever state currently has a posterior probability above 50%. This means the model adapts continuously to the instrument and timeframe you're trading, without the need for a training phase, without look-ahead, and without the risk of a single regime's parameters drifting toward another's.

HMMs in Trading — What They Show and Why They're Useful

Markets don't behave the same way all the time. A momentum strategy that performs brilliantly in a trending regime will bleed in chop; a mean-reversion strategy that thrives in ranging markets gets destroyed in a sustained trend. Regime detection is the discipline of figuring out which kind of market you're in before committing to a strategy.

HMMs are particularly well-suited to this problem because:

They're probabilistic, not binary. Instead of telling you "it's a bull market," they tell you "there's a 72% probability this is a bull regime." That distinction matters enormously for position sizing, risk management, and knowing when to wait.

They have memory. The transition matrix means the model can't flip on a single bar. If it called Bull last bar with 80% confidence, it takes sustained evidence to shift that.

The states are inferred, not defined by rules. There's no arbitrary threshold like "above the 200MA = bull." The model learns what each regime looks like in terms of the underlying feature distribution.

2. What This Indicator Does

At its core, this indicator runs a three-state Gaussian HMM using three z-scored features derived from an adaptive trend engine. Each bar it outputs a probability for Bull, Bear, and Chop. The dominant state colours the bars, the probabilities populate the dashboard, and the trend engine's basis and trailing level are plotted directly on the price chart so the model is fully transparent.

The Three Features

All three features are z-scored against a rolling window before entering the model, so they sit on a common scale regardless of instrument or timeframe.

Feature 1 — Trend Position: (close − trailing_level) / ATR14, then z-scored. The trailing level is a ratcheting ATR band around a dual-MA midline — it only moves in the trend's favour, which filters out noise. Price well above the level is strong bull evidence; well below is bear evidence; near the level suggests indecision or chop.

Feature 2 — Basis Slope: The rate of change of the dual-MA midline, ATR-normalised and z-scored. This measures whether the trend reference itself is rising or falling, and how fast. A slow grind higher reads differently from a sharp spike, and both read differently from a flat midline.

Feature 3 — ADX Strength: Z-scored ADX. ADX rises when the market is trending in either direction and falls when it's ranging. The bull and bear emission priors for this feature are identical (+0.5) because ADX is directionless — it only distinguishes trending from ranging. Chop gets a negative ADX prior (−0.5) to reflect that ranging markets have below-average directional strength.

The Adaptive Trend Engine

The trend basis is a dual-MA midline: the average of a fast MA and a slow MA (at 2× the fast length), smoothed using your choice of MA type.

The trailing level sits at an ATR band below the basis during uptrends and above it during downtrends. With the Min/Max Ratchet enabled, the level can only move in the trend's favour — it won't retreat on a retracement bar, which significantly reduces whipsaw flips. The basis and trailing level are plotted on your price chart, coloured by the current dominant regime.

Emission Parameter Design
The prior means are set symmetrically so neither bull nor bear is favoured at initialisation:
FeatureBullBearChopTrend Position+1.0−1.00.0Basis Slope+0.7−0.70.0ADX Strength+0.5+0.5−0.5
The standard deviations start at 1.0 and adapt via learning. Bull and Bear are exact mirrors — there is no directional bias baked into the model.

Transition Matrix Structure

The off-diagonal transition probabilities are asymmetric by design. When the model exits a Bull or Bear regime, 80% of the exit probability routes through Chop — not directly to the opposite regime. This reflects the realistic observation that markets rarely flip directly from trending up to trending down without a period of consolidation first. Exits from Chop are split 50/50 to Bull and Bear.

3. How This Differs From Other HMM Indicators on TradingView

Several HMM indicators exist on TradingView. Here's how this one is different:

vs. Static emission parameters: Most HMM indicators on TradingView use fixed emission parameters — the model's definition of what each regime "looks like" is set at publication and never changes. This indicator adapts its emission parameters online via dominant-state EM learning, so the model continuously calibrates to what Bull, Bear, and Chop actually look like on your specific instrument and timeframe.

vs. Separate pane oscillators: The majority of HMM indicators on TradingView run as subplot oscillators showing regime probabilities in a separate pane. This indicator runs as a price chart overlay — the trend engine that generates the model's primary features is plotted directly on your bars, so the model's inputs are always visible alongside its outputs.

vs. Momentum and volatility features: Several published HMM indicators use raw price returns, rate-of-change, or historical volatility as their observation features. This indicator uses a purpose-built adaptive trend engine instead — specifically the distance from a ratcheting trailing level and the slope of a dual-MA basis. These are more directly connected to trend structure than raw returns or volatility measures, and the ratcheting mechanism filters out pullback noise before the feature ever reaches the model.

vs. Full Baum-Welch training: Some implementations use full Baum-Welch EM on a fixed lookback window, which requires a defined training period and can introduce look-ahead bias if not implemented carefully. This indicator uses only causal bar-by-bar forward updates — it never looks ahead and has no training window.

vs. Volume-based features: Some indicators incorporate volume ratio as an observation feature. This indicator deliberately avoids volume — volume data is unreliable, inconsistent, or entirely absent on many instruments and timeframes (particularly forex and synthetic indices). All three features are built purely from price structure.

The key differentiators in summary:

Adaptive online learning — emission parameters update every bar on the dominant state, no training window required
Purpose-built trend engine features — trend position and basis slope capture trend structure more precisely than raw returns
Overlay on price chart — the trend engine is visible alongside the probability output
Asymmetric transition matrix — regime exits route through chop before flipping, reducing false direct reversals
Emission temperature control — softens the model's decisiveness to avoid overconfident calls on noisy data
Adaptive MA basis combined with ADX to identify trend


4. Configuration & Inputs

1. Adaptive Trend Engine (big thanks to Crak_Trading for his excellent Adaptive Trend indicator
Source — Price input for the trend engine. Default is HLC3 (a noise-reduced proxy for the bar's "true price"). You can change this to Close, HL2, or any other source.

Adaptive Length — The period for the fast MA. The slow MA is automatically set to 2× this value. The basis is the midpoint of the two. Shorter = more responsive, more noise. Longer = smoother, more lag. 20 is a balanced default for most timeframes.

Smoothing — Period for the ATR band smoothing. Controls how quickly the band width responds to changes in volatility. Higher = slower, smoother bands.

Band Multiplier — Width of the ATR band around the basis. Higher values require price to move further from the basis before a trend flip occurs, reducing whipsaw at the cost of more lag on genuine reversals.

Band Type — How the band width is calculated. True Range (default) uses the average of the bar's true range, which is sensitive to gaps. ATR uses the standard 14-period ATR. StDev uses the rolling standard deviation of price, which responds faster to volatility spikes.

MA Type — The moving average used for the basis calculation. Various options (EMA, SMA, WMA, HMA, RMA) are available for comparison.

Use Min/Max Ratchet — When enabled, the trailing level can only move in the direction of the current trend. In an uptrend it can only rise; in a downtrend it can only fall. This prevents the level from retreating on retracement bars and significantly reduces false trend flips.

2. ADX Settings
DMI Length — The lookback for the DI+ and DI− directional movement calculations. 14 is the standard Wilder setting.

ADX Smoothing — Smoothing period for the ADX line itself. 14 is standard. Higher values produce a smoother, slower-reacting ADX.

Z-Score Lookback — The rolling window used to z-score all three features. A longer window produces a more stable baseline and makes the z-scores less sensitive to recent volatility changes. 50 bars is a reasonable default; increase to 100+ for higher timeframes.

3. Transition Matrix
P(Bull | Bull) — The probability that the market stays in a Bull regime from one bar to the next. Higher values make bull regimes stickier and slower to exit. 0.80 is the default, meaning an 80% chance of remaining bull each bar. The remaining 20% is split: 80% routes to Chop, 20% routes directly to Bear.

P(Bear | Bear) — Same as above for the Bear regime.

P(Chop | Chop) — The probability of remaining in Chop. Set lower by default (0.60) because choppy periods tend to resolve faster than trends persist. When Chop exits, the probability is split 50/50 to Bull or Bear.

Note: Higher persistence values increase regime stability but slow the model's response to genuine regime changes. Lower values make it more reactive but noisier.

4. Adaptive Learning
Enable Adaptive Learning — When on, the emission means and standard deviations update incrementally each bar for whichever regime currently has >50% posterior probability. Over time, the model calibrates to what Bull, Bear, and Chop actually look like on your instrument. When off, the parameters stay fixed at their initial prior values.

Learning Rate — Controls the speed of adaptation. 0.05 (default) is slow and stable — good for most use cases. Values around 0.10–0.15 adapt faster but produce noisier parameter estimates. Values above 0.20 should be used with caution as they can cause the emission distributions to drift away from their priors quickly on anomalous bars.

Min Emission Std Dev — A floor on the emission standard deviation. Prevents the Gaussian distributions from collapsing to near-zero width, which would make the model pathologically confident and brittle. 0.3 is a safe default.

5. HMM Settings
Emission Temperature — A softening parameter applied to the raw emission likelihoods before the HMM update. At temperature 1.0, the likelihoods are used as-is, which can produce very sharp, confident regime calls. Higher values (default 2.0) flatten the differences between regimes' likelihoods, keeping probabilities in a more realistic 50–70% range for clear signals rather than snapping to 90%+. Think of it as a confidence dampener — useful on noisy instruments or timeframes where overconfident calls are common.

6. Visuals
Show Basis / Show Trailing Level — Toggle the dual-MA midline and ratcheting trailing level plots on the price chart.

Basis / Trail Line Width — Line thickness for each plot.

Color Transition Speed — Controls the smoothing of bar colour transitions between regime changes. Lower values (closer to 0) produce very gradual colour transitions; higher values (closer to 1.0) make colour changes near-instant. 0.4 is the default for a natural-looking blend.

Bull / Bear / Chop Weak & Strong colours — Each regime has a gradient from a "weak" colour (lower confidence) to a "strong" colour (high confidence). Bars are coloured by the dominant regime's probability within that gradient. The same colours are used for the basis line.

Table Position — Where the dashboard appears on the chart. All eight TradingView anchor positions are available.

Table Text Size — Four sizes: Tiny, Small (default), Normal, Large. The regime label row (BULLISH / BEARISH / CHOP) automatically renders one step larger than the body text for visual hierarchy.

5. The Dashboard — How to Read It

The dashboard table shows the model's current state in real time. All values update on the close of each bar.

Row: What It Shows

REGIME: The dominant state: BULLISH, BEARISH, or CHOP. Coloured by the current bar colour.CONFIDENCEThe probability of the dominant state, followed by HIGH (>65%), MED (>50%), or LOW (≤50%).

P(BULL): Probability the market is currently in a Bull regime, as a percentage.
P(BEAR): Probability of Bear regime.
P(CHOP): Probability of Chop regime.sig B/Br/CThe current emission standard deviations for Bull, Bear, and Chop respectively, followed by LRN (learning enabled) or FIX (fixed).

How to Use the Confidence Tiers
HIGH confidence (>65%) — The model has a strong view. The dominant regime's probability is well above the other two. This is when the signal is most actionable as a strategy filter.

MED confidence (50–65%) — The model has a lean but not a strong conviction. One regime is leading but the others are not far behind. Use as context rather than a hard filter.

LOW confidence (≤50%) — The three probabilities are close together. The model is genuinely uncertain. This is not a failure state — it's an honest reflection of ambiguous market conditions. Avoid relying on it as a filter until confidence improves.

The sig B/Br/C Row
This row shows the adaptive emission standard deviations for each regime. At startup, all three are 1.0. As the model learns:

Values shrinking toward the floor (default 0.3) mean the model is seeing consistent, tight feature values in that regime — it has a precise picture of what it looks like.

Values staying near 1.0 or above mean the regime is observing noisy, inconsistent feature values — the model has a broad, uncertain picture of it.

If Bull and Bear sigmas drift far apart, it may indicate one regime has been much more prevalent than the other, and you may want to reset the indicator or consider whether your instrument is structurally one-sided on your chosen timeframe.

As a Strategy Filter
This indicator is not designed to generate buy and sell signals on its own. It is designed to tell you what kind of strategy is appropriate right now:

BULL dominant (HIGH/MED): Favour trend-following long setups. Momentum indicators and breakout strategies are in their element. Ignore oversold signals from oscillators.

BEAR dominant (HIGH/MED): Favour trend-following short setups or defensive positioning. Overbought oscillator signals can be ignored.

CHOP dominant or LOW confidence: Trend-following strategies are likely to churn. Consider mean-reversion approaches, tighter stops, reduced position sizes, or standing aside entirely.

Alerts
Three alert conditions are included, all non-repainting (they trigger on confirmed bar closes only):

HMM: Regime → BULLISH — The dominant regime has shifted to Bull.
HMM: Regime → BEARISH — The dominant regime has shifted to Bear.
HMM: Regime → CHOP — The dominant regime has shifted to Chop.


This indicator is open-source. The code is fully commented and structured to be readable, developed and aid learning for all users

Clause de non-responsabilité

Les informations et publications ne sont pas destinées à être, et ne constituent pas, des conseils ou recommandations financiers, d'investissement, de trading ou autres fournis ou approuvés par TradingView. Pour en savoir plus, consultez les Conditions d'utilisation.