Machine Learning Random Forest Strategy | GainzAlgoMachine Learning Random Forest Strategy
We are excited to introduce the Machine Learning Based Random Forest Strategy indicator.
What Even Is a Random Forest?
Machine learning and AI get thrown around so loosely these days that they've almost lost all meaning. So let's start from the beginning.
A Random Forest is an ensemble learning method. Instead of relying on a single model, it combines many models that work together and vote on an outcome.
The individual models are called decision trees.
A decision tree is essentially a flowchart:
Is a feature above or below a threshold?
If yes, go left.
If no, go right.
Continue until a prediction is reached.
The problem with a single decision tree is that it is fragile. Train it on slightly different data and you may get a completely different tree. This creates high variance and causes overfitting.
This is the same weakness many rule-based indicators suffer from. They perform well in one market regime and break down when conditions change.
A Random Forest solves this problem through two core mechanisms:
Bootstrap Sampling — Each tree is trained on a random subset of historical data using sampling with replacement.
Random Feature Selection — Each tree can only evaluate a random subset of features at every split.
Without random feature selection, every tree would focus on the same dominant signal and become nearly identical.
By forcing trees to learn different relationships, prediction errors become less correlated. When many uncorrelated predictors are averaged together, noise tends to cancel out while useful signal remains.
This is the foundation of ensemble learning and the reason Random Forests remain one of the most widely used machine learning models.
The Pine Script Problem (And How We Solved It)
Pine Script was never designed to support traditional machine learning workflows.
There are no native machine learning primitives, no recursion, strict execution limits, and memory is largely restricted to arrays and matrices.
Building a traditional multi-level decision tree inside Pine Script is therefore extremely difficult.
The solution was to use decision stumps.
A decision stump is simply a decision tree with exactly one split.
By themselves, stumps are weak predictors. However, when many stumps are combined together using random feature selection, they form a legitimate shallow Random Forest.
The core ensemble behavior remains intact:
Each stump learns a slightly different relationship.
Prediction errors become decorrelated.
Averaging outputs creates a more stable forecast.
This is not a workaround.
A depth-1 Random Forest is still a Random Forest. Production libraries such as scikit-learn simply allow deeper trees, while the underlying ensemble mechanism remains the same.
Threshold Optimization Using Information Gain
A naive stump implementation would select completely random thresholds.
The problem is that random thresholds often produce meaningless 50/50 predictions.
To solve this, the model performs a threshold search.
Each stump evaluates multiple candidate thresholds and selects the one that maximizes Information Gain using Gini Impurity.
Gini Impurity Explained
Gini = 0 → Perfectly pure node.
Gini = 0.5 → Completely mixed node.
Lower values are better.
Information Gain measures how much impurity is reduced after a split.
The model evaluates multiple threshold candidates and selects the threshold that best separates bullish and bearish outcomes.
This is the same methodology used by scikit-learn's DecisionTreeClassifier using the Gini criterion.
The Two Models Running In Parallel
The indicator actually runs two separate Random Forest models simultaneously.
1. RF Classifier
The classifier answers a binary question:
"Is the next move likely bullish or bearish?"
It outputs a probability representing the likelihood that the next close will be higher than the current close.
This probability drives the signal generation process.
Bull probability exceeds threshold → ▲ Bullish Signal
Bear probability exceeds threshold → ▼ Bearish Signal
2. Regression Forest
The regression forest estimates the magnitude of the next move.
Instead of predicting direction, it predicts expected return.
This value appears as "Exp. Ret" inside the statistics table.
Having both models creates stronger confirmation.
High Bull Probability + Positive Expected Return = Strong Confirmation
High Bear Probability + Negative Expected Return = Strong Confirmation
Conflicting Signals = Reduced Conviction
Features: What The Model Actually Looks At
All features are normalized to a 0-100 scale.
Anchor Oscillator
Users can select:
RSI
MFI
Stochastic
Z-Score
This acts as the model's primary momentum or mean reversion feature.
Trend Correlation Feature
The model measures how strongly price has been correlated with time over a specified lookback period.
High values indicate strong directional trends.
Low values indicate choppy or sideways conditions.
Momentum / ATR Feature
Raw momentum is normalized using ATR.
This allows momentum strength to remain comparable across different volatility environments.
The Rolling Training Window
The model does not train on all historical data.
Instead, it continuously trains on the most recent N bars.
Every new bar:
Oldest sample is removed.
Newest sample is added.
Model retrains using current market conditions.
This is critical because markets are non-stationary.
Patterns that worked years ago may no longer be relevant today.
The rolling window helps the model adapt to changing market conditions.
Preventing Lookahead Bias
Many PulseWire machine learning indicators accidentally introduce lookahead bias.
This occurs when a model trains using information that would not have been available at the time of the prediction.
This implementation avoids that problem by using lagged feature values and future returns as targets.
The model only learns from information that genuinely existed before the outcome occurred.
Adaptive Threshold: The Self-Correcting Layer
One of the most unique aspects of this indicator is its adaptive threshold system.
The default probability threshold is 60%.
However, that threshold is not fixed.
After trades resolve:
Strong recent performance → Threshold remains relaxed.
Weak recent performance → Threshold automatically increases.
This forces the model to demand greater conviction during difficult market conditions.
When active, an orange ▲ marker appears next to the threshold value inside the statistics table.
This indicates that the model has tightened its own standards due to recent underperformance.
Signal Logic & Cooldown
Signals are not generated continuously.
Instead, the indicator uses edge-detection logic.
Signals only trigger when probability crosses above the required threshold.
Cross Above Threshold → New Signal
Remain Above Threshold → No New Signal
Additionally, a cooldown period prevents repetitive signals in the same direction.
The default cooldown is 10 bars.
This reduces signal clustering and improves overall readability.
Reading The Statistics Table
The table provides a complete snapshot of model activity.
Bull Prob — Current bullish probability estimate.
Signal — Current directional bias.
Exp. Ret — Expected return estimate.
Anchor — Selected oscillator value.
Eff. Thresh — Current effective threshold.
The backtest section includes:
Total Signals
Win Rate
Cumulative PnL
Average Trade PnL
Profit Factor
Wins & Losses
These values serve as a reality check based on current settings and chart conditions.
How To Use The Indicator
Do not blindly chase every arrow.
The strongest opportunities occur when multiple components align.
Look for:
High Bull Probability
Positive Expected Return
Clear Trend Structure
Supportive Market Conditions
When Bull Probability and Expected Return disagree, consider that a warning sign and reduce conviction.
Training Window & Tree Selection
The training window controls how much recent history the model learns from.
Short Window = Faster Adaptation
Long Window = Greater Stability
The number of trees controls prediction smoothness.
More Trees = Smoother Predictions
Fewer Trees = Faster Computation
Default settings provide a balanced starting point for most markets.
ADX Filtering
Optional ADX filtering can be enabled to isolate signals during stronger trending environments.
This tends to perform particularly well on higher timeframes.
What This Isn't
A few honest disclaimers:
This is not a deep neural network.
This is not a full-depth Random Forest implementation.
This is not a guaranteed profit system.
This is not immune to changing market conditions.
The model uses depth-1 decision stumps due to Pine Script limitations.
While this prevents complex nonlinear interactions, it preserves the core ensemble learning principles that make Random Forests effective.
The indicator intentionally uses only a handful of carefully selected features rather than overwhelming the model with unnecessary inputs.
Wrapping It Up
The Machine Learning Random Forest Strategy combines legitimate ensemble learning concepts with practical market analysis.
By leveraging Random Forest classification, regression forecasting, adaptive probability thresholds, and rolling retraining windows, the indicator provides a unique framework for evaluating both direction and expected magnitude of future price movement.
Use it as a decision-support tool, combine it with sound risk management, and let probability—not prediction—guide your trading process. Indicator

The Strat Sequence Continuation / Reclaim Engine v1.0The Strat Sequence Continuation / Reclaim Engine
The Strat Sequence Continuation / Reclaim Engine is a body-close-based study designed to help traders review how specific Strat candle sequences have historically resolved on the selected chart timeframe.
This indicator combines two separate views:
1. **Markov Regime Permission Panel**
A regime-style table that evaluates recent price behavior and displays market state, return, transition probabilities, permission, and trade behavior context. This table can be turned on/off by the user.
2. **Strat Sequence Continuation / Reclaim Table**
A focused table that measures whether selected Strat sequences continued by body close or failed/reclaimed the relevant reference level.
The sequence table evaluates setups such as:
* Failed 2U → x
* Failed 2D → x
* F2U → 2D → x
* F2D → 2U → x
* F2U → 2D → 2D → x
* F2D → 2U → 2U → x
* 2-2U → x
* 2-2D → x
* 2-1-2U → x
* 2-1-2D → x
* 3-1-2U → x
* 3-1-2D → x
* 3H → x
* 3L → x
For bullish sequences, continuation is counted only when the next candle closes above the applicable reference candle high.
For bearish sequences, continuation is counted only when the next candle closes below the applicable reference candle low.
If price does not close beyond the reference level, the event is classified as reclaim/fail.
The table also includes:
* User-selected lookback
* Live setup candle read
* Live sequence watch
* Body-close decision rule
* Row visibility controls
* Minimum sample threshold filtering
* Optional bull/bear color coding
This tool is intended for historical sequence review, market context, and discretionary analysis. It does not predict future price movement, generate buy/sell signals, or provide financial advice. All outputs depend on the selected symbol, timeframe, lookback settings, and available chart history.
Indicator

Institutional Order Flow Signals [PMT]Institutional Order Flow Signals applies a Gaussian Naive Bayes classifier — trained entirely within Pine Script® v6 — to cumulative volume delta divergence in order to surface, in real time, three mutually exclusive market regime states: bullish re-alignment, bearish re-alignment, and order flow divergence.
The core question this indicator addresses is distinct from threshold-crossover approaches: given the current statistical pattern of delta momentum, price/CVD divergence, and delta slope, what is the posterior probability that the market is entering — or exiting — a directional institutional order flow regime?
――――――――――――――――――――――――――――――――――――――
🔷 WHAT IT MEASURES
🔸 Cumulative Volume Delta (CVD)
CVD is the running sum of intrabar net order flow — buy volume minus sell volume — estimated via the close-position formula: bull_vol = volume × (close − low) / (high − low). The cumulative series tracks persistent institutional buying or selling pressure independently of price direction, making it a first-order proxy for directional order flow without requiring exchange-level bid/ask data.
🔸 Three Z-Score Normalised Features
Each bar, the classifier receives three inputs derived from CVD and z-score normalised for cross-instrument compatibility:
F1 — CVD Momentum : rate of change of CVD over N bars, normalised by its rolling mean and standard deviation. Encodes how rapidly buying or selling pressure is accelerating relative to its own recent baseline.
F2 — Price/CVD Divergence : price rate of change minus CVD rate of change. A large positive value signals price rising while order flow is falling — the classic institutional distribution pattern. Near-zero values indicate price and flow agreement.
F3 — CVD Slope : linear regression slope of CVD over a short window, z-score normalised. Provides a direction-of-flow signal independent of F1's momentum measure, satisfying the Naive Bayes conditional independence assumption as closely as CVD-derived features can.
🔸 Market Regime Labels
Three mutually exclusive regimes are recognised. A bullish re-alignment bar is one where both price ROC and CVD ROC are positive — institutional flow and price confirm each other to the upside. A bearish re-alignment bar is the symmetric case. A divergence bar occurs when price and order flow point in opposite directions — historically associated with regime transitions and distribution/accumulation activity.
――――――――――――――――――――――――――――――――――――――
🔷 THE CLASSIFIER
🔸 Welford Online Learning
The classifier accumulates running sufficient statistics — count, mean, and variance — for each of the nine (feature × regime) combinations using Welford's numerically stable online update. No historical arrays are stored. The model's parameters shift gradually with each new bar, making it adaptive to changing market microstructure conditions without a fixed lookback window.
🔸 Gaussian Likelihood + Bayesian Posterior
Each feature is modelled as a Gaussian distribution under each class. The joint likelihood of the current feature vector is computed by multiplying the three per-feature probability densities under the Naive Bayes independence assumption. A class prior — updated empirically from observed regime frequencies — is combined with the joint likelihood via Bayes' theorem to produce posterior probabilities P(Bull | F1,F2,F3) and P(Bear | F1,F2,F3) for the current bar. A warmup gate suppresses signals until the classifier has accumulated statistically meaningful training observations.
――――――――――――――――――――――――――――――――――――――
🔷 SIGNALS AND DISPLAY
🔸 High-Conviction Buy — P(Bull) > 85%
A long signal fires when the bull posterior clears the configurable threshold, CVD momentum confirms, and price is above the trend EMA. The threshold is surfaced on the label itself, making the confidence level explicit at every entry rather than hidden inside an opaque signal.
🔸 Bear Signal — CVD Divergence
A short signal fires when the bear posterior clears threshold and F2 is in active divergence territory — price moving up while order flow is declining, or the symmetric distribution case. CVD divergence without posterior confirmation does not produce a signal; both conditions are required simultaneously.
🔸 Bull Regime Band — CVD Aligned
A fill band anchored to the trend EMA expands when the classifier assigns high posterior probability to a sustained bullish re-alignment regime. The opacity of the band scales with the posterior — faint during low-confidence periods, saturated when the classifier considers the regime firmly established.
🔸 Info Table
Live readout displays current bull and bear posteriors, CVD direction, and training bar count. The Trained N counter confirms the classifier has completed warmup before acting on any signal.
――――――――――――――――――――――――――――――――――――――
🔷 INPUTS
Classifier Lookback — minimum training bars before signals activate. Default 100.
Entry Posterior Threshold — minimum posterior required. 0.60 permissive; 0.70 default; 0.80 high-conviction only.
CVD Momentum Period — lookback for F1 and F2 rate of change.
CVD Slope Period — regression window for F3.
Z-Score Period — normalisation window applied across all three features.
Trend EMA Period — macro filter; long signals only fire above EMA, short signals below.
――――――――――――――――――――――――――――――――――――――
🔷 REQUIREMENTS AND LIMITATIONS
The classifier requires a warmup period before signals are valid. The CVD estimator is synthetic — derived from intrabar price position, not actual bid/ask data — and introduces noise on instruments with low liquidity or wide spreads. The Naive Bayes independence assumption is partially violated because all three features are CVD-derived; the posteriors function as relative confidence scores rather than calibrated frequentist probabilities.
――――――――――――――――――――――――――――――――――――――
Built natively in Pine Script® v6. No external libraries, no data feeds, no fixed lookback arrays. The Gaussian Naive Bayes classifier trains continuously from the chart's own bar history using Welford's online algorithm. Open source — Mozilla Public License 2.0. Indicator

Probabilistic Regime Tensor [JOAT]Probabilistic Regime Tensor
Introduction
Probabilistic Regime Tensor classifies market state into Trend, Mean Reversion, or Shock using logistic transforms of statistical inputs.
This open-source indicator is designed as a context tool, not a standalone trading system. It focuses on explaining the current market state with restrained visuals and confirmed-bar logic where signals are used.
Core Concepts
1. Trend Probability
Regression slope, variance ratio, and normalized return behavior feed the trend model.
2. Mean-Reversion Probability
Contracting variance ratio, weak slope, and autocorrelation behavior feed the reversion model.
3. Shock Probability
Volatility rank and fast/slow return divergence feed the shock model.
4. Probability Entropy
The three probabilities are normalized and entropy shows whether the classifier is decisive or uncertain.
pTrend = logistic(trendInput) / probabilitySum
Features
Three-state probability model
Trend, mean, and shock probabilities
Dominant confidence and entropy
Sparse regime labels
Movable quant HUD
Input Parameters
Statistical and fast windows
Dominant probability gate
Cooldown
Candle and HUD toggles
HUD position selector
How to Use This Script
Use PRT to decide which style of analysis is more appropriate: continuation, mean reversion, or volatility caution.
Limitations
The script uses historical OHLCV data and cannot know future prices.
Signals and states can be late during fast reversals because confirmed-bar logic is used to reduce repainting.
Model outputs should be interpreted with market context, risk controls, and independent analysis.
No visual state should be treated as a certain trade outcome.
Originality Statement
PRT is original in using normalized logistic probabilities and entropy to classify market regime.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice, investment advice, or a recommendation to buy or sell any financial instrument. All calculations are derived from historical market data and may produce inaccurate readings in some market conditions. No indicator can predict future market behavior. Use proper risk management and independent judgment.
-Made with passion by jackofalltrades
Indicator

Signal Forge [LuxAlgo]The Signal Forge indicator is a modular technical analysis engine that allows users to blend 11 distinct technical filters into a unified signal and backtest the results in real-time. This tool aims to simplify strategy development by providing a visual framework for testing indicator confluence and risk management settings without writing code.
🔶 USAGE
The script provides a flexible logic system for generating signals based on the alignment of multiple technical components. Users can toggle specific indicators on or off and choose between "strict" mode (requiring ALL active indicators to agree) or "any" mode (where ANY active indicator can trigger a signal).
Signals are displayed on the chart as glowing orbs connected to the price action. Each signal includes a real-time historical win rate label at the moment of entry, allowing for a visual audit of the strategy's performance over time.
🔹 Indicator Selection
The tool includes 11 harmonized indicators:
SMA Crossover
RSI Filter (Levels)
MACD Crossover
Supertrend
Stochastic (Trend-based)
Bollinger Bands (Basis Filter)
EMA Crossover
Awesome Oscillator
Parabolic SAR
CCI Filter
ADX/DI Filter
🔹 Risk Management
Users can enable ATR-based Take Profit, Stop Loss, and Trailing Stop levels. When active, these levels are plotted on the chart. The Trailing Stop feature includes a specialized gradient fill that highlights the "breathing room" between the price and the exit level.
🔶 DETAILS
🔹 Dashboards
The script features two distinct dashboards to provide a comprehensive overview of the strategy:
Indicator Dashboard: Shows the real-time bullish/bearish status of all 11 indicators, their individual "standalone" win rates visualized with histograms, and their current toggle status.
Performance Dashboard: Provides a high-level summary of the combined strategy performance, including Net Profit %, Win Rate, Profit Factor, and Total Trades.
🔹 Logic Harmonization
To ensure different indicator types work together effectively, mean-reversion tools like the Stochastic and Bollinger Bands have been reconfigured to act as trend-confirmation filters. For example, the Stochastic signal is bullish when the %K is in the upper half of its range (> 50) rather than looking for oversold extremes, ensuring it aligns with trend-following components like Moving Averages.
🔶 SETTINGS
🔹 Signal Logic
Require All Enabled Indicators to Align: When enabled, every checked indicator must have the same directional bias to generate a signal.
🔹 Risk Management (ATR)
ATR Length: The period used for volatility-based exit calculations.
Take Profit/Stop Loss/Trailing Stop: Toggles and multipliers for managing trade exits.
🔹 Visuals
Orb Distance (ATR): Controls the vertical offset of signal orbs from the price candle.
Orb Base Size: Adjusts the thickness and glow intensity of the signal markers.
🔹 Dashboards
Dashboards: Enable or disable the table overlays.
Position/Size: Options to move and scale the Indicator and Performance tables to fit different screen layouts.
Indicator

MLP - BTC Breakout Probability [Deep Learning] [Open Source]I trained a single Multilayer Perceptron on 13 years of Bitcoin price history and open-sourced the result. Not because it's perfect, but because the idea is worth sharing.
The concept is simple.
Most breakout strategies are rule-based. Fixed levels, static conditions. This one is different, instead of predicting direction, the model learned the distribution of Bitcoin's daily price moves. You pick a threshold, it gives you the probability. Same model, any level.
How to use it
Pick a percentage threshold , by doing that you're asking the model to evaluate. When price breaks that level and the model is showing meaningful confidence, a label is shown on the chart.. Daily only. BTC only.
Under the hood
A lightweight Multilayer Perceptron (MLP) trained on ~4,700 daily candles of raw OHLC data from May 2009 to May 2022 . The architecture is two hidden layers (16→8), ReLU activations throughout, and a sigmoid output that squashes the result into a clean 0–1 probability score. ReLU keeps the internal representations sparse and non-linear, sigmoid makes the output as a probability.
What makes this interesting is that the model didn't just learn a raw number, it learned the underlying distribution of Bitcoin's daily price moves. That's what allows a single model to answer probability questions across different thresholds rather than being hardcoded to one fixed level.
The output isn't a prediction, it's a calibrated belief about where price is likely to go, derived from 13 years of market structure.
Honest limitations
Fat tails eat this model alive. The features are correlated and the model has no concept of liquidity. It underestimates the extremes.
Daily timeframe only. Bitcoin only. Long only.
This was built as a personal project, mostly for fun and to serve as a working example of how ML concepts can be applied to market data.
Disclaimer
This indicator is provided for educational and informational purposes only. It does not constitute financial advice, trading recommendations, or a guarantee of future results. Past performance does not predict future returns. You alone are responsible for your trading decisions. Always test thoroughly in a simulated environment before trading with real capital. Indicator

Predictive Breakout Channels | GainzAlgoAbout the Indicator
The Predictive Breakout Channels indicator is a predictive machine-learning engine designed to map institutional market structure and calculate the statistical probability of impending breakouts. Instead of relying on traditional lagging indicators, the system dynamically anchors itself to major market pivots using a rolling Linear Regression Channel framework.
By evaluating a combination of localized trend correlation, relative strength, institutional volume distribution, and variance metrics, the engine projects real-time target zones while simultaneously calculating a directional probability score directly on the chart the moment a breakout occurs.
Dynamically anchors to institutional pivot structures
Uses a rolling Linear Regression Channel
Evaluates trend correlation, RSI, and variance metrics
Projects real-time ATR-based target zones
Calculates breakout probability scores directly on-chart
Designed to distinguish genuine breakouts from fakeouts
The Core Theory of Breakouts
Markets spend the majority of their time consolidating rather than trending. During these equilibrium phases, liquidity pools accumulate on both sides of the range while volatility compresses beneath the surface.
A breakout represents the structural transition from equilibrium into expansion.
When institutional order flow aggressively consumes localized liquidity, price breaches structural boundaries and volatility rapidly expands outward. The challenge for traders has never been identifying that a breakout occurred — the real challenge is determining whether the move has enough structural backing to sustain itself or whether it is simply a liquidity trap designed to reverse shortly afterward.
The Predictive Breakout Channels engine was specifically designed to address that exact problem.
The Logic Engine — ANOVA & The Power of Variance
To help solve the fakeout problem, this engine incorporates ANOVA, short for Analysis of Variance.
Originally developed by legendary statistician Ronald Fisher, ANOVA has historically served as one of the foundational statistical tools used throughout medical research, behavioral science, and high-level quantitative analysis. Its purpose is to determine whether differences between groups of data are statistically meaningful or simply random noise.
In this indicator, that same statistical framework is adapted directly to price action.
The engine continuously evaluates the structural differences between groups of candle data — including highs, lows, and closes — in real time in order to measure the quality and significance of underlying market expansion.
The Niche Secret — F-Statistic & Volatility Compression
Quantitative modeling revealed a particularly powerful characteristic regarding variance measurements inside the ANOVA engine.
When the raw ANOVA F-Statistic becomes drastically elevated, or when the standardized Z-Score breaches extreme thresholds such as 2 standard deviations, it often signals a state of hyper-compressed market consolidation.
Think of it like winding a mechanical spring tighter and tighter.
As variance compresses to rare statistical extremes, market energy begins building beneath the surface. Eventually that stored pressure releases through aggressive volatility expansion.
This variance surge acts as a leading indicator for impending volatility before the actual breakout even occurs.
However, variance alone cannot determine directional bias. Because of this, the engine layers in additional confirmation modules such as RSI and Trend Correlation Length to help determine whether institutional momentum is favoring bullish or bearish continuation.
Indicator Settings & Customization
The system is fully modular, allowing traders to fine-tune the engine based on their preferred asset class, timeframe, or trading style.
Anchored LinReg Channel Settings: Customize left and right pivot lookbacks alongside standard deviation multipliers to control how the channel dynamically anchors itself to price structure.
ANOVA Confirmation: Fine-tune the lookback period and baseline Z-Score thresholds required for breakout validation.
Feature Filters: Adjust RSI and Trend Correlation baseline lengths to make directional probability scoring more aggressive or more selective.
High Variance Alert Label: Disabled by default. When enabled, the engine plots visual warning labels whenever variance compression reaches statistically elevated levels.
Include HTF Trend Filter: Controls whether breakout signals are filtered using higher timeframe trend conditions.
The Strategic Dilemma — Higher Timeframe Trend Filtering
The indicator includes a dedicated HTF Trend Filter toggle that leverages higher timeframe EMA spreads to determine whether lower timeframe breakout signals align with broader institutional trend conditions.
Choosing whether to enable this filter depends entirely on the type of market environment you prefer trading.
1. HTF Filter ON — Trend Following Regime
Filters out a significant amount of lower timeframe noise
Produces fewer but statistically stronger breakout signals
Aligns entries with broader institutional money flow
Increases overall follow-through probability
However, because the engine becomes heavily biased toward the macro trend, it may intentionally suppress counter-trend reversals or early-stage trend shifts.
2. HTF Filter OFF — Agile / Mean-Reversion Regime
Allows the engine to react dynamically in both directions
Captures sharp intraday reversals more aggressively
Performs well in swinging or range-bound environments
Increases breakout frequency substantially
The tradeoff is naturally higher exposure to lower timeframe noise and shorter average continuation during counter-trend conditions.
How to Trade with the Indicator
When price closes outside the Linear Regression Channel while simultaneously satisfying the statistical validation criteria, the engine prints a breakout entry signal alongside a projected probability score.
At the same time, the system projects 4 distinct ATR-based Target Zones labeled T1 through T4.
Aggressive Traders: May choose to execute immediately on the breakout close while targeting T2 or T3 with structural stops positioned back within the channel.
Conservative Traders: May choose to use the Probability Score as a filter or wait for a localized retest of the broken channel boundary before entering.
The High Variance Play
When the High Variance Alert label appears, traders should avoid impulsively chasing the immediate candle.
Instead, the label should be treated as an early warning that volatility expansion is rapidly approaching.
The preferred approach is to wait for the subsequent confirmed breakout signal, then trade the resulting momentum expansion into the projected target zones.
High variance does not predict direction
It predicts volatility expansion
Directional confirmation comes afterward through breakout validation
Wrapping It Up
The Predictive Breakout Channels indicator bridges quantitative data science with classic market microstructure principles.
By treating volatility as a measurable statistical property rather than a visual guessing game, the engine helps traders identify where the market is coiling, estimate the probability of expansion, and navigate breakout environments using structured statistical confirmation instead of emotion.
Whether used for momentum continuation, volatility expansion, or intraday breakout trading, the system was designed to provide traders with a clearer framework for distinguishing meaningful expansion from market noise. Indicator

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

Nyx Transition Corridor [JOAT]Nyx Transition Corridor
Introduction
Nyx Transition Corridor is an open-source probabilistic regime corridor. It estimates whether the current bullish, bearish, or neutral state has recently tended to persist, then draws adaptive volatility corridors around price. The indicator is built for context, probability, and controlled visualization rather than aggressive signal clutter.
Core Concepts
1. Regime State
The script classifies each bar as bullish, bearish, or neutral using EMA alignment, adaptive basis location, and return behavior.
2. Rolling Transition Model
Recent state transitions are counted to estimate continuation probability for the current state.
pBullBull = math.sum(fromBull * toBull, transitionLen) / math.sum(fromBull, transitionLen)
3. Adaptive Basis
The basis reacts faster when price movement is efficient and slower when the market is choppy.
4. Probability Corridor
ATR, volatility rank, and continuation probability determine the corridor width. Outer rails identify stretched conditions.
5. Compact Execution Rails
Optional small rails mark educational entry, stop, and targets when a probability reclaim or continuation event occurs.
Features
Three-state regime model: Bull, bear, and neutral states
Transition probability: Rolling persistence estimate for current state
Adaptive basis: Efficiency-weighted smoothing
Volatility-ranked corridor: Bands expand and contract with market stress
Confirmed HTF filter: Optional higher-timeframe EMA uses confirmed previous HTF data
Compact trade rails: Smaller educational rails to reduce chart obstruction
Dashboard: Shows probabilities, spread, efficiency, volatility rank, and HTF state
Input Parameters
Adaptive basis length controls centerline memory
Transition memory controls probability stability
Continuation threshold controls signal selectivity
Rail settings control optional educational projections
How to Use This Indicator
Step 1: Read the regime
The dashboard shows whether the model is bullish, bearish, or neutral.
Step 2: Compare probabilities
Large spreads between bull and bear odds indicate clearer directional context.
Step 3: Use the corridor
The corridor shows where price is trading relative to the adaptive probability field.
Indicator Limitations
Transition probabilities are historical estimates, not forecasts
Neutral markets can persist even when price briefly crosses the basis
The optional rails are visual projections and not trading advice
Originality Statement
Nyx Transition Corridor combines a state-transition model, efficiency-adjusted basis, volatility-ranked width, confirmed HTF filtering, and compact execution visuals. Its purpose is to map probabilistic state context, not to duplicate a standard moving-average band.
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice. Probability estimates are based on historical state transitions and do not predict future behavior.
-Made with passion by jackofalltrades
Indicator

Caldera Meridian Strategy [JOAT]Caldera Meridian Strategy
Introduction
Caldera Meridian Strategy is an open-source Pine Script v6 strategy that combines trend regime, pressure, structure, auction location, and transition probability into a single rules-based execution model. The strategy is designed to be transparent: each decision component is calculated directly inside the script, and entries are processed on confirmed bars.
This strategy is not intended to prove future profitability. It is a research framework for studying how multiple market-context filters interact with ATR-based risk and staged exits.
Core Concepts
1. Regime Filter
The strategy uses fast, mid, and slow EMAs to classify bullish, bearish, or neutral trend conditions. A confirmed higher-timeframe EMA can also be used as a directional filter.
trendBull = fast > mid and mid > slow and close > mid
trendBear = fast < mid and mid < slow and close < mid
2. Transition Probability
A simple rolling transition model estimates whether the current regime has recently persisted. This is used as a filter rather than a prediction.
3. Pressure and Auction Location
The strategy estimates bid/ask pressure from candle body position, range, and volume. It also tracks VWAP-style weighted price and value deviation bands to avoid entries in poor auction locations.
4. Structure Confirmation
Confirmed pivots are used to detect delayed structure breaks, sweeps, and displacement events. Pivot confirmation is non-repainting but naturally delayed.
5. ATR-Based Risk Management
Entries use ATR or structure-based stops. Exits are staged across TP1, TP2, and TP3 using configurable R multiples.
Features
Rules-based long and short logic: Combines trend, pressure, structure, auction, and probability filters
Confirmed-bar execution: Entry and risk-off logic uses closed-bar conditions
ATR and structure stops: Stops use volatility and recent structure references
Three staged exits: TP1, TP2, and TP3 use configurable R multiples and quantity percentages
Realistic default costs: Commission is set to 0.05% and slippage to 1 tick in the strategy declaration
Dashboard: Shows position state, scores, regime, continuation, pressure, auction, and risk-off status
Default Strategy Properties
Initial capital: 100,000
Commission: 0.05 percent
Slippage: 1 tick
Pyramiding: 0
Orders processed on close
How to Use This Strategy
Step 1: Use a clean chart
For publication and testing, use a standard chart type and avoid adding unrelated scripts to the chart.
Step 2: Review the dashboard
The dashboard explains why the strategy is flat, long, short, or in a risk-off state.
Step 3: Evaluate across markets
Do not judge a strategy from a small sample. Test across multiple symbols, timeframes, and market regimes.
Strategy Limitations
Backtest results do not imply future results
Pivot-based structure is confirmed only after the pivot length has passed
Costs and slippage may differ from live trading conditions
The model can underperform in choppy markets where filters repeatedly conflict
The strategy is a research framework and not a complete trading plan
Originality Statement
Caldera Meridian Strategy integrates multiple independent modules rather than relying on a single crossover or oscillator. Its usefulness comes from studying how regime, structure, pressure, auction location, and transition persistence interact before a trade is allowed.
Disclaimer
This strategy is provided for educational and informational purposes only. It is not financial advice. Trading involves risk of loss. Backtests are historical simulations and do not predict future performance. Always use proper risk management.
-Made with passion by jackofalltrades
Strategy

Session Probability Grid [JOAT]Session Probability Grid
Introduction
Session Probability Grid is an open-source session auction map. It builds percent-based ladder levels from the active session open, tracks historical hit behavior for those levels, and displays probability-style context for expansion, exhaustion, and unusual session movement.
The problem it solves is session framing. Traders often know the open is important, but they may not know whether a move is normal for the current symbol and timeframe. This script records session outcomes and converts them into visible ladder probabilities.
Core Concepts
1. Session Open Ladder
The script creates six upside and six downside levels from the session open using configurable percentage steps. These levels frame how far price has moved away from the open.
2. Historical Hit Memory
At the end of each session, the script updates arrays storing hit counts, sample counts, and continuation distance. This creates a rolling sample of how often each ladder has been reached.
3. Opening Range Context
The first configurable number of bars defines the opening range. The session box and opening range box help distinguish early balance from later expansion.
4. Expansion and Exhaustion States
Expansion states identify movement through areas with supportive historical behavior. Exhaustion states mark stretched locations where continuation may be less reliable.
5. Session VWAP Gradient
The optional session VWAP gradient adds a live auction mean reference so ladder movement can be compared against the developing session control line.
Features
Open-relative ladder: Six upside and six downside levels based on configurable percent steps.
Statistical memory: Tracks hit count, sample count, and continuation distance from completed sessions.
Probability cards: Right-side cards show ladder behavior without crowding price.
Expansion and exhaustion states: Highlights meaningful session movement conditions.
Session and opening range boxes: Frames current auction development.
Session VWAP gradient: Adds a developing mean reference.
Candle coloring: Bars can be colored by session state.
Dashboard: Shows session state, nearest ladder, hit probability, expected continuation, and range condition.
Alerts: Upside expansion, downside expansion, upper exhaustion, and lower exhaustion.
Input Parameters
Core Session: Active Session, Opening Range Bars, Stat Sample Cap, Session Range Box, Opening Range Box.
Ladder: Open-Relative Ladders and Step 1 through Step 6.
Signals and Visuals: Auction State Zones, State Projection Bars, Continuation Probability Gate, Right Probability Cards, Session Candle Color, Session VWAP Gradient, Dashboard.
How to Use This Indicator
Step 1: Start from the session open
The ladder levels are built from the open, so they frame the current session relative to its starting price.
Step 2: Compare price to the ladder
As price approaches a ladder level, check the probability card and dashboard for historical hit and continuation context.
Step 3: Distinguish expansion from exhaustion
Expansion and exhaustion states help separate normal auction development from stretched movement.
Indicator Limitations
Probabilities are based on the chart's available historical sessions and are not universal statistics.
Session boundaries depend on the selected exchange/session setting.
The script needs enough completed sessions to build useful samples.
Probability context does not predict future price.
Originality Statement
Session Probability Grid is original in its combination of open-relative ladders, rolling hit memory, continuation-distance storage, session VWAP context, opening range framing, and expansion/exhaustion visualization. It is not just a static percent-level tool; it updates its context from completed session behavior.
Disclaimer
This script is for educational and informational purposes only. It is not financial advice and does not recommend trades. Historical session behavior may not repeat. Use independent analysis and risk management.
Made with passion by jackofalltrades
Indicator

ATR Exceedance Probability Model [LuxAlgo]The Volatility Exceedance Probability Model (VEPM) indicator is a comprehensive statistical tool designed to quantify the significance of volatility spikes, determine the likelihood of trend continuation, and categorize market environments into specific regimes.
🔶 USAGE
The indicator provides a multi-layered view of volatility, allowing traders to distinguish between standard market noise and statistically significant "exceedance" events.
🔹 Oscillator Interpretation
The main oscillator plots the current exceedance frequency (the rate at which price or range breaches ATR-based thresholds) against a long-term baseline.
Bullish/Significant Glow: When the Z-Score of the frequency exceeds the sensitivity threshold, the oscillator glows green, indicating a high-probability volatility expansion.
Bearish/Normal Glow: When the frequency falls below the baseline, the oscillator shifts toward red, signaling a contraction in volatility.
Frequency Delta: The area between the current frequency and baseline frequency is filled to highlight the momentum of volatility expansion or exhaustion.
🔹 Chart Visuals & Regimes
The script overlays information directly on the price action to provide context:
ATR Bands: Dynamic bands based on the Average True Range act as the "exceedance" barrier.
Regime Boxes: The indicator automatically identifies "Quiet," "Normal," and "High Vol" regimes. These are visualized as colored boxes (defaulting to High Vol) to show the duration and range of specific volatility climates.
Significance Dots: Circles appear at the top of the chart to mark bars that have breached the volatility threshold.
🔹 Dashboard Metrics
A real-time dashboard provides quantitative data:
Exceedance Freq: The percentage of bars in the short-term window that breached the ATR levels.
Serial Break Prob: The historical probability that a breach will be followed by another breach (continuation).
Clustering Edge: The statistical advantage of volatility clustering; a positive value suggests that volatility is currently feeding on itself.
🔶 DETAILS
The VEPM operates on the principle that volatility is not constant but "clusters" in time. It uses the following logic to derive its metrics:
Exceedance Detection: It calculates whether the current price range (True Range) or price levels (High/Low) exceed a user-defined ATR multiplier.
Statistical Z-Score: By comparing the current frequency of these breaches to a long-term baseline (200 bars by default), the model calculates a Z-Score to determine if the current activity is statistically "abnormal."
Continuation Probability: The model looks back at previous breaches and calculates how often they resulted in immediate follow-through, providing a "Serial Break" percentage.
🔶 SETTINGS
🔹 Core Settings
ATR Length: The lookback period used for the Average True Range calculation.
ATR Multiplier: The threshold used to define what constitutes a "breach" or exceedance.
Breach Detection Method: Choose between comparing the bar's total range to ATR or checking if price levels exceed the previous bar's bands.
🔹 Statistical Windows
Short-Term Window: The period used to calculate the current exceedance frequency.
Baseline Window: The long-term period used to establish the "normal" mean of volatility frequency.
Z-Score Sensitivity: Determines the threshold for identifying statistically significant volatility spikes.
🔹 Visuals
Show ATR Bands: Toggles the visibility of the ATR-based levels on the chart.
Bands Mode: Determines if bands are offset from a central basis (SMA/EMA) or from the bar's High/Low.
Regime Box Options: Toggles background boxes for Quiet, Normal, or High Volatility regimes.
🔹 Dashboard
Dashboard: Enables or disables the on-screen information table.
Position/Size: Controls the location and scale of the dashboard UI.
Indicator

MTF Kinetic Oscillator | Rainbow MatrixGENERAL OVERVIEW
The MTF Kinetic Oscillator is a multi-timeframe order-flow probability oscillator that fuses 5 timeframes into a single composite score, blended with three independent order-flow sensors (CVD, Volume Climax, Squeeze) and plotted against a self-adaptive Fibonacci channel that recalibrates to current volatility conditions. Instead of treating an oscillator as a fixed 0-100 envelope where the same threshold means the same thing across all market regimes, the indicator continuously classifies the current score against an adaptive channel — and colors the chart accordingly.
The main goal of this indicator is to give traders a clean, automatic read on where the order-flow consensus sits across 5 timeframes simultaneously, and how stretched that consensus is relative to its own recent statistical range — without having to manually monitor multiple oscillators on multiple timeframes. Every value the oscillator displays is the result of a weighted aggregation of 5 timeframe scores, modulated by order-flow sensors, and contextualized against an adaptive channel.
It plots a single score line that travels through five color zones (yellow, orange, red, purple for upper extremes; green, teal, blue, aqua for lower extremes), each corresponding to a probabilistic regime. Combined with the Info Panel HUD, Vacuum Trail convergence lines, and Black Swan dynamic glow, the indicator gives a complete read on order-flow direction, statistical position, and proximity to exhaustion zones — all from a single oscillator pane.
This indicator was developed for traders who already understand oscillator-based indicators (RSI, MFI, Stochastic, CCI) and want a multi-timeframe aggregation that calibrates its thresholds to current volatility instead of using fixed 0-100 boundaries.
WHAT IS THE THEORY BEHIND THIS INDICATOR?
Most oscillators on PulseWire — RSI, MFI, CCI, Stochastic, and their derivatives — share two common architectural choices: they operate on a single timeframe, and they classify against fixed thresholds (typically 70/30 or 80/20). This treats every market regime as statistically equivalent.
The problem: market regimes are not equivalent. A score of 75 during a tight-range, low-volatility period is structurally different from a score of 75 during a volatile expansion phase. Fixed thresholds applied to a non-stationary distribution produce systematic mismatches — overbought readings that resolve into further upside, oversold readings that continue lower, signals that appear at the wrong moments precisely when volatility shifts regimes. This mismatch becomes most visible during transitions between volatility regimes: trend climaxes, capitulation lows, squeeze breakouts.
This indicator addresses both issues at once. First, the per-timeframe score is built from a Log-Normal Z-Score regression of price (which respects the asymmetric distribution of returns) blended with RSI through a sigmoid normalization. Second, the 5 per-timeframe scores are aggregated through Fibonacci weights (0.15 / 0.20 / 0.25 / 0.25 / 0.15) into a single global score — giving the most weight to the middle macro horizons rather than the shortest or longest timeframes. Third, the global score is plotted not against fixed 0-100 thresholds, but against a self-adaptive channel whose boundaries are re-computed every bar from the highest and lowest scores in the lookback window, smoothed by EMA, and proportioned by Fibonacci ratios (1.50/1.85, 1.85/1.85, 2.75/1.85, 3.85/1.85).
The three order-flow sensors — CVD Z-Score, Volume Climax, and Squeeze — operate as modulators of the base score: the CVD bonus amplifies the score when directional order pressure dominates (clamped at ±12 points), Volume Climax drag dampens the score when abnormal volume is detected (statistical exhaustion signal), and the Squeeze damper compresses score amplitude to 25% during compressed-volatility regimes (suppressing false signals during low-conviction lateral phases).
Why traders use it: each color zone on the chart represents a different probabilistic regime, calibrated to current volatility. When the score sits between the median and the inner band (yellow/green), the order-flow consensus is in normal operating range — equilibrium. When the score crosses into the second band (orange/teal), the move has crossed into directional territory. The third band (red/blue) marks the threshold beyond which most of the impulse has already happened — exhaustion. The fourth band (purple/aqua) marks the tail of the distribution — a Black Swan event in Taleb's sense — where score positions rarely persist under normal volatility conditions.
The three order-flow sensors and the adaptive Fibonacci channel are not independent layers stacked in the same pane. They map three different aspects of the same question: where the multi-timeframe order-flow consensus currently sits (the score), how that consensus is being modulated by live order-flow pressure (the sensors), and how stretched that modulated value is relative to its own recent statistical range (the channel). The integration of all three components into a single oscillator is the reason they exist in one script rather than as three separate indicators: the cross-component blending is what surfaces multi-sensor confluence that separate-script approaches cannot produce.
MTF KINETIC OSCILLATOR FEATURES
The indicator includes 6 main features:
Multi-Timeframe Score Engine
CVD Order-Flow Sensor
Volume Climax and Squeeze Sensors
Adaptive Fibonacci Channel
Vacuum Trail and Black Swan Dynamic Glow
Info Panel HUD and Alerts
Multilingual interface and full customization across all visual layers.
MULTI-TIMEFRAME SCORE ENGINE
🔹 What It Does
The core of the indicator. For each of the 5 configured radar timeframes, the engine performs three operations:
◇ Calculates a Log-Normal Z-Score regression of price (hlc3 transformed via natural logarithm, fitted with linear regression, residuals normalized by their own standard deviation).
◇ Computes a per-timeframe RSI at a Fibonacci-aligned length (8, 13, 21, 34, 55 — one per timeframe).
◇ Blends the Z-Score (via sigmoid normalization) and the RSI into a single per-timeframe score, bounded 0-100.
The 5 per-timeframe scores are then aggregated through Fibonacci weights (0.15 / 0.20 / 0.25 / 0.25 / 0.15) into a single global score representing the multi-horizon order-flow consensus.
🔹 Method
The regression runs in log space, addressing the asymmetric nature of price distribution that linear estimators (such as the Simple Moving Average) fail to account for. The directional reference (high vs low) is selected per bar based on candle direction — green candles use the high (upward pressure reference), red candles use the low (downward pressure reference). This produces a Z-Score that reflects the directional intent of each bar rather than the midpoint average.
The sigmoid normalization compresses Z-Scores into a bounded 0-100 range without losing the asymmetric information of extreme values. The RSI component anchors the score to a familiar momentum reference, blending two independent signal families into one bounded value per timeframe.
🔹 Hierarchical Weighting
The five timeframes are weighted by structural significance using Fibonacci proportions:
◇ TF1 (Trigger, default 5): weight 15% — fastest reactivity, lowest weight.
◇ TF2 (Intraday, default 13): weight 20% — session-scale resolution.
◇ TF3 (Macro 1, default 55): weight 25% — backbone of the score.
◇ TF4 (Macro 2, default 233): weight 25% — institutional reference horizon.
◇ TF5 (Base, default 987): weight 15% — macro trend anchor.
The middle horizons (TF3 and TF4) carry the highest weight because they typically represent the most structurally significant reference for institutional decision-making — short enough to react to current conditions, long enough to filter intraday noise.
CVD ORDER-FLOW SENSOR
🔹 What It Does
The CVD (Cumulative Volume Delta) sensor estimates the difference between buyer and seller volume per bar — measuring market-order aggression. The signed delta is normalized to a Z-Score against a 50-period rolling reference, and the resulting bonus is clamped at ±12 points before being added to the global score.
🔹 Method
For each bar, total volume is split between buyer share (proportional to `close - low / range`) and seller share (proportional to `high - close / range`). The signed delta is the difference. A 50-period mean and standard deviation define the reference; the current delta is expressed as a Z-Score against that reference, then multiplied by 4 and clamped to ±12 to control its contribution to the final score.
🔹 Why It Matters
The Z-Score component answers "where is the multi-timeframe consensus", and the RSI component answers "what is the momentum". The CVD sensor answers a separate question: "who is currently aggressive in the order book". When the multi-timeframe consensus is bullish and CVD aggression confirms it, the bonus amplifies the score. When the consensus is bullish but CVD shows seller aggression, the bonus subtracts from the score — surfacing a divergence between consensus and order-flow.
VOLUME CLIMAX AND SQUEEZE SENSORS
🔹 Volume Climax
A standalone sensor that detects abnormal volume conditions (volume Z-Score above 3.0). When triggered, a climax drag is applied to the score, signaling potential exhaustion. The HUD reports this state explicitly in the Status row.
🔹 Squeeze
A volatility-compression detector based on the percentage-rank of the current range against a 20-period lookback. When the range compresses to its 15th percentile or lower, the squeeze flag activates and the score amplitude is dampened to 25% of its normal range — preventing false directional signals during compressed-volatility regimes.
🔹 Why They Matter
These sensors operate on a different axis from the price-direction sensors. Volume Climax surfaces statistical exhaustion before it becomes visible in price; Squeeze suppresses noise during periods when the oscillator would otherwise produce false reads. Together they make the oscillator behave correctly during regime transitions, where standard oscillators are typically least reliable.
ADAPTIVE FIBONACCI CHANNEL
🔹 What It Does
The global score is plotted against a self-adaptive channel rather than against fixed 0-100 thresholds. The channel boundaries are re-computed every bar from the highest and lowest scores in a 50-bar lookback window, smoothed by 10-period EMA, and then proportioned through Fibonacci ratios into four zones:
◇ Z-Breathing (inner, yellow/green) — ratio 1.50 / 1.85 (≈ 0.811)
◇ Z-Alert (upper limit, orange/teal) — ratio 1.85 / 1.85 = 1.000 (the visible anchor)
◇ Z-Exhaustion (outer, red/blue) — ratio 2.75 / 1.85 (≈ 1.486)
◇ Black Swan (extreme edge, purple/aqua) — ratio 3.85 / 1.85 (≈ 2.081)
🔹 Why It Adapts
Fixed thresholds (70/30 or 80/20) treat every volatility regime as equivalent. The adaptive channel calibrates the rainbow visual to the actual statistical envelope of the current regime — overbought during a low-volatility consolidation does not mean the same as overbought during a volatility expansion, and the channel reflects that.
🔹 Visual Rendering
The space between adjacent channel boundaries is filled with a semi-transparent color matching the zone palette (toggleable via "Show Thermal Zone Fills"). This makes the current zone immediately visible without having to read the score number — the visual position alone tells you the regime.
VACUUM TRAIL AND BLACK SWAN DYNAMIC GLOW
🔹 Vacuum Trail
Ghost convergence lines projecting from exhaustion extremes back toward the channel median. The lines anchor at a level 15% inside the inner Breathing zone (not at the channel boundary itself), which produces visual convergence inward rather than along the edge — useful for anticipating the typical mean-reversion path after extreme touches.
🔹 Black Swan Dynamic Glow
The outermost ±3.85σ-equivalent boundaries are rendered as a main line plus a wide outer glow whose intensity scales with the score's distance from the boundary. The glow becomes bright when the score is near the Black Swan zone and fades when far — drawing visual attention only when the statistical tail is approached.
🔹 Why They Matter
Both elements give the oscillator a sense of direction beyond the score's current position: the Vacuum Trail visualizes the expected return path during exhaustion; the Black Swan Glow makes statistical tail events visible at a glance, before the score itself crosses the boundary.
INFO PANEL HUD AND ALERTS
🔹 What the HUD Shows
A compact corner panel reports six live values:
◇ SCORE — the current global score (0-100) with color matching the active channel zone
◇ PROB. — the absolute probability (distance from neutral 50 expressed as percentage)
◇ DIRECTION — BUY / SELL / NEUTRAL based on score position relative to the median
◇ CHANNEL — current channel regime classification (Uptrend / Downtrend / Sideways / Compression / Expansion)
◇ RHYTHM — score velocity classification (Fast / Slow)
◇ STATUS — Black Swan / Squeeze / Climax / Neutral, prioritized by severity
🔹 Customization
The HUD can be positioned in any of the four chart corners and rendered in any of five font sizes. The display language is controlled by the System Language input.
🔹 Alerts
Three alert types are available:
◇ Exhaustion Alert — fires when the score crosses above 85% (buying exhaustion) or below 15% (selling exhaustion).
◇ Squeeze Alert — fires when the squeeze flag activates (volatility compression detected).
◇ Black Swan Alert — fires when the score enters the ±3.85σ-equivalent extreme zone; uses an edge-trigger arm/disarm mechanism (fires once on entry, locks while inside, re-arms only on exit).
All alerts are gated by `barstate.isconfirmed` and use `alert.freq_once_per_bar` to prevent duplicate firings on the same candle. Five `alertcondition` blocks are also exposed for users who prefer the PulseWire alert UI.
MULTILINGUAL INTERFACE
The indicator supports five languages for the HUD display and alert messages: English (default), Português, Español, Русский, and 中文 (Chinese). Code, comments, group names and input labels remain in English regardless of the selected language.
For reference, the English text of all multilingual UI strings used in the HUD and alerts:
◇ BUY / SELL / NEUTRAL — direction states
◇ SQUEEZE — Low Volatility. Await the Explosion.
◇ CLIMAX — Abnormal Volume Detected. Possible Exhaustion.
◇ UPTREND / DOWNTREND / SIDEWAYS / COMPRESSION / EXPANSION — channel states
◇ FAST / SLOW — rhythm states
◇ SCORE: / DIRECTION: / CHANNEL: / RHYTHM:
◇ BLACK SWAN — EXTREME HIGH / BLACK SWAN — EXTREME LOW
◇ Buying Exhaustion Alert: " Buying Exhaustion: Score above 85%. High reversal probability."
◇ Selling Exhaustion Alert: " Selling Exhaustion: Score below 15%. High reversal probability."
◇ Squeeze Alert: " Squeeze Active: Volatility maximally compressed. Explosion imminent."
◇ Black Swan Alert: " Score reached the dynamic channel's extreme zone. Maximum statistical tension. Reversal probable."
HOW TO USE
This indicator is not a signal generator. It is a state classifier: it tells you where the multi-timeframe order-flow consensus currently sits, how stretched that consensus is relative to its own recent statistical range, and which order-flow regime (climax, squeeze, normal) is currently active.
🔹 Reading the Oscillator
◇ The score line color matches the active channel zone — visual position alone identifies the regime.
◇ The HUD reports the score numerically and classifies the channel/rhythm/status in plain language.
◇ Vacuum Trail lines indicate the expected mean-reversion path during exhaustion conditions.
◇ Black Swan glow intensity scales with proximity to the statistical extreme.
🔹 Tactical Reading
◇ Score between dyn_mid and inner band: equilibrium zone. Order-flow consensus is in normal range.
◇ Score crossing into the Alert band: directional move asserting itself across multiple timeframes.
◇ Score at the Exhaustion band: most of the impulse has already happened — continuation in trend direction becomes structurally less favorable.
◇ Score touching the Black Swan band: statistical tail event. Mean-reversion context is elevated, but regime change is also possible — the boundary itself is adaptive, so a sustained breach indicates the volatility envelope expanding.
◇ Squeeze state active: oscillator is operating in low-conviction mode. Wait for squeeze release before trusting directional reads.
◇ Climax state active: abnormal volume has been detected. Exhaustion context is present regardless of score position.
🔹 Multi-Timeframe Reading
◇ The default radar configuration (5/13/55/233/987) follows Fibonacci minute periods and is calibrated for intraday and swing trading.
◇ For scalping, configure shorter timeframes (e.g., 1/3/8/21/55).
◇ For position trading, configure longer timeframes (e.g., 60/240/D/W/M).
◇ The middle-weighted timeframes (TF3 and TF4) carry the most influence — choose them carefully.
INPUTS EXPLAINED
🔹 System Language
Display language for the HUD and alert messages. Options: English (default), Português, Español, Русский, 中文 (Chinese).
🔹 MTF Synchronization (TF1 to TF5)
Configure each of the five timeframes to aggregate. Defaults: 5, 13, 55, 233, 987 (Fibonacci minutes). Weights are fixed at 15/20/25/25/15 percent respectively.
🔹 Show Thermal Zone Fills
Toggle for the semi-transparent rainbow fills between adjacent channel boundaries.
🔹 Show Vacuum Trail (Ghost Lines)
Toggle for the convergence ghost lines from exhaustion extremes back toward the channel median.
🔹 Show Dynamic Median Line
Toggle for the channel midline (dyn_mid) — the adaptive zero-reference of the oscillator.
🔹 Show Black Swan Lines (Dynamic Glow)
Toggle for the outermost ±3.85σ-equivalent boundaries with proximity glow.
🔹 Show Info Panel
Toggle for the corner HUD reporting score, direction, channel, rhythm, and status.
🔹 Panel Position
Position of the HUD on the chart. Four corners available: Bottom Right (default), Bottom Left, Top Right, Top Left.
🔹 Font Size
HUD font size. Options: Tiny (default), Small, Normal, Large, Huge.
🔹 Exhaustion Alert
Toggle for the alert that fires when the score crosses ±85/15 thresholds.
🔹 Squeeze Alert
Toggle for the alert that fires when the squeeze flag activates.
🔹 Black Swan Alert
Toggle for the alert that fires when the score enters the adaptive extreme zone.
IMPORTANT NOTES
The MTF Kinetic Oscillator works on any timeframe. The default MTF configuration (5/13/55/233/987 in minutes) is calibrated for intraday and swing trading on liquid instruments. The Fibonacci-aligned RSI lengths (8/13/21/34/55) and per-timeframe data lengths (288/96/72/60/40) are tuned to provide roughly equivalent statistical resolution across all five horizons.
The indicator works best on instruments with reliable volume data: crypto perpetual contracts, large-cap equities, futures, major forex pairs. On low-volume instruments, the CVD component becomes less reliable, though the score engine and channel continue to function correctly using the Z-Score and RSI components alone.
Alerts fire once per confirmed bar. The Black Swan alert uses an edge-trigger arm/disarm mechanism that prevents repeated firings while the score remains inside the extreme zone. Historical bars never repaint after they close. The live bar updates intra-bar as expected for a real-time indicator.
The Value Area calibration factor (vp_k = 2.51) used internally by the score engine for the Volume Profile distance component is tuned to approximate the conventional 70% Value Area definition. The Fibonacci sigma multipliers (1.50, 1.85, 2.75, 3.85) used by the adaptive channel are intentionally non-standard — they are Fibonacci-inspired proportions, not arbitrary choices, and they map to four behavioral regimes derived from observation rather than to integer statistical thresholds.
Pine Script v6. Open-source under Mozilla Public License 2.0.
UNIQUENESS
The MTF Kinetic Oscillator is unique in four ways. First, it operates across 5 timeframes simultaneously, aggregating per-timeframe scores via Fibonacci-proportioned weights (0.15 / 0.20 / 0.25 / 0.25 / 0.15) rather than operating on a single timeframe like RSI, MFI, CCI, or Stochastic. Second, the per-timeframe score is built from a Log-Normal Z-Score regression of price (which respects the asymmetric distribution of returns) blended with RSI through sigmoid normalization — producing a bounded composite that combines two independent signal families per horizon. Third, the global score is plotted not against fixed 0-100 thresholds but against a self-adaptive Fibonacci channel whose boundaries are recomputed every bar from the highest and lowest scores in the lookback window — calibrating the rainbow visual to current volatility regime rather than to static numerical levels. Fourth, three independent order-flow sensors (CVD Z-Score, Volume Climax detection, and Squeeze volatility compression) modulate the score continuously, with the Squeeze damper compressing score amplitude to 25% during low-conviction lateral phases — suppressing false directional signals at exactly the moments standard oscillators are typically least reliable. The combination of Fibonacci-weighted multi-timeframe aggregation, log-space Z-Score plus RSI per timeframe, adaptive Fibonacci channel, and three order-flow modulators produces an oscillator that behaves differently from single-timeframe and fixed-threshold oscillators, particularly during volatility regime transitions where standard oscillators are least reliable. Indicator

Covenant Regime Register [JOAT]Covenant Regime Register
Introduction
Covenant Regime Register is an open-source market context indicator that classifies whether price is currently behaving like a directional auction or a rotational auction. Instead of treating trend detection as a single yes-or-no output, the script builds two competing probability streams and continuously updates which state has stronger evidence.
The problem this indicator solves is context drift. Many tools are applied the same way in every environment even though trending conditions and ranging conditions reward very different decisions. Covenant Regime Register separates those environments first, then exposes confidence, directional efficiency, and bias so the trader can decide whether to lean into continuation logic or step back into rotation logic.
Core Concepts
1. Multi-factor regime observations
The regime engine does not rely on one input. It blends normalized returns, normalized volatility, directional efficiency, and slope persistence into a two-state regime model:
logReturn = math.log(close / nz(close , close))
realizedVol = ta.stdev(logReturn, volatilityLength)
efficiencyRatio = math.abs(close - close ) / math.sum(math.abs(ta.change(close)), efficiencyLength)
This keeps the classification grounded in both movement quality and volatility behavior.
2. Probabilistic state competition
Directional and rotational states each receive an emission score. Those scores are then smoothed through a persistence-heavy probability engine so the output does not flip on every small fluctuation:
posteriorTrend = emissionTrend * priorTrend
posteriorRange = emissionRange * priorRange
trendProb := trendProb + learningInput * (targetTrend - trendProb)
The result is a stable state register rather than a noisy binary switch.
3. Confidence-aware classification
The script only considers a regime confirmed when the dominant state exceeds the user-defined confidence threshold on a confirmed bar. This helps reduce false transitions during temporary turbulence.
4. Probability spread visualization
Trend probability and range probability are plotted together, while the spread between them is shaded as a separate area. This lets the user see whether the market is decisively one-sided or only marginally biased.
5. Institutional dashboard
The top-right dashboard reports current state, confirmation status, trend probability, range probability, efficiency, and directional bias using a restrained dark palette designed to stay readable on a clean chart.
Features
Two-state regime model: Directional auction versus rotational auction
Multi-factor classification: Uses returns, volatility, efficiency, and slope instead of a single oscillator threshold
Probability outputs: Trend and range are shown as separate probability streams
Confidence gate: Regimes are only considered confirmed above the user-defined threshold
Spread visualization: Shows the separation between the two competing states
Dark institutional dashboard: Compact top-right panel with current state and supporting metrics
Confirmed-bar regime alerts: Alerts only fire when a new regime is confirmed on bar close
Non-repainting design: Uses only current-timeframe information and confirmed-bar state transitions
Input Parameters
Regime Engine:
Return Lookback: Smoothing window for the return series
Volatility Lookback: Window used to normalize realized volatility
Efficiency Length: Measures directional travel versus rotational travel
Probability Learning: Controls how quickly the posterior probabilities adapt
Trend Confirmation Threshold: Minimum dominant probability required before a regime is treated as confirmed
Visual System:
Show Regime Backdrop
Show Probability Spread
Show State Ribbon
Show Dashboard
How to Use This Indicator
Step 1: Read the dominant state
If Trend Probability is above Range Probability and the confidence threshold is met, the market is behaving more directionally. If Range Probability dominates, the market is behaving more rotationally.
Step 2: Check confirmation
Use the confirmation state before treating the output as actionable. Developing readings can still change as the current bar closes.
Step 3: Use efficiency and bias together
High efficiency with strong directional bias supports continuation logic. Low efficiency with range dominance supports mean-reversion or lower-aggression decision making.
Step 4: Apply it as a filter
This indicator is best used as a context layer for other tools. It is not intended to predict the next bar by itself.
Indicator Limitations
Regime models classify the present environment; they do not forecast future direction
Extremely fast reversals can temporarily lower confidence before the new state stabilizes
Range and trend can overlap during transition periods, so marginal readings should be treated cautiously
Originality Statement
Covenant Regime Register is original in how it combines normalized return behavior, normalized volatility, directional efficiency, and slope persistence into a compact two-state probability register with an explicit confidence gate. It is published because:
The script produces competing regime probabilities rather than a single trend flag
The classification emphasizes state persistence and bar-close confirmation instead of hyper-reactive regime flipping
The dashboard surfaces regime context in a compact format suitable for use as a decision filter alongside other indicators
Disclaimer
This indicator is provided for educational and informational purposes only. It is not financial advice and does not guarantee future market behavior. All regime classifications are derived from historical and current price behavior and can produce false or delayed readings. Always use independent judgment and proper risk management.
Indicator

Volatility Heatmap Bands [PickMyTrade]━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
WHAT IT DOES
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Volatility Heatmap Bands fits a log-normal distribution to recent price returns and draws a statistically calibrated price envelope — then colours every bar by where it sits inside that envelope.
Simple version: the red band at the top is the "overbought wall." The cyan band at the bottom is the "oversold wall." When bars turn red, price is statistically stretched toward the top. When bars turn cyan, price is statistically stretched toward the bottom. The colour tells you whether a move is normal or extreme — without reading a single number.
Three layers power every calculation:
▸ Log-Normal Drift (μ) — rolling mean of log-returns, representing the direction price is diffusing
▸ Volatility (σ) — rolling standard deviation of log-returns, updated every bar
▸ Itô Correction (−½σ²) — converts the arithmetic mean to a geometric mean, required for continuous-time price models. Without this, the envelope is systematically biased upward
The result is a probability corridor that widens in volatile markets and tightens in calm ones — automatically, with no manual adjustment.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
THE HEATMAP EXPLAINED
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Each bar is coloured by a single value: the normalised position of close within the 10th–90th percentile envelope.
position = (close − 10th band) / (90th band − 10th band)
0.0 → close is at or below the 10th band → deep cyan
0.5 → close is at the midpoint → neutral
1.0 → close is at or above the 90th band → deep red
This is not a momentum oscillator and not RSI. It is a spatial measure of where price sits inside its own forward-projected distribution. A deep-red bar means the current close is in the top decile of the statistically projected range — not that it is rising fast, but that it has reached a zone that is historically reached only 10% of the time.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SIGNALS — ▲ LONG / ▼ SHORT
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
A breakout signal fires when price exits the N-bar channel:
▲ Long — close breaks above the highest close of the last N bars
▼ Short — close breaks below the lowest close of the last N bars
An optional trend filter (slow EMA gate) removes counter-trend signals:
• Longs only when close is above the trend EMA
• Shorts only when close is below the trend EMA
Signals appear as small triangles on the chart. They are not trade recommendations — they mark a structural breakout that coincides with a momentum expansion, for the trader to act on within their own framework.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
VOLATILITY REGIME DETECTION
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
σ is compared to its own rolling distribution via a percentile rank:
≥ 75th percentile of σ → High Vol regime (subtle orange background)
25th – 75th → Normal regime (no tint)
< 25th percentile of σ → Low Vol regime (subtle blue background)
Why it matters: the same breakout signal in a High Vol regime carries a wider envelope and therefore a different risk profile than the same breakout in Low Vol. The background tint makes the regime visible at a glance.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
WHAT MAKES IT DIFFERENT
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Most volatility bands (Bollinger, Keltner, Donchian) are constructed from past price movement around a moving average. They describe where price has been.
VHB projects forward. The envelope is calculated at the current close and extended H bars into the future using the fitted distribution. The bands show where price is statistically likely to be in H bars — not where it has been.
Consequence: in a trending market the bands tilt with the drift. In a mean-reverting market the bands remain flat. The geometry of the envelope changes with market character, not with arbitrary multiplier choices.
The Itô correction is not a cosmetic detail. In continuous-time finance, the expected log-price grows at μ − ½σ², not μ. Omitting the correction causes the upper band to overstate likely price levels by an amount that grows with σ² — small in calm markets, significant during volatility expansion. VHB applies the correction on every bar.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
HOW TO USE IT
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1. Apply to any liquid instrument — futures (MNQ, NQ, ES, CL, GC), forex pairs, crypto
2. Choose your timeframe:
• 1m / 5m — scalping, intraday momentum
• 15m / 1H — intraday swing
• 4H / Daily — positional
3. Read the heatmap first:
• Cyan bars near the lower band → price is statistically cheap relative to its own distribution
• Red bars near the upper band → price is statistically expensive
4. Wait for a signal ▲ / ▼ to confirm directional intent
5. Use the info panel (bottom-right) to monitor CDF Score, σ/bar, regime, and band levels in real time
6. Set alerts via the Alerts tab for Long Signal, Short Signal, or Regime changes
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SETTINGS REFERENCE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
| Input | Default | Purpose |
|---|---|---|
| Fit Lookback | 100 | Bars used to estimate μ and σ |
| Holding Horizon | 10 | Bars forward the distribution is projected |
| Breakout Channel | 20 | N-bar high/low for signal detection |
| Trend Filter | ON | EMA gate — removes counter-trend signals |
| Trend EMA Length | 200 | Slow EMA period for directional gate |
| Show Outer Bands | ON | 10th and 90th percentile lines |
| Show Median | ON | 50th percentile — Itô-corrected drift line |
| Show Inner Bands | OFF | 25th and 75th percentile lines |
| Fill Band | ON | Dark fill between 10th and 90th |
| Heatmap Bar Colour | ON | Cyan–red gradient by envelope position |
| Highlight Regime | ON | Subtle background tint by volatility regime |
| Show Info Panel | ON | Live σ, CDF score, drift, bands, signal |
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
NOTES
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
• Requires at least Fit Lookback bars of history before the first band appears
• Works on any asset class; continuous instruments (futures, forex) show the cleanest log-return distribution
• The indicator does not repaint — all band values are calculated from confirmed closed bars
• Signals use close for channel calculation — no lookahead bias
• This tool is for research and educational purposes only. It is not financial advice.
Indicator

Smooths IB MapSmooths IB Map — Initial Balance Probability Engine
Overview
Smooths IB Map is an Initial Balance indicator built around a statistical probability engine rather than simple level plotting. The Initial Balance (IB) is the price range established during the first hour of the regular trading session (9:30–10:30 ET by default). This range has long been used by institutional and retail traders as a reference for the day's expected price behavior — price frequently sweeps one or both IB extremes before reversing or continuing. This indicator quantifies that tendency and makes it actionable.
What makes this different
1 — Timeframe-independent data collection. Most IB indicators compute statistics directly from chart bars. This means the sample size — and therefore the probabilities — change depending on which timeframe the chart is set to. A 1-minute chart may only hold 16 days of history while a 15-minute chart holds 240, producing completely different numbers from the same lookback setting. This indicator solves that problem by anchoring all data collection inside request.security("5") — a fixed 5-minute reference feed. Probabilities are identical on any chart timeframe.
2 — Exponential decay weighted probability. A raw historical average gives equal weight to a sweep that happened 200 days ago and one that happened last week. This indicator applies exponential decay (factor 0.85 per day of age) so that recent sessions contribute proportionally more to the probability estimate. When market regime shifts, the indicator adapts faster than a simple percentage would.
3 — Range-conditional probability. Every historical IB day is classified as SMALL (<70% of the historical average range), NORMAL (70–130%), or LARGE (>130%). The indicator then computes the IBH and IBL sweep rate specifically for days that match today's size bucket. If today's IB is unusually tight, the conditional column in the table shows the sweep rate from similar tight-range days only — a more relevant reference than the overall average.
4 — First-break direction tracking. The table shows what percentage of historical days saw the IBH break first vs the IBL break first vs both sweeping on the same bar. Over a large enough sample this can reveal directional tendencies for specific instruments and sessions.
5 — Failed retest signal. After a level is swept, price often pulls back to retest it from the other side. If the retesting candle closes back on the swept side (confirming rejection), the level has flipped from resistance to support or vice versa. The indicator detects this condition and plots a colored circle directly on the wick of the confirming bar — one signal per level per day, first confirmed retest only.
How to use it
Add the indicator to any intraday chart (1m through 60m). Set your IB Open and IB Close times to match your instrument's session. Set the Data Cutoff to the time after which you do not want sweeps counted — for US equities, 16:00 ET is appropriate. Increase the Lookback Days to the maximum your plan supports (the tooltip explains approximate limits by plan). The probability labels display inside the IB box as a percentage — green indicates a historically high sweep rate (≥65%), red indicates low (≤35%), and white is neutral. The third column of the data table shows the conditional probability for today's IB size bucket. A teal circle on a bar's low signals a bullish failed retest of the IBH. A red circle on a bar's high signals a bearish failed retest of the IBL. All four alert conditions (IB formed, IBH swept, IBL swept, failed retest) are available for notification.
Notes
Designed and built for MNQ/NQ futures but compatible with any intraday instrument. A minimum of 5 completed historical sessions is required before probability values are shown. Statistics are always computed from completed days only — the current in-progress session is excluded. The failed retest signal requires the sweep to have been established on at least one prior bar before it can trigger, preventing false fires on the original sweep candle itself. Indicator

Market Regime Classifier [EXCAVO]Four-State Probabilistic Regime Detection Using a Hidden Markov Model
The Market Regime Classifier applies a four-state Hidden Markov Model (HMM)
to classify the current market environment as Bullish, Bearish, Volatile, or Sideways.
Rather than using fixed thresholds on ADX or moving average slopes, the model maintains
and continuously updates a probability distribution across all four states on every bar,
producing smooth, low-noise regime identification.
This is not a threshold-based classifier. State probabilities update through Bayesian
forward inference, so regime transitions emerge from the data rather than arbitrary
cutoff values.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ HOW TO USE
Step 1 → Add the indicator to a new pane. The confidence histogram
appears immediately, colored by the current regime.
Step 2 → Read the regime from the histogram color and the dashboard
panel. Blue = Bullish, Red = Bearish, Orange = Volatile,
Gray = Sideways.
Step 3 → Monitor the confidence level. Above 80%, the model has high
conviction. Below 60%, the market is transitioning and both
adjacent states have similar probabilities.
Step 4 → Set up alerts for regime transitions. Each state change fires
on a closed bar only, eliminating repainting.
Step 5 → Check the dashboard for individual state probabilities. When
two states have close values, the market is ambiguous - this is
visible in the dashboard before a formal regime change occurs.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ HOW IT CALCULATES
◆ Data Conditioning
Each bar computes the log return: ln(close / close ). The mean and standard
deviation of log returns are calculated over the lookback period. Both are then
normalized: norm_ret = (log_ret - mean) / stdev, and norm_vol = stdev /
sma(stdev, lookback). This standardization makes the model asset-agnostic,
producing consistent behavior across equities, crypto, and forex without
requiring parameter adjustments per instrument.
◆ Gaussian Emission Likelihoods
Each of the four states has a Gaussian emission function that evaluates how
well the current normalized volatility and return match that state's expected
profile. The emission formula is exp(-(x - center)^2 / width), where x is the
normalized observation, center is the expected value for that state, and width
controls the response range:
Bullish: norm_vol = 1.1, norm_ret = +0.8 (moderate volatility, positive drift)
Bearish: norm_vol = 1.1, norm_ret = -0.8 (moderate volatility, negative drift)
Sideways: norm_vol = 0.7, norm_ret = 0.0 (low volatility, no directional bias)
Volatile: norm_vol = 1.6 x sensitivity (elevated volatility, direction-agnostic)
A state's emission is high when the current bar's profile closely matches its center
and decreases exponentially as the observation diverges.
◆ Bayesian Forward Update
The model maintains four state probabilities (p_bull, p_bear, p_side, p_vola)
initialized at 0.25 each. On every bar, unnormalized posteriors are computed:
un_state = emission(state) x (p_state x 0.9 + sum_others x 0.033). The 0.9
self-transition coefficient gives the model inertia - it stays in the current
state unless emissions consistently support a different one. The 0.033
cross-transition coefficient (approximately (1 - 0.9) / 3) keeps all states
reachable. Posteriors are then normalized to sum to 1.0. The smoothing factor
controls how aggressively each bar's emission result shifts the running
probability, acting as an exponential moving average over the posterior series.
◆ State Classification and Confidence
The active regime is the state with the highest posterior probability (argmax).
Confidence equals this maximum probability expressed as a percentage. A regime
change is detected when the dominant state changes on a confirmed (closed) bar,
which fires all alerts. The dashboard shows all four probabilities simultaneously,
making it possible to observe when the market is approaching a state boundary
before the formal regime label changes.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ WHAT MAKES IT DIFFERENT
◆ Probabilistic State Engine
Most regime classifiers use fixed thresholds: if ADX > 25 then trending, otherwise
ranging. This produces abrupt, oscillating switches at the boundary and gives no
information about conviction. The HMM produces a smooth probability distribution
across all four states simultaneously, with conviction visible at every bar as
an explicit confidence percentage.
◆ Four-State Classification
Two-state models (trending vs. ranging) conflate Volatile markets with trending ones
and miss the distinction between low-activity consolidation and trend exhaustion.
Four states allow separate identification of sustained directional moves
(Bullish/Bearish), low-activity accumulation ranges (Sideways), and high-volatility
uncertainty (Volatile) - conditions that require different position sizing and
strategy selection.
◆ Adaptive Volatility Threshold
The Volatile state's emission center scales with the Volatility Sensitivity input.
This makes the model configurable across asset classes: crypto spends more time at
elevated volatility levels and may benefit from a higher sensitivity value than
equities or forex.
◆ Transition Memory (Inertia)
The self-transition coefficient (0.9) gives the model inertia - a single anomalous
bar cannot flip the regime. The classifier requires consistent evidence across
multiple bars to overcome the self-transition bias. This reduces false transitions
during brief volatility spikes or one-bar outliers.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ DASHBOARD
Real-time panel showing the current model state:
Regime - active state (BULLISH / BEARISH / VOLATILE / SIDEWAYS), colored by type
Confidence - highest state probability as a percentage; highlighted orange above 80%
Bullish - current Bullish state probability
Bearish - current Bearish state probability
Volatile - current Volatile state probability
Sideways - current Sideways state probability
Norm Volatility - normalized volatility ratio; highlighted orange above 1.5 x sensitivity
Smoothing - active smoothing factor (informational)
Legend table (bottom left) explains histogram colors. Both panels toggle in Dashboard settings.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ SETTINGS
HMM Engine
Statistical Lookback - 50 bars (period for log-return mean and stdev; higher = more stable but slower to adapt)
Decision Smoothing - 0.40 (exponential smoothing factor; lower = more stable, higher = more reactive)
Volatility Sensitivity - 1.2 (scales the Volatile state emission center; increase for crypto, decrease for equities)
Visualization
Bullish Color - default blue (histogram and ribbon color during Bullish regime)
Bearish Color - default red (histogram and ribbon color during Bearish regime)
Volatile Color - default orange (histogram and ribbon color during Volatile regime)
Show Regime Ribbon - OFF (colored markers at pane bottom showing regime history)
Background Highlight - ON (subtle tint matching the active regime)
Alerts
JSON Alerts - OFF (enable for bot integration via 3Commas, Wunderbit, etc.)
Dashboard
Dashboard Position - Top Right
Show Dashboard - ON
Show Legend - ON
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
▸ ALERTS
Bullish Regime - dominant state changed to Bullish on bar close
Bearish Regime - dominant state changed to Bearish on bar close
Volatile Regime - dominant state changed to Volatile on bar close
Sideways Regime - dominant state changed to Sideways on bar close
Regime Change - any state transition detected on bar close
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Best regards,
EXCAVO
Disclaimer
Trading involves significant risk. This indicator is a technical analysis tool
and does not constitute financial advice, investment recommendations, or a
guarantee of future results. Past indicator behavior does not guarantee future
performance. Always use proper risk management and your own judgment.
Indicator

Regime Transition Intelligence [AGPro Series]Regime Transition Intelligence
Most regime scripts answer a single question: "what regime are we in right now?". Regime Transition Intelligence is designed to answer a different, more actionable set of questions: how long does this regime usually last, how close to its typical end is it, how likely is it to flip within the next N bars, and where does it historically go when it does flip. Instead of treating the current regime as a standalone snapshot, it builds a living, self-calibrating statistical profile of the symbol's own regime behavior and presents it in a compact on-chart dashboard.
The engine runs on three independent axes — Trend Strength (Kaufman Efficiency Ratio + ADX), Chop Risk (Choppiness Index + inverse trend), and Volatility (ATR% normalized over a user-defined lookback). Each axis is classified as LOW / MID / HIGH, either with fixed 33/67 thresholds or with an adaptive percentile rank engine that learns the symbol's own statistical envelope over a rolling window. The three axes are then combined into a discrete regime state: TREND, MIXED, or RANGE / CHOP.
🟦 Overview / What it does
Regime Transition Intelligence is a single-pane overlay indicator that continuously classifies the market into one of three regimes and then layers a full transition intelligence stack on top of that classification:
- A per-regime dwell-time distribution learned from the chart's own completed regime blocks
- A Bayesian-style flip probability that answers "how likely is a regime change within the next N bars, given the current age"
- A 3x3 transition matrix that ranks the most likely next regime with a secondary fallback
- A fatigue score comparing the current regime's age to its historical mean (FRESH / MATURE / EXTENDED)
- A confidence decay tracker that shows whether conviction is BUILDING, STABLE, or FADING within the current regime block
- A compact history ribbon showing the last completed regime blocks with their durations
- Higher-timeframe alignment with a SYNC / DIV indicator and a live beacon at the right edge of the chart
All of this is delivered inside a single configurable dashboard, a directional transition marker layer on the chart, optional regime tint and candle coloring, and a right-edge beacon summarizing the current state.
🟣 Unique Edge / Why it is not a basic mashup
Standard regime indicators report the current state and stop there. Regime Transition Intelligence adds six distinct statistical layers that together form a transition-aware view:
1. Dwell Time Statistics — the script stores every completed regime block in a rolling array (configurable depth) and continuously updates running mean, running variance, running max, and running count per regime code. Statistics are only shown after a minimum number of blocks per regime have been collected, so the user always knows when the sample size is still too small.
2. Exponential Hazard Flip Probability — the baseline flip probability uses P(flip within H bars) = 1 - exp(-H / mean), a standard survival-analysis construction assuming constant hazard. The result is then fatigue-adjusted: if the current age is far above the historical mean, the probability is boosted; if the regime has just started, the probability is damped. The final value is capped at 95% to avoid certainty claims.
3. Transition Matrix — a 3x3 counter records every observed regime transition and is read as a conditional distribution: "given the current regime ends, which regime is it most likely to move to, and what is the runner-up". Both the top candidate and the secondary candidate are displayed with their percentages.
4. Fatigue Score — the ratio of the current age to the historical mean is bucketed into three zones (FRESH, MATURE, EXTENDED) using user-configurable thresholds. It tells the user whether the current regime is still in its early lifecycle or already past its typical end.
5. Confidence Decay Tracker — conviction in the current regime is sampled at the start of each new block and compared to the current conviction. The delta is classified as BUILDING, STABLE, or FADING, which gives an early read on whether the regime is strengthening or losing its grip.
6. History Ribbon — the last N completed regime blocks are compressed into a single compact line such as "C2·M4·C8·M1·M7*", where letters are regime codes and numbers are bar counts, with the current block marked by an asterisk. It gives immediate context on recent regime rhythm at a single glance.
None of these layers is a repackaged classic indicator. They are built on top of a trend / chop / volatility engine but deliver information that is categorically different from a simple "regime yes / no" readout.
🟢 Methodology / Conceptual data flow
1. Feature extraction. Kaufman Efficiency Ratio (net move over lookback divided by summed absolute moves) and normalized ADX are combined into a trend score. The Choppiness Index is normalized against its operating range and blended with inverse trend to produce a chop score. ATR as a percentage of price is normalized against its own lookback min/max to produce a volatility score.
2. Classification. Each score is mapped to LOW / MID / HIGH using either fixed thresholds (Static mode) or percentile rank over an adaptive lookback (Adaptive mode). The three bands are combined into a discrete regime state: TREND when trend is HIGH and chop is LOW, RANGE / CHOP when chop is HIGH, and MIXED otherwise.
3. Block tracking. Every time the regime state changes on a confirmed bar, the previous block is closed: its duration is pushed to a rolling history array and added to the running sum / sum-of-squares / count / max for its regime code. When the history array exceeds its configured depth, the oldest block is popped and its contribution is subtracted from the running totals, which keeps the statistics adaptive and non-expanding.
4. Transition matrix update. When a block closes into a new regime, the 3x3 counter is incremented at the corresponding cell, and the row total is incremented. The conditional distribution for the current regime is read from its row at display time.
5. Statistical outputs. Mean dwell, fatigue ratio, exponential-hazard flip probability, fatigue-adjusted flip probability, top and secondary next regimes, and confidence delta are all derived from the running state and rendered into the dashboard.
6. Higher-timeframe alignment. The same three-axis engine is run on a user-selected higher timeframe via request.security and compared against the current-timeframe regime; the result appears as SYNC or DIV in the header and as an optional HTF row in the dashboard.
🔔 Signals & Alerts / Interpretation
Regime Transition Intelligence is a state-mapping and statistical context tool rather than a directional buy / sell engine. The main on-chart events are:
- Regime Shift — fires when the regime state changes on a confirmed bar
- High Flip Probability — fires when the fatigue-adjusted flip probability crosses a high threshold
- Regime Fatigue Extended — fires on the transition into the EXTENDED fatigue zone
- Confidence Fading — fires on the transition into the FADING confidence zone
How to read the panel:
- Summary + Age tells the user which regime is active and how long it has been active.
- Dwell Context compares the current age to the historical mean in the form "age / mean · % of typical lifespan".
- Fatigue summarizes that comparison as FRESH, MATURE, or EXTENDED.
- Flip Probability reports the statistical odds of a regime change within the user-defined horizon.
- Next Likely names the most probable next regime with its percentage and a secondary fallback.
- Confidence and Conf Decay together tell the user whether the current read is reliable and whether conviction is rising or fading.
- History gives quick situational awareness of recent regime rhythm.
None of these rows should be interpreted as a trade instruction. They are a context layer meant to be combined with the user's own structure and entry framework.
🎛️ Key Inputs
Regime Engine Core — Trend Persistence Length, DMI/ADX Length, Chop Length, ATR Length, Volatility Normalize Lookback.
Adaptive Boundaries — Band Classification Mode (Adaptive / Static), Adaptive Lookback, Adaptive Low / High Percentile.
Transition Intelligence — Regime History Depth, Flip Probability Horizon, Min Blocks Before Stats Activate, Fatigue Fresh / Extended thresholds.
HUD — Display Mode (PRO / MINIMAL), HUD Position, Text Size, transparency controls, individual row toggles, history ribbon length.
Add-ons — Chart Regime Tint, Regime Candle Coloring (Soft / Strong), HTF Peek Timeframe, Transition Markers (location, cooldown, stagger, size, ATR offset), Live Regime Beacon (position, size, stats toggle).
🧭 How to use
1. Add the script to any chart and timeframe. The engine is tuned to work from 15m up to Daily; very low timeframes on illiquid instruments can produce unstable regime blocks and are not the intended use case.
2. Give the script time to collect blocks. Statistics stay in N/A until the configured minimum number of completed blocks per regime has accumulated. On a fresh chart or an illiquid instrument this is expected behavior, not a bug.
3. Read the dashboard top-down. Start with the three axis rows to understand the current market shape, then move to Summary and Age to see what is active and for how long, then use Dwell / Fatigue / Flip / Next Likely to place the current regime inside its historical distribution, and finally use Conf Decay and HTF to sanity-check reliability and alignment.
4. Treat EXTENDED fatigue and high flip probability as context, not as a reversal signal. Regimes can remain in the EXTENDED zone for a while before actually flipping; the statistical profile is descriptive, not deterministic.
5. Combine with structural context. The script does not know about support / resistance, order blocks, or news. It only knows about the symbol's own regime rhythm. Use it as a regime-aware filter on top of the user's existing framework.
⚠️ Limitations & Transparency
This is not a strategy and not a complete trading system. It does not predict price direction and does not generate buy or sell signals. All statistics are estimated from a rolling history of the chart's own regime blocks, so they are sensitive to the chosen engine parameters, the timeframe, and the symbol; different timeframes and different instruments will produce different statistical profiles, and that is by design.
The exponential-hazard flip probability assumes a constant hazard within the current regime, which is a simplification. Real-world regime durations are not perfectly memoryless and the fatigue multiplier is a heuristic correction, not a formal model. The probability is capped at 95% on purpose, because even a heavily aged regime cannot be considered a certainty and the script deliberately avoids certainty language.
The transition matrix is read as a conditional frequency over completed blocks; it is informative about the symbol's own past behavior and should not be interpreted as a forward-looking forecast. Very small samples produce unstable conditional probabilities, which is why stats stay in N/A until a minimum number of blocks is collected.
Regime classification itself reacts to confirmed bars and can change as new data arrives, which is expected for any regime filter. Users who prefer fully non-repainting alerts should rely on the barstate.isconfirmed-gated alert conditions provided.
📜 Risk Disclosure
Trading involves substantial risk of loss and is not suitable for every investor. Past performance is not indicative of future results. This indicator is provided for educational and analytical purposes only and should not be interpreted as financial advice, an investment recommendation or a solicitation to trade. Always combine multiple forms of analysis, manage position size responsibly, and never risk capital you cannot afford to lose. Indicator

Monte Carlo Risk Geometry Simulator [Aslan]Thanks to @KioseffTrading for the polyline retracing system and the plotting system as a whole🙏
♦️ What This Script Does
This is a Monte Carlo simulator for visualising and calculating the probability of a return based on risk geometry of the model (Risk %, RR, WR). It assesses the probability of returns by generating hundreds or thousands of possible outcomes using your win rate, risk-reward, and position sizing. Each line you see is a different plausible “future,” showing how your account could realistically evolve.
🔶 How To Use It
Input your strategy stats, run a large number of simulations, and focus on three things: how wide the equity curves spread, how deep drawdowns get, and the percentage of profitable outcomes. Then adjust your model and repeat.
🔷 Application in Prop Firm evaluations
Using the threshold system, you can see what risk geometry is most likely to pass a prop firm evaluation. Suprisingly, the most probable geometry for passing an eval can sometimes have a negative expected value!
♦️ Bottom Line
This script helps you move from “how much can I make?” to “how likely am I to profit?”
🔎 Monte Carlo Simulations Explained
Monte Carlo simulations are a method of modeling uncertainty by running many random versions of the same system to see all possible outcomes. In trading, instead of assuming one fixed result, it repeatedly simulates sequences of wins and losses based on your strategy’s statistics (like win rate and risk-reward). This creates a distribution of potential equity curves, showing not just what did happen, but could happen. It’s essentially a way to test probability and survival under randomness rather than relying on a single backtest. Monte Carlo simulations are widely used on quant trading desks around the world to model uncertainty, test strategy robustness, and estimate the probability distribution of trading outcomes under real-world randomness. Indicator

Hash Dispersion Cone## Overview
The **Hash Dispersion Cone** is a forward-projecting statistical probability envelope built on realized volatility. Anchored to the current bar's close price, it projects where price is statistically expected to trade over the next N bars using log-normal volatility scaling — the same mathematical framework used by professional options desks and quantitative risk managers.
This is not a buy/sell signal generator. It is a **probability map** — a live, continuously recalculating field that shows the market's statistical boundaries given current realized volatility. When volatility is low, the cone is tight. When volatility is expanding, the cone widens in real time.
> *"Know your range before the market shows it to you."*
> — Hash Capital Research
---
## How It Works
### The Mathematics
The cone is constructed using the **square-root-of-time rule**, a foundational principle of financial mathematics. At each forward bar `t`, the projected price boundaries are calculated as:
```
Upper_k(t) = AnchorPrice × exp( +k × σ × √t )
Lower_k(t) = AnchorPrice × exp( −k × σ × √t )
```
Where:
- `k` = standard deviation multiplier (1 for 1σ, 2 for 2σ)
- `σ` = realized volatility per bar (selected method)
- `t` = number of bars forward
Using the **log-normal form** is intentional and correct. It keeps the cone asymmetric in price space — the upside boundary is always further from anchor than the downside boundary by an equal percentage amount. This reflects how asset prices actually behave: they cannot go below zero, but can theoretically rise without limit.
### Why the Cone Moves With Price
The cone repaints every bar because it is always anchored to the **current close**. This is by design. It answers the question: *"Given what volatility is right now, where could price go from here?"* — not where it could have gone from a past bar.
---
## Volatility Methods
Three realized volatility estimators are available. Each has distinct statistical properties suited to different market conditions.
### Close-to-Close (Default)
The standard log-return standard deviation:
```
σ = stdev( ln(Close / Close ), lookback )
```
Most widely understood. Can underestimate volatility on assets that gap frequently or have large intrabar swings. Best for: **daily timeframes, equities, stable assets**.
### Parkinson (High-Low)
Uses the high-low range instead of close-to-close returns:
```
σ² = mean / (4 × ln2)
```
Approximately **5x more statistically efficient** than Close-to-Close for the same lookback period. Captures intrabar volatility that close-to-close misses. Best for: **crypto, commodities, FX — any asset with large intrabar ranges**.
### Garman-Klass (OHLC)
The most efficient of the three estimators, using all four price points:
```
σ² = mean
```
Most accurate for intraday analysis where the open-to-close gap carries information. Best for: **intraday timeframes (1H, 4H), equities with significant opening gaps**.
---
## Inputs Reference
### Volatility Calculation
| Input | Default | Description |
|---|---|---|
| Lookback Period | 30 | Bars used to calculate σ. Lower = more reactive. Higher = smoother. |
| Volatility Method | Close-to-Close | Estimator used. See Volatility Methods above. |
| Vol Trend MA Length | 10 | SMA length applied to σ for regime classification. |
**Lookback Tuning Guide:**
- `10–20` bars → reactive, tracks recent volatility closely, cone resizes quickly
- `30` bars → balanced default, smooths out single-spike distortions
- `60–100` bars → slow-moving, regime-level volatility, stable cone width
### Projection
| Input | Default | Description |
|---|---|---|
| Forward Bars | 15 | How many bars ahead the cone projects. |
| Show 1σ Band | On | Displays ±1σ boundary (~68% probability zone). |
| Show 2σ Band | On | Displays ±2σ boundary (~95% probability zone). |
| Show Midline Anchor | On | Dotted horizontal line at anchor price. |
**Forward Bars Tuning Guide:**
- `5–10` bars → scalping and intraday setups
- `10–20` bars → swing trading (recommended for 4H/Daily)
- `20–50` bars → position trading and options expiry targeting
**Important:** Doubling forward bars does NOT double the projected range. Due to the √t rule, doubling projection bars widens the cone by only ~41%.
## Visual Guide
### Band Colors and Meaning
```
+2σ ──────────────────────────── Crimson solid (outer extreme, ~95%)
░░░░ TEAL FILL (upside risk zone) ░░░░
+1σ - - - - - - - - - - - - - - Green dashed (primary upside boundary, ~68%)
▓▓▓▓ NAVY FILL (highest-probability core) ▓▓▓▓
MID ····························· Grey dotted (anchor / flat scenario)
▓▓▓▓ NAVY FILL (highest-probability core) ▓▓▓▓
−1σ - - - - - - - - - - - - - - White dashed (primary downside boundary, ~68%)
░░░░ MAGENTA FILL (downside risk zone) ░░░░
−2σ ──────────────────────────── Crimson solid (outer extreme, ~95%)
```
### Three-Layer Fill System
**Navy Core (±1σ interior):** The highest-probability zone. Statistically, ~68% of all future closes are expected to land here. This is where price "wants" to stay in a low-volatility regime.
**Teal Upside Zone (+1σ to +2σ):** The upside risk corridor. Price entering this zone is statistically elevated — possible, but in the outer 14% of expected outcomes.
**Magenta Downside Zone (−1σ to −2σ):** The downside risk corridor. Mirror of the teal zone. Price here signals a statistically significant down-move.
---
## Trading Applications
### 1. Cone Width as Regime Filter
The most important signal is the **width of the cone itself**, not where price is within it.
- **Tight cone** = low volatility, compressed range → range-bound playbook (fade edges, mean revert to midline)
- **Wide cone** = high volatility, expanded range → momentum playbook (ride direction, wider stops)
Never take a counter-trend trade in a wide, expanding cone. Never chase a breakout in a tight, contracting cone.
### 2. Price at 1σ Edge = Mean Reversion Setup
When price reaches the projected +1σ or −1σ label price, it has statistically entered the outer 32% of expected outcomes.
**Setup:**
```
Condition 1: Vol Regime is STABLE (─)
Condition 2: Price has reached the ±1σ label level
Condition 3: Rejection candle confirms (wick, doji, engulf)
Entry: Fade the move back toward midline
Target: Anchor price (midline)
Stop: Just beyond the ±2σ label
R:R: Typically 2:1 to 3:1 depending on cone width
```
### 3. 2σ Touch = Extreme Signal
A touch of the ±2σ boundary represents a 2-standard-deviation move. Statistically, only ~5% of future closes are expected to exceed this level.
- In a **stable** or **contracting** regime: high-conviction mean reversion entry with defined risk to the 2σ line
- In an **expanding** regime: possible breakout continuation — wait for candle confirmation before fading
- Use the 2σ label price directly as a hard stop level for trades taken inside the cone
### 4. Vol Regime Arrow as Trade Filter
The regime classification in the dashboard acts as a meta-filter over all other signals.
- **▲ EXPANDING (red):** Do not counter-trend trade. Only take momentum entries in the direction of the move or stay flat. Cone edges are likely to be broken.
- **▼ CONTRACTING (green):** Volatility is compressing. A breakout is loading. Watch for the first expansion candle and trade the direction of the break. This is often the highest R:R setup the cone generates.
- **─ STABLE (white):** Range conditions active. Mean reversion setups at σ edges are highest probability in this state.
### 5. Stop Placement Reference
The σ label prices at the cone's right edge provide statistically-grounded stop levels:
- **Conservative stop:** Beyond ±2σ label (95% of moves contained)
- **Standard stop:** Beyond ±1σ label (68% of moves contained)
- **Tight stop:** A fixed percentage of the ±1σ distance
This gives every trade a volatility-adjusted stop rather than an arbitrary fixed-pip or percentage stop.
---
## Timeframe Recommendations
| Timeframe | Lookback | Forward Bars | Vol Method | Best Use |
|---|---|---|---|---|
| 5m / 15m | 20 | 10 | Garman-Klass | Scalping entries |
| 1H | 30 | 15 | Parkinson or GK | Intraday swing |
| 4H | 30 | 15 | Parkinson | Swing trading (default) |
| Daily | 30–50 | 20 | Close-to-Close | Position trading |
| Weekly | 20 | 10 | Close-to-Close | Macro range framing |
---
## Asset Class Notes
**Crypto (BTC, ETH, SOL, etc.):**
Parkinson is recommended over Close-to-Close due to large intrabar ranges common in 24/7 markets. Cone will be noticeably wider than equities at equivalent timeframes, reflecting structurally higher realized volatility. The 2σ touch setup is especially reliable on 4H BTC during STABLE regimes.
**FX:**
Parkinson works well. Forward Bars of 10–15 on 4H aligns well with typical intraweek swing durations. Cone width is generally tighter than crypto, making σ edge touches more frequent.
**Equities / Indices:**
Garman-Klass recommended for intraday. Close-to-Close is standard for daily and above. Be aware that equity close-to-close can underestimate true vol during earnings season — consider switching to Garman-Klass temporarily.
**Commodities:**
Parkinson preferred. Energy and agricultural commodities have gap and range behavior similar to crypto.
---
## Technical Notes
- The cone redraws on every bar close. It is anchored to the current close and always projects forward from the most recent confirmed price. This is expected behavior — not a repaint flaw.
- Fills are capped at 16 segments per zone to remain within Pine Script's linefill object limit (~50 total). At default 15 forward bars, all fills render completely.
- The annualization factor is automatically adjusted for timeframe: Daily (√252), Weekly (√52), Monthly (√12), and intrabar (derived from `timeframe.in_seconds()`).
- All price labels use comma-formatted output (e.g., `74,161.34`) for readability at large price scales.
---
## Disclaimer
The Hash Dispersion Cone is an educational and analytical tool. Statistical probability does not guarantee any specific price outcome. All trading involves risk. Past statistical behavior does not guarantee future results. This indicator does not constitute financial advice.
---
*Published on PulseWire by Hash Capital Research * Indicator

Naive Bayes DNA Heatmap | GainzAlgoThe Naive Bayes Volume Heatmap is a predictive analytical suite that moves beyond traditional lagging indicators. While a standard RSI or MACD simply tells you where price has been, this system uses Gaussian Machine Learning to determine the statistical probability of where price is going.
By analyzing the Volume of a candle, the internal distribution of volume, delta, and price force, the indicator visualizes market sentiment as a multi-layered heatmap. It allows traders to see whether the current price action is backed by institutional flow or is simply noise.
Core Logic: The Naive Bayes Engine
The brain of the system is a Gaussian Naive Bayes (GNB) classifier. This is a machine learning algorithm that calculates the probability of an event based on prior conditions.
How it Learns
The model continuously "trains" itself on a lookback window (default 500 bars). It analyzes two primary features:
Intensity (Feature 1): Relative Volume (1m mode) or Net Delta (Footprint mode).
Directional Force (Feature 2): The relationship between price spread and volume (1m mode) or POC Distance (Footprint mode).
Here is the self contained function that does the heavy lifting of the probability analysis:
f_naive_bayes(float feat1, float feat2, float target, int len) =>
m1_f1 = ta.sma(target > 0 ? feat1 : na, len), m1_f2 = ta.sma(target > 0 ? feat2 : na, len)
m0_f1 = ta.sma(target <= 0 ? feat1 : na, len), m0_f2 = ta.sma(target <= 0 ? feat2 : na, len)
v1_f1 = math.pow(ta.stdev(target > 0 ? feat1 : na, len), 2), v1_f2 = math.pow(ta.stdev(target > 0 ? feat2 : na, len), 2)
v0_f1 = math.pow(ta.stdev(target <= 0 ? feat1 : na, len), 2), v0_f2 = math.pow(ta.stdev(target <= 0 ? feat2 : na, len), 2)
p1 = nz(ta.sma(target > 0 ? 1.0 : 0.0, len), 0.5)
l1 = f_pdf(feat1, nz(m1_f1), nz(v1_f1)) * f_pdf(feat2, nz(m1_f2), nz(v1_f2)) * p1
l0 = f_pdf(feat1, nz(m0_f1), nz(v0_f1)) * f_pdf(feat2, nz(m0_f2), nz(v0_f2)) * (1.0 - p1)
prob = nz(l1 / (l1 + l0 + 0.000001), 0.5)
This function is the engine of the indicator. It implements a Gaussian Naive Bayes Classifier directly in Pine Script to calculate the real-time probability of a bullish move.
Here is a breakdown of how this code processes market data:
Class Separation (The "M" and "V" Variables)
The function splits historical data into two buckets based on the target (Price Action):
Bucket 1 (Bullish): Data from bars that closed green.
Bucket 0 (Bearish): Data from bars that closed red.
It then calculates the Mean (m) and Variance (v) for each feature within those buckets. This creates two distinct "profiles"—essentially a mathematical fingerprint of what a Bullish bar looks like versus a Bearish one.
Bayesian Inference (The Result)
Finally, it applies Bayes' Theorem to combine these likelihoods with the Prior Probability (p1)—which is simply the historical win rate of green bars over the lookback period.
The final prob is a normalized value between 0 and 1. If the result is 0.85, the model is signaling an 85% statistical probability that the current market conditions align with historical bullish reversals.
The Math
As discussed above, the engine uses the Probability Density Function (PDF) to map these features onto a bell curve. It asks: "In the past, when we saw this specific volume intensity and this specific price force, how often did the next bar close green versus red?"
The result is a Win Probability %. If the probability is >50%, the bias is Bullish; <50% is Bearish.
The Heatmap
The Heatmap is a vertical stack of 20 independent probability layers.
Multi-Horizon Smoothing: Each layer represents a different generation of the Naive Bayes calculation, ranging from ultra-fast (5-bar smoothing) to long-term (100-bar smoothing).
Specialized Features
The Power Index (The White Line)
The Power Index is your Confluence Meter . It scans all 20 layers of the data and counts how many are currently signaling a trend above a 60% threshold.
A spiking Power Index indicates that the trend is synchronizing across all time horizons, a high-probability entry signal.
Footprint Mode vs. 1-Minute Mode
1-Minute Precision: When active, the script uses request.security_lower_tf to deconstruct the current chart bar into 1-minute slices. It finds the "hidden" intent inside the candle that standard indicators miss.
Footprint Analysis: This mode hooks into raw Exchange Order Flow. It calculates Aggressive Buying vs. Aggressive Selling to feed the Naive Bayes engine the most "raw" data possible.
The sidebars: Unique to Footprint mode, these wide neon bars appear to the right of the heatmap.
Real-Time Volume Scaling: The bars grow and shrink based on the current bar's Buy/Sell volume ratio.
Divergence Spotting: If the Heatmap is bright Aqua (Bullish) but the Pink Sell Box is 80% full, you are witnessing Absorption, big players are absorbing the selling, often leading to a massive squeeze.
How to Use the Suite
The Elite Entry
Identify the Bias: Check the NB Probability in the table. You want to see >65% for a high-probability trade.
Confirm the Match: Ensure the heatmap layers are expanding (moving from the dark center toward the bright edges).
Check the Power Index: Wait for the white line to curve upward, confirming momentum is stacking.
The Signal: When the "NB SIGNAL" cell in the table flips to ELITE LONG or ELITE SHORT, the statistical edge is at its peak.
The Elite Exit
Exit when the inner layers of the heatmap turn back to Midnight Charcoal or the opposite color. This indicates that the immediate heartbeat of the trend has faded, even if the longer-term layers are still colored. Indicator

Wraith Protocol OscWhat Is This Indicator?
Rather than plotting raw price, it normalizes the entire lookback range onto a clean 0–100 scale, making it easier to visualize where price currently sits relative to its recent high and low — and how Fibonacci levels, volume clusters, and momentum all align in one unified pane.
Core Components & What They Do=>
1. Normalized Price Axis (0–100 Scale)
The indicator rescales price so that the lowest point of the lookback period = 0 and the highest = 100. This instantly tells you whether price is near the bottom, middle, or top of its recent range without doing any manual math.
2. Fibonacci Levels-
Eleven key Fibonacci ratios are plotted across the normalized range: -0.13, 0, 0.13, 0.236, 0.382, 0.5, 0.618, 0.786, 0.886, and 1.0, plus 1.13. Each level shows the actual price value alongside the ratio and normalized position. These act as dynamic support and resistance zones within the lookback window.
3. Volume Profile-
A horizontal volume profile is plotted to the right of the range box, split into buy volume (bullish candles) and sell volume (bearish candles) per price bucket. The Point of Control (POC) — the price level with the highest total volume — is highlighted in red. This is the most important level on the chart because it shows where the most trading activity has occurred.
4. Fibonacci Gap-Probability Arrows-
This is the signal engine. At the current bar, the indicator measures the gap between the current normalized price and the nearest Fibonacci level above and below. It then calculates a probability: if price is very close to the lower Fibonacci level and far from the upper one, the upward probability score is higher, and vice versa. The ▲ and ▼ arrows show these gap distances and probability percentages live on the chart.
Visual reinforcement — the dominant direction arrow renders in full brightness, the weaker direction fades to 50% opacity, so the bias is immediately readable without even reading the numbers.
Reading it in practice (both for long and short):
prob 60–70% → moderate bias, worth noting
prob 70–80% → strong bias, consider positioning
prob 80%+ → price is almost sitting on a level, high-conviction setup zone
5. Info Table-
A dashboard table showing: total candle count in the lookback, the largest single buy and sell candle price, buy/sell volume rates as percentages, trend bias (Bullish/Bearish), Fibonacci-derived support (0.886 retracement) and resistance (0.618 retracement), estimated P&L between those two levels, and the final directional Estimate (Up/Down/Neutral) derived from the probability arrows.
How to Trade with It=>
Step 1 — Read the Estimate first.
The bottom-right cell of the info table shows "Up (X%)" or "Down (X%)". This is your directional bias for the current bar. A probability above 60% is a meaningful lean; above 70% is a strong signal.
Step 2 — Confirm with Volume Profile.
Check where the POC line sits relative to current price. If the Estimate says "Up" and price is below the POC, the POC acts as a magnet — that is a higher-conviction long setup. If price is above the POC and the Estimate says "Down", look for mean-reversion short opportunities.
Step 3 — Use Fibonacci levels as entry and exit zones.
The 0.382, 0.5, and 0.618 levels are the most commonly respected. A bounce off the 0.618 normalized level (meaning price is near 38 on the 0–100 scale) with a bullish volume profile and an "Up" Estimate is a textbook long entry. Target the 0.382 or 0.236 level above for exits.
Step 4 — Check Buy Rate vs Sell Rate.
If Buy Rate is above 55% and the trend reads "Bullish", that confirms institutional buying pressure within the lookback window. Avoid longs when Sell Rate dominates even if the Estimate temporarily reads "Up" — it may just be a brief pullback within a downtrend.
Step 5 — Support and Resistance for Stop Placement.
The table's Support level (0.886 retracement) is a logical stop-loss zone for long trades. If price closes below it, the bullish thesis is invalidated. Resistance (0.618) is the first profit target.
Recommended Timeframes=>
The indicator is highly adaptable, but it performs best under these conditions:
Intraday Scalping — 3min to 15min: Use a lookback of 30–50 candles. The probability arrows update quickly and help identify short-term Fibonacci bounces within the session range.
Intraday Swing — 15min to 1 Hour: The default 60-candle lookback works well here. This is the sweet spot for the indicator — enough data for a meaningful volume profile while still being reactive to intraday structure.
Swing Trading — 4 Hour to Daily: Increase the lookback to 80–120 candles. Fibonacci levels at this timeframe represent multi-day support and resistance and are widely watched by institutional participants.
Avoid on tick charts or very low-volume instruments — the volume profile becomes unreliable without sufficient trade data.
Practical Tips=>
When the normalized close is between 40 and 60 (mid-range), treat signals as lower confidence — price is in no-man's-land between major Fibonacci levels.
The dominant volume bucket highlighted in teal/cyan on the profile is the strongest magnet zone. Price frequently returns to it.
Enable "Extend to Right Edge" on Fibonacci levels when using this for swing trades so you can see where levels project into future candles.
Flipping the Volume Profile to the left is useful when you want to keep the right side of the chart clean for price action reading.
⚠️ Disclaimer:
This indicator is provided strictly for educational and informational purposes only. It does not constitute financial advice, investment advice, or a recommendation to buy or sell any financial instrument. Past performance of any signal or strategy derived from this tool does not guarantee future results. All trading involves substantial risk of loss, including the possible loss of your entire invested capital. The probability estimates shown are purely mathematical calculations based on Fibonacci gap distances and do not predict future price movement. Always conduct your own due diligence, apply proper risk management, and consult a licensed/SEBI regd. financial advisor before making any trading decisions. (Pls read the entire description above) Happy Trading !! 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
