Probability Horizon - Bayesian SVJD Model# Probability Horizon — Bayesian SVJD Model
## What it does
Probability Horizon is a forward-looking probability projection tool. It does **not** generate buy or sell signals, does **not** act as a strategy, and does **not** place orders. Its single purpose is to display, at each bar, where price **may** be over a user-set horizon, drawn as a forward cone with three percentile lines (25%, 50%, 75%) plus an 8-row diagnostic dashboard.
The cone is the visual answer to two questions the indicator computes every bar:
1. **How wide should the distribution of forward outcomes be?** — set by expected total variance over the horizon.
2. **Should the distribution tilt up or down?** — set by a Bayesian-averaged probability of an up-move.
The wider the cone, the more uncertain the model is. The more the cone tilts, the more directionally confident the model is. A flat, narrow cone means "I expect range-bound, low-vol conditions." A wide, steeply tilted cone means "I expect a directional move under elevated variance."
## Why these components are combined (justification for the mashup)
This script combines several quantitative methods — KAMA, z-score, Haar wavelet, Kalman filter, Hamilton regime-switching, Hawkes process, Heston stochastic volatility, Merton jump-diffusion, Bayesian model averaging, and a calibration tracker. To a reviewer this can look like a collection of indicators bolted together, but it is not. It is **one** statistical model — a Stochastic Volatility Jump-Diffusion (SVJD) framework — whose pieces are mathematically required to produce a forward probability distribution.
Each component has a specific structural role:
- **Forward variance estimation.** A probability cone needs a forward-variance number. The naive choice is realized volatility × √horizon (pure Brownian motion), but this ignores two well-documented facts about financial returns: variance is mean-reverting (Heston, 1993) and returns have fat tails from discrete jumps (Merton, 1976). The Heston + jump-diffusion combination addresses both. The script uses the Heston integrated-variance closed form for the mean-reverting diffusion component, adds a Merton jump-variance contribution, and optionally adds a vol-of-vol uncertainty term. The result is a horizon-dependent variance estimate that dynamically narrows when volatility is elevated (expected to decay back to mean) and widens when volatility is depressed (expected to rise).
- **Directional probability.** To tilt the cone, a probability of direction is required. A single signal is unreliable, so five orthogonal sub-models each output their own P(up):
- A short-term KAMA-trend model
- A z-score mean-reversion model
- A Haar wavelet decomposition model (price denoised into trend + cycle + noise; signal fires only on the trend band)
- A Kalman-adaptive smoothing model (smoothing factor adapts to noise level in real time)
- A Hamilton 3-state regime model with Gaussian observation likelihoods (Bull / Bear / Range)
- **Sub-model combination.** The five P(up) values are combined via Bayesian model averaging with online weight updates. Each bar, after a fixed evaluation horizon, every sub-model is scored by log-loss against the actual outcome. Weights update via exponential decay: a model that predicted correctly gains weight; a model that failed loses weight. A minimum weight floor prevents any model from being silenced completely, so it can recover if its regime returns. Weights are renormalised to sum to 1.
- **Crisis dampening.** A Hawkes self-exciting point process monitors volatility clustering. Each large absolute return is treated as an event that boosts the process's intensity by α and decays exponentially at rate β. When intensity rises above a threshold multiple of its baseline, the final Bayesian probability is shrunk toward 0.5 — the higher the intensity, the stronger the shrinkage. This is how the model says "I have no idea — treat this as a coin flip" during regime breaks.
- **Self-correcting calibration.** A calibration tracker logs every prediction and checks the realized outcome after a fixed horizon. Predictions are binned by predicted probability (50–60%, 60–70%, etc.). If a bin's actual historical hit rate is below its predicted midpoint, future predictions in that bin are shrunk further toward 0.5. This is the model's honesty mechanism: it learns from its own miscalibration and tones itself down where it has been overconfident.
Each component answers a specific structural question. Remove any one and a specific capability disappears: no Heston → cone width does not adapt to vol regime; no calibration → no self-correction; no Hawkes → no crisis dampening; no Bayesian averaging → one model dominates and the system becomes brittle.
## How the components interact (data flow)
Every confirmed bar, the script executes the following pipeline:
1. **Measure** five raw market dimensions: KAMA slope, z-score vs trend, realized-vol percentile, OBV/price divergence, higher-TF trend.
2. **Each sub-model** maps its directional bias and strength to a probability in . The maximum single-model probability is capped at 0.60 because empirical calibration on multiple markets showed that anything higher is overconfident.
3. **Bayesian model averaging** combines the five sub-model probabilities into a single raw P(up), weighted by each sub-model's recent log-loss accuracy.
4. **Hawkes modifier** is applied: if intensity is above its warning threshold, the raw P(up) is pulled toward 0.5 in proportion to how far above threshold the intensity is.
5. **Calibration shrinkage** is applied: the post-Hawkes probability is checked against its calibration bin's historical hit rate, and shrunk further toward 0.5 if that bin has been overconfident.
6. **Forward variance** is computed separately: Heston integrated variance + Merton jump variance + optional vol-of-vol uncertainty, all over the projection horizon.
7. **The cone is drawn** with width set by the square root of forward variance and tilt set by the final shrunk probability. Three percentile lines (P25, P50, P75) are plotted from the current bar to the horizon endpoint.
Direction (sub-model probabilities → Bayesian average → Hawkes modifier → calibration shrinkage) is one half of the pipeline. Variance (Heston + jumps + vol-of-vol) is the other half. They meet at the cone, where one determines tilt and the other determines width.
## How to use it
**On the chart.** The cone shows the model's current view of the forward distribution. The P50 line is the median expected level given the implied drift. The P25 and P75 lines bracket the interquartile range. If P25 and P75 are roughly equidistant from current price, the model has no strong directional view; if the cone tilts noticeably up or down, the Bayesian probability favours that direction. A wider cone means more uncertainty; a narrower cone means tighter forward variance.
**The optional Monte Carlo cloud** (off by default) overlays bootstrap-resampled forward paths drawn from the asset's actual recent returns. Unlike the cone, it makes no Gaussian assumption — it shows the empirical distribution of forward outcomes given the asset's own recent return history.
**The 8-row dashboard** (top-right) is where the model exposes its full state:
- **Row 1 — Verdict.** Current direction (Bull / Bear / Neutral) and final P(up) percentage.
- **Row 2 — Direction.** A 10-character probability bar plus the size of the calibration shrinkage applied in percentage points.
- **Row 3 — 5 Models.** Up/down icons for each sub-model and the agreement count (e.g., "4/5 agree"). Trust the verdict more when 4 or 5 of 5 agree; trust it less when only 3 of 5 agree.
- **Row 4 — Regime.** Combined market regime (Quiet Bull / Quiet Bear / Volatile-Range / Crisis) plus the Hamilton dominant state.
- **Row 5 — Vol.** Volatility state vs long-run mean: HIGH (above mean, cone narrowing as vol decays), LOW (below mean, cone widening as vol rises), or AT MEAN. Includes the current sigma.
- **Row 6 — Risk.** Hawkes status: ✓ calm or ⚠ CRISIS. When CRISIS fires, the probability has been shrunk toward 0.5.
- **Row 7 — Honesty.** This is the most important diagnostic. It shows the actual historical hit rate for predictions in the 50–60% probability bin, with a Wilson confidence interval. If the system has predicted 55% many times and the actual rate is 53–58%, it is well-calibrated. If actual is below 50%, the system is currently overconfident and shrinkage is active.
- **Row 8 — Samples.** Total confirmed predictions and a trust level (low / warm-up / OK). Trust the cone less when total samples are below 50; trust it most when samples exceed 200.
## Suitable timeframes
The script auto-scales internal lookbacks to the chart timeframe relative to a 15-minute reference, so the same defaults work across 15-minute, 1-hour, 4-hour, and daily charts without manual tuning. Below 15 minutes the Hamilton 3-state model is automatically disabled because sample sizes become too small for reliable likelihood estimation; the other four sub-models continue to operate.
## What is original
Combining KAMA, wavelets, Kalman, Hamilton, Heston, Merton jumps, and a Hawkes process is not by itself new — these are all published methods. The original aspects of this script are:
- The **specific combination**: a five-model Bayesian ensemble for direction, with Hawkes-process crisis dampening and a self-correcting calibration tracker, all wrapped around a Heston + jump-diffusion variance estimate. I am not aware of a public Pine Script that combines all of these into a single probability cone with this data flow.
- The **calibration shrinkage mechanism**: the model logs every prediction, scores it after a fixed horizon, and applies bin-specific shrinkage to future predictions in bins where it has been overconfident. This is a self-correcting honesty layer that runs entirely on-chart, with Wilson confidence intervals and optional regime-specific calibration tables (Bull / Bear / Range).
- The **transparent diagnostic dashboard**: rather than hiding the model behind a single line, the dashboard exposes the verdict, model agreement, regime, vol state, crisis indicator, calibration quality, and sample size in eight rows. Users can see at a glance not only what the model thinks, but how much to trust it.
## Limitations (please read)
- **Pine Script cannot perform true maximum-likelihood estimation.** Heston and jump-diffusion parameters are estimated using approximation methods (AR(1) regression on log-variance, exponential moving averages for jump moments, rolling averages for long-term variance). The directional behaviour is correct — when vol is high, the cone narrows; when jumps are frequent, the cone widens — but exact parameter values are not equivalent to those a quantitative research desk would produce with MLE on tick data.
- **OHLCV data only.** No order-book data, no alternative-data feed, no options input, no fundamental input.
- **Calibration needs sample accumulation.** The Honesty row shows "warming up" until at least ~30 confirmed predictions have matured. Pine has no cross-session persistence, so calibration is rebuilt from chart history each time the indicator loads on a new chart.
- **Monte Carlo is deterministic.** Paths use a Linear Congruential Generator seeded by bar_index for reproducibility within a session. The same chart at the same moment produces the same cloud. This is intentional.
- **This is a probability indicator, not a strategy.** There are no backtest results, no equity curve, no position management. The script cannot tell you what to do; it only tells you what its model currently thinks the distribution of forward outcomes is.
- **Past calibration does not guarantee future calibration.** Market regimes change, parameters drift, and the cone should be treated as a visualisation aid rather than a prediction.
## Inputs of note
The defaults work without modification on most liquid instruments at most timeframes. Inputs worth knowing:
- **Auto-scale lookbacks** (on by default) — keeps the same defaults usable across timeframes.
- **Bayesian learning rate η** (default 0.15) — how fast sub-model weights adapt. Higher = faster but noisier.
- **Min Bayesian Probability** (default 0.62) — the threshold the dashboard uses to call a bar "Bull" or "Bear" rather than "Neutral".
- **Heston κ floor / ceiling** — bounds the mean-reversion-speed estimate. Defaults (0.02 to 0.30) handle most markets.
- **Hawkes warning threshold** (default 2.0× baseline) — when crisis dampening kicks in.
- **Monte Carlo Cloud** (off by default) — overlays bootstrap paths. Turn on if you want an empirical (non-Gaussian) view of forward outcomes alongside the cone.
## Disclaimer
This script is published for educational and analytical purposes only. It does not constitute financial advice, investment advice, a recommendation to buy or sell any financial instrument, or a solicitation of any transaction. The author is not a registered investment adviser and nothing in this script should be construed as personalised investment guidance.
Past performance does not guarantee future results. The probability projections shown by this indicator are model outputs, not forecasts of what will actually happen. Trading and investing involve substantial risk of loss and are not suitable for every investor. Users are solely responsible for their own trading decisions and for verifying that any approach is appropriate for their personal financial situation, risk tolerance, and applicable regulations.
The author and Market_Logic_India accept no liability for any losses, damages, or trading outcomes resulting from the use, misuse, or interpretation of this script. Use at your own risk.
Indicator

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 PulseWire, 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 PulseWire 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. Indicator

Signal Projection ExplorerMany traders focus on building full strategies right away — combining entries, exits, stop-losses, take-profits, filters, and position sizing.
But there is a problem with that approach:
👉 It often hides the true quality of the underlying signal.
When multiple layers are added on top (risk management, opposite signals, overlays), it becomes very difficult to answer a simple but critical question:
“Is this signal actually good on its own?”
🎯 What this indicator does
This tool is designed to analyze raw signals in isolation.
Instead of jumping straight into a full strategy, it lets you explore:
👉 What tends to happen to the price after a signal occurs?
🔍 How it works
The script detects signals in historical data (Golder Cross in this script).
It collects all occurrences of those signals.
For each signal, it tracks price performance over the next X bars.
It then builds a distribution of outcomes and projects it forward from the current price.
📈 What you see on the chart
Instead of a single prediction, you get a range of historical outcomes:
🔴 Worst P&L → maximum adverse move after the signal
🟢 Best P&L → best-case outcome
🔵 25th percentile → lower bound of typical outcomes
🟠 75th percentile → upper bound of typical outcomes
⚪ Mean → average path
🟣 Median → typical (robust) path
All of these are projected forward from the current price, giving you an intuitive view of possible scenarios.
📋 Stats Table
The table summarizes key metrics at the selected projection horizon:
Number of signals used
Final P&L for each line (Worst / Best / Percentiles / Mean / Median)
Distribution metrics like Spread and IQR
This gives you a quick read on:
Expected return
Risk range
Outcome dispersion
🧠 Why this matters
This tool helps you:
Separate signal quality from strategy complexity
Understand risk vs reward before adding filters
Avoid overfitting strategies on weak signals
Build better systems from strong foundations
⚠️ Important note
This is not a prediction tool.
It shows historical tendencies based on past signals — not guaranteed future outcomes.
Always use it as:
a research tool
a context layer
not a standalone trading system
🚀 Final thought
Before optimizing entries, exits, and risk…
👉 Make sure your signal itself has an edge.
This indicator helps you see that clearly.
Indicator

Indicator

Indicator

Forward-Projecting Opportunity Cone [ChartPrime]🔶 OVERVIEW
In a market defined by uncertainty, the Forward-Projecting Opportunity Cone provides a mathematically grounded roadmap for price action. Instead of predicting a single direction, this tool uses historical volatility and standard deviation to project a "cone" of high-probability price boundaries into the future.
By calculating the Expected Move based on annualized volatility, the indicator visualizes where price is statistically likely to remain over a specified window, helping traders identify trend exhaustion, mean reversion opportunities, and low-probability "tail events."
🔶 THE MATHEMATICS OF PROBABILITY
The indicator operates on the principle of Standard Deviation ( σ (sigma)) applied to logarithmic returns. It calculates the annualized volatility of the asset and projects it forward using the "Square Root of Time" rule:
1σ Zone (68.2% Probability): The "Normal" range. Most price action occurs here.
2σ Zone (95.4% Probability): The "Exhaustion" range. Reaching these levels often suggests a significant move is underway or nearing a limit.
3σ Zone (99.7% Probability): The "Extreme" range. Price hitting the 3rd sigma is a rare event often followed by sharp mean reversion or "Black Swan" momentum.
🔶 THE COMMAND CENTER: DYNAMIC DASHBOARD
The integrated dashboard is designed to act as a real-time risk-assessment engine, providing deep insights into the asset's current "volatility health" and the structural parameters of the projection.
Annualized Volatility: Displays the raw percentage of the asset's movement potential over a year based on the current timeframe.
Volatility Percentile: Contextualizes current volatility by ranking it against the last 252 bars. It tells you if the market is currently "quiet" or "explosive" compared to its own history.
Volatility Regime: Automatically classifies the market into LOW (Teal), NORMAL (Violet), or HIGH (Amber) regimes, allowing you to adjust your strategy based on the current environment.
Sigma Distance & Direction: Tracks exactly how many standard deviations price has moved from the anchor point and whether it is trending above or below the mean.
Expected % Moves: Provides precise mathematical targets for 1 σ (sigma), 2 σ (sigma), and 3 σ (sigma) moves in percentage terms for your specific projection window.
Anchor Price: Displays the exact price level where the statistical model begins. This allows for pinpoint accuracy when measuring moves from a specific Pivot High or Low.
Projection Window: Shows the duration (in bars) that the current cone extends into the future, defining the specific time horizon for the probability model.
🔶 CORE VISUAL INDICATIONS
The Pivot-Anchor "Cone Lock": Unlike standard moving bands, this can anchor to a fixed structural point (Pivot High/Low). This allows you to measure the probability of a specific trend's lifecycle from its inception.
Real-Time Zone Tracking: The indicator provides active labels like "Inside 1 σ (sigma)" for stable trends or "Beyond 3 σ (sigma) ✦" to warn of extreme volatility blowouts.
Gradient Probability Mapping: The cone utilizes a fading visual engine. As the projection moves further into the future, the colors soften, representing the natural increase in market "entropy" and uncertainty over time.
🔶 TRADING APPLICATIONS
Mean Reversion: When price pierces the 3 σ (sigma) (Amber) zone , it is in a territory that occurs less than 1% of the time. This is a high-conviction signal to look for reversal setups.
Trend Stability: A healthy, institutional-led trend typically grinds along the 1 σ (sigma) (Teal) boundary . If price remains here, the trend is sustainable.
Mathematical Take-Profits: Use the 1 σ (sigma) and 2 σ (sigma) levels at the tip of the cone to set take-profit targets that are statistically realistic for the current market state.
🔶 CONCLUSION
The Forward-Projecting Opportunity Cone is more than a volatility band; it is a structural probability engine. By anchoring math to price action and providing a comprehensive dashboard of risk metrics, it helps traders remain objective, avoid chasing extremes, and understand exactly where "normal" ends and "opportunity" begins. Indicator

Transform Swing Forecast SignalName:
Transform Candle Swing Reversal Explorer
Searchable Name:
Transform Swing Forecast Signal
Short title:
TFX Forecast Signal
Summary
Transform Candle Swing Reversal Explorer is a simplified exploratory script designed to visualize transform-style directional movement, swing/reversal framing, and hypothetical forecast candles on PulseWire charts. It is meant to help users inspect chart structure, directional shifts, and possible path-expansion behavior in a lightweight format.
It is also meant for users who want to better understand transform candles and transform-style movement in a simpler script, and for users who are looking to develop, create, test, or modify their own engine/script from an open source starting point for personal use, instead of needing the full operational engine source to do that. Users who want a pre-built ready-to-test/use operational engine should search for Transform Entry Exit Reversal.
How it works
The script builds a simple causal transform path from raw price and displays it as wickless transform candles plus a transform path line. It uses a lightweight alternating turning-point method to mark possible swing/reversal areas and a simplified forecast model to project hypothetical future candles and targets.
This explorer version is focused on visualization and exploratory chart reading. It does not include the best-fit transform engine, advanced pivot-timing/replay structure, or the full execution/trade-management architecture used in Transform Entry Exit Reversal. The goal is to demonstrate the category and some of its possibilities in a simpler script format.
It is also intended to serve as a lighter open source starting point for users who want to better understand transform candles and transform-style movement, and develop/create, test, or modify their own personal script/engine from that foundation.
Forecast model note
Forecast candles in this script are hypothetical path projections, not literal future predictions. They are intended to show a possible future movement/path-expansion sketch, not an exact real-world directional or target-hit probability.
Features
Wickless transform candle display
Transform path line
Alternating swing/reversal markers
Hypothetical forecast candles
Forecast target lines and labels
Small status table
Simple trend-flip alert
Who it’s for
This script is best suited for traders and researchers who want a lightweight exploratory tool for studying transform-style chart structure, swing/reversal framing, and hypothetical future path behavior.
It is especially suited for users who want to better understand transform candles and transform-style movement in a simpler script, and for users who want to develop, create, test, or modify their own personal script/engine from a lighter open source starting point.
Who it’s not for
This script is not best suited for users looking for advanced replay diagnostics, execution-ready trade management, or a complete transform/pivot engine workflow.
It is also not best suited for users mainly looking for a pre-built ready-to-test/use operational engine, since that is the role of Transform Entry Exit Reversal.
Final note
This is an exploratory swing/reversal visualization script. Its purpose is to demonstrate a simplified transform-candle, swing/reversal, and forecast-candle concept that can help users understand the broader category.
It is also intentionally suited to users who want to better understand transform candles and transform-style movement in a simpler open source script, and create, test, or modify their own personal script/engine, rather than use Transform Entry Exit Reversal directly. Indicator

Transform Candle Swing Reversal ExplorerName:
Transform Candle Swing Reversal Explorer
Short title:
TFC Swing Reversal Explorer
Summary
Transform Candle Swing Reversal Explorer is a simplified exploratory script designed to visualize transform-style directional movement, swing/reversal framing, and hypothetical forecast candles on PulseWire charts. It is meant to help users inspect chart structure, directional shifts, and possible path-expansion behavior in a lightweight format.
It is also meant for users who want to better understand transform candles and transform-style movement in a simpler script, and for users who are looking to develop, create, test, or modify their own engine/script from an open source starting point for personal use, instead of needing the full operational engine source to do that. Users who want a pre-built ready-to-test/use operational engine should search for Transform Candle Pivot Swing Reversal Engine.
How it works
The script builds a simple causal transform path from raw price and displays it as wickless transform candles plus a transform path line. It uses a lightweight alternating turning-point method to mark possible swing/reversal areas and a simplified forecast model to project hypothetical future candles and targets.
This explorer version is focused on visualization and exploratory chart reading. It does not include the best-fit transform engine, advanced pivot-timing/replay structure, or the full execution/trade-management architecture used in Transform Candle Pivot Swing Reversal Engine. The goal is to demonstrate the category and some of its possibilities in a simpler script format.
It is also intended to serve as a lighter open source starting point for users who want to better understand transform candles and transform-style movement, and develop/create, test, or modify their own personal script/engine from that foundation.
Forecast model note
Forecast candles in this script are hypothetical path projections, not literal future predictions. They are intended to show a possible future movement/path-expansion sketch, not an exact real-world directional or target-hit probability.
Features
Wickless transform candle display
Transform path line
Alternating swing/reversal markers
Hypothetical forecast candles
Forecast target lines and labels
Small status table
Simple trend-flip alert
Who it’s for
This script is best suited for traders and researchers who want a lightweight exploratory tool for studying transform-style chart structure, swing/reversal framing, and hypothetical future path behavior.
It is especially suited for users who want to better understand transform candles and transform-style movement in a simpler script, and for users who want to develop, create, test, or modify their own personal script/engine from a lighter open source starting point.
Who it’s not for
This script is not best suited for users looking for advanced replay diagnostics, execution-ready trade management, or a complete transform/pivot engine workflow.
It is also not best suited for users mainly looking for a pre-built ready-to-test/use operational engine, since that is the role of Transform Candle Pivot Swing Reversal Engine.
Final note
This is an exploratory swing/reversal visualization script. Its purpose is to demonstrate a simplified transform-candle, swing/reversal, and forecast-candle concept that can help users understand the broader category.
It is also intentionally suited to users who want to better understand transform candles and transform-style movement in a simpler open source script, and create, test, or modify their own personal script/engine, rather than use Transform Candle Pivot Swing Reversal Engine directly. Indicator

Swing Structure Forecast [BOSWaves]Swing Structure Forecast - Statistical Swing Projection System with Volatility-Adaptive Support and Resistance Detection
Overview
Swing Structure Forecast is a statistically-driven swing analysis system that maps directional price structure through confirmed pivot identification, where support and resistance zones construct automatically at each swing extreme and a probabilistic forecast beam projects the next swing leg using aggregated historical swing measurements.
Rather than applying fixed price targets, universal extension ratios, or lagging directional filters, zone boundaries, forecast direction, and projection magnitude are governed by structural pivot confirmation, ATR-proportioned zone sizing, and rolling statistical measurement of completed swing history across a configurable sample window.
This produces a continuously refreshed structural map alongside a data-grounded forward projection. Zones breathe with volatility cycles and forecasts are calibrated to the instrument's own measured behaviour rather than theoretical constants or fixed multiples.
Price is therefore assessed against structurally-anchored zones derived from confirmed swing pivots, with directional expectations built from the statistical record of prior completed legs rather than external reference points.
Conceptual Framework
Swing Structure Forecast is built on the premise that genuine support and resistance originate at confirmed swing extremes, and that the statistical character of completed swing legs contains meaningful information about the magnitude and duration of the move that will follow.
Standard projection methodologies apply predetermined ratios that treat every instrument and market condition as interchangeable. This framework instead extracts magnitude expectations from the instrument's own swing record, building an evidence base from recent completed legs and distilling it into a statistically-grounded projection originating at the current confirmed pivot.
Three core principles shape the design:
Support and resistance zones should originate at structurally confirmed swing highs and lows, not at indicator crossovers, arbitrary distances, or price patterns lacking pivot confirmation.
Zone width must respond to prevailing volatility, expanding proportionally when ATR is elevated and compressing when market conditions quieten.
Forecast targets and projection uncertainty should be derived from the distribution of the instrument's own recent swing history, with variability expressed visually rather than hidden behind a single projected level.
This repositions price structure work from passive historical reference into an active, instrument-specific projection framework that updates with each new confirmed swing.
Theoretical Foundation
The indicator unifies structural pivot detection, ATR-responsive zone construction, rolling statistical aggregation, and Fibonacci extension mapping.
Swing highs and lows are established through a rolling highest/lowest comparison across a configurable lookback window, accepting only pivots surrounded by sufficient structural confirmation on both sides. A 200-period ATR provides a slow-moving, stable volatility reference that scales zone thickness and beam width proportionately across varying instruments and timeframes. Completed swing percentages and durations populate a rolling sample array, with three aggregation modes — weighted, average, and median — giving users direct control over how heavily recent legs are weighted against older history. Standard deviation across this sample governs beam width, producing narrow projections when swing history is consistent and widening the beam when prior legs have varied significantly in magnitude.
Four internal systems work in coordination:
Pivot Detection Engine : Confirms swing highs and lows through multi-bar structural comparison, withholding confirmation until price movement validates the extreme and eliminating repainting.
Zone Construction System : Builds dual-layer ATR-proportioned boxes at each confirmed pivot, applying progressive opacity reduction with age and monitoring for structural breach events.
Forecast Engine : Processes the rolling swing sample through the selected statistical method and casts the next projected leg as a smoothed cone beam originating at the current pivot, scaled by historical variance.
Fibonacci Extension System : Deploys individually toggleable extension levels beyond the primary forecast target, each with a fully configurable ratio for defining continuation objectives.
This structure keeps the structural map and forward projection permanently coupled, refreshing in unison whenever a new swing confirms.
How It Works
Swing Structure Forecast processes price through a structured sequence of pivot-aware operations:
Pivot Confirmation : Bar highs and lows are continuously compared against a rolling window of configurable length. A swing high locks in once price retreats sufficiently from the peak; a swing low locks in once price advances sufficiently from the trough, ensuring no repainting occurs.
Zone Placement : A dual-layer box anchors at each confirmed pivot. An outer boundary encloses the broader reaction area and an inner zone concentrates the higher-probability interaction region.
Age-Based Fading : Zone opacity diminishes progressively as elapsed bars accumulate since formation, weighting recent structural levels visually above older historical context.
Breach Detection : A close beyond a zone's anchor level triggers conversion to a dotted outline and initiates an automatic removal sequence, purging invalidated structure from the chart.
Swing Recording : Each completed leg is logged as a percentage magnitude and a bar duration into the rolling sample array, capped at the user-defined sample count with oldest entries discarded first.
Statistical Aggregation : The selected method, weighted, average, or median, resolves the sample into an expected magnitude and duration for the forthcoming swing leg.
Beam Construction : A three-layer cone extends forward from the current pivot anchor using smoothstep-eased interpolation, with width proportional to sample standard deviation and opacity grading across nested layers.
Target Zone : A bounding box placed at the beam terminus presents the projected price level and expected percentage move, with box height communicating the degree of forecast uncertainty.
Fibonacci Extensions : Configurable ratio levels project beyond the primary target, establishing pre-mapped objectives for continuation moves that exceed the base projection.
These processes collectively sustain a live structural framework and a statistically-grounded projection that regenerates with every newly confirmed swing pivot.
Interpretation
Swing Structure Forecast should be read as a structural boundary map combined with a probabilistic directional projection:
Support Zones (Green) : Constructed at confirmed swing lows, marking price regions where prior downside pressure exhausted and upward reversals originated.
Resistance Zones (Red) : Established at confirmed swing highs, identifying areas where prior upside pressure stalled and downward reversals began.
Zone Opacity : Communicates structural age. Vivid zones reflect recent pivot formation; subdued zones represent older levels retained for broader historical context.
Broken Zones : Transition to faint dotted outlines on breach, preserved as reference markers without visually competing with structurally intact levels.
Forecast Beam : Extends forward from the most recently confirmed pivot, projecting the statistically expected next leg. Cone width encodes uncertainty drawn from sample variance.
Narrow Beam : Prior swing history shows consistent magnitude, indicating relatively high projection confidence.
Wide Beam : Prior swing history shows significant variability, indicating greater uncertainty and warranting additional confirmation before acting.
Target Zone and Label : Mark the statistically derived price destination alongside expected percentage move and absolute price level.
Fibonacci Extensions : Pre-mapped levels beyond the primary target defining structured continuation objectives for extended directional moves.
Path Markers : Dot markers positioned along the beam centerline with opacity fading toward the target, conveying projected trajectory and directional progression.
Structural context, beam width, and sample consistency are more significant than any individual projected value in isolation.
Signal Logic and Visual Cues
Swing Structure Forecast operates through two principal visual frameworks:
Structural Zones : Continuously maintained support and resistance boxes anchored at confirmed pivots. Intact zones carry unbroken structural relevance; broken zones document levels that price has already closed through and structurally dismissed.
Forecast Beam : Repositions automatically on every new swing confirmation, simultaneously refreshing the beam geometry, target zone, path markers, and Fibonacci extensions to reflect the updated pivot origin and current statistical aggregation.
Alert conditions trigger on confirmed swing high and swing low events, supporting systematic structural monitoring without requiring active chart observation.
Strategy Integration
Swing Structure Forecast applies across structure-based, mean-reversion, and trend-continuation trading methodologies:
Structure-Referenced Entries : Treat intact zones as interaction boundaries for entry decisions, assigning greater weight to recently formed levels over aged, heavily faded structure.
Instrument-Calibrated Targets : Use the statistical projection as a primary take-profit reference built from the instrument's own measured swing history rather than applied universal ratios.
Beam Width Conviction Scaling : Adjust confirmation requirements relative to current beam width. Wide beams call for additional validation before committing; narrow beams reflect historically stable swing magnitude.
Fibonacci Continuation Planning : Reference extension levels beyond the primary target when trending conditions suggest the initial projection may be exceeded.
Broken Zone Flip Monitoring : Track recently breached zones as candidate reversal levels where former support may transition to resistance and vice versa following structural invalidation.
Multi-Timeframe Structural Context : Reference higher-timeframe zones as macro boundaries while applying lower-timeframe forecast projections for entry precision and target identification.
Sample Population Patience : Defer high-conviction treatment of projection outputs until the sample window has accumulated sufficient completed swings, particularly on instruments or timeframes with limited history.
Technical Implementation Details
Core Engine : Rolling highest/lowest pivot detection with configurable lookback and no-repaint confirmation logic
Zone Construction : Dual-layer ATR-proportioned boxes with progressive opacity fading, breach detection, and automatic invalidation removal
Statistical Model : Weighted, average, or median aggregation across configurable rolling sample with standard deviation uncertainty scaling
Forecast Geometry : Smoothstep-eased three-layer polyline beam with standard deviation width scaling and graduated opacity
Target Visualisation : Projection label with percentage move and price level enclosed by uncertainty-proportioned target box
Fibonacci System : Five independently toggleable extension levels with fully configurable ratios
Alert Coverage : Swing high confirmation and swing low confirmation events
Performance Profile : Optimised for real-time execution across all timeframes with configurable zone capacity and sample limits
Optimal Application Parameters
Timeframe Guidance:
1 - 15 min : Near-term swing structure with short-horizon projection for intraday approaches
1H - 4H : Intraday to multi-session structural mapping with intermediate forecast range
Daily - Weekly : Macro swing structure identification with extended projection targets
Suggested Baseline Configuration:
Swing Length : 16
Zone Width (ATR) : 0.3
Max Level Age : 300 bars
Samples : 20
Method : Weighted
Forecast Bars : 5
Fib Extensions : 1.0, 1.272, 1.618 active
These suggested parameters serve as a starting baseline; their effectiveness varies with the instrument's volatility profile, characteristic swing cadence, and preferred zone density, so incremental adjustment across multiple session types is recommended before drawing performance conclusions.
Parameter Calibration Notes
Apply the following refinements to adjust behaviour without modifying core logic:
Zones too wide : Lower Zone Width (ATR) to narrow zone boundaries, particularly on lower timeframes where ATR values produce oversized zones relative to typical price movement.
Too many zones forming : Raise Swing Length to impose stricter structural requirements before a pivot qualifies for zone creation.
Beam excessively wide : Sample history contains high variance. Raise Samples to dilute outlier legs or switch to Median to limit their influence on the projected magnitude.
Projection slow to reflect recent behaviour : Lower Samples or switch to Weighted method to concentrate projection weight on the most recently completed swing legs.
Significant pivots going undetected : Lower Swing Length to increase sensitivity and qualify shorter structural moves as confirmed pivots.
Forecast visual range misaligned with chart : Modify Forecast Bars to adjust how far projection visuals extend rightward without altering the underlying price target calculation.
Stale levels persisting on chart : Reduce Max Level Age to accelerate removal of older unbroken zones, keeping structural reference anchored to recent pivot history.
Adjustments should be applied incrementally and assessed across varied session conditions rather than calibrated against a single market period.
Performance Characteristics
High Effectiveness:
Markets exhibiting rhythmic swing sequences with clearly defined structural turning points
Instruments where volatility follows identifiable expansion and contraction patterns that ATR captures proportionately
Trend-continuation approaches targeting measured extensions derived from the instrument's own swing record
Mean-reversion strategies using confirmed structural zones as primary entry and exit reference boundaries
Reduced Effectiveness:
Directionless, low-conviction conditions generating frequent shallow pivots that populate the sample with structurally insignificant measurements
Event-driven or gap-heavy sessions producing swing magnitudes that are unrepresentative of normal instrument behaviour
Instruments with erratic or non-stationary volatility profiles where ATR-based proportioning loses consistency
Early sessions on a given timeframe before sufficient completed swings have accumulated to produce statistically reliable projections
Integration Guidelines
Confluence : Pair with BOSWaves volume tools, order flow indicators, or broader market structure analysis to reinforce zone and forecast interpretation
Sample Discipline : Reserve high-conviction treatment for projections generated once the sample window is fully populated with completed swings
Breach Acceptance : Treat breached zones as structurally void and resist anchoring expectations to levels price has already invalidated with a closing breach
Beam Width Respect : Read a wide beam as a requirement for additional confirmation before acting, not permission to disregard the projection entirely
Directional Consistency : Sustain bias aligned with the current forecast direction until a newly confirmed swing pivot shifts the projection origin
Timeframe Confluence : Highest-quality structural setups emerge when active zones and forecast direction correspond across multiple timeframes simultaneously
Disclaimer
Swing Structure Forecast is a professional-grade swing structure and statistical forecasting tool. All projections are derived from historical swing behaviour and represent probabilistic expectations rather than assured outcomes. Performance depends on the consistency of prior swing history, prevailing market conditions, parameter selection, and disciplined application. BOSWaves recommends deploying this indicator as one component within a comprehensive analytical framework incorporating trend context, volume analysis, and rigorous risk management practices. Indicator

Spline Quantile Regression Channel [LuxAlgo]The Spline Quantile Regression Channel indicator implements an advanced non-linear regression model to fit a flexible, multi-level channel over recent price action. Unlike standard linear regression which identifies the mean trend, this tool fits specific price percentiles (quantiles) using cubic splines, providing robust support and resistance zones that adapt to market volatility and non-linear structures.
🔶 USAGE
The indicator is designed to provide a sophisticated view of the current trend and its extremes. By fitting cubic splines to specific quantiles, the script offers a "bendable" channel that can follow complex price movements more accurately than traditional straight-line regressions.
🔹 Trend Identification
The median line (default 0.5 quantile) represents the central tendency of the price action. When the spline is sloping upward, it indicates a non-linear bullish regime; a downward slope indicates a bearish regime.
🔹 Support and Resistance
The upper and lower bands represent the specified extremes (e.g., the 90th and 10th percentiles). These act as dynamic boundaries:
Prices reaching the upper band often indicate overextended conditions within the current lookback period.
Prices reaching the lower band suggest the asset is trading at the lower end of its recent distribution.
🔹 Forecasting
The indicator projects the calculated spline into the future using a dashed line. This forecast is a mathematical extrapolation of the current non-linear trend, helping traders visualize where the price distribution is headed if the current momentum and curvature persist.
🔶 DETAILS
The script employs several advanced mathematical concepts to ensure accuracy and stability:
Cubic Spline Basis: The model uses a piecewise polynomial basis ($1, x, x^2, x^3$) combined with truncated power functions at "knots." This allows the curve to change its curvature locally, adapting to swings that a simple polynomial cannot capture.
Quantile Optimization: Instead of minimizing squared errors (OLS), the script uses an Iteratively Reweighted Least Squares (IRLS) solver to minimize the "check function." This allows the script to target specific percentiles of the price data.
Numerical Stability: To prevent matrix overflows common in high-degree polynomial calculations, the script standardizes price data (Z-score) and scales time coordinates between 0 and 1 before performing matrix inversion.
🔶 SETTINGS
🔹 Spline Configuration
Lookback Period: The number of historical bars used to fit the spline regression. Larger windows result in a more "macro" trend, while smaller windows react quickly to recent changes.
Internal Knots: Determines the "flexibility" of the spline. More knots allow the curve to follow price swings more tightly, while fewer knots yield a smoother, more rigid curve.
🔹 Optimization
IRLS Iterations: The number of optimization passes for the solver. Higher values improve the accuracy of the quantile fit, especially in volatile markets.
Forecast Length: The number of bars to project the calculated spline into the future.
🔹 Quantile Levels
Upper Quantile: The specific percentile for the upper band (e.g., 0.95 for the top 5%).
Median Quantile: The central percentile (typically 0.5 for the median).
Lower Quantile: The specific percentile for the lower band (e.g., 0.05 for the bottom 5%).
🔹 Visuals
Colors: Individual color settings for the upper, median, and lower bands.
Line Width: Controls the thickness of the polylines rendered on the chart.
Indicator

Regime-Adaptive kNN Breakouts + Kalman Predictor [TechnicalZen]Regime-Adaptive kNN Breakout Classifier + Kalman Price Predictor
Why This Indicator Exists
Most breakout indicators treat every compression pattern equally. In reality, a volatility contraction forming during a high-ADX trending environment with surging volume behaves very differently from the same pattern in a choppy, low-volume consolidation.
This indicator addresses that gap by combining three distinct analytical engines:
Multi-Period Compression Detection — Scans across multiple bar periods to find the tightest range relative to recent history, identifying genuine volatility contraction zones where expansion is statistically likely.
Regime-Adaptive kNN Classification — A machine learning gate that evaluates the market regime surrounding each compression zone using Kalman-filtered features. Only setups with sufficient similarity to historically successful breakouts are allowed through.
Kalman Price Predictor — A state-space estimator tracking price position and velocity, enabling forward projection with a widening uncertainty cone.
The result is an indicator that learns which market conditions produce successful breakouts and provides a probabilistic price forecast — not just pattern detection.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
HOW IT WORKS
1. Multi-Period Compression Detection
The engine evaluates bar ranges across 2 to 20 periods, computing each period's range (highest high minus lowest low) and comparing it against the minimum range observed within an adaptive lookback window. When the current range is tighter than any historical range in the window, a compression zone is identified. The smallest qualifying period is selected — representing the most extreme volatility contraction.
An optional Inside Bar filter adds a complementary signal when the current bar's range is entirely contained within the prior bar.
2. ADX-Adaptive Lookback Window
The comparison window dynamically adjusts based on trend strength:
High ADX (strong trend) — shorter lookback, more responsive to compression during momentum phases
Low ADX (ranging market) — longer lookback, requiring more extreme contraction before triggering
This prevents the indicator from being too sensitive in trending markets or too sluggish in ranging conditions.
3. Kalman-Filtered Feature Space
Four market regime features are computed on every bar and smoothed through independent Kalman filters using a position + velocity state-space model. The Kalman filter reduces noise while tracking each feature's rate of change — achieving smoothing without the lag penalty of traditional moving averages.
The kNN classifier operates entirely on these Kalman-filtered features:
Relative Volume — Volume / SMA(Volume, 100) — captures participation surge or drought, Kalman-smoothed to filter out single-bar volume spikes
Relative ATR — ATR(14) / SMA(ATR, 100) — captures volatility expansion vs contraction regime, Kalman-smoothed for stable regime identification
ADX Normalized — ADX / 50 — measures trend strength (direction-agnostic), Kalman-smoothed to track trend momentum
Distance from MA — (Close - Trend MA) / ATR — price position relative to trend, Kalman-smoothed to reduce whipsaw noise
By filtering the feature space through the Kalman estimator before classification, the kNN operates on cleaner, denoised regime signals rather than raw noisy measurements. This is the critical link between the Kalman filter and the kNN — the classifier's accuracy depends on the quality of its input features.
4. kNN Breakout Classification
When a compression zone triggers a breakout, the classifier:
Constructs a feature vector from the four Kalman-filtered regime features
Scans the history buffer using Manhattan distance to find similar past regime conditions
Selects the k-nearest resolved neighbors — only TP (take-profit) and SL (stop-loss) outcomes vote; pending and time exits are excluded entirely
Computes a distance-weighted classification score where closer neighbors have proportionally more influence
Compares the score against the user-defined confidence threshold
If the score falls below the threshold, the setup is silently skipped. The classifier has learned which combinations of volume regime, volatility regime, trend strength, and price position tend to produce winning breakouts.
Key design choices:
Adaptive k — k = floor(sqrt(resolved outcomes)), clamped between user-defined min/max. The number of neighbors consulted grows naturally as the classifier accumulates experience, preventing overfitting to sparse early data.
Warmup phase — During the first N resolved outcomes, all setups pass through to build the training set. The classifier only begins filtering after accumulating sufficient data.
Feedback loop — Every exit writes its outcome back to the history buffer. TP exits score 1.0, SL exits score 0.0. The classifier genuinely learns from the specific chart and timeframe it is applied to.
Distance-weighted voting — Prevents outlier neighbors from distorting the classification. A very close TP neighbor outweighs several distant SL neighbors, producing more nuanced probability estimates.
5. Kalman Price Predictor
A fifth Kalman filter runs on price itself, maintaining three estimates simultaneously:
Filtered position — optimal smoothed price estimate
Velocity — estimated rate of price change per bar
Covariance matrix — estimation uncertainty and cross-correlations
The velocity component enables forward projection: Predicted Price = Filtered Position + Velocity x Projection Bars . The uncertainty cone is scaled by ATR and widens proportionally to the square root of the projection horizon — reflecting the theoretical uncertainty growth of price over time.
Projection trail: The last 5 projections are displayed with graduated transparency (50% to 90%), creating a visual history of how the forecast has evolved. A consistent, parallel trail suggests strong directional conviction; a diverging or oscillating trail signals uncertainty.
6. Trend-Aware Exit System
The exit system uses four complementary mechanisms, each feeding outcomes back to the kNN:
Take Profit — R-multiple target (default 2R, where R = compression zone range). Scored as 1.0 in kNN feedback.
Stop Loss — Opposite side of compression zone, optionally requiring price to also be wrong-side of the Trend MA. This trend-aware condition reduces whipsaw stops in strong trends. Scored as 0.0 in kNN feedback.
Trailing Stop — Activates after 1R profit, trails by ATR x multiplier. Dynamic protection that locks in gains.
Time Exit — Maximum bars in trade before forced exit. Scored as 0.5 (neutral) — neither rewarding nor penalizing the kNN for inconclusive setups.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
VISUAL GUIDE
Chart Elements
Compression boxes — Colored zones marking detected volatility contraction (green = bullish breakout, red = bearish)
Extended levels — Dotted lines projecting the high and low of each compression zone forward
Entry labels — Direction and kNN confidence percentage (e.g., "Long 72.5%")
Exit labels — TP / SL / T markers with R-multiple detail in tooltip
Projection line — Dashed line extending forward from Kalman-filtered price
Uncertainty cone — ATR-scaled filled area widening into the future
Projection trail — 5 fading historical projections showing forecast evolution
Kalman price line — Optional smoothed price curve (off by default)
Dashboard (bottom-right)
Win Rate — Percentage of resolved trades hitting TP (tinted green or red)
Trades — Win / Loss count
Mode — Distance-weighted classification
Phase — Warmup (building data) or Active (filtering enabled)
k — Current adaptive k value
Score — Latest kNN confidence score
History — Buffer fill level (e.g., 45/60)
Projection — Predicted price with directional arrow
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SETTINGS GUIDE
Detection
Enable Inside Bar (default: On) — Include Inside Bar patterns alongside compression detection
Adaptive kNN
Enable kNN Filter (default: On) — Toggle the ML classification gate
k Min / k Max (default: 2 / 10) — Bounds for adaptive k. Auto-scales with sqrt of resolved outcomes
Confidence Threshold (default: 0.25) — Minimum kNN score to accept a setup. Lower values are more permissive; higher values are more selective
Min Resolved to Activate (default: 15) — TP/SL outcomes needed before the classifier begins filtering
History Buffer Size (default: 60) — Maximum stored breakout patterns for comparison
Kalman Filter
Process Noise Q (default: 0.01) — Controls how much the filter expects the underlying signal to change between bars. Higher values make the filter more responsive but noisier
Measurement Noise R (default: 0.10) — Controls how much the filter distrusts each new measurement. Higher values produce smoother output with more lag
Show Price Projection (default: On) — Display the forward projection line and uncertainty cone
Projection Bars (default: 10) — How far forward to project price
Projection Color (default: Aqua) — Color for all projection elements
Show Uncertainty Cone (default: On) — Display the ATR-scaled confidence band
Cone Width (default: 1.0 ATR) — Width multiplier for the uncertainty cone. Adjustable per instrument
Show Kalman Price Line (default: Off) — Display the smoothed Kalman price estimate on chart
Trend Filter
Enable Trend Filter (default: On) — Restrict breakouts to trend-aligned direction only
Trend MA Mode (default: Adaptive) — Static = fixed MA length; Adaptive = MA length scales dynamically with the compression lookback
MA Type (default: EMA) — Exponential or Wilder's (RMA) moving average
Adaptive Multiplier (default: 2.0) — Lookback x Multiplier = MA length in adaptive mode
Static MA Length (default: 200) — Fixed MA length when in static mode
Adaptive Look Back
Look Back Mode (default: ADX Adaptive) — Static = fixed comparison window; ADX Adaptive = window scales with trend strength
ADX Length (default: 14) — Period for ADX calculation
ADX Low / High (default: 10 / 35) — ADX range mapped to lookback bounds. Higher ADX compresses the lookback
LB Min / LB Max (default: 20 / 120) — Minimum and maximum lookback window size
Exits
TP (R-multiple target) (default: On) — Take-profit at R-multiple of compression zone range
SL (opposite side) (default: On) — Stop-loss at opposite boundary of compression zone
Target R (default: 2.0) — Take-profit distance as multiple of range
Trend-Aware SL (default: On) — SL only triggers when price is also wrong-side of Trend MA
Trailing Stop (default: On) — Trails by ATR x multiplier after 1R profit
Trail ATR Multiplier (default: 1.5) — Trail distance = ATR(14) x this value
Time Exit (default: On, 50 bars) — Force exit after maximum bars in trade
Visual Settings
Bull / Bear / Time colors — Customizable directional colors
Box Fill / Border Transparency — Compression zone box appearance
Extend Levels (default: 50 bars) — Forward projection distance for compression zone levels
Level Width / Style — Line appearance for projected levels
Max Patterns Kept (default: 120) — Maximum drawing objects maintained on chart
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
THE KALMAN-kNN PIPELINE
The two ML components are not independent — they form a pipeline:
Kalman filters denoise the four regime features on every bar, producing clean estimates of volume regime, volatility regime, trend strength, and price position
kNN classifier operates on these Kalman-filtered features, comparing the current denoised regime against historically successful and unsuccessful breakout conditions
Kalman price filter independently tracks price dynamics, projecting the estimated trajectory forward with quantified uncertainty
The classifier's accuracy fundamentally depends on the quality of its input features. By feeding Kalman-filtered signals rather than raw measurements, the kNN compares regime states rather than noisy observations — producing more stable and meaningful similarity assessments.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CREDITS AND ACKNOWLEDGMENTS
This indicator builds upon concepts from two published works:
Smart NR2–NR20 and Inside Bar by Zeiierman — multi-period compression detection, adaptive lookback via ADX, and breakout trigger architecture
kNN Market Architecture by LuxAlgo — application of k-nearest neighbors classification to filter market signals using relative volatility and volume features
Original contributions in this indicator:
Kalman filter state-space estimation for feature smoothing (position + velocity model with full covariance tracking)
Kalman-to-kNN pipeline — classifier operates on denoised regime features, not raw measurements
Regime-adaptive kNN classification with distance-weighted voting on resolved outcomes only
Real-time feedback loop where exit outcomes update the kNN training data
Adaptive k scaling based on accumulated classifier experience
Kalman price predictor with forward projection and ATR-scaled uncertainty cone
Graduated projection trail showing forecast evolution
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
This indicator is for educational and informational purposes only. It does not constitute financial advice. All investments involve risk, and past performance does not guarantee future results. The kNN classifier learns from historical patterns on the specific chart and timeframe it is applied to — its effectiveness may vary across different instruments and market conditions. Always conduct your own analysis and risk management.
Indicator

Analogue Matcher | GainzAlgoAnalogue Matcher: Dual-Path Regression Projection
What It Is
The Analogue Matcher is a high-performance pattern recognition engine designed to find historical "price twins." Unlike standard fractals that look for raw shape similarity, this tool utilizes Linear Regression Analysis to identify periods in the past where market velocity (slope) and trend consistency ($R^2$) were near-identical to current conditions. It then projects those historical outcomes forward as "Ghost Candles," providing a probabilistic roadmap of where price might go.
How It Works
The indicator operates by scanning a user defined amount of lookback bars of history in real-time (Default 500).
• The Scan: It calculates the current regression slope over a user-defined window.
• The Match: It iterates through the lookback period to find the closest matches based on a strict Slope Tolerance .
• Dual-Path Intelligence: In "Dual Mode," the script identifies the single best Bullish outcome and the single best Bearish outcome simultaneously. This prevents "bias-blindness" by showing you the best-case scenarios for both directions.
Understanding Confidence & R2
The "Conf (R²)" column in your dashboard is the heart of the script's decision-making.
• Slope Similarity: Measures how closely the historical angle matches the current angle.
• R2 (Coefficient of Determination) : Measures the "cleanliness" of the trend. An R2 of 100.0 is a perfect straight line; 0.0 is pure noise.
• The Percentage: Our algorithm combines these two factors. A 90%+ Confidence rating means you have found a historical twin that moved at the same speed and with the same level of trend maturity as the current bar.
How to Use: A Risk Management Approach
This is not a "magic signal" generator—it is a Risk Management and Bias Tool .
• Identify Convergence: If both the Bullish and Bearish paths show high confidence (>80%) and both point in the same direction, you have high-probability confluence.
• Divergence Warning: If the Bullish path has 95% confidence but the Bearish path has only 10%, the historical precedent for a trend reversal is mathematically weak. Your bias in this case would lean bullish. Inverse if it’s flipped with a high bearish confidence and a low bullish confidence.
• Filtering Noise: Use the R2 percentage to ignore "messy" matches. If the confidence is below 50%, the analogue is likely too "noisy" to be used for a high-conviction trade entry.
• Single Mode for Speed: Switch to Single Mode on lower timeframes (1m, 5m) to find the absolute "Best Fit" twin for quick scalping targets.
Master the Engine: Key Inputs
To get the most out of the Analogue Matcher , it’s essential to understand the "knobs" you are turning. Tuning these correctly is the difference between finding a perfect twin and seeing random noise.
• Mode Selection (Single vs. Dual): Single Mode: Focuses the processing power on finding the absolute "Best Fit" regardless of direction. Ideal for high-speed scalping or very large lookbacks. Dual Mode: The full "Risk Management" suite. It forces the script to find both a Bullish and a Bearish path to show you the two most likely outcomes.
• Projection Window: This determines the size of the "Ghost." If set to 50, the script analyzes a 50-bar trend and projects a 50-bar future.
• Lookback Period: This is how far into the past the engine scans. While the script is optimized for performance, keeping this within a reasonable range (500–2000) ensures fast UI response.
• Slope Tolerance: This is your "Sensitivity" setting. Lower Values (0.001 - 0.004): Very strict. The script will only show matches that have a nearly identical angle of attack. Higher Values (>0.01): More lenient. Use this in highly volatile markets (like Crypto) where trends are aggressive and vary in steepness.
Examples
In this image, we can see BTCUSD on the daily. The confidence favours a bullish move, both Bearish and Bullish possible paths are plotted. Let’s see what happens.
The outcome was an initial bullish move though with a bit of a neutral tilt, as it ended relatively flat.
Now let us look at ES1!:
In this case, the indicator is showing 2 possible paths (Dual Mode), with a bullish tilt. Let’s see what happened next:
The move was indeed bullish, and volatility remained intact through the move.
Important Considerations
The indicators true strength stems from its ability to act as a risk management tool and compare the degree of “fit” of each respective path (i.e. bullish vs. bearish). If you are looking to take a bearish position on a ticker, but you see that the R2 skew slightly favours a move to the upside, you may want to hold off on pulling the short trigger until you have a skew that fits your bias.
While the paths are likely not going to be a perfect, identical match, the power comes from understanding the confidence skew of the bullish vs bearish path. This is your saving grace for managing risk in your positions.
Though the matches are not likely to be perfect, they are scaled to the ticker’s ATR and thus can be used to help you gauge potential entries, exits and positioning areas.
For example, if we look at SPY on the hourly timeframe:
We see we have a bearish skew. The bearish path has sizeable upside. We can use this forecasted range to identify potential entry/resistance areas like so:
Now let’s see how it plays out:
You can see that the key forecast areas provided actual levels for support and resistance!
Concluding Remarks
In a market driven by algorithmic repetition, the Analogue Matcher gives you the power to see the "scripts" the market has run before. By quantifying the similarity of price action through regression, traders can move away from "gut feelings" and toward data-driven forecasts.
Indicator

Indicator

RSI Prediction by Range Segmentation [LuxAlgo]The RSI Prediction by Range Segmentation indicator projects a future path for the Relative Strength Index (RSI) by analyzing and averaging historical patterns that originated from similar RSI levels. This tool provides a probabilistic forecast based on how the RSI has historically behaved after reaching specific value segments.
🔶 USAGE
The indicator segments the RSI range (0-100) into multiple horizontal zones. When the current RSI value falls into a specific zone, the script identifies all historical instances where the RSI was in that same zone and calculates the average path it took over a subsequent period.
Users can observe the dynamic polyline forecast extending from the current RSI value to anticipate potential overbought or oversold conditions before they occur. The RSI line itself changes color based on its position relative to the 50 level, providing an immediate visual cue for bullish or bearish momentum.
🔹 Range Segmentation
The RSI scale is divided into "Range Segments" (e.g., 10 segments of 10 points each). This allows the indicator to categorize market momentum into specific states. By increasing the number of segments, you make the historical matching more precise but may have fewer historical samples to average. A step-line is plotted to visualize the base of the current segment being analyzed.
🔹 The Forecast
The forecast is generated only on the most recent bar using a polyline. It looks at the current RSI segment, retrieves the "Historical Limit" of stored patterns for that specific segment, and plots the mathematical average of those paths. The forecast color is dynamic: it appears bullish if the predicted endpoint is higher than the current RSI, and bearish if it is lower.
🔹 Overbought/Oversold Fills
To highlight extreme momentum, the script includes conditional vertical gradient fills. When the RSI rises above the user-defined Overbought Level, a green gradient fills the space between the RSI and the level. Conversely, when it drops below the Oversold Level, a red gradient appears.
🔶 DETAILS
The script utilizes User-Defined Types (UDTs) to store sequences of RSI values (Segments) within specific RangeData objects. This architecture allows the script to efficiently manage memory while maintaining a deep history of price momentum patterns.
Every time a new bar is processed, the script "looks back" at a pattern of a specific length and stores it in the bucket corresponding to where that pattern started (the anchor point). This creates a library of outcomes categorized by their starting momentum state, which is then accessed on the real-time bar to generate the forecast.
🔶 SETTINGS
🔹 General Settings
Historical Limit : Determines the maximum number of historical segments stored for each RSI range. A higher limit provides a more "smoothed" average by including more historical data.
Forecast Length : The number of bars into the future the prediction will extend. This also defines the length of the historical patterns being recorded.
Range Segments : The number of divisions for the 0-100 RSI scale. For example, setting this to 10 creates segments of 10 units (0-10, 10-20, etc.).
RSI Length : The lookback period for the standard RSI calculation.
🔹 Levels
Overbought Level : The threshold above which the RSI is considered overbought and the bullish gradient fill is triggered.
Oversold Level : The threshold below which the RSI is considered oversold and the bearish gradient fill is triggered.
🔹 Colors
Bullish Color : The color used for the RSI line (when > 50), the overbought gradient, and bullish forecasts.
Bearish Color : The color used for the RSI line (when < 50), the oversold gradient, and bearish forecasts.
Level Color : The color of the Overbought, Oversold, and Center (50) horizontal levels.
Indicator

Indicator

Adaptive Spectral Forecast [WillyAlgoTrader]📡 Adaptive Spectral Forecast is an overlay indicator that applies Goertzel spectral analysis to decompose price into its dominant cyclical components, reconstructs them as a harmonic sum, and then extrapolates the resulting waveform forward in time to generate a visual forecast with confidence bands. Signals fire when the forecast direction changes with sufficient signal-to-noise ratio and trend alignment — projecting where price is likely to oscillate next based on the cycles detected in recent history.
This is a fundamentally different approach from trend-following or momentum-based indicators. Instead of asking "where is price going based on its direction and speed?", spectral analysis asks "what recurring cycles exist in this price data, and where do they project to next?" The Goertzel algorithm is a targeted frequency detector — it scans a range of cycle periods, measures the power (amplitude²) at each frequency, identifies the dominant peaks, computes their exact phase and amplitude via DFT projection, and recombines them into a multi-harmonic forecast that decays toward the adaptive trend as it extends into the future.
🧩 WHY THESE COMPONENTS WORK TOGETHER
Raw price is a mix of trend, cycles, and noise. Attempting to forecast raw price directly fails because trend and cycles require different extrapolation methods: trend continues linearly, cycles repeat sinusoidally, and noise should not be extrapolated at all.
This indicator solves the problem through decomposition and reassembly:
EMA trend extraction → Hann-windowed detrending → Goertzel spectral scan → SNR peak detection → DFT coefficient extraction → Harmonic recombination with decay → Trend re-addition → Confidence bands
Each stage addresses a specific challenge:
— Trend extraction separates the slow directional component so it can be extrapolated linearly (via slope), not sinusoidally
— Hann windowing reduces spectral leakage — without it, the finite data window creates false frequency peaks that contaminate the analysis
— Goertzel scanning efficiently measures power at each candidate frequency without computing a full FFT — enabling targeted, adaptive-resolution frequency detection
— SNR filtering ensures only cycles with meaningful signal strength are included — weak noise-level frequencies are discarded
— DFT coefficient extraction computes the exact amplitude and phase of each selected cycle on un-windowed data (the Hann window is only for spectral scanning, not for coefficient calculation — this preserves correct amplitudes)
— Harmonic decay causes the cyclic component to gradually fade toward the trend as the forecast extends forward — reflecting the reality that detected cycles have limited persistence
— Confidence bands widen with √(bars ahead) × ATR, showing that forecast uncertainty grows with distance
Removing any component breaks the pipeline: without detrending, the Goertzel scan detects the trend as a low-frequency "cycle". Without Hann windowing, spectral leakage creates phantom peaks. Without SNR filtering, the forecast includes noise-level harmonics that produce random oscillations. Without decay, the harmonic projection repeats forever at full amplitude (unrealistic). The full pipeline is required.
🔍 WHAT MAKES IT ORIGINAL
1️⃣ Goertzel spectral analysis for cycle detection.
The Goertzel algorithm is a single-frequency DFT that computes the power at one specific period using a recursive formula:
s0 = data + 2×cos(2π/period) × s1 − s2
After iterating through all N data points, the power is: (s1 − s2×cos(ω))² + (s2×sin(ω))², normalized by N² for cross-period comparability.
The indicator scans every integer period from Min Cycle Period (default 8) up to N/2, with an adaptive step size: every period for fast cycles (≤30 bars), step of 2 for longer cycles (reducing computation without losing resolution where it matters most). For each period, the Goertzel power is computed, producing a power spectrum — a map of which cycle lengths carry the most energy in the current price data.
This is fundamentally more targeted than an FFT. An FFT computes power at all frequencies simultaneously but at fixed resolution (determined by window size). The Goertzel approach allows scanning exactly the frequency range of interest with customizable resolution.
2️⃣ SNR-based peak detection with fallback.
From the power spectrum, the indicator identifies local peaks (frequencies where power is higher than both neighbors) and computes the Signal-to-Noise Ratio for each: SNR = peak_power / mean_power_across_all_frequencies. Only peaks with SNR ≥ Min Cycle SNR (default 2.0) are accepted as genuine cycles — the rest are considered noise-level fluctuations.
If no peaks pass the SNR filter (possible in highly random or trend-dominated price action), the algorithm falls back to the single strongest frequency. In this case, the dashboard displays "Weak*" strength and buy/sell signals are suppressed — the forecast is shown for visual reference only, but the indicator acknowledges that no reliable cyclical structure was found.
The top N peaks (sorted by power, N = Harmonics Count, default 5) are selected as the dominant cycles.
3️⃣ DFT coefficient extraction on un-windowed data.
For each selected cycle period, the indicator computes exact sine and cosine coefficients using standard DFT projection:
a = (2/N) × Σ data × sin(2π × i / period)
b = (2/N) × Σ data × cos(2π × i / period)
Critically, this computation uses the raw detrended data (without Hann windowing). The Hann window was only applied for the spectral scan (to identify which frequencies are dominant). Using windowed data for coefficient extraction would distort the amplitude of the harmonics. This two-pass approach — windowed scan for detection, raw data for coefficients — is a key design choice that preserves forecast accuracy.
4️⃣ Harmonic extrapolation with configurable decay.
The forecast is constructed by evaluating the harmonic sum at each future bar:
forecast = trend_projection + Σ (a_k × sin(ω_k × t) + b_k × cos(ω_k × t)) × decay^(t − t_base)
Where trend_projection = trend_last + trend_slope × bars_ahead (linear extrapolation of the EMA trend). The decay factor (default 0.97) causes harmonic amplitude to reduce by 3% per bar, so the cyclic component gradually fades and the forecast converges toward the trend line.
At decay = 1.0, harmonics repeat at full amplitude forever (pure cycle projection). At decay = 0.95, they fade rapidly (forecast becomes trend-only within ~20 bars). Default 0.97 provides meaningful oscillation for the first 20–30 bars before fading. The forecast line is colored by segment: green segments where the forecast is rising, red where falling. Reversal dots mark predicted peaks and troughs.
5️⃣ ATR-based confidence bands with √t scaling.
Uncertainty in the forecast grows with distance. The confidence band width is calculated as:
band_width = ATR(14) × confidence_multiplier × √(bars_ahead)
The √t scaling follows the mathematical principle that forecast variance grows linearly with time horizon (standard deviation grows with square root). The ATR provides the natural volatility scale of the instrument. At bar +1, the band is approximately ATR × multiplier. At bar +25, it's 5× wider. This gives a realistic visual envelope of where price might actually be, not just the central harmonic forecast.
6️⃣ 3-bar consensus forecast direction.
Instead of using a simple "is the next bar higher or lower?" check (which is noisy), the forecast direction is determined by majority vote over 3 bars:
The indicator evaluates the forecast at t+0, t+1, t+2, t+3 and counts upward moves: upVotes = (y1>y0 ? 1:0) + (y2>y1 ? 1:0) + (y3>y2 ? 1:0). If ≥2 of 3 transitions are upward → forecast direction is bullish. If ≤1 → bearish. This consensus approach prevents a single-bar oscillation from flipping the forecast direction.
7️⃣ Trend alignment filter for signal quality.
When enabled (default on), buy signals require the EMA trend slope to be positive, and sell signals require negative slope. This prevents the indicator from generating counter-trend signals when a cycle oscillation temporarily points against the broader trend — which is the most common source of false signals in cycle-based systems.
If the trend filter blocks a direction change, the forecast visualization still updates (you can see the cycle projection) but no signal label is emitted. Additionally, signals are suppressed when the SNR is below the minimum threshold or when the spectral scan fell back to a single non-significant frequency.
8️⃣ Adaptive trend extraction with linear extrapolation.
The trend component is extracted using an EMA with configurable smoothing (default 30 bars), applied forward using the buildTrendArray function. The trend's slope is computed via weighted linear regression over the last 5 points of the trend array — providing a stable slope estimate that isn't dominated by a single bar.
The trend is extrapolated linearly into the forecast: trend_forecast = trend_last + slope × i. This linear projection is appropriate for the short-term forecast horizon (15–55 bars) where trend curvature is typically negligible.
9️⃣ Historical fit visualization.
The reconstructed harmonic sum + trend is plotted over historical data as a polyline, showing how well the detected cycles explain the actual price movement. This serves as an immediate visual validation: if the fit tracks price well, the detected cycles are meaningful. If the fit diverges significantly, the current market regime may not have strong cyclical structure (reflected in low SNR scores in the dashboard).
The fit line is colored by trend direction (green for bullish slope, red for bearish) and decimated for performance (every 1–3 bars depending on lookback length).
🔟 Four presets with coordinated parameter scaling.
— Conservative : lookback ≥ 150, harmonics ≤ 3, forecast ≥ 40 bars — stable, long-term cycles, less overfitting risk
— Default : user settings unchanged
— Aggressive : lookback ≤ 80, harmonics +1, forecast ≤ 25 — faster adaptation, more cycles included
— Scalping : lookback ≤ 50, harmonics +2, forecast ≤ 15 — shortest window, most harmonics, very short projection
Each preset adjusts lookback (spectral window), harmonics count (complexity), and forecast length (projection horizon) as a coordinated unit. Longer lookback needs fewer harmonics (the cycles are more stable). Shorter lookback needs more harmonics (to capture the faster fluctuations within the compressed window).
⚙️ HOW IT WORKS — CALCULATION FLOW
Step 1 — Data collection: The last N bars (Analysis Lookback, default 144) of the selected price source are collected into an array, oldest first.
Step 2 — Trend extraction: An EMA with the Trend Smoothing period (default 30) is applied across the array using a forward-pass recursive formula: trend = α × price + (1−α) × trend . This produces a smooth trend array.
Step 3 — Detrending + Hann window: Each bar's trend value is subtracted from its price. The residual is multiplied by a Hann window: w = 0.5 × (1 − cos(2π×i/(N−1))). This isolates the cyclical component while minimizing spectral leakage at the data boundaries.
Step 4 — Goertzel spectral scan: For each candidate period from minPeriod to N/2 (adaptive step: 1 for periods ≤30, 2 for longer), the Goertzel algorithm computes power. The result is a power spectrum across all scanned frequencies.
Step 5 — Peak detection: Local maxima in the power spectrum are identified (power > both neighbors). Each peak's SNR is computed against the mean power. Peaks with SNR ≥ threshold are accepted. If none pass, the strongest single frequency is used as fallback (with "Weak*" marking).
Step 6 — Coefficient extraction: For the top N peaks (by power), sine and cosine coefficients are computed via DFT projection on raw (un-windowed) detrended data. This gives exact amplitude and phase for each cycle.
Step 7 — Forecast generation: The trend is extrapolated linearly using its 5-bar regression slope. Each harmonic is evaluated at future time steps with decay applied. The sum of trend + decayed harmonics produces the central forecast line. Confidence bands = ATR × multiplier × √(bars_ahead).
Step 8 — Direction and signals: 3-bar consensus determines forecast direction. Trend filter and SNR check gate signal emission. Buy/sell labels appear on bar-close confirmation.
📖 HOW TO USE
🎯 Quick start:
1. Add the indicator — the historical fit and forecast line appear on the last bar
2. The colored dotted line extending right is the forecast (green = rising, red = falling)
3. Colored dots (●) on the forecast mark predicted peaks and troughs
4. Dotted lines above and below = confidence bands (forecast uncertainty zone)
5. ▲/▼ labels = buy/sell signals when the forecast direction changes
👁️ Reading the chart:
— 🟢 Green solid line on history = harmonic fit (uptrend slope)
— 🔴 Red solid line on history = harmonic fit (downtrend slope)
— 🟢🔴 Dotted line extending right = forecast (colored by direction: green rising, red falling)
— 🔵 Upper/lower dotted lines = confidence bands (uncertainty grows with distance)
— 🟢 ● dots = predicted troughs (potential support)
— 🔴 ● dots = predicted peaks (potential resistance)
— 🟢 ▲ below bar = buy signal (forecast changed to bullish)
— 🔴 ▼ above bar = sell signal (forecast changed to bearish)
📊 Dashboard fields:
— Trend: current EMA trend direction (Bullish / Bearish / Neutral)
— Forecast: predicted direction (▲ Up / ▼ Down / — Flat)
— Signal: current state (BUY / SELL / Bullish Bias / Bearish Bias / Wait)
— Strength: cycle quality based on average SNR (Strong > 5.0 / Medium > 2.5 / Weak / Weak* = fallback)
— Dom. Cycle: dominant cycle period in bars (e.g., "34 bars")
— Cycles: how many cycles passed SNR filter vs. requested (e.g., "3 / 5")
— Timeframe, preset, version
🔧 Tuning guide:
— Forecast too noisy: reduce Harmonics Count (3), increase Min SNR (3.0+), increase Trend Smoothing
— Forecast too smooth: increase Harmonics Count (5–7), decrease Min SNR (1.5), decrease Trend Smoothing
— Cycles don't match price: increase Analysis Lookback (200+) for more stable cycle detection, or decrease for faster adaptation
— Forecast fades too fast: increase Decay Rate toward 0.99–1.0
— Forecast unrealistic long-term: decrease Decay Rate toward 0.95, reduce Forecast Bars
— Too many false signals: enable Trend Alignment Filter, increase Min SNR
— Scalping 1–5M: use Scalping preset (lookback ≤50, 7 harmonics, 15-bar forecast)
— Swing 4H–1D: use Conservative preset (lookback ≥150, 3 harmonics, 40-bar forecast)
⚙️ KEY SETTINGS REFERENCE
⚙️ Main:
— Analysis Lookback (default 144): spectral analysis window — the last N bars analyzed
— Harmonics Count (default 5): how many dominant cycles to include in the forecast
— Min Cycle Period (default 8): shortest cycle to scan for (bars)
— Preset (default Default): Conservative / Default / Aggressive / Scalping
— Trend Alignment Filter (default On): require trend-forecast agreement for signals
🔮 Forecast:
— Forecast Bars (default 55): projection length into the future
— Confidence Band Width (default 1.5× ATR): band multiplier
— Trend Smoothing (default 30): EMA period for trend component
— Harmonic Decay Rate (default 0.97): amplitude reduction per bar (1.0 = no decay)
— Min Cycle SNR (default 2.0): signal-to-noise threshold for cycle acceptance
🎨 Visual:
— Historical fit, trend line, reversal dots, confidence bands (all toggleable)
— Auto / Dark / Light theme
🔔 Alerts
— 🟢 BUY — ticker, price, timeframe, time
— 🔴 SELL — same fields
Both support plain text and JSON webhook format. Signals are bar-close confirmed, direction-locked, trend-filtered, and SNR-gated.
⚠️ IMPORTANT NOTES
— 📐 This is spectral analysis, not trend following. The indicator detects and projects recurring cycles. In markets with strong cyclical structure (commodities, forex majors, crypto with regular oscillations), it performs well. In news-driven or momentum-dominated markets with no cyclical structure, the SNR will be low and the forecast unreliable — the dashboard reflects this via the Strength reading.
— 🚫 No repainting of signals. The spectral analysis runs on barstate.islast (updating the forecast in real time on the current forming bar). Signals only fire on the next barstate.isconfirmed bar, after the forecast direction has been set. This means the forecast line itself updates in real time (by design — it's a live projection), but buy/sell signals are confirmed and do not change retroactively.
— 📊 The forecast is a projection, not a prediction. It shows where price would go if the detected cycles continue with their current amplitude and phase. Real markets introduce new information that disrupts cycles. The confidence bands reflect this growing uncertainty. Treat the forecast as a probabilistic zone, not a target.
— 🔄 "Weak*" strength means no cycles passed the SNR filter and the indicator fell back to the single strongest frequency. In this state, signals are suppressed. The forecast is still shown for visual reference but should not be trusted for trading decisions.
— ⚖️ The Hann window is applied only for spectral scanning , not for coefficient extraction. This is deliberate: the window prevents spectral leakage during frequency detection, but the un-windowed data preserves correct harmonic amplitudes for the forecast.
— 📏 The forecast extends a fixed number of bars into the future. Accuracy degrades with distance — the first 10–15 bars are typically the most reliable. The confidence bands quantify this degradation visually.
— 🛠️ This is a spectral analysis and forecasting tool , not an automated trading bot. It detects cycles, projects them forward, and generates directional signals — trade decisions remain yours.
— 🌐 Works on all markets and timeframes. Cycle periods adapt automatically to whatever timeframe you apply it on. Indicator

SMI Fractal Iron HMASMI FRACTAL IRON HMA
Professional Multi-Engine Trading Overlay
Version 7.0 • February 2026 • Pine Script™ v6 • Overlay Indicator
By NPR21
FIVE INTEGRATED ENGINES
Fractal Pivots │ SMI Filter │ HMA Forecast │ Risk Management │ Short Trend Dashboard
DESCRIPTION
SMI Fractal Iron HMA integrates five complementary analytical engines into a single overlay indicator, designed so that each component addresses a different dimension of trade analysis — structure, momentum, trend context, risk parameters, and real-time directional scoring — and the outputs of each engine reinforce or qualify the signals of the others.
▸ Fractal Pivot Detection
Identifies structural swing highs and lows using fractal pivot logic with a key innovation: the left-side structural lookback and the right-side confirmation delay are split into two independent inputs. This allows traders to maintain high structural selectivity (catching only significant swing points) while independently controlling how many bars of confirmation are required before a signal prints. Setting Right Bars to zero enables zero-delay mode where the label appears on the forming bar itself.
▸ Stochastic Momentum Index (SMI) Filter
A double-smoothed EMA of the price-to-midpoint relationship, scaled to a configurable range. When enabled as a filter, long signals only print when SMI is rising and short signals only print when SMI is falling. Signals opposing the current momentum direction are silently suppressed, reducing noise without adding visual clutter.
▸ HMA Trend Duration Forecast
Tracks the Hull Moving Average slope to determine trend state. Each completed trend’s duration is stored in a rolling sample. The historical average projects the probable length of the current trend. On the chart: a white arrow line shows the forecast window, a Trend ↑ Up Real or Trend ↓ Down Real label updates in real time with the current bar count, and a Prob: label shows the forecasted duration. HMA BUY and HMA SELL labels print at each trend change with optional price display.
▸ Risk Management System
Activates on each confirmed pivot signal and draws five horizontal levels: Entry, Stop Loss (configurable in points or percentage), and three Take Profit tiers calculated as Reward:Risk multiples. Features include:
•TP hit tracking — each level changes to dashed with a check-mark label when price reaches it.
•Trailing stop — moves to breakeven at a configurable threshold, then trails by a fixed offset.
•TP2+ reversal exit — after TP2 is hit, closes the trade if price reverses by a specified distance before TP3.
•P&L dashboard — real-time display of direction, entry, current P&L in the selected currency, R:R ratio, dollar risk/reward at each TP, bars in trade, HMA trend direction, and probable trend length.
•Auto-reset — clears all trade objects when a trade completes (SL, TP3, or TP2+ reversal), readying for the next signal.
▸ Short Trend Dashboard
A 5-component real-time scoring engine that votes on the current bar’s directional bias:
•Momentum (25 pts) — price change vs. ATR-scaled threshold.
•Candle Structure (25 pts) — body-to-range ratio and wick rejection analysis.
•Micro Trend (25 pts) — fast/slow EMA crossover with ATR-normalized gap scoring.
•Acceleration (25 pts) — bar-to-bar momentum change detecting speed gain or loss.
•Volume B/S (10 pts) — estimated buy vs. sell pressure from close position within bar range.
The composite score (0–100) produces a letter grade (A+, A, B, C) and a directional label (BULLISH, BEARISH, LEAN BULL/BEAR, or NEUTRAL). The TEMP Heat Gauge (0–100) blends seven sub-indicators (ROC, RSI, Stochastic, Volume Pressure, EMA Position, Candle, Acceleration) into a single temperature reading (HOT / WARM / NEUTRAL / COOL / COLD). Scalper Mode activates ultra-fast EMA and momentum presets optimized for 1–5 minute charts with Instant Flip detection for single-bar reversals.
▸ Why These Five Engines Together
Each engine answers a different question. The pivot engine identifies where structure turns. The SMI filter confirms whether momentum supports the signal. The HMA forecast provides how long the trend is likely to last. The risk management system defines how much is at stake. The Short Trend Dashboard gives a right now directional confidence score. Together they create a workflow: detect the turn, confirm direction, understand trend context, manage the trade, and monitor conviction — all from a single indicator.
HOW TO USE
▸ Getting Started
1.Add the indicator to your chart. Default settings (Left 5 / Right 1) provide a balanced starting point with strong structural selectivity and minimal delay.
2.BUY labels appear below swing lows. SELL labels appear above swing highs. In Confirmed + Preview mode, semi-transparent labels flicker during bar formation and lock solid at bar close.
3.Use the HMA colored line and trend forecast labels to understand the broader trend context. HMA BUY and HMA SELL labels mark each trend change.
4.Enable Risk Management to see SL/TP lines and the P&L dashboard on each confirmed signal.
5.Monitor the Short Trend Dashboard for real-time confirmation. CONSENSUS +4/5 or +5/5 indicates strong alignment across all components.
▸ Tuning the Pivot Detection
•Left 5 / Right 5: Maximum accuracy. Pivot must be highest/lowest of 11 bars. 5-bar confirmation delay. Best for identifying only major swing points.
•Left 5 / Right 1: Strong selectivity, minimal delay. Preview label flickers on the confirmation bar. Good balance for scalping and active trading.
•Left 5 / Right 0: Zero-delay mode. Label appears on the pivot bar during formation. Fastest possible signal. Useful for scalping when combined with the SMI filter.
•Left 8–10 / Right 0: Zero delay with larger left lookback to compensate for missing right-side confirmation.
▸ Configuring Risk Management
•Enable the Risk Management Overlay toggle. Set Stop Loss in points (e.g., MNQ: 3–5 pts) or as a percentage of entry price.
•Set TP1, TP2, TP3 as Reward:Risk multiples (defaults: 2:1, 3:1, 4:1). Adjust to your trading style.
•Set Point Value for your instrument: MNQ = 2, MES = 5, MYM = 0.5, MGC = 10, MCL = 10.
•The P&L dashboard updates every bar showing dollar P&L, R:R ratio, and TP hit status.
•Enable trailing stop for trades that run: set breakeven threshold, trail start, and trail offset distances.
▸ Reading the Short Trend Dashboard
•Direction + Score: BULLISH/BEARISH/LEAN with a score of 0–100. Grade A+ or A = high conviction.
•TEMP Heat Gauge: Above 70 = HOT (overbought). Below 30 = COLD (oversold). 45–55 = NEUTRAL.
•CONSENSUS: Total vote out of 5 components. +4/5 or +5/5 = strong directional alignment.
•Scalper Mode: Ultra-fast presets for 1–5 min charts. Instant Flip marks single-bar reversals with ** notation.
▸ Label Display Options
•Stack: Label sits directly on the high/low with offset ticks. Text stacks vertically with optional timestamp.
•Pointer: Label offset to the side with a pointer coming off the corner pointing at the exact high/low of the bar.
•Timestamp: Five formats: HH:mm, HH:mm:ss, h:mm a, MMM dd HH:mm, MMM dd. Uses the chart’s time zone.
▸ Suggested Starting Settings
•Scalping (1–5 min): Left 5, Right 1, HMA Length 9–14, Scalper Mode ON, SL 3–5 pts
•Day Trading (5–15 min): Left 5, Right 2–3, HMA Length 14–20, Scalper Mode OFF, SL 5–10 pts
•Swing Trading (1H–4H): Left 5, Right 5, HMA Length 20–50, Scalper Mode OFF, SL 10–25 pts
•Zero-Lag Mode: Left 7–10, Right 0, SMI Filter ON, HMA Length 14, Scalper Mode ON
DISCLAIMER
This indicator is a technical analysis tool designed to assist with identifying potential swing reversal points, trend direction, and trade risk parameters. It is not a standalone trading system and does not constitute financial advice. No indicator can predict future price movement. Past performance of any signal methodology does not guarantee future results. Always use proper risk management and consider multiple sources of analysis. The author assumes no responsibility for trading losses. Use at your own risk. Indicator

KNN Trend Forecaster [UAlgo]KNN Trend Forecaster is a chart overlay forecasting tool that uses a K Nearest Neighbors style similarity engine to estimate the next directional bias and project a probabilistic price path. It converts the current market state into a compact feature vector, compares it to a rolling memory of historical states, and computes an expected forward change as a weighted consensus of the most similar past observations.
The indicator is built for decision support rather than signal chasing. It provides a projected path, a volatility aware tunnel around that path, and optional ghost structures that visualize how the forecast could evolve bar by bar. A minimal UI panel summarizes the current projection and sentiment, while the plot color adapts to bullish, bearish, or neutral expectation.
This script is most effective when treated as a contextual layer. It can help align trade selection with the dominant statistical bias implied by recent conditions, while still leaving execution to your own confirmation rules.
🔹 Features
1) KNN Similarity Forecasting Engine
The core model is a K Nearest Neighbors approach. For each bar, the script builds a three dimensional feature set from momentum, volatility, and relative strength. It then measures the distance between the current feature set and each stored historical feature set. The closest K neighbors are selected, and their realized forward returns are combined into a single prediction.
Model Sensitivity controls K. Lower values behave more reactive and can change bias quickly. Higher values behave more stable and tend to smooth the projection.
2) Feature Design Focused On Trading Context
The feature set is intentionally practical:
RSI captures directional pressure and mean reversion tendencies
ROC captures normalized momentum
ATR captures normalized volatility regime
Normalization ensures that ROC and ATR values are scaled into comparable ranges so the distance metric remains balanced and does not get dominated by raw magnitude differences.
3) Rolling Memory With Outcome Labels
The script builds a training memory in real time. On each confirmed bar, it stores the features from ten bars ago and labels them with the percentage change over the next ten bars. This creates a consistent supervised learning target:
Feature snapshot at time t
Outcome equals return from time t to t plus ten bars
Memory is capped to a fixed size to keep performance stable.
4) Weighted Neighbor Voting For Robust Predictions
Rather than using a simple average of neighbor outcomes, the script assigns higher weight to closer neighbors. Weight is the inverse of distance, which prioritizes highly similar historical states and reduces the influence of weaker matches.
This helps stabilize results when the market is transitioning and the feature landscape becomes noisier.
5) Forecast Path With Adaptive Step Decay
Once a prediction is produced, the script generates a forward path for a user selected Forecast Horizon. The step applied to the path decays with the square root of the forecast index, which makes the projection more confident near the present and more conservative further out.
The result is a smooth curve rather than an aggressive linear extrapolation.
6) Multi Layer Volatility Tunnel
A tunnel can be drawn around the projected path. Its width scales with ATR and expands over the forecast horizon using a square root growth profile. Tunnel Volatility controls how wide the envelope becomes.
This provides a practical view of expected dispersion around the forecast rather than a single deterministic line.
7) Ghost Structures For Bar To Bar Projection Framing
Optional ghost boxes are printed for each forward step. Each box visualizes the projected candle body from the current projected close to the next projected close. The ghost color adapts to whether the step is rising or falling, making momentum and path rhythm easier to read.
8) Neon Glow Path And Target Tag
When enabled, the path is rendered twice using polylines:
A wider glow stroke for visual depth
A thinner main stroke for precision
A target label is placed at the end of the horizon, showing the model predicted change in percent.
9) Projection Basis And Dashboard
A 21 period EMA is plotted as a reference basis, colored by the current prediction bias. A compact table displays the projection value and a sentiment label that classifies the forecast into bullish, bearish, or neutral ranges.
🔹 Calculations
1) Feature Construction
The model uses three features built from common market analytics.
RSI uses standard 14 period RSI:
float f_rsi = ta.rsi(close, 14)
ROC and ATR are normalized into a 0 to 100 style range using rolling min max scaling:
normalize(float src, int len) =>
float mn = ta.lowest(src, len)
float mx = ta.highest(src, len)
(src - mn) / (math.max(mx - mn, 0.000001)) * 100
float f_roc = normalize(ta.roc(close, 10), 100)
float f_atr = normalize(ta.atr(14), 100)
The current feature vector:
FeatureSet current_f = FeatureSet.new(f_rsi, f_roc, f_atr)
2) Training Memory And Outcome Labeling
On each confirmed bar, the script stores the feature snapshot from ten bars earlier and labels it with the forward ten bar return.
Outcome in percent:
float outcome = (close - close ) / close * 100
Training point created from the past feature snapshot:
memory.push(TrainingPoint.new(FeatureSet.new(f_rsi , f_roc , f_atr ), outcome))
Memory is limited for stability:
if memory.size() > 1000
memory.shift()
3) Distance Metric Between Feature Vectors
Similarity is computed using Euclidean distance in three dimensions:
method distance(FeatureSet v1, FeatureSet v2) =>
math.sqrt(math.pow(v1.f1 - v2.f1, 2) + math.pow(v1.f2 - v2.f2, 2) + math.pow(v1.f3 - v2.f3, 2))
Smaller distance means greater similarity.
4) Neighbor Selection And Weighted Prediction
The script computes distances from the current state to each stored training point and gathers the outcomes. It then selects the closest K entries by repeatedly taking the minimum distance.
Each neighbor is weighted by inverse distance:
float w = 1.0 / math.max(td.get(idx), 0.0001)
twc += tc.get(idx) * w
ws += w
pred := twc / ws
This produces pred, a percentage change estimate inferred from the most similar historical contexts.
5) Signal Color Classification
The display color adapts to the sign and magnitude of the prediction. Small values map to a neutral tone, stronger positive values map to bullish tone, and stronger negative values map to bearish tone.
color sig_col = pred > 0.005 ? THEME_UP : pred < -0.005 ? THEME_DN : THEME_MID
6) Forecast Path Generation
Path construction begins from the current close. A base step is derived from the prediction and then decayed across the horizon.
Base step:
float step = (pred / 10.0) * 0.01
Forward projection with square root decay:
float next_c = cur_c * (1 + step * (1.0 / math.sqrt(i)))
This produces a smooth forecast curve where early steps carry more weight than later steps.
7) Volatility Tunnel Width Model
The tunnel uses ATR as the volatility anchor and expands across the horizon:
Outer width:
float v_outer = (atr * expansion * 0.3 * math.sqrt(i))
Inner width is half of the outer width:
float v_inner = v_outer * 0.5
Upper and lower bounds are then computed around the projected close:
float h_out = next_c + v_outer
float l_out = next_c - v_outer
float h_in = next_c + v_inner
float l_in = next_c - v_inner
8) Ghost Structures
For each forecast step, a box is drawn between the current projected close and the next projected close. Its color reflects whether the path step is rising or falling.
color g_col = next_c >= cur_c ? color.new(THEME_UP, 40) : color.new(THEME_DN, 40)
box b = box.new(x1, math.max(cur_c, next_c), x2, math.min(cur_c, next_c), border_color=color.new(g_col, 20), bgcolor=g_col, border_width=1)
9) Path Rendering And Target Tag
When glow is enabled, the script renders a thick glow polyline and a thinner main polyline over the same projected points. A label is placed at the final horizon index showing the predicted percent change.
path_glow := polyline.new(pts, curved=true, line_color=color.new(sig_col, 70), line_width=8)
path_main := polyline.new(pts, curved=true, line_color=sig_col, line_width=2)
target_tag := label.new(bar_index + forecast_len, cur_c, "TARGET: " + str.tostring(pred, "#.##") + "%")
10) UI Summary And Basis Plot
A 21 period EMA is plotted and colored by the current bias. A table panel prints the projection value and a sentiment classification:
Bullish when pred is above 0.01
Bearish when pred is below minus 0.01
Neutral otherwise
This gives an at a glance readout that matches the on chart color theme. Indicator

Variable Sine Wave Fit [LuxAlgo]The Variable Sine Wave Fit indicator uses Ordinary Least Squares (OLS) to fit a dynamic, damped, or expanding sine wave with an underlying linear trend to recent price action. This tool aims to identify cyclical patterns and project their potential continuation into the future, providing a mathematical framework for understanding market regimes and turning points. This indicator is subject to repainting and is displayed retrospectively.
🔶 USAGE
The indicator fits a complex trigonometric model to the price data within a user-defined window. The resulting fit is displayed as a solid line over historical bars and transitions into a dashed extrapolation for the forecasted period.
To use the indicator effectively, traders should observe the relationship between the price and the RMSE bands. If the price remains within these bands, the current cyclical model is considered to be tracking the price action effectively. If the price breaks significantly outside, the cycle may be shifting or breaking down.
🔹 Extrema Markers
Small dot markers are placed at the local maxima and minima of the dashed forecast line. These serve as visual guides for the timing of potential future turning points based on the current mathematical fit.
🔹 Market Regime Dashboard
The dashboard provides a real-time summary of the fitted model's characteristics:
State: Classified based on the amplitude behavior (Damped, Expanding, or Constant) and the linear component (Trending or Ranging).
Best Period: The cycle length (in bars) that currently provides the best fit to the data.
RMSE: The Root Mean Square Error, representing the average deviation of price from the fit.
🔶 DETAILS
The script solves for the best parameters of the following equation:
y = e^(λ * t) * (a * sin(ω * t) + b * cos(ω * t)) + m * t + c
Where:
e^(λ * t): The damping/expansion factor. If λ > 0, the cycle is expanding; if λ < 0, it is damping.
a, b: Coefficients determining the phase and initial amplitude of the sine wave.
m * t + c: A linear regression component that accounts for the underlying price trend.
The "Best Period" is determined through a grid search that minimizes the Sum of Squared Errors (SSE), ensuring the frequency (ω) matches the most dominant local cycle within the search range.
🔶 SETTINGS
🔹 Settings
Window Size (N): The number of historical bars used to calculate the fit.
Auto Period: When enabled, the script searches for the best period within the specified min/max range.
Fixed Period (P): The period used if Auto Period is disabled.
Min/Max Search Period: Defines the boundaries for the automatic cycle search.
Forecast Length: The number of bars to project the fit into the future.
RMSE Band Multiplier: Determines the width of the bands surrounding the fit based on the fit error.
🔹 Visuals
Bullish/Bearish Color: Colors used for the fit line and extrema markers based on the final slope.
Band Color: The color of the RMSE-based envelope.
🔹 Dashboard
Dashboard: Toggles the visibility of the data table.
Position: Moves the dashboard to different corners of the chart.
Size: Adjusts the text and table scale.
Indicator

Hidden Markov Model: Regime Probability [AlgoPoint]Hidden Markov Model: Regime Probability
Traditional technical indicators are deterministic and lagging; they tell you what the price has already done. The Hidden Markov Model (HMM) Regime Probability system takes a completely different, quantitative approach. It uses probabilistic mathematics to estimate the unobservable "Hidden State" (Market Regime) the price is currently operating in.
Inspired by the mathematical models used by institutional quantitative hedge funds, this script doesn't just look at price direction—it calculates the probability of the market being in a specific regime based on real-time observations of Momentum and Volatility.
1. The Three Hidden States (Regimes)
The market is modeled as existing in one of three hidden states:
↗ Bullish Regime: High positive momentum with low or stable volatility. (Steady, grinding uptrends).
↘ Bearish Regime: High negative momentum with high volatility. (Aggressive sell-offs and panic).
↕ Chop / Chaos Regime: Zero/low momentum with high volatility. (Whipsaw, ranging, and unpredictable noise).
2. How It Works (The Quant Engine)
Since Pine Script does not natively support complex matrix optimization, this script builds a robust Pseudo-HMM using a predefined Transition Matrix and Bayesian Updates.
Observables (Emissions): The script calculates the Z-Scores of Smoothed Momentum (Rate of Change) and Volatility (ATR).
Emission Probabilities (Gaussian PDF): It feeds these Z-Scores into a Gaussian Probability Density Function to see how well the current market matches the expected profile of a Bull, Bear, or Chop regime.
Bayesian Update: Using a predefined Markov Transition Matrix (the statistical inertia of a trend), it updates the prior probabilities to give you a real-time percentage (0-100%) for each regime.
3. Advanced Visual Features & UI
We built a custom UI/UX engine to make digesting complex probabilities instantaneous:
Exponential Color Smoothing (Bar Colors): As the probability of a regime increases, the bar colors smoothly transition. We implemented an exponential color blending algorithm to prevent abrupt, distracting color changes and eliminate "muddy" colors during transitions.
Pro Quant Dashboard: A built-in HUD (Heads-Up Display) provides a quick summary. It features a dominant state readout, an overall "Confidence Score", and ASCII-style mini progress bars (████░░░) for rapid visual processing of probabilities without needing to read the numbers.
Stacked Area Oscillator: The bottom panel displays a 0-100 stacked area chart, showing the exact distribution of probabilities across Bull (Green), Chop (Purple), and Bear (Red) states.
4. How to Use This Tool
This is not a standalone Buy/Sell signal indicator. It is a Strategy Filter and a Risk Manager.
When Bull/Bear Probability is Dominant (>50%): The market is trending. Turn ON your trend-following indicators (like Moving Averages or Breakout systems) and ignore overbought/oversold signals.
When Chop Probability is Dominant (>50%): The market is noisy. Turn OFF your trend-following systems. Either switch to Mean Reversion strategies (like RSI or Bollinger Bands) or stay in cash until a clear regime emerges.
Watch the Confidence Score: If the Dashboard shows "LOW" confidence, it means the probabilities are split (e.g., 34% Bull, 33% Chop, 33% Bear). Wait for the model to gain confidence before committing capital.
5. Alerts
The script includes non-repainting alerts that trigger only when the dominant regime changes:
HMM Regime: BULLISH 🚀 * HMM Regime: BEARISH 🩸 * HMM Regime: CHOP ⚖️
6. Settings
Lookback Period: The window used to calculate the Z-scores for momentum and volatility.
Transition Matrix: Allows advanced users to tweak the statistical likelihood of the market staying in its current state versus transitioning to a new one.
Color Transition Speed: Adjusts the smoothness of the bar coloring. A lower value creates a buttery-smooth fade between regimes, while a value of 1.0 makes it instant. Indicator

Singular Spectrum Decomposition [LuxAlgo]The Singular Spectrum Decomposition indicator is a powerful analytical tool that decomposes price action into distinct, interpretable components—Trend, Periodic cycles, and Noise—using the Singular Spectrum Analysis (SSA) methodology.
It provides traders with a clear view of underlying market structures and offers a jump-free, extrapolated trend forecast based on Linear Recurrence Relations (LRR).
Warning: This decomposition is displayed retrospectively ; historical values observed are subject to repainting .
🔶 USAGE
The indicator operates by analyzing a specific window of recent price data to extract its most significant internal dynamics. It splits the "messy" raw price into four visual layers:
Trend (Overlay): The primary low-frequency component, plotted directly on the price chart. This represents the core directional bias of the asset.
Long Term Periodic (P1): The most dominant cyclical component, typically representing major swings or seasonalities.
Short Term Periodic (P2): The second most dominant cycle, capturing faster oscillations and intermediate pullbacks.
Noise: The high-frequency residual data that lacks a consistent pattern, useful for identifying market volatility or "washout" periods.
🔹 Cycle Exhaustion (P1/P2 Extremes)
Traders can monitor the separate indicator pane to identify when cyclical components (P1 and P2) reach historical extremes. When the Long Term Periodic (P1) line begins to curve back toward the zero line after a prolonged extension, it often signals "cycle exhaustion," suggesting that the current swing is losing momentum and a reversal or consolidation may be imminent.
🔹 Trend-Forecast Confluence & Mean Reversion
The dashed Trend extrapolation acts as a projected path for the market's core bias. If the current market price is significantly far from the solid Trend line while the forecast indicates a flattening or reversal, traders can look for mean-reversion opportunities. A price returning to a rising Trend forecast confirms the trend's strength, while a price crossing through a flat Trend forecast suggests a structural shift.
🔹 Timing Entries with Dashboard Metrics
The "Average Period" displayed on the dashboard provides a mathematical blueprint for entry timing. For example, if the Short Term (P2) Average Period is 20 bars, a trader might look for long entries approximately 10 bars after a peak (the expected trough). By aligning these peak-to-trough measurements with the Trend's direction, users can improve the precision of their entries within a trending market.
🔹 Filtering Fakeouts with the Noise Component
The Noise component helps distinguish between high-conviction moves and market "static." A sharp price breakout accompanied by a relatively flat Noise component suggests a sustainable, structurally supported move. Conversely, if a breakout occurs while the Noise component is spiking aggressively, it may indicate a "washout" or a liquidity-driven fakeout that lacks a fundamental trend shift.
🔶 DETAILS
The script implements a full SSA pipeline: Embedding (creating a trajectory matrix), Singular Value Decomposition (via eigendecomposition of the covariance matrix), and Diagonal Averaging (reconstructed the time series).
🔹 Jump-Free Extrapolation
A common issue with LRR-based forecasts is a vertical "jump" at the connection point between historical data and the forecast. This tool solves this by calculating the relative deltas of the LRR projection and anchoring them to the final value of the smoothed SSA reconstruction. This ensures a seamless visual transition while maintaining the mathematical integrity of the projected trajectory.
🔹 Dashboard Metrics
The indicator includes a real-time dashboard that calculates the "Average Period" of the periodic components using zero-crossing detection. This allows traders to quantify the frequency of cycles (e.g., a 40-bar cycle vs. a 15-bar cycle) without manual measurement.
🔶 SETTINGS
Window Length (L): The embedding window. Larger values capture longer cycles and provide a smoother trend, but may increase lag in the decomposition.
Buffer Length (N): The number of recent bars used for the static decomposition.
Forecast Length: The number of bars to extrapolate the Trend component into the future.
Show Trend on Price: Toggles the visibility of the reconstructed trend line on the main chart.
Show Periodic/Noise: Toggles the visibility of the individual sub-components in the indicator pane.
Show Extrapolation: Enables or disables the dashed forecast line for the trend.
Dashboard Settings: Controls the visibility, position, and size of the metrics table.
Indicator

Adaptive Harmonic Forecast [LuxAlgo]The Adaptive Harmonic Forecast indicator decomposes price action into multiple cyclical components and a linear trend to forecast future market movement.
By extracting the most dominant frequencies from recent price data, the tool projects a multi-harmonic model into the future to identify potential reversal points and trend continuations.
🔶 USAGE
The indicator provides a mathematical projection of price action based on the assumption that markets exhibit cyclical behavior. Users can utilize the forecast to anticipate upcoming shifts in momentum or to identify the underlying trend direction.
It is important to note that the forecast is dynamic and recalculates on the most recent bar; therefore, it is best used to confirm momentum shifts when price action aligns with the projected harmonic direction.
🔹 Historical Fit & Forecast
The script displays a solid line over the historical lookback period, representing how well the harmonic model fits the actual price data. Beyond the current bar, a dotted line extends the forecast. This forecast is color-coded: green represents projected upward movement, while red represents projected downward movement. The forecast should be viewed primarily as a timing tool rather than an exact price target, as it projects where the "rhythm" of the market is heading based on current harmonics.
🔹 Trend Line & Reversal Markers
A linear trend line is calculated alongside the sinusoids to show the overall bias (slope) of the lookback period. Additionally, the indicator can plot reversal markers (dots) at the specific points where the forecasted cycles reach a peak or trough. These markers highlight potential future turning points where the composite cycles converge to create a local maximum or minimum.
🔹 Detected Cycles Table
The "Detected Cycles" dashboard allows traders to identify if current price action is dominated by short-term "noise" cycles or larger "structural" cycles. By observing the period lengths (in bars), users can determine the frequency of market swings. If the detected periods are small relative to the lookback, the market is in a high-frequency state; if they are large, the market is exhibiting more stable, long-term cyclicality.
🔶 DETAILS
The script operates through a two-step mathematical process involving spectral analysis and matrix-based regression:
Periodogram Logic (Cycle Detection): The indicator first detrends the data within the lookback window using a linear fit. It then performs a spectral analysis by scanning a range of periods to calculate "spectral power" (the correlation between price and a specific frequency). It identifies "spectral peaks" where price variance is most concentrated, ensuring that only the most meaningful cycles are selected for modeling rather than random noise.
Multi-Harmonic OLS Regression: Once the dominant periods are identified, the script uses Ordinary Least Squares (OLS) regression to solve for the coefficients of a linear combination of basis functions. Specifically, it constructs a model consisting of multiple sine and cosine waves (representing the cycles) and a first-order polynomial (representing the trend). By solving the normal equation using matrix math, the script finds the optimal amplitudes and phases that minimize the squared error against historical price. This composite model is then solved for future time coordinates to create the extrapolation.
🔶 SETTINGS
🔹 Settings
Fit Lookback (N): Determines the number of historical bars used to analyze cycles and fit the model.
Extrapolation Bars: Sets how many bars into the future the forecast should extend.
Number of Sinusoids: The maximum number of individual cycles to include in the composite model (1-10).
🔹 Automatic Cycle Detection
Min Period: The shortest cycle length (in bars) the algorithm is allowed to detect.
🔹 Visuals
Show Reversal Dots: Toggles the markers at forecasted local highs and lows.
Dot Size: Adjusts the visual scale of the reversal markers.
Show Detected Periods: Toggles the data table showing the lengths of the dominant cycles.
🔹 Trend Line
Show Trend Line: Toggles the display of the underlying linear regression line.
Trend Line Color: Sets the color for the historical and projected trend line.
Indicator

Recursive Least Squares Forecast [LuxAlgo]The Recursive Least Squares Forecast indicator uses an adaptive linear regression algorithm to estimate price trends in real-time, projecting future movements via a "Ghost Line" and providing dynamic bands and mean reversion signals for identifying market extremes.
By continuously updating its internal model with every new bar, the script provides a highly responsive framework for both trend forecasting and volatility-adjusted trading.
🔶 USAGE
The indicator aims to identify trend direction and potential exhaustion points. The central RLS mean line represents the current equilibrium price based on the adaptive model, while the bands represent volatility-adjusted extremes.
Users can utilize the tool for both trend following and mean reversion strategies:
Trend Following: Observe the slope and direction of the RLS Mean and the "Ghost Line" projection to determine the prevailing market bias.
Mean Reversion: Use the dynamic bands to identify when price has deviated significantly from its adaptive equilibrium.
Responsiveness: Adjust the Forgetting Factor (λ) to control the model's memory. A lower value (e.g., 0.95) makes the model react quickly to new price pivots, while a higher value (e.g., 0.99) provides a smoother, more stable trend line.
🔹 Mean Reversion Signals
The indicator identifies mean reversion opportunities using a two-step process:
Overextension: A setup begins when the price crosses outside the Upper or Lower Band, indicating an overbought or oversold state.
Entry Signal: A "BUY" or "SELL" signal is triggered when the price crosses back inside the band, suggesting a return to the RLS mean.
Targets: The RLS mean line serves as the primary take-profit target for these mean reversion setups.
🔶 DETAILS
The model assumes a linear relationship where the intercept and slope are updated recursively. The RLS algorithm is an adaptive filter that effectively "learns" the trend at every bar. It uses a state-space approach where the transition matrix is updated using a gain vector, ensuring the most efficient estimate of the current trend trajectory.
Unlike standard Moving Averages, the Recursive Least Squares (RLS) algorithm minimizes the sum of squared prediction errors by giving more weight to recent data. This allows the mean line to pivot quickly when market conditions change without the lag associated with traditional smoothing techniques.
The "Ghost Line" extends from the last bar into the future, providing a linear projection of where the current trend is headed. Surrounding this projection are "Standard Deviation Forecast Bands," which indicate the expected range of price movement based on the current model state.
🔶 SETTINGS
Forgetting Factor (λ): Controls how quickly the model forgets old data. Values closer to 1.0 make the model stable, while lower values make it more adaptive to recent price changes.
Band Multiplier: Standard deviation multiplier for the forecast bands, controlling the width of the mean reversion zones.
Forecast Horizon: Number of bars to project the "Ghost Line" and uncertainty bands into the future.
Show Ghost Line & Bands: Toggles the visibility of the future projection polylines.
Show Mean Reversion Signals: Toggles the visibility of the BUY/SELL labels on the chart.
Indicator
