IQ Session Bayesian Particle Filter [TradingIQ]🔹 OVERVIEW
This indicator runs a genuine Sequential Monte Carlo particle filter; the Bayesian architecture used in robotics and signal tracking... on your chart! Session by session, it learns where trading volume concentrates and paints a forecast of the coming session's entire volume-by-price distribution before that session unfolds: every expected high-volume level at once, not a single line.
It is not a moving average wearing a costume. Each finished session is treated as evidence: hundreds of particles are weighed against what actually traded, resampled, and mutated. Predict → observe → update, honestly Bayesian, every session.
🔹 HOW IT WORKS
Two particle swarms run side by side:
• A shape swarm learns the form of the distribution; one lump or several, wide or tight, and where each volume node sits.
• A drift swarm learns how far from the open the session's center of gravity tends to land.
An empirical-Bayes trust term scales the drift forecast by how much it has actually earned: when its track record is poor, the forecast automatically hugs the open. The prediction you see is the shape swarm's density, re-anchored by the trusted fraction of the drift forecast, rendered through a kernel density estimate whose bandwidth follows Silverman's rule.
🔸 HOW TO READ IT
• Session heatmap — the predicted density painted from the session open to the profile. A two-tone gradient split at the open; the tones swap roles across it, so each side mirrors the other. Bold color = expected business, fade = expected quiet.
• Mirrored profile — the forecast on the left, split bullish/bearish at the session open; the realized session volume on the right in a single neutral color.
• Confidence honesty — the prediction's glow scales with the filter's live confidence. When it has been wrong lately, its side visibly goes quiet. The realized side never fades, because reality doesn't.
• Bias info box — seated between the halves: the share of predicted volume above vs below the open (🢁 / 🢃).
• Expected levels — dashed lines at the probability-weighted average predicted price of each half: the session's expected bull and bear magnets.
• HVN lines + POC — the predicted high-volume levels. The point of control always shows; the HVN Threshold input is your dial between a few safe targets and every level worth watching.
🔹 SELF-TUNING
Every statistical free parameter tunes itself from data: the KDE bandwidth (Silverman's rule for visual convenience), the observation noise, the swarms' search domain (tracks the observed session spread), the mutation rate (genetic adaptation), the scout rate (scales with recent error), and the center trust (regression shrinkage). The inputs you are given are visual preferences plus a compute preset. There is nothing statistical to fiddle with, on purpose.
🔸 INPUTS
• Session Engine — Session Timeframe (the session boundary; must exceed the chart timeframe), Prediction Quality (particles per swarm, Fast 100 → Max 4000), Sessions to Keep.
• Volume Profile — toggles for the profile, bias box and expected levels; width, offset, info-box width, transparency.
• Session Heatmap — toggle, faint/bold density transparencies, Tone A / Tone B.
• High Volume Nodes — toggle, HVN Threshold %, reach, color.
• Colors — Bullish, Bearish, Realized.
🔹 VALIDATION
The filter was tested on real intraday data; 10 large-cap symbols, three session horizons, every prediction one-step-ahead and out-of-sample, against uniform, yesterday's-profile, Gaussian-fit, rolling-average and EWMA baselines, with the test harness itself audited too.
• Against naive prediction (uniform prior, yesterday's profile) it wins every metric tested at every horizon.
• Against the strongest profile-averaging methods it trades wins: they edge the single-lump fit metrics; the filter captures materially more of the session's actual traded volume with its predicted levels, and is the only method that reliably names multiple simultaneous targets .
• On sessions with two or more real volume peaks; roughly 4 in 10 sessions, its targets covered 19–42% more realized volume than the best alternative.
🔸 LIMITATIONS AND HONEST NOTES
• The forecast for a session is set when that session opens and is not repainted ; the realized half updates live as the session trades.
• It estimates a distribution of volume , not a promise of direction. The bias %, expected levels and HVN set are probability-weighted readings of that distribution.
• The filter is stochastic by nature: two chart reloads can differ in fine detail, the way two runs of any Monte Carlo method do. The structure it finds is stable; the pixel-level noise is not.
• Requires volume data from your data feed. Not supported on non-standard chart types.
• The chart timeframe must be lower than the session timeframe.
Indicator

Indicator

Adaptive Lorentzian Classification [Quantum Algo]Quantum ML Engine — Adaptive Lorentzian Classification
█ OVERVIEW
Quantum ML Engine is a machine-learning classifier that predicts the direction of price over a configurable horizon using an Approximate Nearest Neighbors (ANN) search across historical feature vectors. Instead of relying on a single oscillator, it compares the current bar's "fingerprint" — a vector of up to six normalized features — against thousands of past bars, finds the most similar market conditions, and lets those historical outcomes vote on what is likely to happen next.
By default the engine measures similarity with Lorentzian distance, log(1 + |Δ|), rather than Euclidean distance. Market data is heavily distorted around major events (CPI prints, FOMC, black swans), and Lorentzian distance naturally compresses these outliers — analogous to how mass warps space-time — so a single extreme bar cannot dominate the neighbor selection.
This is an original, fully self-contained implementation written from scratch with zero library imports. The concept of applying Lorentzian distance to kNN classification on charts was pioneered in the open-source work of @jdehorty (Machine Learning: Lorentzian Classification), building on earlier kNN studies by @capissimo. Full credit to both for the foundational research. This script does not reuse their code; it re-derives the approach independently and extends it in the ways described below.
█ WHAT IS DIFFERENT IN THIS IMPLEMENTATION
1 — Time-aligned training set
Each training sample pairs the feature vector recorded AT a given bar with the realized outcome over the following H bars. Features and labels are stored on the same time axis, so the classifier learns from correctly matched cause-and-effect pairs. There is no lookahead: a sample only enters the training set once its outcome is fully realized.
2 — ATR neutral-zone labeling
Historical moves smaller than a configurable multiple of ATR are labeled NEUTRAL instead of long/short. Sideways noise therefore never teaches the model a false directional lesson. Set the multiplier to 0 to disable.
3 — Six engineered features with importance weights
RSI, WaveTrend, CCI, ADX, MFI (volume flow) and Fisher Transform, each normalized to a common 0–1 scale. Every feature slot has its own weight input, so you can tell the engine which dimensions matter more for your market without removing features entirely.
4 — Four selectable distance metrics
Lorentzian (default), Manhattan, Euclidean, and a 50/50 Lorentzian-Manhattan Hybrid. Switching metrics changes the geometry of the neighborhood and is a powerful tuning lever per asset class.
5 — Distance-weighted voting with a confidence score
Closer neighbors vote louder (weight = 1 / (1 + distance)). The agreement between neighbors is expressed as a 0–100% confidence value printed on every bar, and a minimum-confidence gate suppresses low-conviction signals entirely.
6 — Adaptive K
The neighbor count automatically shrinks (up to 40%) when volatility ranks high over the last 100 bars, making the model more reactive in fast markets, and expands back in quiet regimes for stability. Can be disabled for a fixed K.
7 — Sliding training window
The engine always trains on the most recent N bars rather than the oldest bars in chart history, so the model reflects current market structure.
8 — Configurable prediction horizon
The training/holding horizon is an input (1–20 bars) instead of a hardcoded constant.
9 — Three exit modes
Fixed-horizon exits, dynamic kernel-slope exits, and an optional ATR trailing stop with the stop level plotted on the chart.
10 — Higher-timeframe confluence filter
Optionally require price to be above (longs) or below (shorts) an EMA on a higher timeframe of your choice.
█ HOW IT WORKS
1. On every bar, six features are computed and normalized.
2. The bar's feature vector is compared against samples inside the sliding training window, sampled with a minimum chronological spacing (default 4 bars) so neighbors come from distinct market episodes rather than one cluster.
3. A monotonic distance threshold maintains a stable pool of approximate nearest neighbors; when the pool exceeds K, the threshold resets to the 75th-percentile distance, allowing genuinely closer samples to rotate in over time.
4. Neighbors vote long / short / neutral, weighted by proximity. The weighted sum becomes the prediction; the degree of agreement becomes the confidence.
5. The raw signal is then passed through optional filters: volatility regime (recent ATR vs long-run ATR), trend regime (EMA separation normalized by ATR), ADX, EMA/SMA trend, higher-timeframe trend, and a Nadaraya-Watson kernel regression filter (rational quadratic estimate with a Gaussian crossover mode for smoother color transitions).
6. Entries print only when the ML signal, the confidence gate, and all enabled filters agree.
█ SETTINGS GUIDE
General — source, training window size, prediction horizon, neutral-zone width.
ML Engine — K, adaptive K toggle, chronological spacing, distance metric, distance weighting, minimum confidence.
Feature Engineering — feature type, parameters and weight for each of the six slots.
Filters — volatility, regime, ADX, EMA/SMA, higher-timeframe confluence.
Kernel — lookback, relative weighting, regression level, lag, smoothing mode.
Exits — fixed vs dynamic exits, ATR trailing stop and multiplier.
Display — bar colors, prediction labels (value + confidence), dashboard, color compression.
█ DASHBOARD
The on-chart panel shows the live signal, prediction confidence, current adaptive K, volatility and trend regime states, kernel bias, and a calibration win-rate. The calibration statistic simply checks whether price moved in the predicted direction over the horizon after each signal. It exists ONLY to give feedback while tuning features — it is not a backtest, includes no costs or risk management, and must not be treated as a performance claim.
█ USAGE NOTES
— Works on any symbol and timeframe; intraday (15m–4H) and daily charts are typical starting points. Crypto, FX, indices and equities all behave differently — retune the features and metric per market.
— Higher minimum confidence = fewer but more selective signals. Raising chronological spacing diversifies neighbors on lower timeframes.
— Signals are evaluated on bar close. Like any bar-close logic, the in-progress bar can change until it closes.
— Best used as a confluence layer inside a complete trading plan with your own risk management, not as a standalone buy/sell system.
█ CREDITS
Concept inspiration: @jdehorty (Machine Learning: Lorentzian Classification) and @capissimo (kNN implementations). This script is an independent, original implementation with the extensions listed above.
█ DISCLAIMER
This script is provided for educational and informational purposes only. It is not financial advice, and past behavior — including the on-chart calibration statistics — does not guarantee future results. Trading involves substantial risk of loss. Always do your own research and manage risk responsibly. Indicator

EMA Horizon█ OVERVIEW
The EMA Horizon indicator offers a modern, structural upgrade to the classic Exponential Moving Average. While standard EMAs are indispensable tools for trend identification, they inherently suffer from "live candle blindness" —flickering wildly on the current unclosed bar and causing traders to miss critical intraday touches or fall into false breakout traps.
EMA Horizon solves this by calculating an immediate forward-looking volatility corridor based on the asset's actual physical extremes (High/Low), anchored tightly to its closing history. It provides an unchanging, reliable boundary range for the current candle asset space, allowing traders to see exactly where the EMA would be pushed under extreme conditions.
---
█ THE PROBLEM WITH STANDARD EMAs
A standard EMA updates continuously based on the live ticking close . During highly volatile periods, the indicator line bends and flexes dramatically inside the current bar. This real-time distortion creates two major issues:
The Flicker Trap: Price can spike out of an EMA zone and snap back before the candle closes, leaving no historical trace of the breach and causing missed execution opportunities.
Lagging Boundaries: Standard bands (like envelopes or Keltner channels) look backward at historical averages. They fail to tell you how a single massive, aggressive live expansion bar will mathematically impact the underlying moving average trend line right now.
---
█ THE SOLUTION & MECHANICAL EDGE
EMA Horizon does not simply calculate an EMA of all Highs or all Lows (which smoothly degrades accuracy over time). Instead, it preserves the integrity of pure historical closing prices up to the immediate moment.
From that clean historical baseline, it executes a "one-off" look-ahead calculation: it processes the current candle's High and Low as if they were the immediate next closing prices .
The High Band shows the ultimate ceiling the EMA could reach on the next step.
The Low Band shows the absolute floor the EMA could drop to on the next step.
By utilizing the built-in Bands Offset parameter, you can shift this entire calculation forward across your timeline. When shifted, the boundaries sitting under your live candle are locked—derived entirely from the previous candle's completed structure. This eliminates real-time repainting and gives you an unshakeable roadmap for price interaction.
---
█ FEATURES
Pure History Anchoring: The base EMA line relies strictly on closing prices, ensuring your core trend logic remains untainted by extreme wicks.
Next-Bar Step Simulation: Dynamically maps out the mathematical limits of the moving average based on immediate price expansion boundaries.
Global Visual Alignment: The script features a unique global offset parameter that shifts both the baseline EMA and its projection bands uniformly. This completely avoids visual distortion and allows you to perfectly map historical structures without losing physical perspective.
---
█ HOW TO USE
Add to Chart: Search for "EMA Horizon" in your PulseWire indicator panel and apply it.
Configure your Length: Adjust the Length input to match your primary trend tracking asset class (e.g., 9 for short-term momentum, 21 or 50 for structural trends).
Set your Offset Look:
Set Bands Offset to 0 to observe the real-time maximum range expansion matching the current candle's high/low.
Set Bands Offset to 1 to push the indicator one bar to the right. This allows you to track how the current live asset price responds to the locked, unchangeable projection generated by the previous closed bar.
Identify True Deviations: Watch for instances where a candle aggressively drives through the green horizon cloud. If the asset price slices cleanly past the projected bands, it indicates an exhaustion phase or an institutional velocity breakout that goes beyond standard mathematical trend boundaries.
Indicator

Indicator

Predictive Monte Carlo Engine [LuxAlgo]The Predictive Monte Carlo Engine tool is a high-performance forecasting suite that uses probabilistic simulations to project future price paths based on historical volatility and market regimes.
🔶 USAGE
The indicator generates hundreds of potential price paths starting from the current bar (or an anchored point) to visualize the most likely price distribution over a user-defined projection length. It serves as a powerful volatility and support/resistance mapping tool, providing traders with an "expected value" range rather than a single fixed forecast.
Users can choose between three distinct mathematical methods to generate these paths, apply regime filters to isolate specific market conditions, and utilize a real-time dashboard that renders a visual "forecasted candle" for the next period.
🔹 Anchor Mode
By default, the simulation recalculates and updates on every new bar. By enabling Anchor Mode , users can lock the projection starting point. The engine will then only update every X bars (e.g., every 100 bars). This allows traders to observe how price actually reacted against historical Monte Carlo projections and Support/Resistance levels as the chart progresses.
🔶 DETAILS
The engine utilizes three primary simulation methodologies:
Geometric Brownian Motion (GBM): A stochastic process that assumes returns follow a log-normal distribution. This is the industry standard for modeling asset prices, ensuring prices remain positive and incorporating both drift and volatility.
Simple Random Walk (SRW): A basic additive model where price changes are sampled from a normal distribution based on historical mean and standard deviation.
Historical Shuffle (Bootstrapping): Instead of using random numbers, this method randomly samples actual historical price returns from the lookback period. This preserves the "fat tails" and unique characteristics of the specific asset being traded.
🔹 Regime Filtering
To improve accuracy, the engine can filter the historical data used for simulations. If "Trend" or "Momentum" regimes are selected, the indicator only calculates volatility and drift from past bars that match the current market environment (e.g., only using data from previous uptrends to forecast a current uptrend).
🔹 Fading S/R Zones
The tool identifies four key levels based on the simulation distribution: Max, R1 (90th percentile), S1 (10th percentile), and Min. These are rendered as horizontal zones that feature a unique horizontal gradient, fading as they extend into the future to represent the increasing uncertainty of the projection over time.
🔶 SETTINGS
🔹 Monte Carlo Settings
Simulation Method: Choose between GBM, SRW, or Historical Shuffle.
Regime Filter: Filter historical data by Trend (SMA) or Momentum (RSI).
Historical Lookback: The number of past bars used to calculate volatility.
Projection Length: How many bars into the future the paths extend.
Simulation Count: Number of individual paths to calculate (max 200).
Volatility Multiplier: Scales the historical volatility to simulate "stress-test" scenarios.
Anchor Mode: When enabled, locks the projection to update only at specific intervals.
🔹 Style
Path Percentiles: Adjust the thresholds for coloring the "Top" and "Bottom" path groups.
Colors: Customize the colors for bullish, bearish, and neutral paths, as well as the average projection line.
Show S/R Levels: Toggles the visibility of the horizontally fading Support and Resistance zones.
🔹 Dashboard
Show Dashboard: Toggles the statistical metrics table.
Next Candle Prediction: Enables the "Forecasted Candle" visual, which uses the 1-bar-ahead expected mean and distribution to render a text-based candlestick on the dashboard.
Indicator

RSI ReverseRSI Reverse is an analytical tool that reverse-engineers the Relative Strength Index (RSI) to project the estimated price levels required to reach your specific Overbought (OB) and Oversold (OS) targets.
Instead of acting solely as a lagging oscillator, this script calculates the mathematical distance price needs to travel over a user-defined number of future bars to push the RSI to your desired levels. (Note: These are mathematical projections based on current calculations, intended to be used as reference levels rather than guaranteed absolute predictions.)
Here is a breakdown of the indicator's configuration:
⚙️ Core Configuration
RSI Length: The lookback period for the base RSI calculation (Default: 14).
Overbought Target (OB): The upper RSI target level you want to project a price for (e.g., 70, 80).
Oversold Target (OS): The lower RSI target level you want to project a price for (e.g., 30, 20).
⏱️ The 5-Scenario Projections (Time Horizons)
Reaching an RSI of 70 on the very next bar requires a significantly different price movement compared to reaching it gradually over 30 bars. To account for this, the script provides 5 independent and fully customizable time scenarios:
Scenario 1 to 5 (Bars): You can define the exact number of bars for each of the 5 scenarios (Default: 1, 5, 14, 30, 60 bars).
The indicator simultaneously calculates and displays the required price to hit your OB/OS targets across all 5 time horizons. This allows you to observe how the target price dynamically shifts depending on how fast or slow the market moves.
🎨 Clean UI Dashboard
To keep your charts clean from visual clutter, all 10 projected target prices are displayed in a compact, non-intrusive table.
Table Position: Choose between Top-Right, Middle-Right, or Bottom-Right to ensure it never blocks your price action.
Text Size: Adjustable from Small to Large to fit your screen setup.
🔬 Under the Hood: Accuracy & Logic
Mathematical Precision: For Scenario 1 (Next Bar), the target is a 100% mathematically exact reverse-calculation. For multi-bar scenarios, the engine does not merely divide the required movement linearly. Instead, it utilizes an advanced ATR (Average True Range) step-distribution to simulate realistic market volatility, yielding a highly logical price estimate rather than a rigid straight line.
The Analytical Limitation: It is crucial to remember that a projected target is a mathematical destination assuming current momentum is maintained. Relying purely on technical analysis from a single timeframe has inherent limitations and can expose you to market noise.
💡 Practical Application & MTFA
Multi-Timeframe Analysis (MTFA): To overcome the limitations of single-timeframe chart analysis, it is highly recommended to combine this tool with MTFA. For example, if your higher-timeframe macro structure is in a bullish trend, look to execute limit buy orders exactly at the projected Oversold (OS) levels on your lower timeframe.
Dynamic Reference Levels: Use the projected prices as dynamic areas of interest to gauge where the market might become mathematically overextended.
Confluence: Combine these projected price matrixes with your existing chart analysis (e.g., support/resistance, order flow, or liquidity blocks) to identify high-probability zones for potential take-profits or limit entries. 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

Probabilistic Breakout Forecaster [LuxAlgo]The Probabilistic Breakout Forecaster indicator calculates the statistical probability of price breaking out of a defined range within a specific future time horizon. Using a log-normal random walk model, it provides traders with a quantitative estimate of whether current price action is likely to exceed local highs or lows.
🔶 USAGE
The indicator is displayed in a separate pane, showing two oscillating probability lines: a bullish breakout probability (positive values) and a bearish breakout probability (negative values).
When the bullish probability line approaches or exceeds the 50% threshold, it indicates a higher statistical likelihood that the price will break above the recent range high within the specified forecast horizon. Conversely, when the bearish probability line (plotted negatively) reaches the -50% threshold, it suggests a high probability of a breakdown below the recent range low.
The tool is particularly useful for:
Identifying potential breakout candidates before the price movement occurs.
Assessing the risk of "fakeouts" by comparing price proximity to the range boundary versus the statistical probability of a sustained move.
Determining if current volatility levels are sufficient to support a trend continuation.
🔹 Dashboard
The real-time dashboard provides a concise summary of the current forecast:
Bullish/Bearish Probabilities: The exact percentage chance of a breakout within the selected horizon.
Squeeze Intensity: A metric indicating how compressed the current volatility is relative to historical averages. High squeeze intensity (above 50%) often precedes significant expansion.
Horizon: The number of bars the current forecast is looking into the future.
🔶 DETAILS
The script utilizes a Log-Normal Random Walk model to forecast price distributions. This approach assumes that price returns follow a normal distribution, allowing the script to calculate the Z-score for the distance between the current price and the range boundaries.
🔹 Breakout Probability
The probability is derived using the Normal Cumulative Distribution Function (CDF). It calculates the area under the bell curve beyond the upper and lower range boundaries, adjusted for the square root of time (Forecast Horizon) and the standard deviation of log returns (Volatility Lookback).
🔹 Volatility Squeeze
The Squeeze Intensity metric compares the current Average True Range (ATR) to its 100-period simple moving average. When the ATR is significantly lower than its historical average, the intensity increases, signaling that the market is in a period of low-volatility consolidation that often leads to a "volatility explosion."
🔶 SETTINGS
🔹 Calculation Settings
Range Length: The lookback period used to determine the highest high and lowest low that act as the breakout boundaries.
Forecast Horizon (Bars): The number of bars into the future the model is predicting. A longer horizon generally increases the probability of hitting a boundary but decreases the precision of the timing.
Volatility Lookback: The period used to calculate the standard deviation of log returns, which informs the "width" of the expected price distribution.
🔹 Visualization
Bullish/Bearish Color: Customizes the colors for the respective probability plots and fills.
Fill Transparency: Adjusts the visibility of the area between the probability lines and the zero baseline.
🔹 Dashboard
Enable Dashboard: Toggles the visibility of the on-screen information table.
Position: Moves the dashboard to different corners of the chart.
Size: Adjusts the scale of the dashboard text and cells.
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

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

Monte Carlo Mean Reversion Heatmap [LuxAlgo]The Monte Carlo Mean Reversion Heatmap indicator is a statistical forecasting tool that uses Geometric Brownian Motion (GBM) to simulate 100+ potential future price paths and visualize the mathematical probability of price returning to a specific mean.
🔶 USAGE
The indicator provides a visual "probability cloud" projecting from the current price into the future. It helps traders identify statistical overextensions and the likelihood of a trend reversal toward a long-term average.
🔹 1. Assessing Mean Reversion Probability
The dashboard shows a Mean Reversion % . This tells you how many of the 100 simulated paths "touched" or "crossed" the EMA ribbon within the projection window (e.g., the next 30 bars).
High Probability (>70%): If the current price is far from the EMA but the probability of reversion is high, it suggests the market is "overextended." You might look for a counter-trend trade back toward the EMA.
Low Probability (<30%): This suggests that volatility is so high or the trend is so strong that price is statistically unlikely to return to the mean anytime soon. This often happens during "parabolic" runs.
🔹 2. Trading the "Probability Fan"
The dotted lines (5%, 50%, 95%) represent the statistical boundaries of where price is expected to stay.
Overbought/Oversold: If price moves outside the 5% or 95% lines, it is making a move that only happens in 1 out of 20 scenarios. This is a "statistical extreme." Traders often look for reversals or profit-taking when price enters these outer edges of the cone.
The Median Path (50%): This dashed line represents the "most likely" path based on current momentum (drift). It serves as a realistic target for trend-following trades.
🔹 Heatmap Density
The heatmap represents the density of the simulated paths. Darker areas indicate a higher concentration of paths, marking the price zones with the highest mathematical probability of being reached according to the model.
🔶 DETAILS
The engine behind this script is the Geometric Brownian Motion (GBM) model. GBM is a continuous-time stochastic process used in mathematical finance to model stock prices.
The model assumes that price changes follow a random walk with two components:
Drift: The deterministic trend of the mean (directional bias).
Volatility: The random "noise" or shocks based on historical log-returns.
By running 100 individual simulations simultaneously, the script generates a distribution of outcomes rather than a single linear prediction. This allows the user to see the "width" of uncertainty in the current market environment.
🔶 SETTINGS
🔹 Mean Calculation
Mean Length: The period of the EMA used as the target for mean reversion analysis.
Mean Color: The color of the target EMA line on the chart.
🔹 Monte Carlo Simulation
Simulations: The number of random paths to calculate (higher values increase accuracy but may impact performance).
Projection Length: How many bars into the future the simulation projects.
Volatility Lookback: The window used to calculate historical log-volatility for the simulation.
Include Drift: When enabled, the simulation accounts for the slope (trend) of the Mean EMA.
🔹 Visuals
Price Bins: Determines the vertical resolution of the heatmap.
Heatmap Color: The base color used for the probability density cloud.
Show Percentile Lines: Toggles the visibility of the 5%, 50%, and 95% projection lines.
🔹 Dashboard
Show Dashboard: Toggles the statistical information table.
Position/Size: Controls the location and scale of the dashboard on the chart.
Indicator

Indicator Configuration Forecasting [LuxAlgo]The Indicator Configuration Forecasting tool identifies historical market regimes that share a similar technical configuration to the current market and projects future price action based on those historical outcomes. By encoding multiple technical indicators into a state vector and employing a K-Nearest Neighbors (KNN) search, the script provides a probabilistic forecast including a median path and confidence intervals.
🔶 USAGE
The indicator works by "memorizing" the state of various user-selected technical indicators at every bar. When the current bar's configuration matches or closely resembles a previous historical state, the script records how the price moved in the subsequent N bars from that point in time.
🔹 Forecast Interpretation
Median Forecast (Dashed Gray): Represents the 50th percentile (median) of all matched historical outcomes. This is the central tendency of the forecast.
Upper Bound (Dashed Green): Represents the 75th percentile of historical outcomes, suggesting a bullish boundary for the projected move.
Lower Bound (Dashed Red): Represents the 25th percentile of historical outcomes, suggesting a bearish boundary for the projected move.
Match Labels: Small labels appearing on the historical price action indicate exactly where the most similar configurations were found in the past.
🔹 Configuration Strategy
Users can toggle various indicators to define what constitutes a "similar" market state. For example, if only "SMA Cross" and "Supertrend" are enabled, the script will look for historical periods where the trend relationship and SMA positioning were identical to the current bar, regardless of RSI or MACD values.
🔶 DETAILS
The script utilizes a state-encoding methodology to calculate distances between the current market environment and the past. Each enabled indicator is converted into a discrete value (e.g., 1 for bullish, -1 for bearish, 0 for neutral). These values form a vector for the current bar.
The algorithm then scans through the "Historical Lookback" period to find the "Top K" neighbors—the points in history where the vector distance to the current state is minimized. To ensure variety in the forecast, the script includes logic to prevent overlapping matches, ensuring that the selected historical points are distinct events.
Once the matches are identified, the script calculates the percentage returns for the specified "Forecast Horizon (N)" and projects those returns onto the current price to generate the visual forecast.
🔶 SETTINGS
🔹 Parameters
Top K Neighbors: The number of similar historical configurations to include in the forecast calculation.
Forecast Horizon (N): How many bars into the future the forecast should extend.
Historical Lookback: The maximum number of historical bars the script will search through to find matches.
🔹 Indicator Configuration
RSI/SMA/Supertrend/MACD/ADX/etc.: Toggle switches to include or exclude specific technical conditions from the similarity search.
RSI: Looks for similar overbought (>70) or oversold (<30) states.
SMA Cross: Looks for similar Fast/Slow SMA relationships.
Supertrend: Matches the current direction of the Supertrend.
MACD: Matches the relationship between the MACD Line and Signal Line.
🔹 Visibility & Style
Show Individual Match Paths: When enabled, draws the actual historical price paths from the match points directly on the current chart for visual comparison.
Median/Upper/Lower Colors: Customizes the colors of the forecast lines and the shaded confidence intervals.
Dashboard: Toggles the information panel showing the number of matches found and forecast confidence.
Indicator

Pulse Mean AcceleratorPulse Mean Accelerator (PMA) | MisinkoMaster
Pulse Mean Accelerator (PMA) is a high-speed adaptive trend engine designed to dynamically accelerate or stabilize its behavior depending on how aggressively price moves relative to its underlying structure. Instead of acting like a traditional moving average that simply lags behind price, PMA attempts to anticipate momentum expansion by accelerating when price pulses strengthen and stabilizing when market movement slows.
The result is a responsive yet smooth trend-following tool that adapts to both trending and consolidating markets. PMA is particularly useful for traders who want earlier participation in expanding trends without sacrificing structural clarity.
By combining adaptive acceleration, volatility awareness, and layered smoothing, PMA balances speed and stability to help traders remain aligned with developing momentum.
Key Features
Adaptive acceleration that reacts when price movement intensifies
Automatically slows down during consolidation to reduce noise
Multiple moving average types supported for flexibility
Volatility-aware responsiveness adjustment
Optional confirmation logic to filter weak signals
Multiple smoothing modes for balancing speed vs stability
Dynamic candle coloring reflecting active trend state
Automatic Long and Short markers when direction changes
Works across fast intraday and slower swing environments
Designed to reduce lag while preserving structure
How It Works
Pulse Mean Accelerator begins with a moving average structure but enhances it by measuring how aggressively price moves relative to that baseline. When price starts moving faster than the average, acceleration increases, allowing the indicator to catch up quickly.
When price slows or becomes erratic, acceleration reduces, preventing excessive reaction to noise.
Volatility measurements are incorporated to scale this acceleration, ensuring that responsiveness adapts naturally to current market conditions. Strong moves result in quicker adaptation, while quiet markets lead to smoother, calmer behavior.
Additional smoothing layers can then be applied, allowing traders to choose between faster responsiveness or more stable structure depending on their trading style.
Optional confirmation logic ensures that signals are not triggered solely by temporary price spikes, helping filter weaker moves.
The outcome is a moving average framework that behaves more like a dynamic trend engine rather than a static lagging indicator.
Trend Detection Logic
Trend direction is determined by how price behaves relative to the accelerated mean structure.
Bullish phases occur when price maintains strength above the adaptive mean while momentum confirms upward pressure. Bearish phases occur when price weakens below the structure and downward momentum dominates.
Signals appear when participation shifts strongly enough to confirm directional change, helping traders detect transitions from consolidation to expansion phases.
Acceleration Behavior
A defining characteristic of PMA is its pulse acceleration mechanism.
• Strong price pulses increase responsiveness
• Weak or slow price movement reduces acceleration
• Volatility conditions influence adaptation speed
• Structure remains smooth when momentum is weak
This dynamic adjustment helps traders enter trends earlier while avoiding excessive reactions during sideways markets.
Smoothing Modes
PMA includes multiple smoothing options so users can tune responsiveness:
• Raw acceleration for fastest reaction
• Exponential stabilization for balanced behavior
• Additional smoothing layers for structural clarity
• Double smoothing for maximum noise reduction
This flexibility allows PMA to be tailored for scalping, intraday trading, or higher-timeframe trend following.
Visual Signals
The indicator provides several visual cues for ease of interpretation:
• Candle coloring reflects active trend direction
• Adaptive mean and accelerated mean are plotted together
• Long and Short markers appear when trend shifts occur
• Filled areas highlight separation between price and structure
These features help traders read market structure quickly without relying on numerical interpretation.
Inputs Overview
Users can customize behavior through adjustable components including:
• Price source selection used in calculations
• Moving average type controlling base structure
• Length settings affecting responsiveness
• Acceleration sensitivity determining reaction speed
• Volatility measurement type influencing adaptation
• Smoothing mode selection for stability control
• Optional confirmation filtering for signal validation
These controls allow the tool to be tuned for both aggressive and conservative trading approaches.
Usage Notes
Ideal for traders needing faster adaptation to momentum expansion
Helps detect early stages of trend acceleration
Useful for filtering sideways noise while remaining reactive to breakouts
Works well in volatile assets where traditional averages lag
Can be combined with support/resistance or volume tools for confirmation
Higher smoothing settings suit swing traders, lower smoothing benefits intraday traders
Confirmation mode reduces false signals in choppy markets
Parameter tuning improves performance across different assets
Best Use Scenarios
Pulse Mean Accelerator performs particularly well in:
• Momentum expansion phases
• Breakouts from consolidation ranges
• Trend continuation environments
• High-volatility market conditions
• Assets showing periodic acceleration bursts
• Markets transitioning from low to high volatility
It is especially effective where traditional moving averages react too slowly to developing moves.
Summary
Pulse Mean Accelerator transforms traditional moving average logic into an adaptive trend engine capable of accelerating when price momentum expands and stabilizing during calm conditions. By blending acceleration, volatility awareness, and flexible smoothing, it provides traders with a faster yet structured view of market direction.
PMA is best suited for traders seeking earlier trend participation while maintaining smooth, readable structure across both fast-moving and consolidating markets. Indicator

Indicator

Indicator

Pivot Points Standard w/ Future PivotsPivot Points Standard with Future Projections
This indicator displays traditional pivot point levels with an added feature to project future pivot levels based on the current period's price action.
Key Features:
Multiple Pivot Types: Choose from Traditional, Fibonacci, Woodie, Classic, DM, and Camarilla pivot calculations
Flexible Timeframes: Auto-detect or manually select Daily, Weekly, Monthly, Quarterly, Yearly, and multi-year periods
Future Pivot Projections: Visualize potential pivot levels for the next period based on current price movement
Custom Price Scenarios: Test "what-if" scenarios by entering a custom close price to see resulting pivot levels
Customizable Display: Adjust line styles, colors, opacity, and label positioning for both historical and future pivots
Historical Pivots: View up to 200 previous pivot periods for context
Future Pivot Options:
The unique future pivot feature calculates what the next period's support and resistance levels would be using the current period's High, Low, Open, and either the current price or a custom price you specify for the closing value. Future pivots are displayed with customizable line styles (solid, dashed, dotted) and opacity to distinguish them from historical levels.
Use Cases:
Plan entries and exits based on projected support/resistance
Scenario analysis with custom price targets
Identify key levels before the period closes
Multi-timeframe pivot analysis
Works on all timeframes and instruments. Indicator

Indicator

Machine Learning Moving Average [BackQuant]Machine Learning Moving Average
A powerful tool combining clustering, pseudo-machine learning, and adaptive prediction, enabling traders to understand and react to price behavior across multiple market regimes (Bullish, Neutral, Bearish). This script uses a dynamic clustering approach based on percentile thresholds and calculates an adaptive moving average, ideal for forecasting price movements with enhanced confidence levels.
What is Percentile Clustering?
Percentile clustering is a method that sorts and categorizes data into distinct groups based on its statistical distribution. In this script, the clustering process relies on the percentile values of a composite feature (based on technical indicators like RSI, CCI, ATR, etc.). By identifying key thresholds (lower and upper percentiles), the script assigns each data point (price movement) to a cluster (Bullish, Neutral, or Bearish), based on its proximity to these thresholds.
This approach mimics aspects of machine learning, where we “train” the model on past price behavior to predict future movements. The key difference is that this is not true machine learning; rather, it uses data-driven statistical techniques to "cluster" the market into patterns.
Why Percentile Clustering is Useful
Clustering price data into meaningful patterns (Bullish, Neutral, Bearish) helps traders visualize how price behavior can be grouped over time.
By leveraging past price behavior and technical indicators, percentile clustering adapts dynamically to evolving market conditions.
It helps you understand whether price behavior today aligns with past bullish or bearish trends, improving market context.
Clusters can be used to predict upcoming market conditions by identifying regimes with high confidence, improving entry/exit timing.
What This Script Does
Clustering Based on Percentiles : The script uses historical price data and various technical features to compute a "composite feature" for each bar. This feature is then sorted and clustered based on predefined percentile thresholds (e.g., 10th percentile for lower, 90th percentile for upper).
Cluster-Based Prediction : Once clustered, the script uses a weighted average, cluster momentum, or regime transition model to predict future price behavior over a specified number of bars.
Dynamic Moving Average : The script calculates a machine-learning-inspired moving average (MLMA) based on the current cluster, adjusting its behavior according to the cluster regime (Bullish, Neutral, Bearish).
Adaptive Confidence Levels : Confidence in the predicted return is calculated based on the distance between the current value and the other clusters. The further it is from the next closest cluster, the higher the confidence.
Visual Cluster Mapping : The script visually highlights different clusters on the chart with distinct colors for Bullish, Neutral, and Bearish regimes, and plots the MLMA line.
Prediction Output : It projects the predicted price based on the selected method and shows both predicted price and confidence percentage for each prediction horizon.
Trend Identification : Using the clustering output, the script colors the bars based on the current cluster to reflect whether the market is trending Bullish (green), Bearish (red), or is Neutral (gray).
How Traders Use It
Predicting Price Movements : The script provides traders with an idea of where prices might go based on past market behavior. Traders can use this forecast for short-term and long-term predictions, guiding their trades.
Clustering for Regime Analysis : Traders can identify whether the market is in a Bullish, Neutral, or Bearish regime, using that information to adjust trading strategies.
Adaptive Moving Average for Trend Following : The adaptive moving average can be used as a trend-following indicator, helping traders stay in the market when it’s aligned with the current trend (Bullish or Bearish).
Entry/Exit Strategy : By understanding the current cluster and its associated trend, traders can time entries and exits with higher precision, taking advantage of favorable conditions when the confidence in the predicted price is high.
Confidence for Risk Management : The confidence level associated with the predicted returns allows traders to manage risk better. Higher confidence levels indicate stronger market conditions, which can lead to higher position sizes.
Pseudo Machine Learning Aspect
While the script does not use conventional machine learning models (e.g., neural networks or decision trees), it mimics certain aspects of machine learning in its approach. By using clustering and the dynamic adjustment of a moving average, the model learns from historical data to adjust predictions for future price behavior. The "learning" comes from how the script uses past price data (and technical indicators) to create patterns (clusters) and predict future market movements based on those patterns.
Why This Is Important for Traders
Understanding market regimes helps to adjust trading strategies in a way that adapts to current market conditions.
Forecasting price behavior provides an additional edge, enabling traders to time entries and exits based on predicted price movements.
By leveraging the clustering technique, traders can separate noise from signal, improving the reliability of trading signals.
The combination of clustering and predictive modeling in one tool reduces the complexity for traders, allowing them to focus on actionable insights rather than manual analysis.
How to Interpret the Output
Bullish (Green) Zone : When the price behavior clusters into the Bullish zone, expect upward price movement. The MLMA line will help confirm if the trend remains upward.
Bearish (Red) Zone : When the price behavior clusters into the Bearish zone, expect downward price movement. The MLMA line will assist in tracking any downward trends.
Neutral (Gray) Zone : A neutral market condition signals indecision or range-bound behavior. The MLMA line can help track any potential breakouts or trend reversals.
Predicted Price : The projected price is shown on the chart, based on the cluster's predicted behavior. This provides a useful reference for where the price might move in the near future.
Prediction Confidence : The confidence percentage helps you gauge the reliability of the predicted price. A higher percentage indicates stronger market confidence in the forecasted move.
Tips for Use
Combining with Other Indicators : Use the output of this indicator in combination with your existing strategy (e.g., RSI, MACD, or moving averages) to enhance signal accuracy.
Position Sizing with Confidence : Increase position size when the prediction confidence is high, and decrease size when it’s low, based on the confidence interval.
Regime-Based Strategy : Consider developing a multi-strategy approach where you use this tool for Bullish or Bearish regimes and a separate strategy for Neutral markets.
Optimization : Adjust the lookback period and percentile settings to optimize the clustering algorithm based on your asset’s characteristics.
Conclusion
The Machine Learning Moving Average offers a novel approach to price prediction by leveraging percentile clustering and a dynamically adapting moving average. While not a traditional machine learning model, this tool mimics the adaptive behavior of machine learning by adjusting to evolving market conditions, helping traders predict price movements and identify trends with improved confidence and accuracy.
Indicator

Volume Surprise [LuxAlgo]The Volume Surprise tool displays the trading volume alongside the expected volume at that time, allowing users to spot unexpected trading activity on the chart easily.
The tool includes an extrapolation of the estimated volume for future periods, allowing forecasting future trading activity.
🔶 USAGE
We define Volume Surprise as a situation where the actual trading volume deviates significantly from its expected value at a given time.
Being able to determine if trading activity is higher or lower than expected allows us to precisely gauge the interest of market participants in specific trends.
A histogram constructed from the difference between the volume and expected volume is provided to easily highlight the difference between the two and may be used as a standalone.
The tool can also help quantify the impact of specific market events, such as news about an instrument. For example, an important announcement leading to volume below expectations might be a sign of market participants underestimating the impact of the announcement.
Like in the example above, it is possible to observe cases where the volume significantly differs from the expected one, which might be interpreted as an anomaly leading to a correction.
🔹 Detecting Rare Trading Activity
Expected volume is defined as the mean (or median if we want to limit the impact of outliers) of the volume grouped at a specific point in time. This value depends on grouping volume based on periods, which can be user-defined.
However, it is possible to adjust the indicator to overestimate/underestimate expected volume, allowing for highlighting excessively high or low volume at specific times.
In order to do this, select "Percentiles" as the summary method, and change the percentiles value to a value that is close to 100 (overestimate expected volume) or to 0 (underestimate expected volume).
In the example above, we are only interested in detecting volume that is excessively high, we use the 95th percentile to do so, effectively highlighting when volume is higher than 95% of the volumes recorded at that time.
🔶 DETAILS
🔹 Choosing the Right Periods
Our expected volume value depends on grouping volume based on periods, which can be user-defined.
For example, if only the hourly period is selected, volumes are grouped by their respective hours. As such, to get the expected volume for the hour 7 PM, we collect and group the historical volumes that occurred at 7 PM and average them to get our expected value at that time.
Users are not limited to selecting a single period, and can group volume using a combination of all the available periods.
Do note that when on lower timeframes, only having higher periods will lead to less precise expected values. Enabling periods that are too low might prevent grouping. Finally, enabling a lot of periods will, on the other hand, lead to a lot of groups, preventing the ability to get effective expected values.
In order to avoid changing periods by navigating across multiple timeframes, an "Auto Selection" setting is provided.
🔹 Group Length
The length setting allows controlling the maximum size of a volume group. Using higher lengths will provide an expected value on more historical data, further highlighting recurring patterns.
🔹 Recommended Assets
Obtaining the expected volume for a specific period (time of the day, day of the week, quarter, etc) is most effective when on assets showing higher signs of periodicity in their trading activity.
This is visible on stocks, futures, and forex pairs, which tend to have a defined, recognizable interval with usually higher trading activity.
Assets such as cryptocurrencies will usually not have a clearly defined periodic trading activity, which lowers the validity of forecasts produced by the tool, as well as any conclusions originating from the volume to expected volume comparisons.
🔶 SETTINGS
Length: Maximum number of records in a volume group for a specific period. Older values are discarded.
Smooth: Period of a SMA used to smooth volume. The smoothing affects the expected value.
🔹 Periods
Auto Selection: Automatically choose a practical combination of periods based on the chart timeframe.
Custom periods can be used if disabling "Auto Selection". Available periods include:
- Minutes
- Hours
- Days (can be: Day of Week, Day of Month, Day of Year)
- Months
- Quarters
🔹 Summary
Method: Method used to obtain the expected value. Options include Mean (default) or Percentile.
Percentile: Percentile number used if "Method" is set to "Percentile". A value of 50 will effectively use a median for the expected value.
🔹 Forecast
Forecast Window: Number of bars ahead for which the expected volume is predicted.
Style: Style settings of the forecast.
Indicator

Machine Learning Price Predictor: Ridge AR [Bitwardex]🔹Machine Learning Price Predictor: Ridge AR is a research-oriented indicator demonstrating the use of Regularized AutoRegression (Ridge AR) for short-term price forecasting.
The model combines autoregressive structure with Ridge regularization , providing stability under noisy or volatile market conditions.
The latest version introduces Bull and Bear signals , visually representing the current momentum phase and model direction directly on the chart.
Unlike traditional linear regression, Ridge AR minimizes overfitting, stabilizes coefficient dynamics, and enhances predictive consistency in correlated datasets.
The script plots:
Fit Line — in-sample fitted data;
Forecast Line — out-of-sample projection;
Trend Segments — color-coded bullish/bearish sections;
Bull/Bear Labels 🐂🐻 — dynamic visual signals showing directional bias.
Designed for researchers, students, and developers, this tool helps explore regularized time-series forecasting in Pine Script™.
🧩 Ridge AR Settings
Training Window — number of bars used for model training;
Forecast Horizon — forecast length (bars ahead);
AR Order — number of lags used as features;
Ridge Strength (λ) — regularization coefficient;
Damping Factor — exponential trend decay rate;
Trend Length — period for trend/volatility estimation;
Momentum Weight — strength of the recent move;
Mean Reversion — pullback intensity toward the mean.
🧮 Data Processing
Prefilter:
None — raw close price;
EMA — exponential smoothing;
SuperSmoother — Ehlers filter for noise reduction.
EMA Length, SuperSmoother Length — smoothing parameters.
🖥️ Display Settings
Update Mode:
Lock — static model;
Update Once Reached — rebuild after forecast horizon;
Continuous — update every bar.
Forecast Color — projection line color;
Bullish/Bearish Colors — colors for trend segments.
🐂🐻 Bull/Bear Signal System
The Bull/Bear Signal System adds directional visual cues to highlight local momentum shifts and model-based trend confirmation.
Bull (🐂) — appears when upward momentum is confirmed (momentum > 0) .
Displayed below the bar, colored with Bullish Color.
Bear (🐻) — appears when downward momentum is dominant (momentum < 0) .
Displayed above the bar, colored with Bearish Color.
Signals are generated during model recalculations or when the directional bias changes in Continuous mode.
These visual markers are analytical aids , not trading triggers.
🧠 Core Algorithmic Components
Regularized AutoRegression (Ridge AR):
Solves: (X′X+λI)−1X′y
to derive stable regression coefficients.
Matrix and Pseudoinverse Operations — implemented natively in Pine Script™.
Prefiltering (EMA / Ehlers SuperSmoother) — stabilizes noisy data.
Forecast Dynamics — integrates damping, momentum, and mean reversion.
Trend Visualization — color-coded bullish/bearish line segments.
Bull/Bear Signal Engine — visualizes real-time impulse direction.
📊 Applications
Academic and educational purposes;
Demonstration of Ridge Regression and AR models;
Analysis of bull/bear market phase transitions;
Visualization of time-series dependencies.
⚠️ Disclaimer
This script is provided for educational and research purposes only.
It does not provide trading or investment advice.
The author assumes no liability for financial losses resulting from its use.
Use responsibly and at your own risk. Indicator
