Structural Language ModelOverview
Structural Language Model treats price action as a language. Each bar is tokenised into one of five structural symbols, and a low-order Markov model learns the grammar — the probability of what comes next given the recent context. Instead of "match the nearest historical shape" (fragile, overfit-prone k-NN), it estimates P(next token | last k tokens): a nonparametric conditional-move model that proves or disproves itself, live, on your symbol. It is a research/forecast read, not a signal service.
The five-symbol grammar
Every bar becomes one token, built from robust intrabar primitives (gap-immune, no fragile sweep/FVG detection), with adaptive thresholds so the alphabet stays balanced across symbols and timeframes:
X− down impulse · d ordinary down · c compression / indecision · u ordinary up · X+ up impulse
The model then learns grammar like c → X+ (breakout), X+ → X− (reversal), runs of u/X+ (trend), X+ → c (exhaustion), using order-1 or order-2 transition counts with Laplace smoothing, updated online.
Why these parts are one tool
The tokeniser turns raw OHLC into a balanced, information-rich alphabet — without it the Markov counts are dominated by whatever token is most common.
The Markov model reads out, each bar, a directional bias (P up-ish − P down-ish), a predictability score (how peaked the next-token distribution is, via normalized entropy), a structural-surprise spike (−log P of the token that just printed — a grammar break), and the full next-bar probability ladder.
The harness is the part that makes it honest. It's prequential (predict-then-update: each transition is scored from counts that exclude its own outcome, so every score is out-of-sample), it runs a walk-forward in-sample vs out-of-sample split with Wilson 95% intervals, and it draws a reliability curve — binning OOS predictions by predicted P(up) and showing the realized up-rate per bin. A rising, significant curve = real calibrated information; a flat one = none. Remove any part and you can no longer answer "is this model actually calibrated on this market?"
How to use it
Read the directional bias line against its conviction bands as context, not a trigger, and check predictability for how peaked the forecast is. Then read the harness — the model is only worth trusting where the out-of-sample up-lean lift is above 1 and/or the reliability spread is positive and significant (✓sig). A flat or insignificant curve means there's no calibrated edge here; treat it as descriptive only, or try another symbol/timeframe. The dashboard has a Compact layout (default: forecast + the one calibration line that matters) and a Pro layout (the full ladder, in/out-of-sample lift, and the three-bin reliability curve). Bias-turn crosses are optionally mirrored on the price chart. It is never a standalone signal.
Non-repainting
Tokens and counts update only on confirmed bars, and the score for bar t uses counts as they stood before bar t's transition was added — nothing reads its own future. The live next-bar forecast naturally refines as the current bar forms (it's a forecast, not a settled statistic). All harness figures are out-of-sample by construction.
Honest limits
OHLCV only. A per-bar tokeniser maximises samples but is coarser than a swing/event grammar (a documented future extension). Any edge is typically modest and market/timeframe-dependent — directional forecasting on noisy price is hard, and no indicator has an inherent edge. That's exactly why the harness is built in: validate it before trusting it.
Outputs for other scripts
Generic EXP_* plots — bias, predictability, structural surprise, live P(next up-ish), and the OOS lift — are published to the Data Window for use from other scripts via input.source().
Concept credits
Markov chains / n-gram language models — A. Markov (1913); C. Shannon (1948)
Prequential (predict-then-update) evaluation — A. P. Dawid (1984)
Additive (Laplace) smoothing — P.-S. Laplace
Entropy — C. Shannon (1948)
Wilson score interval — E. B. Wilson (1927)
Synthesis and Pine implementation are the author's own; no third-party Pine code reused.
Disclaimer
Research and education only. Not financial advice, not a signal service, not a guarantee of future results. Validate with your own testing, apply realistic costs, and manage risk. Indicateur

Markov Regime Oscillator PRO🟦 Markov Regime Oscillator PRO is a quantitative regime-classification and forward-probability forecasting engine rendered as a centred oscillator panel. Every bar is classified into one of three regimes — Bull, Bear, Sideways — using a drift-adjusted, volatility-normalised k·σ·√N threshold. The regime sequence feeds two parallel semi-Markov transition matrices (Young / Mature) with exponentially-decayed counts, producing live N-bar forward probabilities and 95 % Bayesian credible intervals on the next-bar probability vector.
The indicator integrates nine analytical layers — drift-adjusted classification, adaptive k·σ·√N threshold, EWMA-decayed transition matrix, semi-Markov duration conditioning, N-bar forecast cone via matrix iteration, Bayesian credible intervals, stationary distribution, velocity precursor with optional momentum filter, and multi-timeframe confluence — each rendered on a single oscillator panel through reference levels, a regime ribbon, gradient fill, three-layer neon glow signals, and an in-panel forecast polyline. A 30-row PRO status dashboard rendered on the main price chart (not the oscillator panel) reports every readout in real time.
Built with mathematical honesty. Every +1 forward probability carries a 95 % Dirichlet-posterior credible interval, the EWMA half-life is user-set so the model can adapt as market character evolves (2020 ≠ 2024), the semi-Markov split splits the chain on regime age so mature trends are not treated like young ones, and the documentation is explicit about what the model can and cannot predict.
🟦 HOW THE CORE ENGINE WORKS
Regime Classification
Each bar, the engine measures the rolling N-bar log return — optionally adjusted for the long-term drift of the asset:
logRet_raw = log(close / close )
meanDrift = SMA(log(close / close ), driftWin)
logRet = logRet_raw − N × meanDrift (when Drift Adjustment is ON)
The bar is labelled by comparing this return against the configured boundary:
- `logRet > +threshold` → BULL
- `logRet < −threshold` → BEAR
- otherwise → SIDEWAYS
The classification runs every bar with no look-ahead. When the optional Momentum Filter is enabled, the Bull / Bear labels additionally require the oscillator velocity to agree with the direction — killing late entries on exhausted moves.
Adaptive Threshold (k · σ · √N)
Traditional Markov regime indicators use a fixed percentage cut — e.g. "±5 % over 20 bars". This collapses on real markets: the same 5 % is trivial in a 2017 mania and never reached in 2023 chop. The fix is to scale the boundary with realised volatility:
threshold_adaptive = k × σ × √N
where σ is the per-bar log-return standard deviation over a configurable window (default 100 bars). Under a random walk, k = 1.0 cuts at the 16th / 84th percentiles; k = 2.0 at the 2.5th / 97.5th percentiles. The default k = 1.5 reproduces classic ±1.5-sigma thresholds.
Fixed-percentage mode is still available for users who want to lock the threshold deliberately.
Drift Adjustment (Alpha-Adjusted Classification)
Strong-trending markets (long BTC bull runs, persistently uptrending equity indices) carry a non-zero baseline drift. Without adjustment, the rolling log return systematically exceeds zero in such markets — producing excessive Bull-regime flips that reflect baseline drift rather than incremental kinetic energy.
The fix is to subtract the long-term mean drift before threshold comparison:
logRet_excess = log(close / close ) − N × mean(log returns, driftWin)
Log returns become EXCESS returns over the asset's own long-run drift — what quant desks call "alpha-adjusted" classification. The default 250-bar drift window approximates one trading year on the daily timeframe.
Oscillator Value
The classified log return is normalised by the active threshold and scaled to ±100 = boundary, clipped at ±300:
oscVal = clip( logRet / threshold × 100, ±300 )
The oscillator value is the central panel signal. Reference levels at ±100 (solid) mark the official regime boundaries, ±70 (dashed) mark the pending early-warning zone, and 0 (dashed) is the neutral midline.
Regime Confidence
Once classified, the move's strength is normalised relative to the active boundary:
confidence = |logRet| / threshold
| Confidence | Tier | Visual |
|---|---|---|
| < 1.0× | weak | ▱▱▱ |
| 1.0× – 2.0× | moderate | ▰▱▱ |
| 2.0× – 3.0× | strong | ▰▰▱ |
| ≥ 3.0× | stretched | ▰▰▰ |
The confidence value feeds the High Confidence alert (≥ 2.5× trigger) and is reported in the Status dashboard.
🟦 EWMA DECAY ON TRANSITION COUNTS
The Ancient-History Problem
A classic Markov chain counts every historical transition with equal weight — a Bull→Bear flip from five years ago contributes the same as one from yesterday. This breaks when market character changes: the 2020 COVID crash regime dynamics are not the same as 2024 retail mania, but a vanilla counter weighs them identically.
The Refinement (EWMA / RiskMetrics-style decay)
Markov Regime Oscillator PRO applies exponential decay to the transition counts every confirmed bar BEFORE incrementing for the new transition:
decayFactor = 0.5 ^ (1 / halfLife)
counts = counts × decayFactor (all 9 cells, every bar)
counts = counts + 1.0 (new transition)
After `halfLife` bars, an old count weighs HALF its original. This is the same math RiskMetrics uses for EWMA volatility — adapted here to regime transition memory.
| Half-life | Behaviour |
|---|---|
| 50 – 200 | highly reactive — adapts fast, probabilities noisy |
| 300 – 700 | balanced (default 500) |
| 1000+ | stable — slow adaptation, smooth probabilities |
The decay is applied to all three matrices in lockstep (full, young, mature) so the semi-Markov split below stays internally consistent.
🟦 SEMI-MARKOV DURATION CONDITIONING
The Memoryless Problem
A standard Markov chain says: "Given I'm in Bull, the probability of staying Bull tomorrow is X — regardless of whether Bull started yesterday or 200 bars ago." This is the memoryless property, and on real markets it's wrong. A 200-bar-old Bull regime carries different mean-reversion risk than a 5-bar-old one.
The Refinement
Markov Regime Oscillator PRO additionally builds two CONDITIONAL transition matrices:
- `P_young` — transitions counted when the source regime's age was below the Age Median input
- `P_mature` — transitions counted when the source regime's age was at or above the Age Median
Both matrices are constructed in parallel with the unconditional matrix, using the same per-bar bucketing logic, the same EWMA decay, and the same Dirichlet smoothing.
The active forecast then uses the matrix matching the CURRENT regime's tier — Young or Mature. A 5-bar-old Bull is statistically more likely to continue than a 50-bar-old one; semi-Markov captures this empirically without leaking into the unconditional chain.
The active matrix tier is reported live in the Status dashboard's "Matrix" cell.
🟦 N-BAR FORECAST CONE
Matrix Iteration
The 3×3 transition matrix P encodes one-bar-ahead probabilities. To project further out, the state vector is iterated through P:
s_0 = = unit vector on current regime
s_{k+1} = s_k · P (matrix multiplication)
For each step k = 1 … forecastSteps, the iteration produces the probability of each regime at that future bar.
Expected Oscillator Value
At each forecast step, the expected oscillator value is computed as:
E = 100 · ( P(Bull | k) − P(Bear | k) )
This number is +100 when the model expects pure Bull, −100 when pure Bear, and ~0 when Side.
In-Panel Polyline
The cone is rendered as a colored polyline extending PAST the last confirmed bar into the future, drawn via `line.new()` so segments are pixel-stable on any chart zoom. Each segment is colored by the dominant regime at that step (Bull / Bear / Side).
Honest Limitation
The cone is reliable up to ~5 bars; beyond that the iteration converges toward the stationary distribution and the forecast loses information. The default Forecast Horizon is 5 bars — covers the meaningful window without illusion.
The forecast is matrix-implied, not a momentum extrapolation. If the oscillator is currently at +250 (strong Bull) but the matrix says P(Bull → Side) is high, the cone will regress to the matrix-implied expected value — showing a visual "cliff" at step 1. This is mathematically honest, not a bug.
The dashboard's "HORIZON +N" cell reports the dominant regime at the terminal forecast step plus its probability — for a single-glance read of where the chain expects to be at horizon end.
🟦 BAYESIAN CREDIBLE INTERVALS
Why Ranges, Not Point Estimates
A forecast like "P(Bull) +1 = 75 %" carries hidden uncertainty. With only 30 historical Bull-source transitions, the true probability could plausibly be anywhere between 55 % and 90 %. With 2000 historical Bull-source transitions, the same 75 % is tightly bracketed at, say, 73 – 77 %.
Reporting a single number hides the difference. Hedge-fund and academic forecasts always carry uncertainty bands; this oscillator does the same.
The Derivation (Dirichlet Posterior, Gaussian Approximation)
The transition matrix posterior is Dirichlet(α + counts) with Laplace (α = 1) prior. Each marginal is Beta with parameters (α_i, Σα − α_i). The Gaussian approximation to that Beta gives:
mean = α_i / Σα
var = α_i · (Σα − α_i) / ( Σα² · (Σα + 1) )
95 % CI ≈ mean ± 1.96 · √var
The CI is computed for the +1 row (the most actionable forecast) and clipped to .
Reading the Dashboard
P(Bull) +1 75 %
| CI Width | Interpretation |
|---|---|
| Narrow (e.g. 73 – 77) | large sample, robust estimate, trust the call |
| Wide (e.g. 50 – 95) | small sample, fragile estimate, don't bet the desk |
This is the difference between a quantitative estimate and an indicator guess.
🟦 STATIONARY DISTRIBUTION π
Power-iterating the matrix to convergence yields the stationary distribution — the long-run probability of being in each regime, independent of the current state. With 50 iterations on a well-behaved stochastic matrix, the distribution is essentially converged.
π(Side) + π(Bull) + π(Bear) = 1.0
The dashboard's "STATIONARY π" section reports each component. Reading π reveals the asset's structural bias regardless of the current regime — e.g., π(Bull) = 55 % on BTC daily tells you the market spends a majority of its time in Bull regimes over the long run, which is fundamentally different from a sideways-grinding instrument with π(Side) = 60 %.
The stationary distribution also serves as the asymptote of the forecast cone: as k → ∞, the cone collapses to π.
🟦 VELOCITY PRECURSOR & MOMENTUM FILTER
Velocity Definition
The oscillator velocity is the N-bar rate-of-change of the oscillator value:
velocity = oscVal − oscVal
velocityThr = VELOCITY_BASE · √(velocityWin / 5)
The threshold auto-scales with the window so the accel / decel / flat labels stay meaningful at any setting.
Early-Warning Cue
Velocity flips direction BEFORE the official ±100 boundary is crossed — it is a leading indicator of regime change. The Status dashboard's "Velocity" cell displays:
- ↑ accelerating (velocity > +threshold) — colored bull
- ↓ decelerating (velocity < −threshold) — colored bear
- ═ flat — neutral
This partially mitigates the inherent lookback lag of threshold-based regime detection.
Optional Momentum Filter
When the Momentum Filter is enabled, regime classification additionally requires velocity sign agreement:
Bull → logRet > +threshold AND velocity > 0
Bear → logRet < −threshold AND velocity < 0
This kills late-entry signals where price has extended past the threshold but momentum is already exhausted — a classic source of false signals at trend tops/bottoms. Reduces signal count, raises signal quality. Recommended for swing trading, optional for scalping.
🟦 PENDING-REGIME EARLY WARNING
Because the regime is classified from `log(close / close )`, the official regime label inherently lags. This is structural, not a bug, but can be partially mitigated.
Inside Sideways, when the log return reaches 70 % of either boundary, the dashboard fires an early-warning cue:
distance_fraction = max(|logRet| / threshold, ...)
isPending = (regime == SIDE) AND (distance_fraction ≥ 0.70)
The Status panel's "Pending" cell displays the direction the return is leaning toward and the current fraction:
⚠ ▲ BULL 87 %
Color matches the leaning regime. The Pending Regime alert (default OFF, opt-in) fires on the first bar a pending state is entered.
This is not a regime change signal — it's a "watch this" cue, triggered roughly 30 % before the official threshold is crossed. Used alongside the official regime change, it gives the user advance notice without compromising the threshold's strictness.
🟦 SELECTABLE SIGNAL SMOOTHING
A second smoothed signal line overlays the main oscillator. Crossovers between the main and signal lines mark momentum-of-regime shifts — these often precede actual regime changes by 1-3 bars.
Four smoothing algorithms are available:
| Method | Character |
|---|---|
| EMA (default) | Exponential — classic lag/smoothness |
| HMA | Hull — near-zero lag for short windows |
| ALMA | Arnaud Legoux (0.85, 6.0) — Gaussian-weighted, smoothest |
| SMA | Simple — most stable, most lag |
The Signal Cross alert can be optionally filtered by HTF alignment — when enabled, the alert fires only when LTF and HTF regimes match. Filter is auto-bypassed when HTF Confluence is globally OFF (silent-kill protection).
🟦 MULTI-TIMEFRAME CONFLUENCE
The same regime logic runs on a user-configured higher timeframe via `request.security` with `lookahead = barmerge.lookahead_off` and `gaps = barmerge.gaps_off` (anti-repaint mandatory). The result is reported in the Status dashboard's HTF block:
| State | Display | Color |
|---|---|---|
| HTF regime matches LTF regime | ✓ ALIGNED | bull |
| HTF regime differs from LTF | ⚠ DIVERGENT | bear |
| Insufficient HTF data | — | foreground |
Divergent regimes are common at trend turns — the LTF flips before the HTF catches up. Aligned regimes carry higher conviction. A separate alert ("MTF Confluence") fires on regime entries only when the HTF agrees.
Recommended pairings:
| Chart | HTF |
|---|---|
| 15m | 1H |
| 1H | D |
| 4H | W |
| D | W |
| W | M |
Use at least 3× your chart timeframe — anything closer and the two regimes track each other with no information gain.
🟦 OSCILLATOR PANEL VISUAL LAYER
Main Oscillator Line
The oscillator value plotted as a continuous line with five color tiers reflecting regime strength:
| Range | Color |
|---|---|
| ≥ +100 | full Bull |
| +70 to +100 | dim Bull (pending up) |
| −70 to +70 | neutral Side |
| −100 to −70 | dim Bear (pending down) |
| ≤ −100 | full Bear |
Line width is configurable 1 – 5 pixels.
Signal Line
A smoothed overlay of the main oscillator, faded foreground color, single-pixel width. Drives the Signal Cross alert and the dashboard Signal cell.
Reference Levels
Three horizontal levels per panel side:
- ±100 — official regime boundaries (solid plot line)
- ±70 — pending early-warning zones (dashed `line.new`)
- 0 — neutral midline (dashed `line.new`)
The dashed lines use `line.new()` rather than `plot.style_circles` so they remain pixel-stable at any chart zoom — they will NOT rescale or fragment.
Regime Ribbon
The oscillator panel background is tinted to the current regime color at 20 % opacity. Provides instant regime context at a glance — Bull / Bear / Side periods are visually separated even when zoomed out on long history. Toggleable.
Gradient Fill
The area between the oscillator line and zero is filled in the regime color, with intensity scaling adaptively by distance from zero — stronger color = higher conviction. Empty at zero.
Three-Layer Neon Glow Signals
On every confirmed regime transition (after the Min Hold filter passes), the indicator drops a three-layer halo on the oscillator line:
| Layer | Size | Transparency | Purpose |
|---|---|---|---|
| Outer | size.large | 80 % | Soft halo |
| Middle | size.normal | 50 % | Mid-glow |
| Core | size.small | 0 % | Bright center |
Bull entries (▲ triangle up), Bear entries (▼ triangle down), and Side entries (◆ diamond). The Min Hold input (default 4 bars) requires a new regime to persist before its flip is drawn — kills label spam in choppy zones without affecting the underlying transition counts.
Forecast Cone Polyline
On the last confirmed bar, a colored polyline extends into the future for N bars, plotting the expected oscillator value at each step. Color reflects the dominant regime at that step. Drawn with `line.new()` so segments are pixel-stable; recomputed on every chart refresh.
🟦 PRO STATUS DASHBOARD
A single dashboard rendered on the MAIN PRICE CHART (not the oscillator panel) via `force_overlay = true`. This keeps the oscillator panel uncluttered so the oscillator line, signal line, gradient fill, and forecast cone get the full pane height.
The dashboard is structured in seven sections, all theme-aware:
| Section | Cells |
|---|---|
| REGIME | Regime, Age + tier, Confidence, Pending, Velocity |
| FORECAST +1 | P(Bull), P(Bear), P(Side) — each with 95 % CI |
| HORIZON +N | Dominant regime at terminal forecast step + probability |
| STATIONARY π | π(Bull), π(Bear), π(Side) — long-run equilibrium |
| OSCILLATOR | Value, Signal direction, Threshold, Drift basis points |
| HTF | Regime + Aligned / Divergent status |
| DATA | Mode, Decay half-life, Matrix tier, Sample N |
Position is configurable across 9 chart corners. Text size: Tiny / Small / Normal / Large. Default Tiny so the full 30-row layout fits on any chart without scrolling. Background and text colors flip between Dark and Light display modes.
🟦 COLOR THEMES
Ten cohesive palettes tuned to the Apex design system, each defining three regime axes (Bull, Bear, Sideways):
| Theme | Character | Bull | Bear | Sideways |
|---|---|---|---|---|
| Focus (default) | Modern | Cyan | Deep orange | Cool blue-grey |
| Prism | Classic | Forest green | Crimson | Slate grey |
| Solar | Warm | Amber | Indigo red | Lavender grey |
| Frost | Cool | Sky blue | Soft lavender | Pale steel |
| Laser | Neon | Lime green | Hot crimson | Charcoal grey |
| Aurora | Bright | Gold | Scarlet | Warm beige |
| Plasma | Electric | Aqua | Magenta | Slate teal |
| Bloom | Soft | Mint | Hot pink | Blue-grey |
| Eclipse | Deep | Navy | Dark crimson | Steel grey |
| Carbon | Minimal | Near-white | Mid-grey | Dark grey |
One theme selection drives every visual component: oscillator line, signal line, reference levels, ribbon, fill, glow signals, forecast cone, and all dashboard cells.
Dark / Light Display Mode
Dashboard chrome (background, foreground, borders, section dividers) flips between dark-on-bright and bright-on-dark. The regime axis colors remain consistent across modes — only the panel chrome changes.
🟦 ALERT SYSTEM
Seven alert conditions, each independently togglable:
| Alert | Condition |
|---|---|
| Bull Regime Entry | Regime flipped to BULL (after Min Hold confirmation) |
| Bear Regime Entry | Regime flipped to BEAR (after Min Hold confirmation) |
| Sideways Regime Entry | Regime flipped to SIDEWAYS (default OFF) |
| High Confidence | confidence ≥ 2.5× threshold, first bar of crossing |
| Pending Regime | Inside Sideways, log return ≥ 70 % of either boundary (default OFF) |
| MTF Confluence | Bull / Bear entry + HTF agrees |
| Signal Cross | Main oscillator crosses signal line (default OFF) |
All alerts fire on confirmed bar close. Entry alerts respect the Min Hold filter — a new regime must persist Min Hold bars before its entry alert fires, matching the on-chart glow markers.
The Signal Cross alert can be optionally filtered by HTF alignment (Multi-Timeframe → Filter Signal Cross by HTF). The filter is automatically bypassed when HTF Confluence is globally OFF, so enabling the filter without HTF doesn't silently kill the alert.
🟦 SETTINGS REFERENCE
Theme
- Theme — One of 10 Apex palettes. Default: Focus
- Display Mode — Dark / Light. Default: Dark
Regime Logic
- Threshold Mode — Adaptive (k·σ·√N) / Fixed (%). Default: Adaptive
- Lookback Window — Bars for the rolling log return. Default: 20
- Adaptive k — Sigma multiplier. Default: 1.5
- Fixed Bull Threshold — Used only in Fixed mode. Default: 5.0 %
- Fixed Bear Threshold — Used only in Fixed mode. Default: 5.0 %
- Volatility Window — Bars for the per-bar stdev. Default: 100
- Min Hold — Bars a new regime must persist for entry alerts and glow markers. Default: 4
- Drift-Adjusted Log Returns — Toggle the drift adjustment. Default: ON
- Drift Window — Bars for the long-term mean drift estimate. Default: 250
- Require Momentum Agreement — Velocity sign filter on regime classification. Default: OFF
Bayesian Math
- EWMA Transition Counts (Decay) — Toggle exponential decay. Default: ON
- Decay Half-Life — Bars after which an old count weighs half. Default: 500
- Semi-Markov Duration Conditioning — Toggle the Young / Mature split. Default: ON
- Age Median — Boundary between Young and Mature regimes. Default: 10
- Bayesian Credible Intervals (95 %) — Toggle CI display in the dashboard. Default: ON
Forecast
- Forecast Cone Horizon — Number of bars projected by matrix iteration. Default: 5
- Show Forecast Cone — Toggle the in-panel cone polyline. Default: ON
Oscillator
- Show Signal Line — Toggle the smoothed signal overlay. Default: ON
- Signal Smoothing Method — EMA / HMA / ALMA / SMA. Default: EMA
- Signal Smoothing Length — Window length. Default: 5
- Velocity Window — Bars for the rate-of-change measurement. Default: 5
- Oscillator Line Width — Pixels. Default: 2
Display
- Show Regime Ribbon — Toggle the panel background tint. Default: ON
- Show Gradient Fill — Toggle the oscillator-vs-zero fill. Default: ON
- Show Reference Levels — Toggle the ±100 / ±70 / 0 horizontal lines. Default: ON
- Show Regime Change Glow — Toggle the three-layer halo markers. Default: ON
Multi-Timeframe
- Enable HTF Confluence — Toggle. Default: ON
- HTF Resolution — Higher timeframe. Default: D
- Filter Signal Cross by HTF Alignment — Conditional filter on cross alert. Default: OFF
Dashboard
- Show Status Dashboard — Toggle. Default: ON
- Position — Nine chart corners. Default: Top Right
- Size — Tiny / Small / Normal / Large. Default: Tiny
Alerts
- Bull / Bear / Sideways Regime Entry — Independent toggles
- High Confidence (≥ 2.5×) — Default: ON
- Pending Regime — Default: OFF
- MTF Confluence — Default: ON
- Signal Cross — Default: OFF
🟦 COMPATIBILITY
Works on all asset classes and all timeframes in TradingView Pine Script v6.
- Crypto: Spot, futures, perpetual contracts
- Forex: All pairs
- Equities: Stocks, ETFs, indices
- Commodities: Metals, energy, agriculture
- Timeframes: 1m through Monthly
The adaptive threshold normalises by per-bar realised volatility, and the drift adjustment normalises by the asset's long-run mean drift — together making the regime classification volatility-and-drift-agnostic across assets without manual recalibration. The same default settings work on BTCUSDT daily, SPY weekly, and EURUSD 4H — only the HTF resolution input should be adjusted to match the chart timeframe.
🟦 TECHNICAL NOTES
- Pine Script v6
- `max_labels_count = 500`, `max_lines_count = 500`, `max_bars_back = 5000`
- No repainting — all regime classifications are computed on confirmed bar close. The HTF request uses `lookahead = barmerge.lookahead_off` and `gaps = barmerge.gaps_off`
- Transition counting uses `barstate.isconfirmed` to avoid double-counting the live bar
- Regime change debouncing uses `ta.barssince` to avoid runtime-indexed history reads (which can trip "cannot determine max_bars_back" in Pine v6)
- Heavy computation (P matrix construction, N-step iteration, Bayesian CI math, stationary distribution power iteration, dashboard rendering) is gated on `barstate.islast` to run once per chart render
- Matrix multiplication is implemented as unrolled single-line expressions over a flat 9-cell array for portability and speed
- EWMA decay multiplies all 9 cells of all 3 matrices (counts, countsYoung, countsMature) once per confirmed bar — O(27) per bar overhead
- Dirichlet smoothing prevents NaN propagation when a regime has not appeared in visible history — empty rows fall back to uniform 1/3
- Duration buckets classify by the SOURCE regime's age at the moment of transition (`regAge `), so the bucketing reflects the regime that was about to transition rather than the destination
- `ta.crossover` / `ta.crossunder` are computed at global scope every bar to satisfy Pine's stateful-series rule (the gated cross events read from the cached values)
- Dashboard is rendered with `force_overlay = true` on the main price chart — keeps the oscillator panel free of UI clutter
- Reference-level dashed lines use `line.new()` with `style = line.style_dashed` and `extend = extend.both` for pixel-stable rendering at any zoom
🟦 LIMITATIONS — READ THIS
This indicator is statistically honest about what it can and cannot do. Four known limitations:
1. The Markov assumption is partially violated. Markets are not memoryless. The semi-Markov Young / Mature split mitigates this but does not eliminate it. EWMA decay further mitigates by down-weighting ancient transitions, but a truly path-dependent process (one where the SEQUENCE of recent regimes matters, not just the last one) is not captured.
2. Forward probabilities are not predictions. They are conditional probabilities under the chain assumption with the credible intervals quantifying the SAMPLING uncertainty around them. A "Bull 58 % at +5 bars" reading does not mean "58 % chance the next 5 bars are bullish" — it means "given a long-run sample of similar starting states and the active EWMA-decayed transition matrix, 58 % were in Bull at +5 bars". Use the cone as ONE input alongside other analysis.
3. The regime label lags by N bars. This is structural — the rolling log return necessarily looks back. The Pending early warning and the optional Momentum Filter partially mitigate this but cannot eliminate the lag. Treat the official regime change as a confirmation, not a leading signal.
4. Forecast cone reliability decays with horizon. By +5 bars the cone is at the edge of usefulness; by +20 bars it collapses toward the stationary distribution and carries no additional information beyond π. The default horizon is 5 bars for this reason. Do not over-interpret the right side of the cone.
🟦 DISCLAIMER
This indicator is provided for educational and informational purposes only. It does not constitute financial advice. Past performance does not guarantee future results. The forward probabilities are conditional estimates derived from historical transition counts under a (semi-)Markov model assumption — they are NOT guarantees about future market behaviour. Always conduct your own analysis and apply proper risk management. Indicateur

Markov Forecaster PRO🟦 Markov Forecaster PRO is a regime-classification and probability-forecasting engine built on a discrete-time Markov chain over three states — Bull, Bear, Sideways. Every bar is labelled from its rolling N-bar log return; the labels feed a 3×3 transition matrix that is power-iterated for the stationary distribution and exponentiated for forward-probability cones (P¹, P³, P⁵, P^horizon). Unlike the dozens of textbook Markov indicators on TradingView, this one layers four original refinements on top of the standard chain construction — each addressing a well-known weakness of the memoryless Markov assumption.
The indicator integrates seven analytical layers — adaptive regime classification, semi-Markov duration tracking, sample-size disclosure, pending-regime early warning, forward-probability forecasting, look-ahead-free backtesting with fees and slippage, and multi-timeframe confluence — each rendered on a single overlay chart through a regime ribbon, three-layer neon glow signals, and four theme-aware dashboard panels.
Built with statistical honesty in mind. The backtest charges configurable commission and slippage on every entry and exit, the transition matrix flags rows with insufficient data, the duration-conditional probabilities are shown alongside the unconditional ones, and the documentation is explicit about what the model can and cannot predict.
🟦 HOW THE CORE ENGINE WORKS
**Regime Classification**
Each bar, the engine measures the rolling N-bar log return:
logRet = log(close / close )
The bar is labelled by comparing this return against the configured boundary:
- `logRet > +threshold` → BULL
- `logRet < −threshold` → BEAR
- otherwise → SIDEWAYS
The classification runs every bar with no look-ahead. The choice of threshold determines how reactive the regime label is, and this is where the first refinement enters.
**Adaptive Threshold (k · σ · √N)**
Traditional Markov regime indicators use a fixed percentage cut — e.g. "±5 % over 20 bars". This collapses on real markets: the same 5 % is trivial in a 2017 mania and never reached in 2023 chop. The fix is to scale the boundary with realised volatility:
threshold_adaptive = k × σ × √N
where σ is the per-bar log-return standard deviation over a configurable window (default 100 bars). Under a random walk, k = 1.0 cuts at the 16th / 84th percentiles; k = 2.0 at the 2.5th / 97.5th percentiles. The default k = 1.5 reproduces classic ±1.5-sigma thresholds.
Fixed-percentage mode is still available for users who want to lock the threshold deliberately.
**Regime Confidence**
Once classified, the move's strength is normalised relative to the active boundary:
confidence = |logRet| / threshold
| Confidence | Tier | Visual |
|---|---|---|
| < 1.0× | weak | ▱▱▱ |
| 1.0× – 2.0× | moderate | ▰▱▱ |
| 2.0× – 3.0× | strong | ▰▰▱ |
| ≥ 3.0× | stretched | ▰▰▰ |
The confidence value drives the ribbon transparency (in Adaptive Intensity mode), feeds the High Confidence alert (≥ 2.5× trigger), and is reported in the Status dashboard.
🟦 SEMI-MARKOV DURATION BUCKETS
**The Memoryless Problem**
A standard Markov chain says: "Given I'm in Bull, the probability of staying Bull tomorrow is X — regardless of whether Bull started yesterday or 200 bars ago." This is the memoryless property, and on real markets it's wrong. A 200-day-old Bull regime carries different mean-reversion risk than a 5-day-old one.
**The Refinement**
Markov Forecaster PRO additionally builds two CONDITIONAL transition matrices:
- `P_young` — transitions counted when the source regime's age was below its empirical average duration
- `P_mature` — transitions counted when the source regime's age was at or above the average
Both matrices are constructed in parallel with the main P, using the same per-bar bucketing logic and updated continuously. The self-transition probabilities for the current regime are then surfaced in the Status dashboard:
P young / mature 91% / 64%
The user reads this as: "When this regime was young (under its avg duration), it continued 91 % of the time. When mature, only 64 %." On a long-running regime this is the canonical signal that mean-reversion risk is rising — without the rest of the chain math being polluted.
A minimum of 10 samples per bucket is required before a value is shown; below that the cell reports "—" rather than display an unreliable probability.
🟦 FORWARD PROBABILITY CONE
**Matrix Exponentiation**
The 3×3 transition matrix P encodes one-bar-ahead probabilities. To project further out, the matrix is multiplied by itself:
P¹ = P — next bar
P³ = P × P × P — 3 bars out
P⁵ = P × P × P × P × P — 5 bars out
P^h = repeated h times — user-configured horizon
The Forecast Cone panel renders all four horizons for each of the three destination regimes, conditioned on the current regime. A trader reading the row "BULL" sees the probability the market will be in Bull at each horizon, given the current regime.
**Stationary Distribution**
Power-iterating the matrix to convergence yields the stationary distribution — the long-run probability of being in each regime, independent of starting state. With 50 iterations (default), any well-behaved 3×3 stochastic matrix is essentially converged.
stat + stat + stat = 1.0
This is rendered as the "long-run" row in the Forecast panel and the "Long-run share" cell in the Status panel.
**Honest Limitation**
The cone uses the UNCONDITIONAL matrix (averaged over all regime ages). For duration-conditional probabilities, the Status panel's P cell is the relevant readout. This split is explicit in both the cone footer label and the Forecast input tooltip.
🟦 SAMPLE-SIZE DISCLOSURE
A probability is only as reliable as the data behind it. Markov Forecaster PRO surfaces sample size in three places:
**Per-row sample count in the Transition Matrix**
A fifth column "n" in the matrix panel reports the number of transitions from each source regime. The cell is colored by reliability tier:
| Sample N | Tier | Color |
|---|---|---|
| ≥ 100 | high | foreground |
| 30 – 99 | moderate | dim |
| < 30 | low | divergent (warning) |
A row with fewer than 30 transitions is flagged because three-decimal probabilities derived from sparse data are noise, not signal.
**Total Sample N in the Status panel**
The Status dashboard's "Sample N" cell sums all transition counts and reports a global reliability tier:
| Total N | Tier |
|---|---|
| ≥ 200 | high (full color) |
| 50 – 199 | moderate (foreground) |
| < 50 | low (divergent warning) |
**Matrix footer**
The matrix panel's footer also shows the total N in compact notation (e.g. "N = 1.8k") for at-a-glance check.
The goal of this layer is honesty: a freshly-loaded chart with 30 bars of history should NOT display the same matrix as a 10-year chart, and the reliability tier makes the difference obvious without the user having to inspect counts manually.
🟦 PENDING-REGIME EARLY WARNING
**The Lookback Lag**
Because the regime is classified from log(close / close ), the official regime label inherently lags — by the time the threshold is crossed, the move is already N bars old. This is a structural feature of the model, not a bug, but it can be partially mitigated.
**Pending Logic**
Inside Sideways, when the log return reaches 70 % of either boundary, the dashboard fires an early-warning cue:
distance_fraction = max(|logRet| / threshold, ...)
isPending = (regime == SIDE) AND (distance_fraction ≥ 0.70)
The Status panel's "Pending" cell displays the direction the return is leaning toward and the current fraction:
⚠ ▲ BULL 87%
Color matches the leaning regime. The Pending Regime alert (default OFF, opt-in) fires on the first bar a pending state is entered.
This is not a regime change signal — it's a "watch this" cue, triggered roughly 30 % before the official threshold is crossed. Used alongside the official regime change, it gives the user advance notice without compromising the threshold's strictness.
🟦 LOOK-AHEAD-FREE BACKTEST
**The Look-Ahead Trap**
`regime` is derived from `log(close / close )`, which contains today's close. Allocating today's return to today's regime is look-ahead bias — the strategy would "know" today's regime before today's close, which is impossible in real-time trading. Most published Markov backtests have this bug.
**The Fix**
Markov Forecaster PRO allocates positions on the PRIOR bar's confirmed regime:
regForAlloc = regime // yesterday's confirmed regime
If yesterday's regime was Bull, we are long today. The strategy is realisable in real time because the previous bar's regime is known when the current bar opens.
This means the strategy is delayed by one bar relative to the regime label — and that's the correct, honest treatment. If a Bull→Bear flip happens on bar t, the strategy takes bar t's loss (still long from regime =Bull) and exits at bar t+1.
**Fees and Slippage**
Every Bull entry and exit pays the configured per-fill cost:
costFrac = feesPct/100 + slippageBps/10000
costPerFill = log(1 − costFrac) // negative log-space cost
The cumulative cost is debited from the Bull log-return total:
Bull gross = exp(bullLogR) − 1
Bull net = exp(bullLogR + bullCostLogR) − 1
A round-trip pays the fee + slippage twice. With defaults (0.10 % fee, 5 bps slippage), each round-trip costs roughly 0.30 % of equity in log space.
**Display**
The Backtest panel renders:
| Field | Value |
|---|---|
| Per-regime rows | GROSS cumulative log return (no fees) |
| Strategy row | NET cumulative (fees applied) vs Buy-and-Hold |
| Methodology footer | trade count · fee % · slippage bps |
The headline strategy result is the NET number — the realistic outcome a trader would have experienced. The gross numbers are kept for diagnostic comparison.
**What This Is Not**
This is a diagnostic backtest, not a tradable strategy. There is no position sizing, no risk management, no overnight financing, no shorting. It tells you whether "long when prior bar was Bull, flat otherwise" would have beaten buy-and-hold after fees — nothing more.
🟦 MULTI-TIMEFRAME CONFLUENCE
The same regime logic runs on a user-configured higher timeframe via `request.security` with `lookahead = barmerge.lookahead_off` and `gaps = barmerge.gaps_off` (anti-repaint mandatory). The result is reported in the Status dashboard's HTF block:
| State | Display | Color |
|---|---|---|
| HTF regime matches LTF regime | ✓ ALIGNED | bull |
| HTF regime differs from LTF | ⚠ DIVERGENT | bear |
| Insufficient HTF data | — | foreground |
Divergent regimes are common at trend turns — the LTF flips before the HTF catches up. Aligned regimes carry higher conviction. A separate alert ("MTF Confluence") fires on regime entries only when the HTF agrees.
Recommended pairings:
| Chart | HTF |
|---|---|
| 1H | D |
| 4H | W |
| D | W |
Use at least 3× your chart timeframe — anything closer and the two regimes track each other with no information gain.
🟦 VISUAL LAYER
**Regime Ribbon**
The chart background is tinted to the current regime color with three style options:
| Style | Behaviour |
|---|---|
| Subtle | Fixed 92 % transparency (price stays hero) |
| Bold | Fixed 75 % transparency (easy to scan from far) |
| Adaptive Intensity | Transparency scales with confidence (60 % – 95 %) |
In Adaptive Intensity mode, a strong directional move (confidence ≥ 3×) renders the ribbon at full intensity; a weak move stays faint. The ribbon doubles as a visual confidence meter.
**Three-Layer Neon Glow Signals**
On every confirmed regime change (after the Min Hold filter), the indicator drops a three-layer halo on the chart:
| Layer | Size | Transparency | Purpose |
|---|---|---|---|
| Outer | size.large | 80 % | Soft halo |
| Middle | size.normal | 50 % | Mid-glow |
| Core | size.small | 0 % | Bright center |
Bull markers (▲) render below the bar; Bear (▼) and Sideways (◆) render above. The Min Hold input (default 4 bars) requires a new regime to persist before its flip is drawn — kills label spam in choppy zones without affecting the underlying transition counts.
**Confidence Tags (optional)**
An off-by-default toggle adds the confidence multiplier to each signal arrow ("BULL 2.3×"), useful for screen captures and analysis.
🟦 DASHBOARDS
Four theme-aware panels, each independently togglable and positionable:
**Status Panel** (default: Bottom Left)
Compact live readout — current regime, age, confidence, pending direction, average duration, young/mature bucket, P young vs mature, expected remaining bars, long-run share, sample size, and HTF alignment. 16 rows base, 19 with HTF block enabled.
**Transition Matrix Panel** (default: Top Right)
3×3 next-bar P matrix with diagonal-highlighted self-transition cells. The fifth column reports per-row sample size with reliability tier coloring. Matrix footer shows total N.
**Forecast Cone Panel** (default: Middle Right)
Forward probability for each destination regime at horizons +1, +3, +5, and +configured. Steady-state row shows the long-run distribution. Current regime is reported at the bottom for context.
**Backtest Panel** (default: Bottom Right)
Per-regime gross cumulative return, average per-bar, and the bar count. Strategy row shows NET return vs buy-and-hold. Methodology footer lists trade count, fee, and slippage.
All four panels share the same theme palette and adapt to Dark / Light display mode. Text size is independently configurable (Tiny / Small / Normal / Large).
🟦 COLOR THEMES
Ten cohesive palettes tuned to the Apex design system, each defining three regime axes (Bull, Bear, Sideways):
| Theme | Character | Bull | Bear | Sideways |
|---|---|---|---|---|
| Prism | Classic | Forest green | Crimson | Slate grey |
| Focus | Default | Cyan steel | Deep orange | Cool blue-grey |
| Solar | Warm | Amber | Indigo red | Lavender grey |
| Frost | Cool | Sky blue | Soft lavender | Pale steel |
| Laser | Neon | Lime green | Hot crimson | Charcoal grey |
| Aurora | Bright | Gold | Scarlet | Warm beige |
| Plasma | Electric | Aqua | Magenta | Slate teal |
| Bloom | Soft | Mint | Hot pink | Blue-grey |
| Eclipse | Deep | Navy | Dark crimson | Steel grey |
| Carbon | Minimal | Near-white | Mid-grey | Dark grey |
One theme selection drives every visual component: ribbon, glow signals, all four dashboard headers, regime-colored cells, diagonal matrix highlights, and HTF alignment color.
**Dark / Light Display Mode**
Dashboard chrome (background, foreground, borders, section dividers) flips between dark-on-bright and bright-on-dark. The regime axis colors remain consistent across modes — only the panel chrome changes.
🟦 ALERT SYSTEM
Six alert conditions, each independently togglable:
| Alert | Condition |
|---|---|
| Bull Regime Entry | Regime flipped to BULL (after Min Hold confirmation) |
| Bear Regime Entry | Regime flipped to BEAR |
| Sideways Regime Entry | Regime flipped to SIDEWAYS (default OFF) |
| High Confidence | confidence ≥ 2.5× threshold, first bar of crossing |
| MTF Confluence | Regime change + HTF agrees |
| Pending Regime | Inside Sideways, log return ≥ 70 % of either boundary (default OFF) |
All alerts fire on confirmed bar close and use the standard `alertcondition` mechanism. The Min Hold filter applies to entry alerts — a new regime must persist Min Hold bars before its entry alert fires, matching the on-chart glow markers.
The Sideways and Pending alerts are default-off because they can fire more frequently than the other types — opt-in by design.
🟦 SETTINGS REFERENCE
**Theme**
- Theme — One of 10 Apex palettes. Default: Focus
- Display Mode — Dark / Light. Default: Dark
**Regime Logic**
- Threshold Mode — Adaptive (k·σ·√N) / Fixed (%). Default: Adaptive
- Lookback Window — Bars for the rolling log return. Default: 20
- Adaptive k — Sigma multiplier. Default: 1.5
- Fixed Bull Threshold — Used only in Fixed mode. Default: 5.0 %
- Fixed Bear Threshold — Used only in Fixed mode. Default: 5.0 %
- Volatility Window — Bars for the per-bar stdev. Default: 100
- Min Hold — Bars a new regime must persist for label drawing. Default: 4
**Forecast**
- Forecast Horizon — Bars projected by the right-most cone column. Default: 10
- Stationary Power — Power-iteration count. Default: 50
**Regime Ribbon**
- Show Regime Ribbon — Toggle. Default: ON
- Ribbon Style — Subtle / Bold / Adaptive Intensity. Default: Adaptive Intensity
**Signal Labels**
- Show Regime Change Signals — Toggle. Default: ON
- Glow Effect — Three-layer halo toggle. Default: ON
- Show Confidence on Signal — Adds multiplier tag (e.g. "BULL 2.3×"). Default: OFF
**Multi-Timeframe**
- Enable HTF Confluence — Toggle. Default: ON
- HTF Resolution — Higher timeframe. Default: D
**Backtest**
- Trading Fee (% per fill) — Per-side commission. Default: 0.10 %
- Slippage (bps per fill) — Per-side slippage in basis points. Default: 5
**Dashboards**
- Show Status / Matrix / Forecast / Backtest — Independent toggles. Default: all ON
- Dashboard Size — Tiny / Small / Normal / Large. Default: Small
**Panel Positions**
- Status Panel — 9-position grid. Default: Bottom Left
- Matrix Panel — Default: Top Right
- Forecast Panel — Default: Middle Right
- Backtest Panel — Default: Bottom Right
**Alerts**
- Bull / Bear / Sideways Regime Entry — Independent toggles
- High Confidence — Default: ON
- MTF Confluence — Default: ON
- Pending Regime — Default: OFF
🟦 COMPATIBILITY
Works on all asset classes and all timeframes in TradingView Pine Script v6.
- Crypto: Spot, futures, perpetual contracts
- Forex: All pairs
- Equities: Stocks, ETFs, indices
- Commodities: Metals, energy, agriculture
- Timeframes: 1m through Monthly
The adaptive threshold normalises by per-bar realised volatility, making the regime classification volatility-agnostic across assets without manual recalibration. The same default settings work on BTCUSDT daily, SPY weekly, and EURUSD 4H — only the HTF resolution input should be adjusted to match the chart timeframe.
🟦 TECHNICAL NOTES
- Pine Script v6
- `max_labels_count = 500`, `max_lines_count = 100`, `max_bars_back = 5000`
- No repainting — all regime classifications are computed on confirmed bar close. The HTF request uses `lookahead = barmerge.lookahead_off` and `gaps = barmerge.gaps_off`
- Regime change debouncing uses `ta.barssince` to avoid runtime-indexed history reads (which can trip "cannot determine max_bars_back" in Pine v6)
- Heavy computation (matrix exponentiation, stationary distribution, dashboard rendering) is gated on `barstate.islast` to run once per chart render
- Transition counting uses `barstate.isconfirmed` to avoid double-counting the live bar
- Backtest accumulators charge fees at trade boundaries — entries and exits detected by `regForAlloc != regForAlloc `
- Duration buckets use the SOURCE regime's age at the time of transition for classification; the threshold is the empirical average duration of that regime, computed continuously
- Matrix multiplication is implemented as an unrolled 3×3 flat-array routine for portability and speed
- Empty-row fallback to uniform 1/3 in the transition matrix prevents NaN propagation when a regime has not appeared in visible history
🟦 LIMITATIONS — READ THIS
This indicator is statistically honest about what it can and cannot do. Three known limitations:
1. **The Markov assumption is partially violated.** Markets are not memoryless. The duration buckets (Section: Semi-Markov Duration Buckets) mitigate this but do not eliminate it.
2. **Forward probabilities are not predictions.** They are conditional probabilities under the chain assumption. A "Bull 58 % at +10 bars" reading does not mean "58 % chance the next 10 bars are bullish" — it means "given a long-run sample of similar starting states, 58 % were in Bull at +10 bars". Use the cone as ONE input alongside other analysis.
3. **The regime label lags by N bars.** This is structural — the rolling log return necessarily looks back. The Pending early warning partially mitigates this but cannot eliminate the lag. Treat the official regime change as a confirmation, not a leading signal.
🟦 DISCLAIMER
This indicator is provided for educational and informational purposes only. It does not constitute financial advice. Past performance does not guarantee future results. The hypothetical backtest is a diagnostic tool — there is no position sizing, no risk management, and no consideration of overnight financing, dividends, or other real-world frictions beyond the configured fee and slippage. Always conduct your own analysis and apply proper risk management. Indicateur

Liquidity Surge Forecast with Markov Chains [TechnicalZen]Clear direction from Markov Chains confirmed projections.
Publishing this v3 with all the enhancements users desired and more. Thank you for your feedback.
What This Is
A 3D liquidity-and-momentum visualization that tells you where the market is heading right now, how long the current state is likely to hold, and when the next regime change is expected — all backed by a 2nd-order Markov chain that learns from your chart's own history.
Two independent systems — Money Flow (MFI-driven) and Price Current (Hull-VWMA or signed-ADX) — render as layered dotted carpets inside a bounded 3D box. When both systems agree on direction AND the Markov chain confirms, a whale surfaces — 🐳 bullish, 🐋 bearish. Chop gets a shark 🦈. Sideways drift gets a crab 🦀. And when the Markov chain predicts an imminent regime transition, a small hatchling whale appears before confluence forms.
The Current State row tells you, in one line, exactly what to expect next.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Built On
Money Flow Dynamics Forecaster 3D — the original 3D layered-terrain architecture, MFI/RSI momentum carpet, Hull-VWMA price current carpet, slope-extrapolated forecast, rider + whale system.
Same 3D engine. Same dual-system confluence as the foundation. Then: regime classification, Markov statistical learning, current-state intelligence, and a live win-rate scoreboard on top.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Clear Direction — At A Glance
Most indicators show you lines and ask you to interpret. This one tells you plainly, in a single dashboard row:
What regime you're in right now — 🐳 Bull, 🐋 Bear, 🦈 Chop-zone, or 🦀 Sideways
How long it's been held — in bars
Whether the regime is BALANCED or IMBALANCED — based on the Markov chain's next-bar probabilities
When the next regime change is expected — in bars, computed from the stay-probability
Which direction the market leans next — the highest-probability non-current state
Example readouts:
"Current State: 🐳 Bull held 5b · IMBALANCED — stay 68%, change expected in ~3b · next lean: 🦀 Sideways"
"Current State: 🦀 Sideways held 12b · BALANCED — change imminent · next lean: 🐳 Bull"
"Current State: 🐋 Bear held 2b · IMBALANCED — stay 82%, change expected in ~5b · next lean: 🦀 Sideways"
No interpretation required. You read the line, you know where you are, you know what to expect.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
New Features — And Why Each Exists
1. Current State intelligence row
Why: Confluence indicators tell you WHEN a signal fires. They don't tell you "how solid is the current regime," "is a change coming," or "how long do I have before conditions flip." The Current State row answers all three in one glance.
The balanced / imbalanced distinction matters most:
BALANCED — the three next-bar probabilities are close to 1/3 each. No clear direction. A regime change is imminent (could go anywhere). Trade lighter, wait for resolution.
IMBALANCED — one direction dominates. Regime has a preferred path. The stay-probability tells you how long it's likely to persist; the next-lean tells you which direction it will tilt when it does flip.
The expected-bars-to-change is a geometric distribution mean: 1 / (1 − P(stay)). If a regime has 80% stay probability, it's expected to persist ~5 more bars. If 33%, it's expected to flip in ~1.5 bars.
2. 2nd-order Markov chain regime predictor
Why: the original whale logic was reactive — it fires after confluence forms. Markov is predictive — it learns your instrument's transition habits and uses them to gate and anticipate whale signals.
Pure statistics, no black box:
2nd-order — predicts the next regime from the pair of previous regimes, not just one. Captures patterns like "Chop → Sideways → 68% Bull next" that a 1st-order chain would miss.
Laplace smoothing (α=1) — every transition count gets a +1 pseudocount before normalization. Prevents "never observed → 0% forever" failure. Standard in real statistics.
Exponential recency decay — newer transitions count more than old ones (default 0.995/bar). Markets drift; stale history shouldn't dominate current prediction.
Duration conditioning — separate transition matrices for "current state held <5 bars" vs "held ≥5 bars." Regimes behave differently after they've been running. Real statistical sub-populations.
Confidence gating — if the current context has fewer than 10 observations, predictions are flagged low-n . No fabricated probabilities.
Maximum useful substance without gimmick. 3rd-order Markov would need thousands of regime transitions per cell to converge — doesn't happen on typical charts. 2nd-order is the ceiling before diminishing returns.
3. Dual-layer regime classification — Chop-zone 🦈 vs Sideways 🦀
Why: prior versions treated "not trending" as a single category. But there are two fundamentally different kinds of non-trending market:
🦈 Chop-zone — violent range-bound circling. Detected via classic Choppiness Index . Often precedes a sharp breakout.
🦀 Sideways — slow drift, flat angles across close/high/low at both short and long periods. Detected via angle consensus . Often indicates accumulation or distribution.
Showing them separately lets you read which kind of non-trending you're in. Different implications, different decisions.
4. Hatchling whales — pre-signal pre-whales
Why: the Markov chain lets us anticipate confluence before it forms. When the current state is Sideways AND Markov predicts Bull (or Bear) with confidence above the hatchling threshold, a small whale appears at the mid-forecast position — a heads-up that confluence is probabilistically coming.
Full whale (size.huge at forecast edge) = confluence is here now.
Hatchling whale (size.small at forecast mid) = confluence is probably coming soon.
Better entries on regime changes.
5. Markov-gated whale confirmation
Why: sometimes projected-confluence fires, but the instrument's historical pattern says "from this context, the opposite is more likely." That's exactly the setup a trader wants the indicator to filter out .
The gate is permissive — Markov blocks a whale only if it's confident AND its argmax points the opposite direction. Uncertainty or agreement = pass through. Reduces false confluence without over-filtering.
6. Regime-aware 4-column win-rate dashboard
Why: knowing how much time the instrument actually spends in each regime is as actionable as the signals themselves.
Four parallel columns:
🐳 Bull — confluence signals and win rate
🐋 Bear — same, opposite direction
🦈 Chop-zone — CI chop events and % of bars
🦀 Sideways — angle-sideways events and % of bars
If your instrument spends 80% of bars in Chop/Sideways, confluence will be rare — adjust timeframe or instrument. If Markov shows low-n on most bars, the matrix isn't populated yet — wait for more history before trusting predictions.
7. Session-aware for futures
Why: NQ, ES, CL and other overnight-session futures stamp their daily bar at session start , which is the previous calendar evening. Naive `dayofweek(time)` reads NQ's "Friday session" as Thursday. The indicator uses `time_close("D")` — the close of the daily bar, always on the trading date — so regime classification is correct for both cash equities (TSLA, SPY) and overnight futures (NQ, ES). Same indicator, any asset class.
8. Honest evaluation — next-signal MFE or directional close
Why: "close-at-N-bars" is dishonest. Price can move 2×ATR favorably then retrace — close-at-N logs that as a loss. MFE logs it as what it actually was.
Each signal is held pending until the next signal fires. It's a win if either:
The close at next-signal bar was directionally favorable vs entry, OR
The Maximum Favorable Excursion between the two signals reached the ATR-scaled threshold (default 0.5×ATR at entry bar)
Either qualifies. Transparent. Computed live. Disclaimer embedded in the dashboard footer.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
How to Read the Dashboard
┌────────────────────────────────────────────────┐
│ Liquidity Surge + Markov · Win Rate │
├────────┬────────┬─────────────┬───────────────┤
│🐳 Bull │🐋 Bear │🦈 Chop-zone │🦀 Sideways │
│42 sigs │38 sigs │7 events │12 events │
│31 wins │24 wins │120 bars │45 bars │
│73.8% │63.2% │23% │8.6% │
├────────────────────────────────────────────────┤
│Markov Forecast Next: 🐳 52% · 🦀 31% · 🐋 17% │
├────────────────────────────────────────────────┤
│Current State: 🐳 Bull held 5b · IMBALANCED │
│ stay 68%, change expected in ~3b · next: 🦀 │
├────────────────────────────────────────────────┤
│⚠ Not financial advice · Learned on chart hist │
└────────────────────────────────────────────────┘
Reading order:
Column data — how Bull/Bear signals have performed, how much time is spent in each regime
Markov Forecast Next — next-bar regime probabilities (with sample-size confidence)
Current State — the single-line answer to "where am I and what's next"
Footer — disclaimer + config
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
How to Use
Load with defaults.
Wait for ~100-200 bars of history. The Markov matrix needs observations to learn.
Read Current State first. It tells you what to expect.
If BALANCED → expect a regime change, trade light.
If IMBALANCED + change in ~N bars → plan around that window.
Watch for 🐳 / 🐋 full whales at the forecast edge — confluence + Markov confirmed.
Watch for small hatchling whales at forecast mid-point — Markov's early prediction of confluence coming.
Respect 🦈 (chop-zone) and 🦀 (sideways). Don't fight the regime.
Tune Hatchling Threshold and Win Threshold (×ATR) to your instrument and style.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Best Paired With Smart Candle Structures
This indicator answers whether and when to trust the flow. Smart Candle Structures answers where to act. Together: right place, right moment, measurable conviction, regime-aware.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Key Settings
Time Span — past bars rendered + forecast horizon (default 15)
Momentum Source — MFI (default) or RSI
Oscillator Type — Hull-VWMA (default) or signed-ADX
Slope Lookback — bars for slope that fires whales (default 4)
Evaluation Window — bars after a signal to measure MFE (default 5)
Win Threshold (× ATR) — minimum favorable excursion as a multiple of ATR (default 0.5)
Gate Whale by Choppiness — master toggle for 🦈 / 🦀 filter
CI Length / CI Threshold — classic Choppiness Index tuning
Angle Short / Long Period — angle-based sideways lookbacks
Angle Trend / Sideways Threshold — angle degrees defining trending vs sideways
Use Markov Predictor — master toggle for the 2nd-order chain
Count Decay per Bar — recency weighting for Markov counts (default 0.995)
Hatchling Threshold — minimum Markov probability to fire pre-whale (default 55%)
Dashboard Text Size — Tiny / Small / Normal / Large / Huge
Camera — yaw / pitch / scales for the 3D view
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Disclaimer
This is a visualization and analytical tool, not financial advice or a signal service. The Markov chain is trained on your chart's history — it describes what has happened on this instrument at this timeframe, not what will happen. Regime transition probabilities are learned estimates; past frequencies do not guarantee future outcomes. Markets are reflexive and can transition in ways the chain has never observed. Hatchlings, whales, sharks and crabs are visualizations of mathematical predictions — they do not constitute buy or sell recommendations. Trade with your own risk management. Every trade can lose.
The indicator echoes this disclaimer in its dashboard footer so you see it every time you read the chart. It's always there because it's always true.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Clear direction from learned regimes.
— TechnicalZen
Indicateur

Markov 3D Trend AnalyzerMarkov 3D Trend Analyzer
🔹 What Is a Markov State?
A Markov chain models systems as states with probabilities of transitioning from one state to another. The key property is memorylessness: the next state depends only on the current state, not the full past history. In financial markets, this allows us to study how conditions tend to persist or flip — for example, whether a green candle is more likely to be followed by another green or by a red.
🔹 How This Indicator Uses It
The Markov 3D Trend Analyzer tracks three independent Markov chains:
Direction Chain (short-term): Probability that a green/red candle continues or reverses.
Volatility Chain (mid-term): Probability of volatility staying Low/Medium/High or transitioning between them.
Momentum Chain (structural): Probability of momentum (Bullish, Neutral, Bearish) persisting or flipping.
Each chain is updated dynamically using exponentially weighted probabilities (EMA), which balance the law of large numbers (stability) with adaptivity to new market conditions.
The indicator then classifies each chain’s dominant state and combines them into an actionable summary at the bottom of the table (e.g. “📈 Bullish breakout,” “⚠️ Choppy bearish fakeouts,” “⏳ Trend squeeze / possible reversal”).
🔹 Settings
Direction Lookback / Volatility Lookback / Momentum Lookback
Control the rolling window length (sample size) for each chain. Larger = smoother but slower to adapt.
EMA Weight
Adjusts how much weight is given to recent transitions vs. older history. Lower values adapt faster, higher values stabilize.
Table Position
Choose where the table is displayed on your chart.
Table Size
Adjust the font size for readability.
🔹 How To Consider Using
Contextual tool: Use the summary row to understand the current market condition (trending, mean-reverting, expanding, compressing, continuation, fakeout risk).
Complementary filter: Combine with your existing strategies to confirm or filter signals. For example:
📈 If your breakout strategy fires and the summary says Bullish breakout, that’s confirmation.
⚠️ If it says Choppy fakeouts, be cautious of traps.
Visualization aid: The table lets you see how probabilities shift across direction, volatility, and momentum simultaneously.
⚠️ This indicator is not a signal generator. It is designed to help interpret market states probabilistically. Always use in conjunction with broader analysis and risk management.
🔹 Disclaimer
This script is for educational and informational purposes only. It does not constitute financial advice or a recommendation to buy or sell any security, cryptocurrency, or instrument. Trading involves risk, and past probabilities or behaviors do not guarantee future outcomes. Always conduct your own research and use proper risk management. Indicateur

Markov Chain [3D] | FractalystWhat exactly is a Markov Chain?
This indicator uses a Markov Chain model to analyze, quantify, and visualize the transitions between market regimes (Bull, Bear, Neutral) on your chart. It dynamically detects these regimes in real-time, calculates transition probabilities, and displays them as animated 3D spheres and arrows, giving traders intuitive insight into current and future market conditions.
How does a Markov Chain work, and how should I read this spheres-and-arrows diagram?
Think of three weather modes: Sunny, Rainy, Cloudy.
Each sphere is one mode. The loop on a sphere means “stay the same next step” (e.g., Sunny again tomorrow).
The arrows leaving a sphere show where things usually go next if they change (e.g., Sunny moving to Cloudy).
Some paths matter more than others. A more prominent loop means the current mode tends to persist. A more prominent outgoing arrow means a change to that destination is the usual next step.
Direction isn’t symmetric: moving Sunny→Cloudy can behave differently than Cloudy→Sunny.
Now relabel the spheres to markets: Bull, Bear, Neutral.
Spheres: market regimes (uptrend, downtrend, range).
Self‑loop: tendency for the current regime to continue on the next bar.
Arrows: the most common next regime if a switch happens.
How to read: Start at the sphere that matches current bar state. If the loop stands out, expect continuation. If one outgoing path stands out, that switch is the typical next step. Opposite directions can differ (Bear→Neutral doesn’t have to match Neutral→Bear).
What states and transitions are shown?
The three market states visualized are:
Bullish (Bull): Upward or strong-market regime.
Bearish (Bear): Downward or weak-market regime.
Neutral: Sideways or range-bound regime.
Bidirectional animated arrows and probability labels show how likely the market is to move from one regime to another (e.g., Bull → Bear or Neutral → Bull).
How does the regime detection system work?
You can use either built-in price returns (based on adaptive Z-score normalization) or supply three custom indicators (such as volume, oscillators, etc.).
Values are statistically normalized (Z-scored) over a configurable lookback period.
The normalized outputs are classified into Bull, Bear, or Neutral zones.
If using three indicators, their regime signals are averaged and smoothed for robustness.
How are transition probabilities calculated?
On every confirmed bar, the algorithm tracks the sequence of detected market states, then builds a rolling window of transitions.
The code maintains a transition count matrix for all regime pairs (e.g., Bull → Bear).
Transition probabilities are extracted for each possible state change using Laplace smoothing for numerical stability, and frequently updated in real-time.
What is unique about the visualization?
3D animated spheres represent each regime and change visually when active.
Animated, bidirectional arrows reveal transition probabilities and allow you to see both dominant and less likely regime flows.
Particles (moving dots) animate along the arrows, enhancing the perception of regime flow direction and speed.
All elements dynamically update with each new price bar, providing a live market map in an intuitive, engaging format.
Can I use custom indicators for regime classification?
Yes! Enable the "Custom Indicators" switch and select any three chart series as inputs. These will be normalized and combined (each with equal weight), broadening the regime classification beyond just price-based movement.
What does the “Lookback Period” control?
Lookback Period (default: 100) sets how much historical data builds the probability matrix. Shorter periods adapt faster to regime changes but may be noisier. Longer periods are more stable but slower to adapt.
How is this different from a Hidden Markov Model (HMM)?
It sets the window for both regime detection and probability calculations. Lower values make the system more reactive, but potentially noisier. Higher values smooth estimates and make the system more robust.
How is this Markov Chain different from a Hidden Markov Model (HMM)?
Markov Chain (as here): All market regimes (Bull, Bear, Neutral) are directly observable on the chart. The transition matrix is built from actual detected regimes, keeping the model simple and interpretable.
Hidden Markov Model: The actual regimes are unobservable ("hidden") and must be inferred from market output or indicator "emissions" using statistical learning algorithms. HMMs are more complex, can capture more subtle structure, but are harder to visualize and require additional machine learning steps for training.
A standard Markov Chain models transitions between observable states using a simple transition matrix, while a Hidden Markov Model assumes the true states are hidden (latent) and must be inferred from observable “emissions” like price or volume data. In practical terms, a Markov Chain is transparent and easier to implement and interpret; an HMM is more expressive but requires statistical inference to estimate hidden states from data.
Markov Chain: states are observable; you directly count or estimate transition probabilities between visible states. This makes it simpler, faster, and easier to validate and tune.
HMM: states are hidden; you only observe emissions generated by those latent states. Learning involves machine learning/statistical algorithms (commonly Baum–Welch/EM for training and Viterbi for decoding) to infer both the transition dynamics and the most likely hidden state sequence from data.
How does the indicator avoid “repainting” or look-ahead bias?
All regime changes and matrix updates happen only on confirmed (closed) bars, so no future data is leaked, ensuring reliable real-time operation.
Are there practical tuning tips?
Tune the Lookback Period for your asset/timeframe: shorter for fast markets, longer for stability.
Use custom indicators if your asset has unique regime drivers.
Watch for rapid changes in transition probabilities as early warning of a possible regime shift.
Who is this indicator for?
Quants and quantitative researchers exploring probabilistic market modeling, especially those interested in regime-switching dynamics and Markov models.
Programmers and system developers who need a probabilistic regime filter for systematic and algorithmic backtesting:
The Markov Chain indicator is ideally suited for programmatic integration via its bias output (1 = Bull, 0 = Neutral, -1 = Bear).
Although the visualization is engaging, the core output is designed for automated, rules-based workflows—not for discretionary/manual trading decisions.
Developers can connect the indicator’s output directly to their Pine Script logic (using input.source()), allowing rapid and robust backtesting of regime-based strategies.
It acts as a plug-and-play regime filter: simply plug the bias output into your entry/exit logic, and you have a scientifically robust, probabilistically-derived signal for filtering, timing, position sizing, or risk regimes.
The MC's output is intentionally "trinary" (1/0/-1), focusing on clear regime states for unambiguous decision-making in code. If you require nuanced, multi-probability or soft-label state vectors, consider expanding the indicator or stacking it with a probability-weighted logic layer in your scripting.
Because it avoids subjectivity, this approach is optimal for systematic quants, algo developers building backtested, repeatable strategies based on probabilistic regime analysis.
What's the mathematical foundation behind this?
The mathematical foundation behind this Markov Chain indicator—and probabilistic regime detection in finance—draws from two principal models: the (standard) Markov Chain and the Hidden Markov Model (HMM).
How to use this indicator programmatically?
The Markov Chain indicator automatically exports a bias value (+1 for Bullish, -1 for Bearish, 0 for Neutral) as a plot visible in the Data Window. This allows you to integrate its regime signal into your own scripts and strategies for backtesting, automation, or live trading.
Step-by-Step Integration with Pine Script (input.source)
Add the Markov Chain indicator to your chart.
This must be done first, since your custom script will "pull" the bias signal from the indicator's plot.
In your strategy, create an input using input.source()
Example:
//@version=5
strategy("MC Bias Strategy Example")
mcBias = input.source(close, "MC Bias Source")
After saving, go to your script’s settings. For the “MC Bias Source” input, select the plot/output of the Markov Chain indicator (typically its bias plot).
Use the bias in your trading logic
Example (long only on Bull, flat otherwise):
if mcBias == 1
strategy.entry("Long", strategy.long)
else
strategy.close("Long")
For more advanced workflows, combine mcBias with additional filters or trailing stops.
How does this work behind-the-scenes?
TradingView’s input.source() lets you use any plot from another indicator as a real-time, “live” data feed in your own script (source).
The selected bias signal is available to your Pine code as a variable, enabling logical decisions based on regime (trend-following, mean-reversion, etc.).
This enables powerful strategy modularity : decouple regime detection from entry/exit logic, allowing fast experimentation without rewriting core signal code.
Integrating 45+ Indicators with Your Markov Chain — How & Why
The Enhanced Custom Indicators Export script exports a massive suite of over 45 technical indicators—ranging from classic momentum (RSI, MACD, Stochastic, etc.) to trend, volume, volatility, and oscillator tools—all pre-calculated, centered/scaled, and available as plots.
// Enhanced Custom Indicators Export - 45 Technical Indicators
// Comprehensive technical analysis suite for advanced market regime detection
//@version=6
indicator('Enhanced Custom Indicators Export | Fractalyst', shorttitle='Enhanced CI Export', overlay=false, scale=scale.right, max_labels_count=500, max_lines_count=500)
// |----- Input Parameters -----| //
momentum_group = "Momentum Indicators"
trend_group = "Trend Indicators"
volume_group = "Volume Indicators"
volatility_group = "Volatility Indicators"
oscillator_group = "Oscillator Indicators"
display_group = "Display Settings"
// Common lengths
length_14 = input.int(14, "Standard Length (14)", minval=1, maxval=100, group=momentum_group)
length_20 = input.int(20, "Medium Length (20)", minval=1, maxval=200, group=trend_group)
length_50 = input.int(50, "Long Length (50)", minval=1, maxval=200, group=trend_group)
// Display options
show_table = input.bool(true, "Show Values Table", group=display_group)
table_size = input.string("Small", "Table Size", options= , group=display_group)
// |----- MOMENTUM INDICATORS (15 indicators) -----| //
// 1. RSI (Relative Strength Index)
rsi_14 = ta.rsi(close, length_14)
rsi_centered = rsi_14 - 50
// 2. Stochastic Oscillator
stoch_k = ta.stoch(close, high, low, length_14)
stoch_d = ta.sma(stoch_k, 3)
stoch_centered = stoch_k - 50
// 3. Williams %R
williams_r = ta.stoch(close, high, low, length_14) - 100
// 4. MACD (Moving Average Convergence Divergence)
= ta.macd(close, 12, 26, 9)
// 5. Momentum (Rate of Change)
momentum = ta.mom(close, length_14)
momentum_pct = (momentum / close ) * 100
// 6. Rate of Change (ROC)
roc = ta.roc(close, length_14)
// 7. Commodity Channel Index (CCI)
cci = ta.cci(close, length_20)
// 8. Money Flow Index (MFI)
mfi = ta.mfi(close, length_14)
mfi_centered = mfi - 50
// 9. Awesome Oscillator (AO)
ao = ta.sma(hl2, 5) - ta.sma(hl2, 34)
// 10. Accelerator Oscillator (AC)
ac = ao - ta.sma(ao, 5)
// 11. Chande Momentum Oscillator (CMO)
cmo = ta.cmo(close, length_14)
// 12. Detrended Price Oscillator (DPO)
dpo = close - ta.sma(close, length_20)
// 13. Price Oscillator (PPO)
ppo = ta.sma(close, 12) - ta.sma(close, 26)
ppo_pct = (ppo / ta.sma(close, 26)) * 100
// 14. TRIX
trix_ema1 = ta.ema(close, length_14)
trix_ema2 = ta.ema(trix_ema1, length_14)
trix_ema3 = ta.ema(trix_ema2, length_14)
trix = ta.roc(trix_ema3, 1) * 10000
// 15. Klinger Oscillator
klinger = ta.ema(volume * (high + low + close) / 3, 34) - ta.ema(volume * (high + low + close) / 3, 55)
// 16. Fisher Transform
fisher_hl2 = 0.5 * (hl2 - ta.lowest(hl2, 10)) / (ta.highest(hl2, 10) - ta.lowest(hl2, 10)) - 0.25
fisher = 0.5 * math.log((1 + fisher_hl2) / (1 - fisher_hl2))
// 17. Stochastic RSI
stoch_rsi = ta.stoch(rsi_14, rsi_14, rsi_14, length_14)
stoch_rsi_centered = stoch_rsi - 50
// 18. Relative Vigor Index (RVI)
rvi_num = ta.swma(close - open)
rvi_den = ta.swma(high - low)
rvi = rvi_den != 0 ? rvi_num / rvi_den : 0
// 19. Balance of Power (BOP)
bop = (close - open) / (high - low)
// |----- TREND INDICATORS (10 indicators) -----| //
// 20. Simple Moving Average Momentum
sma_20 = ta.sma(close, length_20)
sma_momentum = ((close - sma_20) / sma_20) * 100
// 21. Exponential Moving Average Momentum
ema_20 = ta.ema(close, length_20)
ema_momentum = ((close - ema_20) / ema_20) * 100
// 22. Parabolic SAR
sar = ta.sar(0.02, 0.02, 0.2)
sar_trend = close > sar ? 1 : -1
// 23. Linear Regression Slope
lr_slope = ta.linreg(close, length_20, 0) - ta.linreg(close, length_20, 1)
// 24. Moving Average Convergence (MAC)
mac = ta.sma(close, 10) - ta.sma(close, 30)
// 25. Trend Intensity Index (TII)
tii_sum = 0.0
for i = 1 to length_20
tii_sum += close > close ? 1 : 0
tii = (tii_sum / length_20) * 100
// 26. Ichimoku Cloud Components
ichimoku_tenkan = (ta.highest(high, 9) + ta.lowest(low, 9)) / 2
ichimoku_kijun = (ta.highest(high, 26) + ta.lowest(low, 26)) / 2
ichimoku_signal = ichimoku_tenkan > ichimoku_kijun ? 1 : -1
// 27. MESA Adaptive Moving Average (MAMA)
mama_alpha = 2.0 / (length_20 + 1)
mama = ta.ema(close, length_20)
mama_momentum = ((close - mama) / mama) * 100
// 28. Zero Lag Exponential Moving Average (ZLEMA)
zlema_lag = math.round((length_20 - 1) / 2)
zlema_data = close + (close - close )
zlema = ta.ema(zlema_data, length_20)
zlema_momentum = ((close - zlema) / zlema) * 100
// |----- VOLUME INDICATORS (6 indicators) -----| //
// 29. On-Balance Volume (OBV)
obv = ta.obv
// 30. Volume Rate of Change (VROC)
vroc = ta.roc(volume, length_14)
// 31. Price Volume Trend (PVT)
pvt = ta.pvt
// 32. Negative Volume Index (NVI)
nvi = 0.0
nvi := volume < volume ? nvi + ((close - close ) / close ) * nvi : nvi
// 33. Positive Volume Index (PVI)
pvi = 0.0
pvi := volume > volume ? pvi + ((close - close ) / close ) * pvi : pvi
// 34. Volume Oscillator
vol_osc = ta.sma(volume, 5) - ta.sma(volume, 10)
// 35. Ease of Movement (EOM)
eom_distance = high - low
eom_box_height = volume / 1000000
eom = eom_box_height != 0 ? eom_distance / eom_box_height : 0
eom_sma = ta.sma(eom, length_14)
// 36. Force Index
force_index = volume * (close - close )
force_index_sma = ta.sma(force_index, length_14)
// |----- VOLATILITY INDICATORS (10 indicators) -----| //
// 37. Average True Range (ATR)
atr = ta.atr(length_14)
atr_pct = (atr / close) * 100
// 38. Bollinger Bands Position
bb_basis = ta.sma(close, length_20)
bb_dev = 2.0 * ta.stdev(close, length_20)
bb_upper = bb_basis + bb_dev
bb_lower = bb_basis - bb_dev
bb_position = bb_dev != 0 ? (close - bb_basis) / bb_dev : 0
bb_width = bb_dev != 0 ? (bb_upper - bb_lower) / bb_basis * 100 : 0
// 39. Keltner Channels Position
kc_basis = ta.ema(close, length_20)
kc_range = ta.ema(ta.tr, length_20)
kc_upper = kc_basis + (2.0 * kc_range)
kc_lower = kc_basis - (2.0 * kc_range)
kc_position = kc_range != 0 ? (close - kc_basis) / kc_range : 0
// 40. Donchian Channels Position
dc_upper = ta.highest(high, length_20)
dc_lower = ta.lowest(low, length_20)
dc_basis = (dc_upper + dc_lower) / 2
dc_position = (dc_upper - dc_lower) != 0 ? (close - dc_basis) / (dc_upper - dc_lower) : 0
// 41. Standard Deviation
std_dev = ta.stdev(close, length_20)
std_dev_pct = (std_dev / close) * 100
// 42. Relative Volatility Index (RVI)
rvi_up = ta.stdev(close > close ? close : 0, length_14)
rvi_down = ta.stdev(close < close ? close : 0, length_14)
rvi_total = rvi_up + rvi_down
rvi_volatility = rvi_total != 0 ? (rvi_up / rvi_total) * 100 : 50
// 43. Historical Volatility
hv_returns = math.log(close / close )
hv = ta.stdev(hv_returns, length_20) * math.sqrt(252) * 100
// 44. Garman-Klass Volatility
gk_vol = math.log(high/low) * math.log(high/low) - (2*math.log(2)-1) * math.log(close/open) * math.log(close/open)
gk_volatility = math.sqrt(ta.sma(gk_vol, length_20)) * 100
// 45. Parkinson Volatility
park_vol = math.log(high/low) * math.log(high/low)
parkinson = math.sqrt(ta.sma(park_vol, length_20) / (4 * math.log(2))) * 100
// 46. Rogers-Satchell Volatility
rs_vol = math.log(high/close) * math.log(high/open) + math.log(low/close) * math.log(low/open)
rogers_satchell = math.sqrt(ta.sma(rs_vol, length_20)) * 100
// |----- OSCILLATOR INDICATORS (5 indicators) -----| //
// 47. Elder Ray Index
elder_bull = high - ta.ema(close, 13)
elder_bear = low - ta.ema(close, 13)
elder_power = elder_bull + elder_bear
// 48. Schaff Trend Cycle (STC)
stc_macd = ta.ema(close, 23) - ta.ema(close, 50)
stc_k = ta.stoch(stc_macd, stc_macd, stc_macd, 10)
stc_d = ta.ema(stc_k, 3)
stc = ta.stoch(stc_d, stc_d, stc_d, 10)
// 49. Coppock Curve
coppock_roc1 = ta.roc(close, 14)
coppock_roc2 = ta.roc(close, 11)
coppock = ta.wma(coppock_roc1 + coppock_roc2, 10)
// 50. Know Sure Thing (KST)
kst_roc1 = ta.roc(close, 10)
kst_roc2 = ta.roc(close, 15)
kst_roc3 = ta.roc(close, 20)
kst_roc4 = ta.roc(close, 30)
kst = ta.sma(kst_roc1, 10) + 2*ta.sma(kst_roc2, 10) + 3*ta.sma(kst_roc3, 10) + 4*ta.sma(kst_roc4, 15)
// 51. Percentage Price Oscillator (PPO)
ppo_line = ((ta.ema(close, 12) - ta.ema(close, 26)) / ta.ema(close, 26)) * 100
ppo_signal = ta.ema(ppo_line, 9)
ppo_histogram = ppo_line - ppo_signal
// |----- PLOT MAIN INDICATORS -----| //
// Plot key momentum indicators
plot(rsi_centered, title="01_RSI_Centered", color=color.purple, linewidth=1)
plot(stoch_centered, title="02_Stoch_Centered", color=color.blue, linewidth=1)
plot(williams_r, title="03_Williams_R", color=color.red, linewidth=1)
plot(macd_histogram, title="04_MACD_Histogram", color=color.orange, linewidth=1)
plot(cci, title="05_CCI", color=color.green, linewidth=1)
// Plot trend indicators
plot(sma_momentum, title="06_SMA_Momentum", color=color.navy, linewidth=1)
plot(ema_momentum, title="07_EMA_Momentum", color=color.maroon, linewidth=1)
plot(sar_trend, title="08_SAR_Trend", color=color.teal, linewidth=1)
plot(lr_slope, title="09_LR_Slope", color=color.lime, linewidth=1)
plot(mac, title="10_MAC", color=color.fuchsia, linewidth=1)
// Plot volatility indicators
plot(atr_pct, title="11_ATR_Pct", color=color.yellow, linewidth=1)
plot(bb_position, title="12_BB_Position", color=color.aqua, linewidth=1)
plot(kc_position, title="13_KC_Position", color=color.olive, linewidth=1)
plot(std_dev_pct, title="14_StdDev_Pct", color=color.silver, linewidth=1)
plot(bb_width, title="15_BB_Width", color=color.gray, linewidth=1)
// Plot volume indicators
plot(vroc, title="16_VROC", color=color.blue, linewidth=1)
plot(eom_sma, title="17_EOM", color=color.red, linewidth=1)
plot(vol_osc, title="18_Vol_Osc", color=color.green, linewidth=1)
plot(force_index_sma, title="19_Force_Index", color=color.orange, linewidth=1)
plot(obv, title="20_OBV", color=color.purple, linewidth=1)
// Plot additional oscillators
plot(ao, title="21_Awesome_Osc", color=color.navy, linewidth=1)
plot(cmo, title="22_CMO", color=color.maroon, linewidth=1)
plot(dpo, title="23_DPO", color=color.teal, linewidth=1)
plot(trix, title="24_TRIX", color=color.lime, linewidth=1)
plot(fisher, title="25_Fisher", color=color.fuchsia, linewidth=1)
// Plot more momentum indicators
plot(mfi_centered, title="26_MFI_Centered", color=color.yellow, linewidth=1)
plot(ac, title="27_AC", color=color.aqua, linewidth=1)
plot(ppo_pct, title="28_PPO_Pct", color=color.olive, linewidth=1)
plot(stoch_rsi_centered, title="29_StochRSI_Centered", color=color.silver, linewidth=1)
plot(klinger, title="30_Klinger", color=color.gray, linewidth=1)
// Plot trend continuation
plot(tii, title="31_TII", color=color.blue, linewidth=1)
plot(ichimoku_signal, title="32_Ichimoku_Signal", color=color.red, linewidth=1)
plot(mama_momentum, title="33_MAMA_Momentum", color=color.green, linewidth=1)
plot(zlema_momentum, title="34_ZLEMA_Momentum", color=color.orange, linewidth=1)
plot(bop, title="35_BOP", color=color.purple, linewidth=1)
// Plot volume continuation
plot(nvi, title="36_NVI", color=color.navy, linewidth=1)
plot(pvi, title="37_PVI", color=color.maroon, linewidth=1)
plot(momentum_pct, title="38_Momentum_Pct", color=color.teal, linewidth=1)
plot(roc, title="39_ROC", color=color.lime, linewidth=1)
plot(rvi, title="40_RVI", color=color.fuchsia, linewidth=1)
// Plot volatility continuation
plot(dc_position, title="41_DC_Position", color=color.yellow, linewidth=1)
plot(rvi_volatility, title="42_RVI_Volatility", color=color.aqua, linewidth=1)
plot(hv, title="43_Historical_Vol", color=color.olive, linewidth=1)
plot(gk_volatility, title="44_GK_Volatility", color=color.silver, linewidth=1)
plot(parkinson, title="45_Parkinson_Vol", color=color.gray, linewidth=1)
// Plot final oscillators
plot(rogers_satchell, title="46_RS_Volatility", color=color.blue, linewidth=1)
plot(elder_power, title="47_Elder_Power", color=color.red, linewidth=1)
plot(stc, title="48_STC", color=color.green, linewidth=1)
plot(coppock, title="49_Coppock", color=color.orange, linewidth=1)
plot(kst, title="50_KST", color=color.purple, linewidth=1)
// Plot final indicators
plot(ppo_histogram, title="51_PPO_Histogram", color=color.navy, linewidth=1)
plot(pvt, title="52_PVT", color=color.maroon, linewidth=1)
// |----- Reference Lines -----| //
hline(0, "Zero Line", color=color.gray, linestyle=hline.style_dashed, linewidth=1)
hline(50, "Midline", color=color.gray, linestyle=hline.style_dotted, linewidth=1)
hline(-50, "Lower Midline", color=color.gray, linestyle=hline.style_dotted, linewidth=1)
hline(25, "Upper Threshold", color=color.gray, linestyle=hline.style_dotted, linewidth=1)
hline(-25, "Lower Threshold", color=color.gray, linestyle=hline.style_dotted, linewidth=1)
// |----- Enhanced Information Table -----| //
if show_table and barstate.islast
table_position = position.top_right
table_text_size = table_size == "Tiny" ? size.tiny : table_size == "Small" ? size.small : size.normal
var table info_table = table.new(table_position, 3, 18, bgcolor=color.new(color.white, 85), border_width=1, border_color=color.gray)
// Headers
table.cell(info_table, 0, 0, 'Category', text_color=color.black, text_size=table_text_size, bgcolor=color.new(color.blue, 70))
table.cell(info_table, 1, 0, 'Indicator', text_color=color.black, text_size=table_text_size, bgcolor=color.new(color.blue, 70))
table.cell(info_table, 2, 0, 'Value', text_color=color.black, text_size=table_text_size, bgcolor=color.new(color.blue, 70))
// Key Momentum Indicators
table.cell(info_table, 0, 1, 'MOMENTUM', text_color=color.purple, text_size=table_text_size, bgcolor=color.new(color.purple, 90))
table.cell(info_table, 1, 1, 'RSI Centered', text_color=color.purple, text_size=table_text_size)
table.cell(info_table, 2, 1, str.tostring(rsi_centered, '0.00'), text_color=color.purple, text_size=table_text_size)
table.cell(info_table, 0, 2, '', text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 1, 2, 'Stoch Centered', text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 2, 2, str.tostring(stoch_centered, '0.00'), text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 0, 3, '', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 1, 3, 'Williams %R', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 2, 3, str.tostring(williams_r, '0.00'), text_color=color.red, text_size=table_text_size)
table.cell(info_table, 0, 4, '', text_color=color.orange, text_size=table_text_size)
table.cell(info_table, 1, 4, 'MACD Histogram', text_color=color.orange, text_size=table_text_size)
table.cell(info_table, 2, 4, str.tostring(macd_histogram, '0.000'), text_color=color.orange, text_size=table_text_size)
table.cell(info_table, 0, 5, '', text_color=color.green, text_size=table_text_size)
table.cell(info_table, 1, 5, 'CCI', text_color=color.green, text_size=table_text_size)
table.cell(info_table, 2, 5, str.tostring(cci, '0.00'), text_color=color.green, text_size=table_text_size)
// Key Trend Indicators
table.cell(info_table, 0, 6, 'TREND', text_color=color.navy, text_size=table_text_size, bgcolor=color.new(color.navy, 90))
table.cell(info_table, 1, 6, 'SMA Momentum %', text_color=color.navy, text_size=table_text_size)
table.cell(info_table, 2, 6, str.tostring(sma_momentum, '0.00'), text_color=color.navy, text_size=table_text_size)
table.cell(info_table, 0, 7, '', text_color=color.maroon, text_size=table_text_size)
table.cell(info_table, 1, 7, 'EMA Momentum %', text_color=color.maroon, text_size=table_text_size)
table.cell(info_table, 2, 7, str.tostring(ema_momentum, '0.00'), text_color=color.maroon, text_size=table_text_size)
table.cell(info_table, 0, 8, '', text_color=color.teal, text_size=table_text_size)
table.cell(info_table, 1, 8, 'SAR Trend', text_color=color.teal, text_size=table_text_size)
table.cell(info_table, 2, 8, str.tostring(sar_trend, '0'), text_color=color.teal, text_size=table_text_size)
table.cell(info_table, 0, 9, '', text_color=color.lime, text_size=table_text_size)
table.cell(info_table, 1, 9, 'Linear Regression', text_color=color.lime, text_size=table_text_size)
table.cell(info_table, 2, 9, str.tostring(lr_slope, '0.000'), text_color=color.lime, text_size=table_text_size)
// Key Volatility Indicators
table.cell(info_table, 0, 10, 'VOLATILITY', text_color=color.yellow, text_size=table_text_size, bgcolor=color.new(color.yellow, 90))
table.cell(info_table, 1, 10, 'ATR %', text_color=color.yellow, text_size=table_text_size)
table.cell(info_table, 2, 10, str.tostring(atr_pct, '0.00'), text_color=color.yellow, text_size=table_text_size)
table.cell(info_table, 0, 11, '', text_color=color.aqua, text_size=table_text_size)
table.cell(info_table, 1, 11, 'BB Position', text_color=color.aqua, text_size=table_text_size)
table.cell(info_table, 2, 11, str.tostring(bb_position, '0.00'), text_color=color.aqua, text_size=table_text_size)
table.cell(info_table, 0, 12, '', text_color=color.olive, text_size=table_text_size)
table.cell(info_table, 1, 12, 'KC Position', text_color=color.olive, text_size=table_text_size)
table.cell(info_table, 2, 12, str.tostring(kc_position, '0.00'), text_color=color.olive, text_size=table_text_size)
// Key Volume Indicators
table.cell(info_table, 0, 13, 'VOLUME', text_color=color.blue, text_size=table_text_size, bgcolor=color.new(color.blue, 90))
table.cell(info_table, 1, 13, 'Volume ROC', text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 2, 13, str.tostring(vroc, '0.00'), text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 0, 14, '', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 1, 14, 'EOM', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 2, 14, str.tostring(eom_sma, '0.000'), text_color=color.red, text_size=table_text_size)
// Key Oscillators
table.cell(info_table, 0, 15, 'OSCILLATORS', text_color=color.purple, text_size=table_text_size, bgcolor=color.new(color.purple, 90))
table.cell(info_table, 1, 15, 'Awesome Osc', text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 2, 15, str.tostring(ao, '0.000'), text_color=color.blue, text_size=table_text_size)
table.cell(info_table, 0, 16, '', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 1, 16, 'Fisher Transform', text_color=color.red, text_size=table_text_size)
table.cell(info_table, 2, 16, str.tostring(fisher, '0.000'), text_color=color.red, text_size=table_text_size)
// Summary Statistics
table.cell(info_table, 0, 17, 'SUMMARY', text_color=color.black, text_size=table_text_size, bgcolor=color.new(color.gray, 70))
table.cell(info_table, 1, 17, 'Total Indicators: 52', text_color=color.black, text_size=table_text_size)
regime_color = rsi_centered > 10 ? color.green : rsi_centered < -10 ? color.red : color.gray
regime_text = rsi_centered > 10 ? "BULLISH" : rsi_centered < -10 ? "BEARISH" : "NEUTRAL"
table.cell(info_table, 2, 17, regime_text, text_color=regime_color, text_size=table_text_size)
This makes it the perfect “indicator backbone” for quantitative and systematic traders who want to prototype, combine, and test new regime detection models—especially in combination with the Markov Chain indicator.
How to use this script with the Markov Chain for research and backtesting:
Add the Enhanced Indicator Export to your chart.
Every calculated indicator is available as an individual data stream.
Connect the indicator(s) you want as custom input(s) to the Markov Chain’s “Custom Indicators” option.
In the Markov Chain indicator’s settings, turn ON the custom indicator mode.
For each of the three custom indicator inputs, select the exported plot from the Enhanced Export script—the menu lists all 45+ signals by name.
This creates a powerful, modular regime-detection engine where you can mix-and-match momentum, trend, volume, or custom combinations for advanced filtering.
Backtest regime logic directly.
Once you’ve connected your chosen indicators, the Markov Chain script performs regime detection (Bull/Neutral/Bear) based on your selected features—not just price returns.
The regime detection is robust, automatically normalized (using Z-score), and outputs bias (1, -1, 0) for plug-and-play integration.
Export the regime bias for programmatic use.
As described above, use input.source() in your Pine Script strategy or system and link the bias output.
You can now filter signals, control trade direction/size, or design pairs-trading that respect true, indicator-driven market regimes.
With this framework, you’re not limited to static or simplistic regime filters. You can rigorously define, test, and refine what “market regime” means for your strategies—using the technical features that matter most to you.
Optimize your signal generation by backtesting across a universe of meaningful indicator blends.
Enhance risk management with objective, real-time regime boundaries.
Accelerate your research: iterate quickly, swap indicator components, and see results with minimal code changes.
Automate multi-asset or pairs-trading by integrating regime context directly into strategy logic.
Add both scripts to your chart, connect your preferred features, and start investigating your best regime-based trades—entirely within the TradingView ecosystem.
References & Further Reading
Ang, A., & Bekaert, G. (2002). “Regime Switches in Interest Rates.” Journal of Business & Economic Statistics, 20(2), 163–182.
Hamilton, J. D. (1989). “A New Approach to the Economic Analysis of Nonstationary Time Series and the Business Cycle.” Econometrica, 57(2), 357–384.
Markov, A. A. (1906). "Extension of the Limit Theorems of Probability Theory to a Sum of Variables Connected in a Chain." The Notes of the Imperial Academy of Sciences of St. Petersburg.
Guidolin, M., & Timmermann, A. (2007). “Asset Allocation under Multivariate Regime Switching.” Journal of Economic Dynamics and Control, 31(11), 3503–3544.
Murphy, J. J. (1999). Technical Analysis of the Financial Markets. New York Institute of Finance.
Brock, W., Lakonishok, J., & LeBaron, B. (1992). “Simple Technical Trading Rules and the Stochastic Properties of Stock Returns.” Journal of Finance, 47(5), 1731–1764.
Zucchini, W., MacDonald, I. L., & Langrock, R. (2017). Hidden Markov Models for Time Series: An Introduction Using R (2nd ed.). Chapman and Hall/CRC.
On Quantitative Finance and Markov Models:
Lo, A. W., & Hasanhodzic, J. (2009). The Heretics of Finance: Conversations with Leading Practitioners of Technical Analysis. Bloomberg Press.
Patterson, S. (2016). The Man Who Solved the Market: How Jim Simons Launched the Quant Revolution. Penguin Press.
TradingView Pine Script Documentation: www.tradingview.com
TradingView Blog: “Use an Input From Another Indicator With Your Strategy” www.tradingview.com
GeeksforGeeks: “What is the Difference Between Markov Chains and Hidden Markov Models?” www.geeksforgeeks.org
What makes this indicator original and unique?
- On‑chart, real‑time Markov. The chain is drawn directly on your chart. You see the current regime, its tendency to stay (self‑loop), and the usual next step (arrows) as bars confirm.
- Source‑agnostic by design. The engine runs on any series you select via input.source() — price, your own oscillator, a composite score, anything you compute in the script.
- Automatic normalization + regime mapping. Different inputs live on different scales. The script standardizes your chosen source and maps it into clear regimes (e.g., Bull / Bear / Neutral) without you micromanaging thresholds each time.
- Rolling, bar‑by‑bar learning. Transition tendencies are computed from a rolling window of confirmed bars. What you see is exactly what the market did in that window.
- Fast experimentation. Switch the source, adjust the window, and the Markov view updates instantly. It’s a rapid way to test ideas and feel regime persistence/switch behavior.
Integrate your own signals (using input.source())
- In settings, choose the Source . This is powered by input.source() .
- Feed it price, an indicator you compute inside the script, or a custom composite series.
- The script will automatically normalize that series and process it through the Markov engine, mapping it to regimes and updating the on‑chart spheres/arrows in real time.
Credits:
Deep gratitude to @RicardoSantos for both the foundational Markov chain processing engine and inspiring open-source contributions, which made advanced probabilistic market modeling accessible to the TradingView community.
Special thanks to @Alien_Algorithms for the innovative and visually stunning 3D sphere logic that powers the indicator’s animated, regime-based visualization.
Disclaimer
This tool summarizes recent behavior. It is not financial advice and not a guarantee of future results. Indicateur

Markov Chain Trend ProbabilityA Markov Chain is a mathematical model that predicts future states based on the current state, assuming that the future depends only on the present (not the past). Originally developed by Russian mathematician Andrey Markov, this concept is widely used in:
Finance: Risk modeling, portfolio optimization, credit scoring, algorithmic trading
Weather Forecasting: Predicting sunny/rainy days, temperature patterns, storm tracking
Here's an example of a Markov chain: If the weather is sunny, the probability that will be sunny 30 min later is say 90%. However, if the state changes, i.e. it starts raining, how the probability that will be raining 30 min later is say 70% and only 30% sunny.
Similar concept can be applied to markets price action and trends.
Mathematical Foundation
The core principle follows the Markov Property: P(X_{t+1}|X_t, X_{t-1}, ..., X_0) = P(X_{t+1}|X_t)
Transition Matrix :
-------------Next State
Current----
--------P11 P12
-----P21 P22
Probability Calculations:
P(Up→Up) = Count(Up→Up) / Count(Up states)
P(Down→Down) = Count(Down→Down) / Count(Down states)
Steady-state probability: π = πP (where π is the stationary distribution)
State Definition:
State = UPTREND if (Price_t - Price_{t-n})/ATR > threshold
State = DOWNTREND if (Price_t - Price_{t-n})/ATR < -threshold
How It Works in Trading
This indicator applies Markov Chain theory to market trends by:
Defining States: Classifies market conditions as UPTREND or DOWNTREND based on price movement relative to ATR (Average True Range)
Learning Transitions: Analyzes historical data to calculate probabilities of moving from one state to another
Predicting Probabilities: Estimates the likelihood of future trend continuation or reversal
How to Use
Parameters:
Lookback Period: Number of bars to analyze for trend detection (default: 14)
ATR Threshold: Sensitivity multiplier for state changes (default: 0.5)
Historical Periods: Sample size for probability calculations (default: 33)
Trading Applications:
Trend confirmation for entry/exit decisions
Risk assessment through probability analysis
Market regime identification
Early warning system for potential trend reversals
The indicator works on any timeframe and asset class. Enjoy! Indicateur

[ALGOA+] Markov Chains Library by @metacamaleoLibrary "MarkovChains"
Markov Chains library by @metacamaleo. Created in 09/08/2024.
This library provides tools to calculate and visualize Markov Chain-based transition matrices and probabilities. This library supports two primary algorithms: a rolling window Markov Chain and a conditional Markov Chain (which operates based on specified conditions). The key concepts used include Markov Chain states, transition matrices, and future state probabilities based on past market conditions or indicators.
Key functions:
- `mc_rw()`: Builds a transition matrix using a rolling window Markov Chain, calculating probabilities based on a fixed length of historical data.
- `mc_cond()`: Builds a conditional Markov Chain transition matrix, calculating probabilities based on the current market condition or indicator state.
Basically, you will just need to use the above functions on your script to default outputs and displays.
Exported UDTs include:
- s_map: An UDT variable used to store a map with dummy states, i.e., if possible states are bullish, bearish, and neutral, and current is bullish, it will be stored
in a map with following keys and values: "bullish", 1; "bearish", 0; and "neutral", 0. You will only use it to customize your own script, otherwise, it´s only for internal use.
- mc_states: This UDT variable stores user inputs, calculations and MC outputs. As the above, you don´t need to use it, but you may get features to customize your own script.
For example, you may use mc.tm to get the transition matrix, or the prob map to customize the display. As you see, functions are all based on mc_states UDT. The s_map UDT is used within mc_states´s s array.
Optional exported functions include:
- `mc_table()`: Displays the transition matrix in a table format on the chart for easy visualization of the probabilities.
- `display_list()`: Displays a map (or array) of string and float/int values in a table format, used for showing transition counts or probabilities.
- `mc_prob()`: Calculates and displays probabilities for a given number of future bars based on the current state in the Markov Chain.
- `mc_all_states_prob()`: Calculates probabilities for all states for future bars, considering all possible transitions.
The above functions may be used to customize your outputs. Use the returned variable mc_states from mc_rw() and mc_cond() to display each of its matrix, maps or arrays using mc_table() (for matrices) and display_list() (for maps and arrays) if you desire to debug or track the calculation process.
See the examples in the end of this script.
Have good trading days!
Best regards,
@metacamaleo
-----------------------------
KEY FUNCTIONS
mc_rw(state, length, states, pred_length, show_table, show_prob, table_position, prob_position, font_size)
Builds the transition matrix for a rolling window Markov Chain.
Parameters:
state (string) : The current state of the market or system.
length (int) : The rolling window size.
states (array) : Array of strings representing the possible states in the Markov Chain.
pred_length (int) : The number of bars to predict into the future.
show_table (bool) : Boolean to show or hide the transition matrix table.
show_prob (bool) : Boolean to show or hide the probability table.
table_position (string) : Position of the transition matrix table on the chart.
prob_position (string) : Position of the probability list on the chart.
font_size (string) : Size of the table font.
Returns: The transition matrix and probabilities for future states.
mc_cond(state, condition, states, pred_length, show_table, show_prob, table_position, prob_position, font_size)
Builds the transition matrix for conditional Markov Chains.
Parameters:
state (string) : The current state of the market or system.
condition (string) : A string representing the condition.
states (array) : Array of strings representing the possible states in the Markov Chain.
pred_length (int) : The number of bars to predict into the future.
show_table (bool) : Boolean to show or hide the transition matrix table.
show_prob (bool) : Boolean to show or hide the probability table.
table_position (string) : Position of the transition matrix table on the chart.
prob_position (string) : Position of the probability list on the chart.
font_size (string) : Size of the table font.
Returns: The transition matrix and probabilities for future states based on the HMM.
Bibliothèque

Indicateur

Markov Chain Trend IndicatorOverview
The Markov Chain Trend Indicator utilizes the principles of Markov Chain processes to analyze stock price movements and predict future trends. By calculating the probabilities of transitioning between different market states (Uptrend, Downtrend, and Sideways), this indicator provides traders with valuable insights into market dynamics.
Key Features
State Identification: Differentiates between Uptrend, Downtrend, and Sideways states based on price movements.
Transition Probability Calculation: Calculates the probability of transitioning from one state to another using historical data.
Real-time Dashboard: Displays the probabilities of each state on the chart, helping traders make informed decisions.
Background Color Coding: Visually represents the current market state with background colors for easy interpretation.
Concepts Underlying the Calculations
Markov Chains: A stochastic process where the probability of moving to the next state depends only on the current state, not on the sequence of events that preceded it.
Logarithmic Returns: Used to normalize price changes and identify states based on significant movements.
Transition Matrices: Utilized to store and calculate the probabilities of moving from one state to another.
How It Works
The indicator first calculates the logarithmic returns of the stock price to identify significant movements. Based on these returns, it determines the current state (Uptrend, Downtrend, or Sideways). It then updates the transition matrices to keep track of how often the price moves from one state to another. Using these matrices, the indicator calculates the probabilities of transitioning to each state and displays this information on the chart.
How Traders Can Use It
Traders can use the Markov Chain Trend Indicator to:
Identify Market Trends: Quickly determine if the market is in an uptrend, downtrend, or sideways state.
Predict Future Movements: Use the transition probabilities to forecast potential market movements and make informed trading decisions.
Enhance Trading Strategies: Combine with other technical indicators to refine entry and exit points based on predicted trends.
Example Usage Instructions
Add the Markov Chain Trend Indicator to your TradingView chart.
Observe the background color to quickly identify the current market state:
Green for Uptrend, Red for Downtrend, Gray for Sideways
Check the dashboard label to see the probabilities of transitioning to each state.
Use these probabilities to anticipate market movements and adjust your trading strategy accordingly.
Combine the indicator with other technical analysis tools for more robust decision-making.
Indicateur

MarkovChainLibrary "MarkovChain"
Generic Markov Chain type functions.
---
A Markov chain or Markov process is a stochastic model describing a sequence of possible events in which the
probability of each event depends only on the state attained in the previous event.
---
reference:
Understanding Markov Chains, Examples and Applications. Second Edition. Book by Nicolas Privault.
en.wikipedia.org
www.geeksforgeeks.org
towardsdatascience.com
github.com
stats.stackexchange.com
timeseriesreasoning.com
www.ris-ai.com
github.com
gist.github.com
github.com
gist.github.com
writings.stephenwolfram.com
kevingal.com
towardsdatascience.com
spedygiorgio.github.io
github.com
www.projectrhea.org
method to_string(this)
Translate a Markov Chain object to a string format.
Namespace types: MC
Parameters:
this (MC) : `MC` . Markov Chain object.
Returns: string
method to_table(this, position, text_color, text_size)
Namespace types: MC
Parameters:
this (MC)
position (string)
text_color (color)
text_size (string)
method create_transition_matrix(this)
Namespace types: MC
Parameters:
this (MC)
method generate_transition_matrix(this)
Namespace types: MC
Parameters:
this (MC)
new_chain(states, name)
Parameters:
states (state )
name (string)
from_data(data, name)
Parameters:
data (string )
name (string)
method probability_at_step(this, target_step)
Namespace types: MC
Parameters:
this (MC)
target_step (int)
method state_at_step(this, start_state, target_state, target_step)
Namespace types: MC
Parameters:
this (MC)
start_state (int)
target_state (int)
target_step (int)
method forward(this, obs)
Namespace types: HMC
Parameters:
this (HMC)
obs (int )
method backward(this, obs)
Namespace types: HMC
Parameters:
this (HMC)
obs (int )
method viterbi(this, observations)
Namespace types: HMC
Parameters:
this (HMC)
observations (int )
method baumwelch(this, observations)
Namespace types: HMC
Parameters:
this (HMC)
observations (int )
Node
Target node.
Fields:
index (series int) : . Key index of the node.
probability (series float) : . Probability rate of activation.
state
State reference.
Fields:
name (series string) : . Name of the state.
index (series int) : . Key index of the state.
target_nodes (Node ) : . List of index references and probabilities to target states.
MC
Markov Chain reference object.
Fields:
name (series string) : . Name of the chain.
states (state ) : . List of state nodes and its name, index, targets and transition probabilities.
size (series int) : . Number of unique states
transitions (matrix) : . Transition matrix
HMC
Hidden Markov Chain reference object.
Fields:
name (series string) : . Name of thehidden chain.
states_hidden (state ) : . List of state nodes and its name, index, targets and transition probabilities.
states_obs (state ) : . List of state nodes and its name, index, targets and transition probabilities.
transitions (matrix) : . Transition matrix
emissions (matrix) : . Emission matrix
initial_distribution (float ) Bibliothèque

Bibliothèque

FunctionBaumWelchLibrary "FunctionBaumWelch"
Baum-Welch Algorithm, also known as Forward-Backward Algorithm, uses the well known EM algorithm
to find the maximum likelihood estimate of the parameters of a hidden Markov model given a set of observed
feature vectors.
---
### Function List:
> `forward (array pi, matrix a, matrix b, array obs)`
> `forward (array pi, matrix a, matrix b, array obs, bool scaling)`
> `backward (matrix a, matrix b, array obs)`
> `backward (matrix a, matrix b, array obs, array c)`
> `baumwelch (array observations, int nstates)`
> `baumwelch (array observations, array pi, matrix a, matrix b)`
---
### Reference:
> en.wikipedia.org
> github.com
> en.wikipedia.org
> www.rdocumentation.org
> www.rdocumentation.org
forward(pi, a, b, obs)
Computes forward probabilities for state `X` up to observation at time `k`, is defined as the
probability of observing sequence of observations `e_1 ... e_k` and that the state at time `k` is `X`.
Parameters:
pi (float ) : Initial probabilities.
a (matrix) : Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing
states given a state matrix is size (M x M) where M is number of states.
b (matrix) : Emissions, matrix of observation probabilities b or beta = observation probabilities. Given
state matrix is size (M x O) where M is number of states and O is number of different
possible observations.
obs (int ) : List with actual state observation data.
Returns: - `matrix _alpha`: Forward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first
dimension refers to the state and the second dimension to time.
forward(pi, a, b, obs, scaling)
Computes forward probabilities for state `X` up to observation at time `k`, is defined as the
probability of observing sequence of observations `e_1 ... e_k` and that the state at time `k` is `X`.
Parameters:
pi (float ) : Initial probabilities.
a (matrix) : Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing
states given a state matrix is size (M x M) where M is number of states.
b (matrix) : Emissions, matrix of observation probabilities b or beta = observation probabilities. Given
state matrix is size (M x O) where M is number of states and O is number of different
possible observations.
obs (int ) : List with actual state observation data.
scaling (bool) : Normalize `alpha` scale.
Returns: - #### Tuple with:
> - `matrix _alpha`: Forward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first
dimension refers to the state and the second dimension to time.
> - `array _c`: Array with normalization scale.
backward(a, b, obs)
Computes backward probabilities for state `X` and observation at time `k`, is defined as the probability of observing the sequence of observations `e_k+1, ... , e_n` under the condition that the state at time `k` is `X`.
Parameters:
a (matrix) : Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing states
given a state matrix is size (M x M) where M is number of states
b (matrix) : Emissions, matrix of observation probabilities b or beta = observation probabilities. given state
matrix is size (M x O) where M is number of states and O is number of different possible observations
obs (int ) : Array with actual state observation data.
Returns: - `matrix _beta`: Backward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first dimension refers to the state and the second dimension to time.
backward(a, b, obs, c)
Computes backward probabilities for state `X` and observation at time `k`, is defined as the probability of observing the sequence of observations `e_k+1, ... , e_n` under the condition that the state at time `k` is `X`.
Parameters:
a (matrix) : Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing states
given a state matrix is size (M x M) where M is number of states
b (matrix) : Emissions, matrix of observation probabilities b or beta = observation probabilities. given state
matrix is size (M x O) where M is number of states and O is number of different possible observations
obs (int ) : Array with actual state observation data.
c (float ) : Array with Normalization scaling coefficients.
Returns: - `matrix _beta`: Backward probabilities. The probabilities are given on a logarithmic scale (natural logarithm). The first dimension refers to the state and the second dimension to time.
baumwelch(observations, nstates)
**(Random Initialization)** Baum–Welch algorithm is a special case of the expectation–maximization algorithm used to find the
unknown parameters of a hidden Markov model (HMM). It makes use of the forward-backward algorithm
to compute the statistics for the expectation step.
Parameters:
observations (int ) : List of observed states.
nstates (int)
Returns: - #### Tuple with:
> - `array _pi`: Initial probability distribution.
> - `matrix _a`: Transition probability matrix.
> - `matrix _b`: Emission probability matrix.
---
requires: `import RicardoSantos/WIPTensor/2 as Tensor`
baumwelch(observations, pi, a, b)
Baum–Welch algorithm is a special case of the expectation–maximization algorithm used to find the
unknown parameters of a hidden Markov model (HMM). It makes use of the forward-backward algorithm
to compute the statistics for the expectation step.
Parameters:
observations (int ) : List of observed states.
pi (float ) : Initial probaility distribution.
a (matrix) : Transmissions, hidden transition matrix a or alpha = transition probability matrix of changing states
given a state matrix is size (M x M) where M is number of states
b (matrix) : Emissions, matrix of observation probabilities b or beta = observation probabilities. given state
matrix is size (M x O) where M is number of states and O is number of different possible observations
Returns: - #### Tuple with:
> - `array _pi`: Initial probability distribution.
> - `matrix _a`: Transition probability matrix.
> - `matrix _b`: Emission probability matrix.
---
requires: `import RicardoSantos/WIPTensor/2 as Tensor` Bibliothèque

FunctionSMCMCLibrary "FunctionSMCMC"
Methods to implement Markov Chain Monte Carlo Simulation (MCMC)
markov_chain(weights, actions, target_path, position, last_value) a basic implementation of the markov chain algorithm
Parameters:
weights : float array, weights of the Markov Chain.
actions : float array, actions of the Markov Chain.
target_path : float array, target path array.
position : int, index of the path.
last_value : float, base value to increment.
Returns: void, updates target array
mcmc(weights, actions, start_value, n_iterations) uses a monte carlo algorithm to simulate a markov chain at each step.
Parameters:
weights : float array, weights of the Markov Chain.
actions : float array, actions of the Markov Chain.
start_value : float, base value to start simulation.
n_iterations : integer, number of iterations to run.
Returns: float array with path. Bibliothèque

Indicateur
