AI K-Means Clustering [TradingFinder] Machine Learning Zones🔵 Introduction
K-Means clustering is an unsupervised machine learning algorithm that groups similar data points around repeatedly updated cluster centers. Each observation is assigned to its nearest center, the centers are recalculated, and the process continues until the clusters converge. In financial market analysis, this structure can separate recurring patterns in price movement, trend direction, volume pressure, and volatility without depending entirely on fixed thresholds. As a result, the same candle may be interpreted differently in a quiet market, a directional trend, or a volatility shock, because its meaning is evaluated in relation to the surrounding market data.
This TradingView indicator applies K-Means machine learning through several connected analysis modules. The Market State engine studies trend bias, price slope, and relative volume pressure to classify the current market regime as an active bullish trend, active bearish trend, soft bullish trend, soft bearish trend, neutral range, or low-volume range. It also compares the current cluster with the dominant cluster across recent candles, helping the trend classification remain more stable when a single large candle, temporary spike, or short-lived price reversal appears.
The Price Zones engine clusters pivot points, historical highs, and historical lows to create dynamic K-Means support and resistance zones. Traders can display all price cluster centers, the nearest K-Means zone, or separate support and resistance lines. Raw, Smooth, and Locked Steps modes control how quickly the zones respond to new price data, while the nearest line changes color according to the detected bullish, bearish, or ranging market state. A Stochastic moving average heatmap is also plotted between the outer zones, adding a visual layer for momentum, overbought and oversold conditions, trend strength, and changing market pressure.
The indicator also combines volatility analysis, price action recognition, cluster quality scoring, and alert conditions. The volatility engine uses normalized ATR, candle range, and return volatility to identify low-volatility compression, normal volatility, high volatility, and volatility shock. The Price Action module evaluates the latest closed candle for bullish and bearish zone breakouts, rejection patterns, momentum candles, and indecision near a clustered price level. A dedicated Quality and Reliability section then measures zone strength, cluster fit, zone width, price distance, and RMSE, helping traders understand whether the current machine learning calculations are strong enough for practical analysis or should be treated only as additional market context.
🔵 How to Use
The easiest way to read this indicator is not to search for one isolated green or red message. Its main value comes from combining several layers of market information: K-Means market state classification, adaptive price zones, price action, volatility conditions, and calculation quality. Each module answers a different question, and the strongest setups usually appear when several modules point in the same direction.
Start with the Market State row in the analysis table. This module applies multidimensional K-Means clustering to trend bias, trend slope, and relative volume pressure. The current cluster shows where the latest market data has been assigned, while the dominant cluster represents the most frequent cluster across the selected state window. The Strength value shows how dominant that cluster is within the recent sample.
The Market State analysis can return the following conditions :
Active Bullish Trend : Positive trend structure supported by stronger relative volume.
Soft Bullish Trend : Positive directional structure, but with weaker participation or less convincing momentum.
Active Bearish Trend : Negative trend structure supported by stronger relative volume.
Soft Bearish Trend : Bearish directional structure that still requires confirmation.
Neutral Range : Trend bias and slope are not strong enough to define a clear direction.
Low-Volume Range : Sideways structure accompanied by relatively weak volume participation.
The distinction between the current and dominant cluster is important. A single large candle can move the current data point into another cluster, but the dominant state may remain unchanged if the broader recent structure still belongs to the previous market regime. This can help prevent every temporary spike, pullback, or abnormal candle from being interpreted as a complete trend reversal.
The next section is Price Zones. Here, K-Means clustering is applied to historical pivot levels, sampled highs, and sampled lows. Instead of drawing a level from only one swing point, the algorithm groups similar historical prices and calculates a center for each price cluster. These cluster centers become adaptive K-Means price zones that may act as support, resistance, breakout references, or reaction areas.
The table displays :
Near : The cluster currently closest to price.
Strength : The percentage of sampled price levels assigned to the nearest cluster.
Nearest : The closest stabilized K-Means zone.
Support : The nearest valid cluster center below the market.
Resistance : The nearest valid cluster center above the market.
A higher Zone Strength means a larger share of the sampled levels belongs to that cluster. However, this should not be interpreted as a guaranteed support or resistance level. It simply shows that more historical observations were grouped around the same price area.
On the chart, users can choose between three visual approaches. Show All K-Means Zone Centers plots the complete set of clustered price levels. Show Nearest Zone displays only the closest stabilized level, while Show K-Means Support/Resistance plots the nearest support and resistance separately.
The nearest line changes color with the detected market state :
Green indicates a bullish market state.
Red indicates a bearish market state.
Blue indicates a neutral or ranging market state.
The zone lines can also be displayed in Raw, Smooth, or Locked Steps mode. Raw mode follows newly calculated cluster centers directly. Smooth mode gradually moves the plotted level toward the new center, creating a more stable visual structure. Locked Steps mode keeps the previous level in place until the new cluster center has moved by a meaningful ATR-based distance.
Between the outer K-Means zones, the indicator draws a Stochastic Moving Average Heatmap. This heatmap is based on a 100-period Stochastic value smoothed with a 50-period exponential moving average. Lower smoothed Stochastic values appear toward the blue and purple side of the color range, middle values move through cyan and green, and higher values progress toward yellow, orange, and red. The heatmap should be read as a visual momentum layer rather than as a standalone buy or sell signal.
The Price Action row studies candle structure in relation to the nearest K-Means zone and recent price behavior. It uses the candle body, upper wick, lower wick, previous high, previous low, and the location of the nearest zone to identify several possible conditions:
Bullish or bearish zone breakout.
Bullish or bearish rejection from a zone.
Bullish or bearish momentum candle.
Indecision at a K-Means zone.
General indecision.
No clear price action.
The Body, Upper Wick Ratio, and Lower Wick Ratio values represent the relative size of the candle body, upper wick, and lower wick compared with the candle’s total range. These values help explain why the indicator classified a candle as momentum, rejection, or indecision. Price Action should always be read together with Market State and Volatility. For example, a bullish momentum candle inside a bearish market state does not automatically create a bullish setup.
The Volatility module runs a separate K-Means model using normalized ATR, candle range percentage, and return volatility. The clustered volatility data is then used to identify four practical market conditions:
Low Volatility Compression : Market movement has contracted and a future expansion may develop;
Normal Volatility : Current movement is close to its recent reference level;
High Volatility : Price movement is elevated and may require smaller position size or wider risk parameters;
Volatility Shock : Abnormal expansion is present, making immediate entries more sensitive to slippage, unstable movement, and rapid reversals.
Volatility acts as a risk filter for the rest of the analysis. Even when Market State and Price Action point in the same direction, a High Volatility or Volatility Shock reading should reduce the confidence placed on an immediate entry.
Finally, review the Quality row. This section provides an internal assessment of how compact, representative, and consistent the current K-Means calculations are. It does not measure future profitability or win rate. Instead, it evaluates the statistical structure of the active price clusters.
The main values include :
Price Q : A combined score based on zone strength, width, fit, and price distance;
Trust : A weighted score combining price-zone quality, market-state dominance, and volatility-cluster dominance;
Fit RMSE : The normalized root mean squared error of the price clusters;
Width : The average dispersion of the nearest cluster around its center;
Reliability : A descriptive grade derived from the internal Trust score.
A narrow cluster with reasonable strength and lower fitting error will usually receive a better score than a wide, weak, or poorly fitted cluster. Use this section to decide how much weight should be given to the current analysis. A weak Quality score does not make the chart unusable, but it suggests that the levels and classifications should be treated as secondary context.
🟣 Bullish Market Reading
A bullish setup becomes more meaningful when the market state, K-Means zones, candle behavior, volatility, and quality readings support the same interpretation.
Check the Market State first : An Active Bullish Trend indicates stronger bullish structure and relative participation. A Soft Bullish Trend still favors the upside, but entries should normally wait for additional confirmation.
Locate price relative to the nearest zone : When price is above the nearest K-Means zone, that level may become an adaptive support reference. A pullback toward the green nearest-zone line can be watched for continuation or rejection behavior.
Look for bullish price action : A Bullish Rejection From Zone suggests that price tested a clustered level and closed with a stronger lower-wick reaction. A Bullish Zone Breakout shows that the candle crossed above the zone with a sufficiently large body. A Bullish Momentum Candle confirms upward pressure, but it is more useful when the Market State is already bullish.
Use the support line as a reference, not an automatic entry : The K-Means support level can help define the area where bullish structure remains valid. A decisive move below it may weaken the long scenario, especially if the Market State also changes.
Confirm volatility conditions : Normal Volatility is generally easier to manage than High Volatility or Volatility Shock. During compression, traders may wait for a confirmed breakout rather than entering before expansion begins.
Review Quality and Reliability : Stronger Quality, Trust, and Zone Strength readings increase the internal consistency of the analysis. Weak scores suggest that the zone may be broad, poorly fitted, or based on a less concentrated cluster.
A practical bullish sequence may therefore look like this: the table shows a Soft or Active Bullish Trend, price remains above or retests a green K-Means zone, a bullish rejection or breakout appears, volatility is not classified as a shock, and Quality remains acceptable. None of these elements guarantees continuation, but their alignment creates a clearer bullish context than any single reading alone.
🟣 Bearish Market Reading
Bearish analysis follows the same process in reverse. The objective is to identify whether downward market structure, clustered resistance, candle behavior, and volatility are supporting the same scenario.
Begin with the Market State : An Active Bearish Trend represents stronger negative bias, slope, and relative volume pressure. A Soft Bearish Trend favors short-side analysis but still requires confirmation before treating the move as established.
Observe price relative to the nearest zone : When price is below the nearest K-Means zone, that level may act as an adaptive resistance reference. A return toward the red nearest-zone line can be monitored for rejection or continuation.
Wait for bearish price action : A Bearish Rejection From Zone appears when price tests a clustered area and forms a stronger upper-wick reaction. A Bearish Zone Breakout indicates that price has crossed below the zone with a sufficiently large bearish body. A Bearish Momentum Candle carries more weight when the broader Market State is already bearish.
Use the resistance line to define context : The K-Means resistance level can help identify where bearish continuation remains structurally reasonable. A sustained break above it may weaken the short scenario, particularly if Market State also shifts toward bullish or neutral conditions.
Do not ignore volatility warnings : A bearish candle during Volatility Shock may be followed by a sharp continuation, but it can also produce rapid retracement and unstable execution. In this condition, the indicator explicitly favors additional confirmation or reduced risk.
Check cluster quality before relying on the level : A weak or wide price cluster may produce a less precise resistance reference. Higher Quality and Reliability readings indicate a more compact and internally consistent zone, not a guaranteed bearish outcome.
A clearer bearish sequence may include a Soft or Active Bearish Trend, price trading below or retesting a red K-Means zone, bearish rejection or breakout behavior, manageable volatility, and an acceptable Quality score. When these components disagree, for example, a bullish momentum candle inside a bearish trend, the table should be read as a warning that momentum alone is not enough to confirm a reversal.
The built-in alert conditions can be used to monitor bullish and bearish K-Means zone breakouts and rejections. Alerts are most useful as notifications that a specific price-action condition has appeared; the final interpretation should still include Market State, Volatility, zone position, and Quality before any trading decision is made.
🔵 Settings
🟣 K-Means Engine Settings
Market State Lookback : Number of recent bars used to cluster trend bias, slope, and relative volume for market-state classification.
Price Zone Lookback : Number of recent bars used to build K-Means price zones from pivots, highs, and lows.
Volatility Lookback : Number of recent bars used to cluster ATR percentage, candle range, and return volatility.
Market State Clusters : Number of clusters used by the Market State model.
Price Zone Clusters : Number of price clusters used to calculate adaptive zone centers.
Volatility Clusters : Number of clusters used by the Volatility model.
Max K-Means Iterations : Maximum number of center-update cycles allowed during each clustering calculation.
Dominant State Window : Number of recent cluster assignments used to determine the dominant market state.
Fast Volatility State Window : Number of recent volatility assignments used to determine the dominant short-term volatility cluster.
Convergence Tolerance : Minimum center movement required to continue the K-Means iteration; lower values increase precision but may require more processing.
🟣 Price Zone Settings
Pivot Length : Number of bars used on each side of a candle to confirm pivot highs and pivot lows.
High/Low Sampling Step : Controls how frequently historical highs and lows are added to the price-zone dataset; lower values use more samples.
Minimum Near-Zone Distance (%) : Minimum percentage distance used to classify price as testing a K-Means zone.
🟣 Execution Control Settings
Historical Calculation Bars : Number of recent historical bars on which calculations and visual outputs are processed.
Refresh Every N Bars : Runs the main K-Means modules once every selected number of bars and always updates them on the latest bar.
🟣 Zone Stabilizer Settings
Zone Plot Mode : Selects how zone lines are displayed: Raw follows new centers directly, Smooth moves gradually, and Locked Steps updates only after a meaningful price shift.
Zone Smooth Length : Controls the smoothing speed in Smooth mode; higher values produce slower and more stable zone movement.
Zone Lock ATR Multiplier : Defines the minimum ATR-based movement required before a zone updates in Locked Steps mode.
Nearest Zone Switch Margin ATR : Prevents frequent switching between nearby zones by requiring the new zone to be closer by an ATR-based margin.
🟣 Display Settings
Show Analysis Table : Shows or hides the market analysis table.
Table Text Size : Sets the size used inside the table.
Table Position : Selects the table location on the chart.
Show All K-Means Zone Centers : Displays all calculated K-Means price-zone centers.
Show Nearest Zone : Displays the stabilized zone closest to the current price, colored by the detected market state.
Show K-Means Support/Resistance : Displays the nearest clustered support below price and resistance above price.
🔵 Conclusion
This indicator brings K-Means clustering, market state analysis, adaptive price zones, volatility classification, and price action context into one structured workflow. Instead of reducing the chart to a single signal, it separates the market into several readable layers: directional behavior, clustered support and resistance areas, candle reactions, volatility conditions, and the internal quality of the current calculations. This makes it easier to understand whether price is trending, ranging, testing a K-Means zone, reacting to a clustered level, or moving through an unstable volatility phase.
Its strongest use comes from confirmation rather than prediction. A bullish or bearish reading becomes more meaningful when the Market State, nearest K-Means zone, Price Action module, Volatility analysis, and Quality score support the same scenario. When these components disagree, the table highlights that uncertainty instead of hiding it. Used this way, the tool works as a machine learning market analysis framework that helps organize recent price data, compare changing market regimes, and identify areas where further confirmation is still required. Indicateur

Machine Learning Price Bands Kernel Regression SignalsOVERVIEW
Every "AI band" on this platform draws two lines and asserts them. None of them can tell you how often price actually stays inside.
This one can — because it is built on a method that comes with a MATHEMATICAL COVERAGE GUARANTEE, and then it CHECKS WHETHER IT KEPT THE PROMISE, live, on your chart:
Coverage (empirical vs nominal) 89.1% vs 90% n = 20,266
Is the miss REAL? -0.9 pp z = -4.3 (real)
Verdict undercovering — real, but small
That is not a band. That is a prediction interval that has been audited, and it is the whole reason this tool exists.
It is a research and framing tool. NOT a strategy, NOT a signal service, NOT a validated edge.
THE MACHINE LEARNING, SPELLED OUT — no buzzwords, here is the actual model
1. NADARAYA-WATSON KERNEL REGRESSION. Non-parametric: no functional form is assumed, the data chooses the shape. Each past bar votes on the current estimate with a Gaussian weight that decays with distance. This is the same estimator Lo, Mamaysky and Wang used in the Journal of Finance to make chart-pattern recognition objective. It is real machine learning, and it is sixty years old.
The kernel here is CAUSAL. It only ever looks backwards. A centred kernel — the kind most "Nadaraya-Watson envelope" scripts use — peeks at bars that have not happened yet, and that is why their historical fit looks so much better than their live one.
2. BANDWIDTH BY PREDICTIVE MODEL SELECTION. The bandwidth h is the only real parameter, and it is not a magic number: several candidates are run in parallel and scored on their ROLLING ONE-STEP-AHEAD SQUARED ERROR. The winner is used. That is honest model selection — the criterion you would use to choose any forecaster — rather than a knob you turn until the chart looks nice.
3. CONFORMAL PREDICTION INTERVALS. The half-width is the (1-alpha) empirical quantile of the recent ABSOLUTE one-step-ahead errors. Under exchangeability this carries a FINITE-SAMPLE coverage guarantee, with NO distributional assumption at all: no normality, no GARCH, no volatility model. The model's own recent mistakes size the band — which is why it widens when the model starts being WRONG, not merely when price starts moving.
4. ADAPTIVE CONFORMAL INFERENCE — Gibbs and Candes, NeurIPS 2021.
Here is the problem with plain conformal prediction on markets, stated plainly: its guarantee holds under EXCHANGEABILITY, and financial returns are the textbook counterexample. Volatility CLUSTERS. So a residual quantile computed over a trailing window is always a step behind, the band is too narrow exactly when it matters, and the misses bunch together. Coverage lands quietly under nominal. Measured live on NIFTY futures before this was added: 89.1% against a nominal 90%, on the 1m, the 3m and the 1h, every one of them roughly four standard errors below target. Not a bug. The assumption breaking.
ACI makes the miscoverage level a LEARNED parameter:
alpha(t+1) = alpha(t) + gamma * (alpha - err(t))
Miss the interval and alpha falls, so the quantile rises and the band WIDENS. Cover it and alpha creeps back, so the band TIGHTENS. Long-run coverage provably converges to the target IRRESPECTIVE OF THE DATA GENERATING PROCESS — no exchangeability assumption anywhere.
A band that notices it is undercovering and fixes itself. Watch the alpha row: where it settles BELOW nominal is a direct measurement of how badly exchangeability fails on your instrument.
MEASURED, ON THE SAME INSTRUMENT, BEFORE AND AFTER:
timeframe plain conformal with ACI
1m 89.1% 90.1%
3m 89.1% 90.1%
5m 89.1% 90.1%
15m 90.1% 90.1%
1h 89.1% 90.1%
(nominal 90%)
Five timeframes, a four-standard-error undercoverage on four of them, closed. The binomial test now returns "calibrated — within sampling noise" and means it. That is not a backtest of a trading rule. That is a mathematical promise being kept, and being checked.
5. NORMALISED NONCONFORMITY — Papadopoulos et al. (2008), Lei et al. (2018).
The plain score |price - fit| is a SCALAR, which means the band is THE SAME WIDTH in a dead tape and in a crash. It therefore OVERCOVERS in calm and UNDERCOVERS in chaos — and the single marginal coverage figure is the average of those two errors, looking correct while being wrong in both directions.
Normalising divides each residual by a local scale estimate before taking the quantile, and multiplies it back when drawing:
score = |price - fit| / sigma band = fit +/- q * sigma
The band now scales with LOCAL DIFFICULTY — and note it is the MODEL'S difficulty, not the market's volatility. Related, but not the same thing, and the first one is what a prediction interval is actually about.
6. THE COVERAGE AUDIT. A guarantee you do not verify is just a claim.
TWO QUESTIONS ABOUT THE COVERAGE, AND THE PANEL ANSWERS BOTH
IS THE MISS REAL? That is a binomial z-test and it needs no tolerance at all. Each bar is a Bernoulli trial with p = nominal, so the standard error of the observed coverage is sqrt(p(1-p)/n).
IS THE MISS BIG ENOUGH TO CARE ABOUT? That is a judgement, and you set it.
These are NOT the same question, and conflating them is how a band gets waved through as "calibrated". Measured live on NIFTY futures: at n = 20,266 the standard error is 0.21 pp, so an empirical coverage of 89.1% against a nominal 90% is a 0.9 pp miss — FOUR STANDARD ERRORS. Unmistakably real. Arguably too small to trade differently. A 5 pp tolerance called that "calibrated", which was the headline row of the script asserting the one thing the script exists to verify, and asserting it wrongly.
The panel now reports the size of the miss, its significance, and a verdict that distinguishes "within sampling noise" from "real, but small" from "MISCALIBRATED — do not trust the band". You get to decide which of those matters to you, and you get the numbers to decide with.
AND THEN THE ROW NOBODY HAS: CONDITIONAL COVERAGE
Coverage 90.0% vs 90% n = 20,178
calm / normal / turbulent 96.4% · 90.1% · 83.2%
A single marginal number can read a perfect 90% while the interval covers 96% of quiet bars and 83% of violent ones. Ninety per cent is then the AVERAGE OF TWO ERRORS — it looks right while being wrong in both directions, and it is wrong in the direction that costs you money exactly when it costs you money.
Exact conditional coverage is provably impossible without strong assumptions. But you can always MEASURE it, and almost nobody does. Bars are split into calm, normal and turbulent thirds by the percentile rank of ATR, and coverage is scored inside each. If the three numbers fan apart, the band is not breathing — and the normalised score is what closes the gap.
Turn the normalised score off and watch those three fan out. That is the demonstration.
FADE OR FOLLOW? THE TOOL DOES NOT PRETEND TO KNOW
Price leaving a 90% interval is statistically unusual. Whether to FADE it (an outlier, so bet on reversion) or FOLLOW it (the model has broken, so bet on the new regime) is an EMPIRICAL question, and the honest answer is often neither.
So both are logged, both are graded, and BOTH ARE TESTED AGAINST EACH OTHER.
That last part matters more than it sounds. Knowing that fading beats an unconditional control, and that following also beats an unconditional control, does not answer the question a trader is actually asking at a band break — which of the two should I do? They are mutually exclusive responses to the SAME event. So they are run head to head with a Welch t-test, and the answer is allowed to be:
FADE or FOLLOW? NEITHER — the break does not tell you which
If the difference does not clear the noise, then on this instrument the break carries no directional information, and saying so IS the finding. A tool that cannot report its own failure is an advertisement, not a measurement.
And the chart agrees with the panel. An unproven direction is still drawn — it is arithmetic, and you may want it — but it is drawn MUTED and labelled "(not proven)". It used to print "Follow the break" in full colour while the panel directly beneath it said "neither proven". The paint has to agree with the code.
THE ANTI-BIAS GUARDS
ENTRY IS THE CLOSE, for the event and for the control alike. A band break is a SIGNAL, not a fill. Entering at the band — a better price — while the control enters at the close hands every signal a free head start and manufactures an edge out of nothing.
THE CONTROL IS DIRECTION-MATCHED. In a downtrend there are more break-downs than break-ups, so FOLLOW skews short and FADE skews long. A direction-skewed event set measured against a 50/50 control inherits the index drift for free and calls it an edge. Longs are compared only with control longs, shorts only with control shorts, and the control is blended back using the events' OWN direction mix.
IDENTICAL GEOMETRY. Every event and every control trade uses the same stop and the same R multiple, so the comparison is apples to apples.
Both barriers on one bar: the STOP is assumed first — conservative, and the only assumption that cannot flatter the result. Unresolved trades at the horizon are marked to market, not booked as losses. Nothing is marked proven below t = 1.96.
NON-REPAINT
The kernel is causal, the bandwidth is chosen on past error only, the interval is built from past residuals, and coverage is scored by asking whether the actual close landed inside the interval that was published BEFORE it. Everything is computed on confirmed bars. Nothing is drawn and then moved.
WHY THESE PARTS ARE ONE TOOL
The regression gives the trend. Without the interval, a band is a guess. Without model selection, the bandwidth is a knob you turn until you like the picture. Without the coverage audit, a conformal interval is an unverified promise. And without the signal calibration, "price left the band" is folklore. Each piece is worthless alone — which is exactly why they ship together.
DATA AND SCOPE
Any symbol, any timeframe. ATR-normalised throughout. No volume required.
EXPORTS (Data Window — consume from other scripts via input.source())
EXP_Fit, EXP_Upper, EXP_Lower, EXP_Bandwidth, EXP_Coverage, EXP_Miscal, EXP_Signal, EXP_Entry, EXP_Stop, EXP_Target
CONCEPT CREDIT
Nadaraya-Watson kernel regression — E. A. Nadaraya and G. S. Watson (1964). Its use for technical pattern recognition in finance — Andrew W. Lo, Harry Mamaysky and Jiang Wang, "Foundations of Technical Analysis", Journal of Finance 55(4), 2000. Conformal prediction — Vladimir Vovk, Alexander Gammerman and Glenn Shafer; the split/inductive form used here follows Papadopoulos et al. and Lei et al. Triple-barrier forward labelling — Marcos Lopez de Prado. Welch's t-test — B. L. Welch. ATR — J. Welles Wilder.
The causal-kernel implementation, the parallel bandwidth selection, the live coverage audit, the binomial calibration test and the fade-versus-follow head-to-head are the author's own. Clean-room implementation; no third-party Pine code is reused. Not affiliated with, nor endorsed by, any of the above.
HONESTY AND LIMITATIONS
Conformal coverage is guaranteed under EXCHANGEABILITY. Financial returns are NOT exchangeable — volatility clusters, regimes shift — so the guarantee is approximate in practice. THAT IS PRECISELY WHY THE COVERAGE IS AUDITED LIVE INSTEAD OF ASSUMED. When empirical coverage drifts from nominal you are watching the assumption break, in real time, and you should believe what you see rather than the label.
A prediction interval says where price is LIKELY TO BE. It says nothing about DIRECTION, and it is not a forecast. Coverage being correct does not make band breaks tradeable — those are two different claims, and the tool tests them separately for exactly that reason.
Calibration figures are IN-SAMPLE, with no costs or slippage, and use overlapping windows. A proven in-sample edge is NOT a guarantee out-of-sample. Nothing here predicts price.
DISCLAIMER
Research and educational tool only. NOT financial advice, NOT a recommendation, and NO guarantee of results. Entry, stop and target output is arithmetic, not advice. Trading carries risk of loss. Test out-of-sample and make your own decisions. The author accepts no liability for any use. Indicateur

XG Boost Lite: Reversals | Gains AlgoWe are excited to release this indicator, which uses our brand-new Arbor library for gradient boosting! This engine brings true, high-performance machine learning natively into Pine Script v6, bypassing the need for external webhooks or API layers. By utilizing iterative, tree-based models on your chart, XGBoost Lite: Reversals adapts directly to the historical structure of the asset you are trading, identifying precise pivot exhaustion points with high statistical conviction.
🧠 Understanding Gradient Boosting & XGBoost
To trade successfully with machine learning, it helps to understand exactly what is happening beneath the hood of the asset's data.The Core TheoryGradient Boosting is a powerful machine learning technique used for regression and classification tasks. Unlike deep learning networks that process data through abstract node layers, gradient boosting relies on an ensemble of simple decision trees, often called "weak learners" or "stumps".
The training process works sequentially:
The Initial Guess: The model makes a basic baseline prediction.Calculating the Error (Residuals): It checks where its prediction missed the actual historical market outcome.
Correcting the Mistakes: A new decision tree is built specifically to predict those errors (the gradient of the loss function).
Iterative Learning: The model repeats this process for several rounds. Each new tree focuses entirely on correcting the flaws of the previous ones, scaling its adjustments by a Learning Rate to maintain stability.
What Makes XGBoost Special?
XGBoost (Extreme Gradient Boosting) optimizes this framework for speed, scalability, and performance. It applies strict regularization techniques to minimize overfitting, ensuring the model doesn't just "memorize" past market noise but instead learns genuine structural behaviors.By evaluating multiple market features simultaneously, it estimates the probability of a specific event occurring.
🛠️ About the Indicator
XGBoost Lite: Reversals is a machine learning-driven technical indicator designed to catch exhaustion and reversal setups.
The Machine Learning Pipeline
Dual Engines: The script fits four separate models simultaneously—a classifier and a regressor for Longs, and a classifier and a regressor for Shorts.
Dynamic Retraining: Rather than remaining static, the model automatically flushes its memory and retrains its internal mathematical weights every n bars to adapt to evolving market regimes.
Strict Non-Repainting Execution: A critical upgrade in this framework forces features and calculations to compute and lock strictly on bar close. Signals, dynamic entry points, and risk metrics are only printed once the triggering candle is finalized, ensuring what you see on the historical chart matches real-time execution perfectly.
The Core Features Evaluated
The model processes a combination of multi-dimensional market inputs to generate a unified prediction:
RSI (14): Evaluates traditional momentum expansion and contraction.
Relative Volume (20): Evaluates institutional engagement by dividing current volume against its 20-period SMA.
Z-Score (20): Measures how far the current price has deviated from its statistical mean.
ADX (14): Gauges the overall strength of the macro trend to prevent trading directly into a runaway freight train.
📊 How to Use the Indicator
The Real-Time Dashboard: When applied to your chart, the indicator renders an advanced Feature Importance Scatter Plot in the right-hand margin.
Distribution Scatter: The horizontal bars plot the historical density of successful signals. Darker, tightly packed nodes represent highly concentrated, high-probability clusters discovered by the algorithm.
Visualizing Signals
When a market pivot is detected (e.g., a structural swing low or high) and the classifier hits your target confirmation probability, a signal arrow prints on the chart displaying the mathematical certainty ($e.g., 74.2\%$) of the reversal.
⚙️ The Settings Inputs
The indicator’s interface is neatly categorized into three primary functional groups:
⚙️ XGBoost Model Settings:
Training Lookback (Bars): (Default: 250) The historical window used to feed the training arrays. Max capped at 300 to remain computational within Pine Script limits.
Retrain Frequency: (Default: 50) Determines how often (in bars) the model recalibrates its trees. Boosting Rounds: (Default: 20) The number of sequential trees (stumps) trained per model. Higher numbers capture deeper complexities but risk overfitting.
Learning Rate: (Default: 0.3) The step size applied to each boosting round to prevent the model from learning too quickly. Min Probability for Signal: (Default: 0.65) The minimum confidence threshold ($65\%$) required from the classification model to trigger an active trade.
ADX Length / Minimum Filter: (Default: 14 / 20.0) Prevents counter-trend signals if the prevailing macro trend is too strong.
🛡️ Target & Risk Management
SL Wick Buffer ×ATR: (Default: 0.25) Sets how much breathing room is given below a swing low wick or above a swing high wick, scaled by ATR.
TP1 ×Risk (R-multiple): (Default: 1.0) Targets a clean 1:1 Risk-to-Reward ratio for the initial profit take.
TP3 Min ×Risk (Floor): (Default: 2.0) The minimum target floor for the machine learning regression objective.
Break-Even After TP1: (Default: True) Automatically moves the Stop Loss to the exact entry price the moment TP1 is captured, eliminating risk on the remainder of the trade.
📈 How to Trade the Indicator
Trading with the machine learning model requires blending quantitative probabilities with standard structural execution:
The Entry: Wait for a Bullish (Neon Purple) or Bearish (Neon Pink) arrow to finalize on a closed candle. The percentage printed indicates the model's confidence.
Placing Risk: The system automatically draws a solid line anchoring your Stop Loss tightly to the local structural wick pivot, applying an ATR buffer to account for minor noise.
Scaling Targets:
Target 1 (TP1): Landed at a symmetrical 1:1 distance. When hit, the indicator dynamically updates your Stop Loss to your entry line, locking in a "scratch-or-better" runner.
Target 2 (TP2): Represents the mathematical midpoint between your baseline risk and the macro ML objective.
Target 3 (TP3): Driven directly by the XGBoost Regression Model. The regressor estimates the potential mathematical expansion based on current market features—if volatility is expanding, TP3 will automatically stretch further to ride major trend changes.
📊 Deep Dive: The Feature Importance & Scatter Plot Dashboard
The dashboard rendered on the right side of the chart acts as the "brain" of the indicator. It provides real-time transparency into exactly how the machine learning model is weighing data and evaluating current market conditions.
Feature Importance Bars (The Relative Weights): The horizontal progress bars display the mathematical percentage weight allocated to each of the four indicators processed during the model's most recent training cycle. These values change dynamically every time the model triggers a retraining block (default: every 50 bars) as it adapts to shifting market conditions. For example, if the market moves into a heavy trending phase, you will notice metrics like the ADX or Z-Score capture a higher percentage of the model's attention, whereas the RSI will frequently become the dominant driver if the asset is range-bound.
The Holographic Scatter Plot (Historical Feature Density): Layered over the progress bars is an advanced distribution scatter plot consisting of individual circular glyphs (○, ◉, ●) that plot a rolling record of the last 30 historical signal points. The horizontal position of each dot shows exactly where the feature value landed relative to its historical extremes (0 on the far left, 1 on the far right). The script introduces a subtle vertical "jitter" to separate these dots so you can visually identify high-density clusters where successful reversal setups frequently occur, while the shifting style of the glyphs flags tightly packed clusters of solid nodes (●) to indicate highly concentrated mathematical sweet spots discovered by the XGBoost classifier.
Indicateur

Arbor_Gradient_Boosting_GainzAlgoGainzAlgo is excited to bring the ability to perform gradient boosting and feature importance selection to Pine Script. Currently, there are no native capabilities within Pine Script for gradient boosting or feature importance selection. Arbor fills this significant gap by introducing a from-scratch Gradient Boosting Machine (GBM) engineered with XGBoost-style mechanics.
Designed to support both classification and regression tasks, and building on our Random Forest approach to Pinescript, Arbor utilizes depth-1 stumps, meaning it performs one split per round without column subsampling.
Because TradingView automatically lists the exported types and function parameters, the following outlines the core mechanics and capabilities you unlock by importing Arbor.
Core Mechanics
Arbor brings advanced machine-learning concepts directly into your Pine Script workflows:Advanced Training: Utilizes Newton leaf steps (second-order hessian weighting) and the exact XGBoost gain formula.
Regularization & Pruning: Integrates L2 regularization (lambda), minimum gain pruning (gamma), and minimum child weight checks to manage model complexity and prevent overfitting.
Stochasticity: Implements Fisher-Yates row subsampling to provide genuine round-to-round stochasticity matching XGBoost's subsample behavior.
Reproducibility: You can pass an optional seed to any fit function to ensure reproducible training runs across reloads.
Model Tiers
The library supports models scaled across three specific feature tiers:
GBM (1 Feature): Built for rapid classification or regression implementations.
GBM3 (3 Features): Purpose-built specifically for classification tasks.
GBM4 (4 Features): Supports both classification and regression, and uniquely offers XGBoost-style, gain-based feature importance evaluation.
Library "Arbor_Gradient_Boosting_GainzAlgo"
Arbor — gradient boosting for Pine Script. From-scratch GBM v2
with XGBoost-style mechanics: Fisher-Yates row subsampling, Newton leaf steps
(second-order hessian weighting), exact XGBoost gain formula with L2
regularization (lambda), minimum gain pruning (gamma), and minimum child
weight. Trees are depth-1 stumps (one split per round) and there is no
column (feature) subsampling — this is an XGBoost-style boosting scheme,
not a full XGBoost reimplementation. Supports classification and regression
across three feature tiers:
- GBM (1 feature) : gbm_fit / gbm_predict
classification or regression via is_classifier
- GBM3 (3 features) : gbm3_fit / gbm3_predict
classification only
- GBM4 (4 features) : gbm4_fit / gbm4_predict / gbm4_importance_pct
classification or regression with XGBoost-style
gain-based feature importance
All variants use Newton leaf steps, exact gain formula, L2 regularization,
Fisher-Yates shuffle subsampling, and gamma/min_child_weight pruning. Pass
an optional seed to any fit function for reproducible training runs.
gbm_fit(feat, target, n_rounds, lr, n_thresh, is_classifier, lambda, gamma, min_child_w, subsample, seed)
Fits a single-feature gradient-boosted stump ensemble using
XGBoost-style mechanics: Newton leaf steps (second-order hessian weighting),
exact gain formula with L2 regularization, gamma pruning, minimum child
weight, and Fisher-Yates row subsampling. Each round fits one depth-1 stump
(this is not a full multi-level tree, and there is no column subsampling).
Supports both binary classification (log-odds + sigmoid) and regression (MSE).
Parameters:
feat (array) : Array of feature values, one per training row
target (array) : Array of targets — 0.0/1.0 for classification, continuous for regression
n_rounds (int) : Number of boosting rounds / stumps to fit
lr (float) : Learning rate / shrinkage applied to each round's leaf contribution
n_thresh (int) : Candidate split thresholds to scan per round
is_classifier (bool) : True = binary classification, False = squared-error regression
lambda (float) : L2 leaf regularization — Ridge-style shrinkage toward zero (XGBoost default: 1.0)
gamma (float) : Minimum gain required to accept a split — prunes weak splits (XGBoost default: 0.0)
min_child_w (float) : Minimum hessian sum per child node — prevents tiny noisy splits (XGBoost default: 1.0)
subsample (float) : Fraction of rows randomly sampled per round via Fisher-Yates (default: 1.0 = all rows)
seed (int) : Optional seed for the row-subsampling shuffle — pass a fixed value for reproducible fits across reloads (default: na = unseeded/random each time)
Returns: Fitted GBM object ready for gbm_predict()
gbm_predict(model, x)
Scores a single feature value against a fitted GBM ensemble.
Parameters:
model (GBM) : A GBM object previously returned by gbm_fit()
x (float) : Feature value to score (same feature definition used in training)
Returns: Predicted probability if classifier, raw predicted value if regressor
gbm3_fit(feat1, feat2, feat3, target, n_rounds, lr, n_thresh, lambda, gamma, min_child_w, subsample, seed)
Fits a 3-feature gradient-boosted classifier using XGBoost-style
mechanics: Newton leaf steps, exact gain formula, L2 regularization, gamma
pruning, minimum child weight, and Fisher-Yates row subsampling. Selects the
best (feature, threshold) pair each round and boosts in log-odds space.
Each round fits a single depth-1 stump; there is no column subsampling.
Parameters:
feat1 (array) : Array of feature 1 values, one per training row
feat2 (array) : Array of feature 2 values, one per training row
feat3 (array) : Array of feature 3 values, one per training row
target (array) : Array of binary targets (0.0 or 1.0), one per training row
n_rounds (int) : Number of boosting rounds
lr (float) : Learning rate / shrinkage
n_thresh (int) : Candidate thresholds scanned per feature per round
lambda (float) : L2 leaf regularization (Ridge shrinkage, XGBoost default: 1.0)
gamma (float) : Minimum gain to accept a split (XGBoost default: 0.0)
min_child_w (float) : Minimum hessian sum per child node (XGBoost default: 1.0)
subsample (float) : Row sampling fraction per round via Fisher-Yates (default: 1.0)
seed (int) : Optional seed for the row-subsampling shuffle — pass a fixed value for reproducible fits across reloads (default: na = unseeded/random each time)
Returns: Fitted GBM3 object ready for gbm3_predict()
gbm3_predict(model, x1, x2, x3)
Scores 3 feature values against a fitted GBM3 classifier.
Parameters:
model (GBM3) : GBM3 object from gbm3_fit()
x1 (float) : Current value of feature 1
x2 (float) : Current value of feature 2
x3 (float) : Current value of feature 3
Returns: Predicted probability
gbm4_fit(feat1, feat2, feat3, feat4, target, n_rounds, lr, n_thresh, is_classifier, lambda, gamma, min_child_w, subsample, seed)
Fits a 4-feature gradient-boosted ensemble with Newton steps, exact gain
formula, L2 regularization, gamma pruning, minimum child weight, Fisher-Yates
row subsampling, and gain-based feature importance tracking.
Supports both binary classification and regression. Each round fits a single
depth-1 stump; there is no column subsampling.
Parameters:
feat1 (array) : Array of feature 1 values, one per training row
feat2 (array) : Array of feature 2 values, one per training row
feat3 (array) : Array of feature 3 values, one per training row
feat4 (array) : Array of feature 4 values, one per training row
target (array) : Array of targets — 0.0/1.0 for classification, continuous for regression
n_rounds (int) : Number of boosting rounds
lr (float) : Learning rate / shrinkage
n_thresh (int) : Candidate thresholds scanned per feature per round
is_classifier (bool) : True = binary classification, False = regression
lambda (float) : L2 leaf regularization (Ridge shrinkage, XGBoost default: 1.0)
gamma (float) : Minimum gain to accept a split (XGBoost default: 0.0)
min_child_w (float) : Minimum hessian sum per child node (XGBoost default: 1.0)
subsample (float) : Row sampling fraction per round via Fisher-Yates (default: 1.0)
seed (int) : Optional seed for the row-subsampling shuffle — pass a fixed value for reproducible fits across reloads (default: na = unseeded/random each time)
Returns: Fitted GBM4 object with importance scores, ready for gbm4_predict() / gbm4_importance_pct()
gbm4_predict(model, x1, x2, x3, x4)
Scores 4 feature values against a fitted GBM4 ensemble.
Parameters:
model (GBM4) : GBM4 object from gbm4_fit()
x1 (float) : Current value of feature 1
x2 (float) : Current value of feature 2
x3 (float) : Current value of feature 3
x4 (float) : Current value of feature 4
Returns: Predicted probability if classifier, raw predicted value if regressor
gbm4_importance_pct(model, feat_idx)
Returns normalized feature importance as % of total gain for one feature.
Importance = accumulated gain credited to this feature across all boosting rounds,
matching XGBoost's xgb.importance() Gain column definition.
Parameters:
model (GBM4) : GBM4 object from gbm4_fit()
feat_idx (int) : Feature index to query (0-3)
Returns: Percentage of total ensemble gain attributed to this feature (0.0–100.0)
GBM
Holds a fitted gradient-boosted stump ensemble (1 feature).
Fields:
thresh (array) : Split threshold for each round's stump
left_val (array) : Newton leaf value when feature < threshold
right_val (array) : Newton leaf value when feature >= threshold
base_score (series float) : Log-odds of training mean (classifier) or mean (regressor)
lr (series float) : Learning rate stored for inference
is_classifier (series bool) : True = sigmoid probability output, False = raw regression output
GBM3
Holds a fitted 3-feature gradient-boosted stump ensemble (classification only).
Fields:
stump_feat (array) : Which feature index (0-2) each round's stump split on
thresh (array) : Split threshold for each round's stump
left_val (array) : Newton leaf value when feature < threshold
right_val (array) : Newton leaf value when feature >= threshold
base_score (series float) : Log-odds of training mean
lr (series float) : Learning rate stored for inference
GBM4
Holds a fitted 4-feature gradient-boosted ensemble with gain-based importance.
Fields:
stump_feat (array) : Which feature index (0-3) each round's stump split on
thresh (array) : Split threshold for each round's stump
left_val (array) : Newton leaf value when feature < threshold
right_val (array) : Newton leaf value when feature >= threshold
importance (array) : Accumulated gain per feature (indices 0-3), raw — normalize via gbm4_importance_pct()
base_score (series float) : Log-odds (classifier) or mean (regressor)
lr (series float) : Learning rate stored for inference
is_classifier (series bool) : True = sigmoid probability output, False = raw regression output Bibliothèque

Liquidity Sweep Intelligence - ML Post-Sweep [Dots3Red]█ LIQUIDITY SWEEP INTELLIGENCE — KNN POST-SWEEP
Usually, a liquidity indicator shows where the price is likely to go to take liquidity. This one tells you what tends to happen after it gets there.
When price sweeps a swing high or low — triggering the stop orders sitting there — we face the immediate question: does it reverse (a stop hunt, fade the move) or does it continue (a genuine breakout)? The answer depends on context. This script tracks every historical sweep on your chart, records the contextual features at the moment it happened, and uses a KNN (K-Nearest Neighbors) model to find the most similar past sweeps and return their actual measured outcomes.
The probability shown is not derived from a formula. It is counted from real historical sweeps on your chart.
█ HOW IT WORKS
1. Pool Detection
Swing highs and swing lows are detected using two pivot lengths — a primary (default 10 bars each side) and a secondary (default 8 bars each side) — to capture both major and minor liquidity levels. Same-side pivots that form within the Equal-Level Tolerance % of each other are merged into a single stronger pool, marked with the ⊜ symbol. These are equal highs (EQH) or equal lows (EQL) — two peaks or two troughs at nearly the same price — which represent a higher concentration of stop orders than a single pivot.
Unswept pools are shown as lines on the chart: dashed for single pivots, solid for equal-level pools. Pools expire after the configured maximum age (default 50 bars) without generating a sweep record.
2. Sweep Detection
A sweep is registered when the close price exceeds a pool level by more than the Sweep Buffer (default 1.4 × ATR). This buffer filters out minor wicks that barely touch a level and requires a genuine close beyond it.
At the moment of the sweep, the script records:
• The direction (high swept or low swept)
• Whether the pool was an equal-level cluster (EQH/EQL)
• How old the pool was in bars
• The current ATR ratio (current volatility relative to the 50-bar baseline)
• Whether the sweep occurred inside an ICT killzone window
3. Outcome Measurement
After the Outcome Window (default 10 bars), the script measures what price actually did. For a swept high, it calculates how far price retraced downward and how far it continued upward, both expressed in ATR units. For a swept low, the directions are reversed. If the retracement exceeded the Reversal Threshold (default 3.5 × ATR), the sweep is classified as a reversal. Otherwise it is classified as a continuation. The result is stored in the KNN training data.
4. KNN Inference
The K-Nearest Neighbors model uses a 5-feature vector for each sweep:
• sweep_dir — was a high swept (1) or a low swept (0)?
• age_norm — how old was the pool when swept, normalized 0–1
• is_equal — was it an EQH/EQL cluster (1) or single pivot (0)?
• atr_ratio_norm — current ATR divided by 50-bar ATR baseline, capped at 3×
• in_kz — did the sweep occur inside a killzone window (1) or not (0)?
For each active sweep, the model computes the Euclidean distance to every recorded historical sweep in the training window, finds the K nearest matches (default 15), and returns three values averaged across those neighbors:
• Reversal probability — what percentage of matched sweeps reversed
• Average reversal distance — how far the reversal moved in ATR units
• Average continuation distance — how far the continuation moved in ATR units
The KNN runs every third bar per event for performance. Output is displayed only after the minimum training threshold (default 20 samples) has been reached.
5. Killzone Context
Four ICT killzone windows are tracked in New York time and used as a contextual feature in the KNN vector:
• Asia KZ — 20:00 to 00:00
• London Open KZ — 02:00 to 05:00
• NY Open KZ — 07:00 to 10:00
• London Close KZ — 10:00 to 12:00
Sweeps that occur inside a killzone are marked with ⚡ in the label. The active killzone is also shown in the dashboard.
█ READING THE LABEL
Each active sweep displays a label at the right edge of the chart:
▲ HIGH SWEPT ⊜ ⚡
Rev 68% | +1.4 ATR | N=47
▲ HIGH SWEPT — a swing high was swept (sell-side stops triggered)
⊜ — the pool was an equal-high cluster (stronger stop concentration)
⚡ — the sweep occurred inside a killzone window
Rev 68% — 68% of the 47 matched historical sweeps reversed
+1.4 ATR — the average reversal distance among those that reversed
N=47 — 47 historical sweeps matched this context
Label color follows sweep direction: orange-red for a swept high (bearish sweep), cyan for a swept low (bullish sweep).
While training data is still being collected, the label shows: Training… (8/20 needed)
█ LIQUIDITY VOID ZONE
When a sweep candle has a long wick, there is a gap between the wick extreme and where price actually closed. This zone — where price moved through too fast for normal order flow — is drawn as a semi-transparent dashed box. It represents an imbalance that price frequently returns to fill. The void is colored by sweep direction.
█ DASHBOARD
The top-right table shows:
• Session KZ — which killzone is currently active, if any
• ATR Ratio — current ATR relative to the 50-bar baseline (amber above 1.5×)
• KNN Training — progress bar showing recorded sweep outcomes vs maximum
• Overall Rev % — total reversal rate across all recorded sweeps on this chart
• Avg Rev Dist — average reversal move in ATR across all reversals
• Avg Cont Dist — average continuation move in ATR across all continuations
• Active Pools — number of unswept pools tracked, with EQH/EQL count
• Pending Sweeps — sweeps waiting for their outcome window to complete
• Resolved — count of confirmed reversals and continuations
• KNN Features — reminder of the five features used in the model
█ SETTINGS
Pool Detection
• Primary Pivot Length (10) — bars each side to confirm a major swing
• Secondary Pivot Length (8) — bars each side for minor swings; 0 disables
• Max Tracked Pools (60) — cap on active pools; oldest removed when exceeded
• Max Pool Age (50 bars) — pools older than this are expired without recording
• Equal-Level Tolerance % (3.0) — proximity threshold for EQH/EQL merging
Sweep Settings
• Sweep Buffer (1.4 × ATR) — minimum close beyond pool to register a sweep
• Outcome Window (10 bars) — measurement window after each sweep
• Reversal Threshold (3.5 × ATR) — minimum retracement to classify as reversal
• Show Liquidity Void Zones — toggle the wick imbalance boxes
• Max Historical Sweeps Shown — cap on how many past events are displayed
KNN Engine
• K Neighbors (15) — historical sweeps to average; higher = smoother, slower to adapt
• Max Training Samples (400) — rolling window; oldest samples dropped when exceeded
• Min Samples Before Display (20) — KNN output hidden until this threshold is reached
• ATR Baseline Period (50) — period for the baseline ATR used in the volatility feature
█ TIMEFRAME
Works on any intraday timeframe. Most useful at 5-minute through 1-hour where enough sweeps accumulate to build meaningful training data within a single session. On daily charts, the training window fills slowly but the signals tend to be higher quality.
The KNN model relearns continuously as new sweeps are recorded and old ones fall outside the rolling window. It adapts to the instrument and timeframe it is applied to.
█ NOTES
The reversal probability reflects historical behavior on this chart and timeframe. It is not a forward guarantee. A sweep with Rev 70% still continues 30% of the time. Use the N count as a confidence indicator — higher N means more matched examples and a more reliable estimate.
The model requires at least 20 sweep outcomes before displaying predictions. On timeframes with infrequent sweeps, this may take time to accumulate.
█ DISCLAIMER
This script is a visualization and analytical tool. It does not generate trade signals and does not constitute financial advice. Past sweep behavior does not guarantee future outcomes. Indicateur

Machine Learning Smart Money Concepts | GainzAlgo
What It Is
This is a TradingView indicator that fuses two ideas that don't usually share a chart:
Smart Money Concepts (SMC): classic structure-based trading, specifically Change of Character (CHoCH) detection off swing highs/lows.
K-Nearest Neighbors (KNN) : a simple, non-parametric machine learning method — used to score each new structure break against the most similar structure breaks that happened earlier on the same chart, and to project price targets from how those similar setups actually played out.
In plain terms: every time price breaks structure, the indicator asks 'what did the last several breaks that looked like this one actually do?' and uses that historical evidence to assign a probability and a set of price targets, instead of relying on a fixed, one-size-fits-all rule.
Structure first (the SMC layer)
The indicator finds swing points using ta.pivothigh / ta.pivotlow with a configurable pivot length. It tracks a simple internal trend state (marketTrend: up / down / neutral) and flags a CHoCH:
Bullish CHoCH: price closes above the last swing high while the prevailing state was not already bullish (i.e., a flip up).
Bearish CHoCH: price closes below the last swing low while the prevailing state was not already bearish (i.e., a flip down).
This is the standard SMC definition of "change of character", the first sign that the prior trend may be giving way to a new one.
Turning the break into an actionable trade
When a CHoCH fires, the script doesn't just say "structure broke", it measures how it broke, using three features computed over the bars since the prior swing point:
Volume delta: An estimate of buy vs. sell pressure on each bar (derived from where the close sits within the bar's range, weighted by volume), averaged over the move. Positive = buyers dominant, negative = sellers dominant.
Displacement: The size of the price move since the swing point, normalized by ATR. This tells you whether the break was a forceful, large-range move or a weak, barely-there one, independent of the instrument's raw volatility.
Velocity: Displacement divided by the number of bars it took (i.e., how fast the move happened.)
Finding lookalikes (the KNN engine)
The script keeps a rolling database (capped at 2,000 records, with a "Historical Memory Window" limiting how far back it'll search) of every previous CHoCH's fingerprint, along with what actually happened afterward.
For a new CHoCH, it:
Filters the database to past events of the same direction (bullish vs. bearish) within the memory window.
Computes Euclidean distance between the new fingerprint and every stored one.
Pulls the K nearest neighbors (default 5) — the most similar past setups.
Uses those neighbors to calculate:
1. A Significance Score = % of the K neighbors where price moved further in the favorable direction than the adverse direction (i.e., a "win rate" among lookalikes).
2. Three price targets, built from the distribution of how far those neighbor setups actually ran:
TP1 (mean × conservative scalar) — a toned-down average outcome.
TP2 (median) — the typical outcome.
TP3 (75th percentile) — a stretch/aggressive outcome.
These 3 targets are represented by a drawn box on the chart.
How the database learns (the "training" loop)
This is the part that makes it adaptive rather than a static rule set. On every bar, the script checks: did a CHoCH happen exactly lookahead bars ago (default 20)? If so, it now has enough hindsight to grade that old setup:
It walks forward through those 20 bars and finds the maximum favorable excursion and maximum adverse excursion from the price at the time of that old CHoCH.
It labels the outcome (favorable > adverse → success) and records the fingerprint as it existed at that time, plus the result, into the database.
So the model is continuously and only ever trained on fully resolved history, never on the bar currently forming. It's an online-learning loop: today's signal is scored against yesterday's already-graded outcomes, and today's setup itself won't be graded and added to the database until lookahead bars from now.
What's Drawn on the Chart
CHoCH connector line: solid line from the broken swing point to the breakout close.
Broken level marker: dashed line showing the swing high/low that got taken out, plus a short dotted line marking the actual break.
Wick trace: a stylized multi-layer glow line tracing the wicks leading into the break (purely visual/aesthetic).
CHoCH region fill: soft fill color between the wick trace and the broken level.
Probability badge: small label (▲/▼ + %) printed near the break; gets a ★ if direction confidence is ≥85%.
CHoCH tag: secondary tiny label showing "+CHoCH / −CHoCH" and the raw significance score.
Target box — a shaded box from TP1 to TP3 with a dotted TP2 line through the middle, extended a fixed number of bars to the right.
Dynamic Target Ribbon: a smoothed (SMA-based) pair of lines tracking the most recent bull/bear target, with a fill between them, giving a continuously-updating visual "zone."
Side panel (table): live readout of bias (bullish/bearish/neutral), current significance score, last TP1/TP2/TP3 with counts of how many of each tier are still outstanding (unhit), database size, current volume delta, the active swing high/low, and the K / Window settings.
Settings Guide
🧠 Quant Engine
Look-Ahead Window (Bars): how many bars forward the model waits before grading a past CHoCH and adding it to the database. Larger = more patient/accurate labeling but slower to build a dataset.
Historical Memory Window: how far back (in bars) the KNN search is allowed to look for neighbors. Smaller = more regime-adaptive (recent behavior only); larger = more data per query but less responsive to regime shifts.
K-Nearest Neighbors (K): how many lookalikes to average over. Lower K = more reactive/noisy; higher K = smoother but slower to reflect new behavior.
Min Significance Score (%): the threshold below which the indicator visually marks a signal as low-conviction (greyed badge) rather than colored.
ATR Period: used both for the displacement feature and for badge placement offsets.
Pivot Length: swing-point sensitivity; smaller = more (and earlier, but less confirmed) swings.
🎯 Target Levels
Conservative Scalar: multiplier applied to the mean neighbor outcome to produce TP1.
Target Extension (Bars): how far right the target box are drawn.
How to Use It
Wait for a CHoCH badge. Direction is shown by the arrow; the percentage is the KNN-derived probability that this break behaves like the favorable-outcome neighbors.
Check the significance score against your threshold. Setups below your Min Significance Score print in a neutral grey, treat these as "structure broke, but the model has no strong opinion" rather than as a clean signal.
Use the target box as a planning zone, not a guarantee. TP1 is the conservative/likely zone, TP2 the typical outcome among similar past moves, TP3 the stretch target, read it as a probability-weighted range, not a prediction.
Watch "DB Records" in the side panel. Early on a chart, or on a symbol with limited history, the database will be small and the KNN matches less statistically meaningful. The model gets more reliable as it accumulates more graded history.
Use the ★ marker as an extra filter. It only appears when directional confidence (not the raw significance score, but the bull/bear probability split) is ≥85%.
Cross-reference with the bias/volume-delta in the panel for a quick read on whether the broader trend state and the most recent candle pressure agree with the new signal.
Helpful Trade Tips
Tip 1: Works extremely well on larger timeframes. Sweet spot is hourly and daily, which positions this indicator well for swing traders. Let's take a look at some examples:
Example 1: SPY 30-Minute timeframe
Here, with extended hours disabled, SPY snagged 8/9 of its target boxes.
Example 2: QQQ Weekly
Here, QQQ touched all recent targets.
This highlights the strength of SMC to aid traders in having higher timeframe and longer range expectations based on the structural changes of the market.
Let's highlight a few other examples:
Example 3: BTCUSD on the Daily timeframe
Here, BTC shows its loyalty to SMC, hitting the majority of its targets on the daily timeframe.
Note: One thing to be aware of, to prevent the chart from looking overly cluttered, the box length has been sized to the immedate range to prevent a messy looking chart. However, you can manually adjust the size by using the "Manual Extension (Bars)" feature in the settings menu to increase the width of the target boxes. Here is an example:
Alerts
You can set custom alerts with this indicator to trigger buy and sell signals based on a probability threshold. You can set the probability thresholds for bearish and bullish conditions within the indicators setting menus. Then, toggle over to the alerts menu and set your Buy and Sell alerts. From there, you will be notified when there is a CHoCH that meets your specific probability threshold. Indicateur

Streaming ML Probability Triple-Barrier, Conformal & CalibratedStreaming-ML Probability — Triple-Barrier, Conformal & Calibrated
What it is
A self-training probability model that estimates P(up-barrier resolves before down-barrier) and — crucially — reports its own calibration. The differentiator is not the classifier; it is the labelling and the honesty layer wrapped around it. The pane shows a probability, an honest uncertainty band, a plain-language verdict, and a reliability diagram that tells you whether to believe any of it.
Why these components belong in ONE script (not a stack of indicators)
They are the stages of one honest prediction pipeline, each fixing a failure mode of a naive "ML" overlay:
Triple-barrier labels define what is predicted as a real, path-dependent outcome (which barrier is hit first) instead of an arbitrary "next bar up?", and resolve forward in time so training only ever sees confirmed results — no look-ahead.
Z-scored, bounded features keep every input finite so no single bar can blow up the online weights.
Logistic SGD + Lorentzian k-NN, fused in log-odds with a Kish decorrelation shrink — a linear model for the trend and a fat-tail-tolerant neighbour vote for non-linear structure, combined without double-counting the shared features.
Regime engine (efficiency + ADX + Hawkes) gives each market state its own calibration and shrinks the probability toward 0.5 where a regime is barely seen — the model defers to a coin flip where it has not learned.
Adaptive Conformal Inference turns the point estimate into a coverage-controlled band that holds under drift, so the uncertainty is honest rather than a fake point estimate.
Conviction + hard vetoes (regime, MTF, participation/CVD, calibration quality) stop the model acting on a number it cannot back up.
The calibration harness — reliability table, Brier score, and forward edge versus an unconditional base rate — is the whole point: a probability is only useful if 70% means 70%.
Labels say what to learn, features feed it, the fused classifier predicts, regime + conformal say how much to trust it, the vetoes gate it, and calibration proves whether any of it held. Remove a stage and the honesty breaks — that is why they ship as one engine.
How it works (mechanics)
Each confirmed bar opens a triple-barrier sample (unless the OU half-life says reversion is too slow to resolve in the horizon). When a sample resolves, the model takes one online gradient step on its own features and outcome, the resolved sample enters the k-NN memory, and the nonconformity score updates the conformal band via Gibbs-Candès ACI. The live probability is the log-odds fusion of the logistic output and the Lorentzian k-NN vote, regime-shrunk during warm-up. A directional signal fires only when the probability band clears the signal margin, conviction clears its floor, and no hard veto trips. Every resolved directional call is then scored against an unconditional same-horizon base rate (Hit% vs Base%, Wilson-bounded, regime- and recency-weighted).
Non-repaint: training only on resolved triple-barrier outcomes, signals on bar close, MTF requested with lookahead_off, no dynamic-length ta(). The live probability updates each bar — a current estimate from fixed historical training.
How to use
Read the VERDICT line first — ACT, STAND ASIDE (no calibrated edge), or WAIT, based on the live signal and the model's own calibration.
Check the reliability diagram / Brier. Points off the diagonal, or Brier ≥ 0.25 (worse than a coin flip), mean the probability is not trustworthy yet — the engine will tell you to stand aside.
A signal fires only on confluence: probability past the band-margin, conviction past the floor, no hard veto.
The conformal band is the honest uncertainty — a wide band means low confidence.
Everything here is descriptive, probabilistic context — never an instruction.
Note on honesty: on pure intraday noise (e.g. NIFTY 1-minute) this model will often show NO EDGE / VETO with Brier ≈ worse than a coin flip — and it says so plainly rather than inventing a signal. That is the intended behaviour.
Use on any market
The Data Source inputs (Close / High / Low / Volume) drive the features, the triple-barrier labels and the calibration, so the model runs on any series (standard candles, Heikin-Ashi, etc.) and any market. All thresholds are ATR-relative. Defaults are set for NIFTY index-futures intraday; change the source or lengths for other assets. Assets with no volume simply contribute nothing through the volume feature.
Originality
Most "machine-learning" indicators emit an uncalibrated score that is never checked against what actually happened. The contribution here is the closed, honest loop: real path-dependent labels, a fused-but-decorrelated classifier, regime-conditional shrinkage, a drift-robust conformal band, conviction/veto gating, and a built-in reliability + Brier + edge harness that can — and often does — tell you the model has no edge right now. It is built to be disprovable, which is the opposite of most signal scripts.
Credits
Triple-barrier labelling & meta-labelling — Marcos López de Prado
Logistic regression / SGD — classical statistics
Lorentzian (non-Euclidean) distance for k-NN — relativistic-distance concept
Conformal prediction — Vovk, Gammerman & Shafer; Adaptive Conformal Inference — Gibbs & Candès
Brier score — Glenn W. Brier
Wilson score interval — Edwin B. Wilson
Efficiency Ratio — Perry Kaufman · ADX / DMI — J. Welles Wilder
Hawkes self-exciting process — Alan G. Hawkes
Ornstein-Uhlenbeck / AR(1) half-life — Ornstein & Uhlenbeck
Effective-sample decorrelation — Leslie Kish
The pipeline assembly, the regime-conditional calibration and the conviction/veto layer are the author's original implementation.
Limitations (honest)
A well-calibrated probability is not an edge after costs. The forward stats are in-sample, close-to-close at a fixed horizon, with no costs, slippage or stops — a study aid, not a backtest. The model is small (six features, online weights); it warms up slowly and will stand aside often. Past behaviour does not assure future behaviour.
Disclaimer
Educational / informational study for chart analysis only. NOT financial advice, NOT a strategy, NOT a recommendation. It places no orders and guarantees no outcome. Markets carry risk; do your own research and manage your own risk. Paper-trade before risking real money. Indicateur

Historical Pattern Projection [MarkitTick]💡 An advanced analytical framework engineered to identify, isolate, and project current price action based on historically correlated market structures. Rather than relying on traditional lagging oscillators or subjective chart patterns, this tool continuously evaluates the most recent sequence of price movements—termed the "fingerprint"—and algorithmically scans historical data to find statistically similar precedents. By projecting the historical outcomes of these matching patterns onto the current chart, it provides an empirical, data-driven perspective on potential near-term price trajectories, seamlessly bridging the gap between quantitative correlation analysis and practical trade management.
✨ Originality and Utility
Traditional technical analysis often relies on rigid, subjective patterns (such as head-and-shoulders or flags) which can be open to interpretation and cognitive bias.
This script completely bypasses subjective pattern drawing by employing a strictly mathematical approach to shape-matching.
It normalizes price action into a pure structural format, allowing it to compare the geometry of the current market with historical markets, regardless of the absolute price levels.
The utility lies in its ability to automatically synthesize the "what happened next" data from historical matches.
Instead of merely signaling overbought or oversold conditions, it provides a probabilistic projection path—a "ghost line"—complete with expected volatility bands and automated risk management levels based on the anticipated outcome.
🔬 Methodology and Concepts
● Core Recognition Engine
• Data Normalization: The current price sequence (the fingerprint) is converted using a statistical Z-Score. This transformation removes the absolute price values and leaves behind the raw volatility-adjusted shape of the trend.
• Deep Historical Scanning: The algorithm iterates backwards through user-defined historical bars (Search Depth) to extract rolling arrays of previous price action.
• Statistical Correlation: Each historical array is compared to the current fingerprint using the Pearson Correlation Coefficient. The resulting value (-1.0 to +1.0) is mathematically scaled into a percentage (0% to 100%) to represent a "Similarity Score."
● Outcome Synthesis and Extrapolation
• Match Aggregation: The script filters out matches that fall below the minimum Similarity Score threshold, keeping only the top configured matches.
• Trajectory Calculation: For each valid match, the script records the price movement that occurred immediately after the historical pattern completed.
• Price Scaling: The historical outcomes are structurally scaled and tethered to the current closing price, allowing the indicator to plot a composite average of these historical outcomes directly into the future empty space of the chart.
🎨 Visual Guide
● On-Chart Projections and Highlights
• ECHO Match Zones: The historical periods that closely match the current price action are highlighted with thick, colored vertical bands (defaulting to deep orange). These zones allow for immediate visual verification of the structural similarity.
• Ghost Line (Projection): Plotted into the future, this solid, fading purple line illustrates the average expected trajectory based on the historical matches. It features an arrow and percentage label at the terminus to indicate the total projected directional move.
• Range Bands: Dashed, semi-transparent purple lines expanding outward from the Ghost Line. These bands represent the expected volatility expansion over the projection period, calculated using a dynamically scaling Average True Range (ATR).
● Trade Management Ecosystem
• Entry Box: A highlighted zone (default yellow) projecting forward from the current bar, representing an optimal entry width based on a fraction of the current ATR.
• Stop Loss (SL) Line: A solid red horizontal line indicating the suggested invalidation level, dynamically placed away from the entry using an ATR multiplier.
• Take Profit (TP) Lines: Three dashed green horizontal lines representing tiered profit targets (TP1, TP2, and TP3), scaled mathematically via ATR multipliers in the direction of the historical bias.
● The ECHO Dashboard Table
• Top Match Score: Displays the similarity percentage of the most highly correlated historical pattern. Color-coded for rapid assessment (Green for Strong >80%, Yellow for Moderate, Orange for Weak).
• Fingerprint & Depth: Confirms the lookback length and the total bars scanned.
• Outcome Metrics: Displays the historical "Votes" (percentage of matches that went Bullish, Bearish, or Neutral) and the overall Average Move.
• Historical Roster: The bottom half of the dashboard ranks the individual top historical matches, detailing their exact score, how many bars ago they occurred, and their specific post-pattern return.
📖 How to Use
• Pattern Validation: Monitor the ECHO Dashboard for patterns that achieve a Similarity Score of 80% or higher. Lower correlation scores should be treated with high skepticism as the historical geometries are not closely aligned.
• Bias Confirmation: Check the "Proj Bias" and "Votes" metrics on the dashboard. A strong projection should ideally have unanimous or near-unanimous historical consensus (e.g., 100% Bullish votes).
• Trade Execution: If a high-probability setup is identified, utilize the projected Trade Management levels. The highlighted Entry Box provides a buffer for execution, while the SL and TP lines offer an objective, volatility-adjusted framework for placing orders.
• Alert Integration: The indicator can be tied to dynamic webhooks. Set an alert on the indicator, and when a "Strong" match is found, it will automatically transmit a JSON payload containing the Entry, Stop Loss, and Take Profit levels for automated systems or notifications.
⚙️ Inputs and Settings
● Core Settings
• Freeze Data: A toggle that stops the algorithm from updating on every tick, locking the current projection in place for stable analysis.
• Fingerprint Length: The number of current bars used to form the recognizable pattern. Shorter lengths are highly responsive but prone to noise; longer lengths find deep structural macro-patterns.
• Search Depth: The maximum number of historical bars the algorithm will scan. Increasing this expands the database but requires more computational resources.
• Min Score (%): The correlation threshold required for a historical pattern to be considered valid.
● Projection & Risk Settings
• Ghost Length: Defines how many bars into the future the algorithm should project the historical outcome.
• Entry Width (xATR): Defines the vertical height of the entry box based on current volatility.
• SL & TP Multipliers: Adjustable factors that determine the distance of Stop Loss and Take Profit levels based on the current 14-period ATR.
🔍 Deconstruction of the Underlying Scientific and Academic Framework
• Z-Score Standardization: The algorithm employs standard score normalization to analyze price action. By subtracting the moving average (mean) from the price and dividing by the standard deviation, the data is transformed into a dimensionless unit. This ensures that a pattern occurring in a low-volatility environment can be mathematically matched to the exact same geometric structure occurring in a high-volatility environment.
• Pearson Correlation Coefficient: The core matching engine relies on Pearson's *r*, a measure of linear correlation between two sets of data. The formula computes the covariance of the current fingerprint and the historical candidate window, divided by the product of their standard deviations. This rigorously quantifies how closely the two price paths mirror each other over the specified timeframe.
• Volatility-Adjusted Target Extrapolation: Rather than using fixed percentages or subjective support/resistance, the script utilizes the Average True Range (ATR) to govern its forward-looking risk management bands. Because market regimes shift, the ATR ensures that the projected bands and trade levels expand during turbulent market phases and contract during periods of consolidation, maintaining mathematical proportionality to current market conditions.
• Algorithmic Caveats: Because the script continuously scans and matches the most recent data, the projected path will shift dynamically as new bars form, unless the "Freeze" function is engaged. Furthermore, the indicator evaluates the close of bars; running this framework on non-standard synthetic charts (such as Heikin Ashi or Renko) is fundamentally flawed due to the artificial smoothing of synthetic price data, which alters the underlying statistical distribution.
⚠️ Disclaimer
All provided scripts and indicators are strictly for educational exploration and must not be interpreted as financial advice or a recommendation to execute trades. We expressly disclaim all liability for any financial losses or damages that may result, directly or indirectly, from the reliance on or application of these tools. Market participation carries inherent risk where past performance never guarantees future returns, leaving all investment decisions and due diligence solely at your own discretion. Indicateur

Machine Learning Adaptive DMI Signals [AlgoAlpha]🟠 OVERVIEW
The Directional Movement Index (DMI) is commonly calculated using a fixed lookback length. But market conditions change over time, and a length that works well during one period may become less effective during another.
This script builds multiple DMI models across a user-defined range of lengths and continuously evaluates their past performance. Each DMI length acts as an independent expert. As new directional flips occur, the script measures how well each expert performed and updates its internal scoring system.
The result is an adaptive DMI that automatically shifts toward lengths that have recently produced better directional signals while reducing the influence of weaker performers.
🟠 CONCEPTS
Expert DMI — A DMI calculation running at a specific lookback length within the tested range.
Directional Flip — A change in trend state when +DI crosses above -DI or when -DI crosses above +DI.
Reward Score — A performance score assigned to each completed flip based on return, move quality, pullback behavior, or win rate.
Maximum Favorable Excursion (MFE) — The largest move in the trade's favor before the next directional flip.
Maximum Adverse Excursion (MAE) — The largest move against the trade before the next directional flip.
Recency Decay — A weighting system that gradually reduces the influence of older observations so recent market behavior has greater impact.
Softmax Weighting — A probability-style weighting process that gives greater influence to higher-scoring DMI lengths when estimating the adaptive length.
🟠 FEATURES
Adaptive +DI and -DI Lines — Displays directional movement using a dynamically selected DMI length that adjusts over time.
Directional Clouds — Color-filled regions between the DI lines help visualize which side currently has directional control.
Bullish and Bearish Flip Signals — ▲ and ▼ markers appear when the Adaptive +DI and -DI lines cross.
ADX Strength Display — Strength squares at the bottom of the pane become more visible as trend strength increases and fade as strength decreases.
Information Table — Displays the active adaptive length, selected scoring mode, memory count, and current bullish or bearish trend state in a customizable table.
🟠 HOW TO USE
Watch for bullish flips when Adaptive +DI crosses above Adaptive -DI to identify potential shifts toward upward directional control.
Watch for bearish flips when Adaptive -DI crosses above Adaptive +DI to identify potential shifts toward downward directional control.
Use the ADX strength squares to gauge whether directional movement is strengthening or weakening.
Increase the tested length range when evaluating a wider variety of market conditions.
Increase Memory and Forget Old Trades values for more stable adaptation and slower length changes.
Decrease Memory or lower the decay factor when faster adaptation to recent behavior is preferred.
Experiment with the available scoring methods to determine whether return, trend quality, or consistency is more important for your analysis.
🟠 CONCLUSION
Machine Learning Adaptive DMI combines traditional DMI calculations with a performance-driven adaptive length selection process. Instead of relying on a fixed lookback period, it continuously evaluates how different DMI lengths have behaved and adjusts accordingly. This provides a dynamic view of directional strength, trend bias, and signal quality that reflects recent market behavior. Indicateur

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

AI-Powered PDH/PDL Power Ranker [PhenLabs]📊 ML-Powered PDH/PDL Power Ranker
Version: PineScript™ v6
📌 Description
ML-Powered PDH/PDL Power Ranker is an adaptive support/resistance indicator that tracks Prior Day High and Prior Day Low levels across a configurable session lookback, then ranks each level on a 0–100 scale based on how strongly price has historically reacted to it.
Instead of treating every PDH and PDL as equally important, this script continuously learns which levels deserve attention. It evaluates live touches, measures the realized rejection after a user-defined confirmation window, and updates each level with either a shared NLMS model or an independent Kalman estimator.
The result is a causal, non-repainting ranking engine that helps traders focus on the strongest daily levels, identify high-confidence reaction zones, and ignore weak or stale liquidity areas.
🚀 Points of Innovation
Adaptive level scoring using two genuine learning models: shared NLMS or per-level Kalman filtering
Strictly causal labeling process that waits for confirmed post-touch reaction before updating any score
Feature-based learning framework using wick rejection, relative volume spike, and ATR-normalized approach momentum
Untouched-level score shrinkage logic that prevents zero-evidence levels from outranking proven levels
Session-aware PDH/PDL generation that respects TradingView session boundaries, including extended-hours configurations
Top-ranked dashboard plus high-confidence zone highlighting and touch alerts for fast execution workflow
🔧 Core Components
PDH/PDL Session Engine: Captures completed-session highs and lows, stores them as active levels, and prunes old levels based on the selected lookback window
ATR Zone Builder: Expands each level into a configurable reaction band using ATR(14), creating realistic touch zones instead of single-price lines
NLMS Learning Model: Uses a normalized least-mean-squares filter to learn a global mapping from touch features to realized reaction quality
Kalman Strength Filter: Maintains an independent latent-strength estimate for each level using scalar Kalman state updates
Causal Touch Resolver: Snapshots features on zone entry, waits a fixed number of bars, then measures realized rejection with no lookahead
Ranking Dashboard: Sorts active levels by display score and shows the strongest zones with age, touch count, and score
🔥 Key Features
Ranks every active PDH and PDL from 0 to 100 so the best daily levels stand out immediately
Offers two adaptive engines so traders can choose between cross-level learning (NLMS) or level-specific state estimation (Kalman)
Uses entry-based touch detection to avoid overcounting consolidations sitting inside the same zone
Applies ATR-normalized reaction measurement so scoring remains comparable across symbols and volatility regimes
Highlights high-confidence zones directly on the chart when price is trading inside them
Triggers alert conditions when price touches a zone whose score is above the high-confidence threshold
Includes a clean top-5 ranking table so traders can identify the strongest daily levels at a glance
🎨 Visualization
Dynamic zone boxes show each PDH and PDL as a buffered reaction area rather than a thin horizontal line
Gradient-based score coloring makes weak levels fade cool and strong levels turn hot
On-chart labels display level type, age in sessions, and current score
Optional background highlight marks bars trading inside a high-confidence zone
Ranking dashboard lists the top levels by score along with touch counts and exact price levels
📖 Usage Guidelines
Level Detection
Session lookback (days) — Default: 7 — Range: 1 to 15 — Controls how many completed sessions of PDH/PDL levels remain active. Lower values keep the chart cleaner; higher values preserve more historical daily structure.
Zone buffer (× ATR-14) — Default: 0.15 — Range: 0.01 to 2.0 — Sets the half-width of each PDH/PDL zone in ATR units. Increase it for volatile markets; reduce it for tighter precision.
Adaptive Model
Adaptive model — Default: NLMS — Options: NLMS or Kalman — NLMS learns globally across all resolved touches, while Kalman maintains a separate evolving strength estimate for each level.
Reaction confirmation bars — Default: 6 — Range: 2 to 50 — Defines how long the script waits after a touch before measuring the realized reaction. Larger values emphasize slower reversals; smaller values emphasize immediate rejection.
NLMS step size (μ) — Default: 0.50 — Range: 0.01 to 2.0 — Controls learning speed for the NLMS model. Higher values adapt faster but can be more reactive.
Kalman process noise (Q) — Default: 0.010 — Minimum: 0.0001 — Controls how quickly a level’s true strength is allowed to drift between observations.
Kalman measurement noise (R) — Default: 0.20 — Minimum: 0.001 — Controls how noisy each touch observation is assumed to be. Higher values smooth updates and slow score changes.
Display & Alerts
Min score to display — Default: 55 — Range: 0 to 100 — Hides weaker levels from the chart while still tracking them internally
High-confidence threshold — Default: 75 — Range: 0 to 100 — Defines which zones qualify for hot-zone highlighting and touch alerts
Show ranking dashboard — Default: true — Toggles the top-ranked PDH/PDL table
Highlight bar inside high-confidence zone — Default: true — Adds background emphasis when price is currently trading inside a strong zone
✅ Best Use Cases
Intraday trading around prior-day liquidity and reaction zones
Session traders who want objective ranking of PDH/PDL instead of manually judging every level
Futures, indices, forex, and crypto markets where daily highs and lows act as repeat reaction points
Confluence trading alongside structure, liquidity sweeps, VWAP, or order-flow tools
Traders who want non-repainting, evidence-based level scoring instead of static daily levels
⚠️ Limitations
The model needs resolved touch history before scores become highly informative, so early readings are more neutral
PDH/PDL relevance depends on symbol behavior, session configuration, and timeframe context
Very low-liquidity markets or feeds with weak volume data can reduce the usefulness of the volume-spike feature
This indicator ranks reaction quality at prior-day levels; it does not predict trend direction by itself
Kalman and NLMS may emphasize different behaviors, so traders should test which model best fits their market
💡 What Makes This Unique
It does not just plot PDH and PDL — it learns which ones actually matter
Its labeling process is fully causal, so model updates occur only after the reaction window has completed
It combines level memory with adaptive inference instead of using a static heuristic score
It prevents untouched levels from dominating the rankings through trust-weighted prior shrinkage
🔬 How It Works
1. Session Level Creation:
At each new daily session boundary, the script stores the completed session’s high and low as fresh PDH and PDL levels
Each level is assigned metadata including age, touch count, score state, and pending-observation slots
2. Touch Feature Capture:
When price enters a zone from outside, the script records three features: wick rejection ratio, relative volume spike, and 3-bar ATR-normalized approach momentum
This entry-only logic prevents repeated relabeling while price chops inside the same zone
3. Causal Reaction Resolution:
After the selected confirmation window expires, the script measures realized rejection strength in ATR units
That realized move is mapped into a normalized target so the model learns from consistent cross-market observations
4. Adaptive Score Update:
In NLMS mode, the shared weight vector updates from every resolved observation, then blends the fresh model prediction with that level’s own EMA of realized reactions
In Kalman mode, each level updates its latent strength estimate using scalar predict-and-correct filtering
5. Display Ranking and Alerts:
The script converts model output into a 0–100 score, ranks active levels, colors zones by strength, and highlights high-confidence areas
An alert condition fires when price touches a zone whose score is already above the selected confidence threshold
💡 Note:
This script is designed to be non-repainting and strictly causal. For best results, use it as a level-prioritization engine inside a broader execution framework that includes market structure, trend context, and risk management. Indicateur

AI Trend Detector | Adaptive Signals [NeuraLib Machine Learning]🔷 AI Trend Detector | Adaptive Signals
AI Trend Detector is a NeuraLib-powered Machine Learning indicator. It trains a compact supervised neural model on confirmed historical movement, then uses the current market state to estimate Bear , Neutral , and Bull pressure.
The model output is converted into a clean visual system:
Trend Oscillator : A 0-100 pressure gauge. Lower values suggest bullish pressure or oversold conditions. Higher values suggest bearish pressure or overbought conditions.
Adaptive MA Cloud : A main-chart adaptive moving average with an AI-biased cloud that expands as model pressure moves away from neutral.
Confirmed Triangles : Optional chart markers for overbought and oversold interactions, with modes for zone entry, zone exit, or confirmed rotation inside a zone.
Dashboard : A compact readout showing the current state, signal value and confidence.
Triangle Alerts : Alert conditions tied to the same confirmed marker logic shown on the chart.
Directional Confidence : An optional 0-100 line showing the stronger directional model probability, calculated from the larger of Bull or Bear pressure. It does not include Neutral probability, so it reflects directional conviction rather than overall model certainty.
This is not a fixed crossover system. The signals are the visual layer of a model-driven trend pressure engine.
---
🔷 How The Model Learns
Each bar contributes a compact feature row based on price movement, adaptive MA context, and distance from the adaptive baseline. NeuraLib stores these rows in a rolling dataset, normalizes the inputs, and trains the model on recent time-series windows.
The model is trained as a 3-class classifier:
Bear
Neutral
Bull
Historical training examples use future-resolved movement to create their target class, but only after that movement has already occurred. This is the supervised learning setup: the model learns from completed historical outcomes, then applies its learned weights to the current live feature window.
The exposed settings allow users to experiment with model size, learning rate, training frequency, smoothing, trend horizon, and signal behavior.
---
🔷 Model Architecture
The model uses a compact temporal classification architecture:
Flattened state window : Recent feature rows are combined into one temporal input.
Temporal convolution stack : Conv1D-style layers extract short-term structure from the recent market sequence.
Global average pooling : The temporal output is compressed into a compact state representation.
Dense classifier head : One or two dense layers process the pooled state.
Three output logits : The model produces Bear, Neutral, and Bull logits, which are converted into display probabilities.
This keeps the model small enough for Pine Script while still giving it a true sequence-learning structure rather than a simple crossover or rule-based signal engine.
---
🔷 Reading The Signals
The oscillator is intentionally inverted for intuitive market reading:
Low values : Oversold or bullish pressure.
Mid values : Balanced or neutral pressure.
High values : Overbought or bearish pressure.
Triangles can be configured through the Triangle trigger setting:
Crossing into : Prints when the oscillator crosses into an overbought or oversold zone.
Going out of : Prints when the oscillator exits an overbought or oversold zone.
Rotation inside zone : Prints when the signal forms a confirmed turn while still inside the zone.
In rotation mode, Rotation confirmation controls how many bars must pass without breaking the candidate peak or trough before the marker is accepted. Rotation triangles print on the confirmation bar, not on the older pivot bar.
The adaptive MA cloud is visual only. The model is not trained on the shifted cloud edge. The cloud simply applies model pressure around the adaptive MA baseline.
---
⚠️ Repainting And Signal Timing
The training and signal system is designed around confirmed bars:
Training rows are pushed on confirmed bars.
Triangle signals are gated with barstate.isconfirmed .
Rotation markers print on the confirmation bar.
No negative plot offsets are used to move markers into the past.
The smoothing path uses current and past values only.
Because this model does not train on the full price history, but instead learns from the most recent N bars, repainting may occur when the script is reloaded at a later date. This happens because the model may begin training from a different market environment.
To help preserve the original model state, adjust the Historical Train Window setting to account for any new bars that have been added since the original run.
---
⚠️ Limitations
Machine Learning inside Pine Script is powerful, but it is still bounded by TradingView's execution model.
The model is compact by design.
Training history is bounded for performance.
Changing hyperparameters rebuilds the model.
Signals depend on the chosen horizon, threshold, smoothing, and triangle mode.
The model estimates directional pressure. It does not know your entries, exits, risk, fees, or position sizing.
This indicator is best treated as a model-based market pressure tool, not as a complete trading system by itself.
This indicator is powered by the NeuraLib Deep Learning Runtime
Disclaimer: This indicator is an analytical and educational tool. It does not guarantee future results, signal accuracy, or financial gain. Past behavior does not ensure future behavior. Use it as one component in a broader trading process, under your own responsibility. Conceptual architecture and quantitative development by Alien_Algorithms.
Indicateur

NLMS Adaptive Trend Filter [BackQuant]NLMS Adaptive Trend Filter
Overview
The NLMS Adaptive Trend Filter is a machine learning inspired trend-following indicator built around one of the most important adaptive filtering algorithms in signal processing: the Normalized Least Mean Squares (NLMS) filter .
Unlike traditional moving averages that use fixed weighting schemes, the NLMS filter continuously learns from incoming market data and updates its internal coefficients in real time. Rather than assuming that price behavior remains constant, the filter attempts to adapt its structure as market conditions evolve.
This approach originates from the field of digital signal processing, where adaptive filters have been used for decades in applications such as:
• Telecommunications
• Radar systems
• Echo cancellation
• Noise reduction
• Speech processing
• Control systems
• Financial signal extraction
The goal of this indicator is to bring one of these adaptive filtering concepts into market analysis by creating a trend model that continually adjusts itself based on prediction error rather than relying on static averaging methods.
Historical Background
The roots of the NLMS filter can be traced back to the work of Bernard Widrow and Ted Hoff in the late 1950s and early 1960s.
While working at Stanford University, they developed what became known as the:
Least Mean Squares (LMS) Algorithm
The LMS algorithm was revolutionary because it provided a computationally simple method for training adaptive systems using gradient descent.
Rather than solving a complex optimization problem all at once, the LMS algorithm updates its weights incrementally after each observation.
The basic concept was:
1. Make a prediction.
2. Measure the prediction error.
3. Adjust the model slightly.
4. Repeat indefinitely.
This idea eventually became one of the foundational concepts behind modern machine learning and online optimization.
Many modern neural networks still rely on the same underlying principle:
Error → Gradient → Weight Update
The LMS algorithm later evolved into several variants, one of the most important being:
Normalized Least Mean Squares (NLMS)
NLMS improves stability by scaling weight updates according to the energy of the input signal.
This prevents learning rates from becoming too aggressive during high-volatility periods and too weak during low-volatility periods.
As a result, NLMS became one of the most widely used adaptive filtering algorithms in engineering.
What Makes NLMS Different From Moving Averages?
Traditional moving averages use predetermined weights.
For example:
Simple Moving Average (SMA)
Every observation receives equal weight.
Example:
20-period SMA
Each bar contributes:
1 / 20 = 5%
regardless of market conditions.
Exponential Moving Average (EMA)
Recent observations receive more weight.
The weighting structure is fixed and never changes.
Weighted Moving Average (WMA)
Uses linearly decreasing weights.
Again, the weighting scheme is fixed.
The problem is that markets do not operate under fixed conditions.
Volatility changes.
Trend persistence changes.
Noise levels change.
Market structure changes.
Yet traditional moving averages continue using the exact same weighting model.
NLMS takes a different approach.
Instead of assigning permanent weights, it learns them dynamically.
The filter constantly asks
"What weighting structure would have predicted the current market best?"
It then updates itself accordingly.
The Core Idea Behind Adaptive Filters
Imagine trying to forecast today's price using the previous 20 bars.
A normal moving average assumes a fixed weighting pattern.
An adaptive filter attempts to learn the optimal weighting pattern.
At every bar:
• A prediction is generated.
• Actual price is observed.
• Prediction error is measured.
• Weights are adjusted.
The process repeats indefinitely.
Over time, the filter learns which historical observations are most useful and which are less important.
Understanding Filter Taps
One of the most important concepts in adaptive filtering is the idea of:
Taps
A tap is simply a historical observation used as an input.
If the indicator uses:
20 taps
it means:
Price
Price
Price
...
Price
are all being used to generate the prediction.
Each tap receives a learned weight.
Instead of:
Current Estimate =Average of past 20 bars
the filter becomes:
Current Estimate =
(w1 × Price ) +
(w2 × Price ) +
(w3 × Price )
...
(w20 × Price )
The weights are continuously adjusted through learning.
How Prediction Works
The indicator attempts to estimate current price using previous observations.
Mathematically:
Prediction = Σ(weight × historical price)
This prediction becomes the filter output.
If the prediction is accurate:
Weights change very little.
If the prediction is poor:
Weights adjust more aggressively.
This allows the model to gradually adapt to changing market conditions.
Prediction Error
The engine measures:
Error = Actual Price − Predicted Price
This error drives all learning.
Large error means:
The model is wrong.
Small error means:
The model is performing well.
The objective is to minimize prediction error over time.
The LMS Learning Rule
The original LMS update rule is:
New Weight =Old Weight + Learning Rate × Error × Input
This is effectively a form of gradient descent.
The filter moves its weights in the direction that reduces future prediction error.
This is conceptually identical to many machine learning optimization methods.
Why Normalization Matters
The original LMS algorithm has a weakness.
When input values become very large:
Weight updates can become unstable.
This is particularly problematic in financial markets where volatility constantly changes.
NLMS solves this problem by normalizing updates according to signal energy.
Instead of:
Weight Update ∝ Error
it becomes:
Weight Update ∝ Error / Signal Power
This creates adaptive scaling.
When volatility expands:
Updates automatically shrink.
When volatility contracts:
Updates automatically expand.
This improves stability significantly.
How the Indicator Uses NLMS
The script implements an online one-step predictor.
For every new bar:
1. Previous M bars are gathered.
2. Current price is predicted.
3. Prediction error is calculated.
4. Weight vector is updated.
5. New estimate becomes available.
This process occurs continuously as new data arrives.
Because no future data is used, the filter remains fully causal and suitable for live trading.
Weight Initialization
Initially all weights are equal:
1 / M
This effectively starts the model as a simple moving average.
Over time the filter learns a custom weighting structure based on market behavior.
The initial equal-weight state acts as a neutral prior.
Step Size (μ)
The learning rate controls how aggressively the filter adapts.
Lower values:
• More stable
• Smoother output
• Slower adaptation
Higher values:
• Faster adaptation
• More responsiveness
• Greater noise sensitivity
Think of μ as controlling the intelligence speed of the model.
Small values make it conservative.
Large values make it reactive.
Regularization (ε)
Regularization prevents division by very small values.
Without it:
Periods of extremely low signal power could create unstable updates.
Regularization improves numerical stability and robustness.
It acts as a safety mechanism for the learning process.
Output Smoothing
After the NLMS estimate is generated, an optional EMA can be applied.
This smoothing is not part of the NLMS algorithm itself.
It exists purely for visual clarity.
The raw adaptive filter already contains the learning logic.
The smoothing stage simply reduces small fluctuations.
Setting smoothing to 1 effectively disables it.
Trend Detection
Trend direction is derived from the slope of the adaptive filter.
Bullish:
NLMS Output > Previous Output
Bearish:
NLMS Output < Previous Output
This creates a directional state machine.
Unlike crossover systems, trend changes occur whenever the adaptive estimate changes slope.
Bullish Flips
A bullish signal occurs when:
Trend changes from bearish to bullish.
This means the adaptive filter has transitioned from declining to rising.
Bearish Flips
A bearish signal occurs when:
Trend changes from bullish to bearish.
This means the adaptive filter has transitioned from rising to falling.
Visual Components
The indicator includes several visualization layers.
Adaptive Filter Line
The main output of the NLMS model.
This represents the learned trend estimate.
Gradient Fill
The space between price and filter is colorized.
Price Above Filter:
Bullish shading.
Price Below Filter:
Bearish shading.
This provides immediate visual context regarding trend alignment.
Edge Glow
An ATR-based glow surrounds price.
This helps emphasize directional conditions while improving chart readability.
Trend Candles
Candles can optionally inherit trend coloration.
Green:
Adaptive trend rising.
Red:
Adaptive trend falling.
This allows traders to visualize the model's directional state directly on price.
How It Differs From Traditional Trend Filters
Most trend indicators answer:
"What is the average price?"
NLMS attempts to answer:
"What weighting structure best predicts current price?"
This distinction is extremely important.
The indicator is not simply smoothing price.
It is continuously learning how price behaves.
Traditional indicators use fixed mathematics.
NLMS uses adaptive mathematics.
Strengths
• Self-adjusting weighting structure.
• Adapts to changing market conditions.
• Based on established signal-processing theory.
• Stable due to normalization.
• Less reliant on arbitrary moving-average formulas.
• Learns continuously.
• Fully causal and non-lookahead.
Limitations
• Not a predictive model in the forecasting sense.
• Can still lag during major regime shifts.
• Excessively large learning rates may introduce noise.
• Small tap counts can become unstable.
• Large tap counts can become sluggish.
Like all adaptive systems, there is a tradeoff between responsiveness and stability.
Best Use Cases
The NLMS Adaptive Trend Filter is particularly effective for:
• Trend identification.
• Regime classification.
• Dynamic support/resistance visualization.
• Adaptive trend following.
• Noise reduction.
• Signal confirmation.
Summary
The NLMS Adaptive Trend Filter applies one of the most important adaptive algorithms in modern signal processing to financial markets. Rather than relying on fixed moving-average weights, it continuously learns from prediction error and updates its internal model in real time. Built upon the pioneering work of Widrow and Hoff, the indicator combines adaptive filtering, normalized gradient descent, and online learning principles into a practical trend-following tool that evolves alongside changing market conditions. The result is a trend model that is fundamentally different from traditional moving averages, not because it smooths price differently, but because it learns how to smooth price as new information arrives.
Indicateur

AI Source Switching Moving Average (Zeiierman)█ Overview
The AI Source Switching Moving Average is an adaptive price-selection and trend intelligence system that combines historical analog recognition, machine learning classification, neural learning, feature optimization, dynamic source selection, and AI-driven trend management into a single framework.
Rather than calculating a moving average from a fixed source such as Close, Open, High, or Low, the indicator continuously evaluates which price source currently contains the most useful market information.
The script transforms each OHLC source into a multi-dimensional feature space, stores historical behavior, searches for similar historical environments, and allows those analogs to vote on which source currently provides the highest predictive value.
An adaptive feature-weighting engine continuously learns which characteristics best separate bullish and bearish conditions, while an online neural model adds a second layer of directional intelligence.
█ Why Is This One Unique
Most moving averages are static.
You select a source:
• Close
• Open
• High
• Low
Then the moving average simply smooths that source. This indicator does something fundamentally different.
Instead of assuming one source is always optimal, it continuously evaluates all four OHLC streams and determines which source currently contains the strongest information based on historical behavior.
The indicator effectively asks:
"Which price source has historically produced the best outcome under conditions most similar to the current market?"
That selected source then becomes the input for the moving average and AI Supertrend. This transforms a traditional moving average into a dynamic source-selection engine.
█ How It Works
⚪ Builds Multi-Dimensional OHLC Features
The model does not analyze raw prices directly.
Each OHLC source is transformed into a behavioral fingerprint consisting of:
• Trend Structure
• Mean-Reversion State
• Momentum
• Volatility Profile
• Range Position
• Price Slope
Every source becomes its own market state representation.
oT = featTrend(open, atrNow)
oM = featMean(open)
oMo = featMomentum(open)
oV = featVol(open)
oR = featRange(open)
oS = featSlope(open, atrNow)
The same feature process is applied to High, Low, and Close.
hT = featTrend(high, atrNow)
lT = featTrend(low, atrNow)
cT = featTrend(close, atrNow)
Instead of asking:
"Where is price?"
The model asks:
"How is this source behaving?"
⚪ Creates A Historical Memory Bank
Every confirmed bar is stored together with:
• Source feature state
• Future market outcome
• Volatility-normalized labels
This becomes the learning dataset.
moveFwd = close - close
bandFwd = learnAtrFactor * atrNow
outcome = moveFwd > 2 * bandFwd ? 3 :
moveFwd > bandFwd ? 2 :
moveFwd > 0 ? 1 :
moveFwd < -2 * bandFwd ? -3 :
moveFwd < -bandFwd ? -2 :
moveFwd < 0 ? -1 : 0
Each stored row contains the feature snapshot plus the outcome label.
rowO = makeRow(oT , oM , oMo , oV , oR , oS , outcome)
Each confirmed observation becomes a real historical example the model can reference later.
if barstate.isconfirmed and bar_index > horizonBars + 120
if validO
addBank(bankO, rowO, memoryDepth)
addBank(bankAll, rowO, memoryDepth * 4)
⚪ Uses Historical Analog Matching
Once enough data has been collected, the model begins searching for historical situations that resemble current conditions.
Similarity is measured using a compressed Lorentzian-style distance function:
compress(d) =>
math.log(1.0 + math.abs(d))
The gap between the current feature state and each historical row is then calculated across all features.
gapTo(t, m, mo, v, r, s, array row) =>
wT * compress(t - row.get(0)) +
wM * compress(m - row.get(1)) +
wMo * compress(mo - row.get(2)) +
wV * compress(v - row.get(3)) +
wR * compress(r - row.get(4)) +
wS * compress(s - row.get(5))
This helps reduce outlier influence and prevents any single feature from dominating the comparison process.
The goal is not to find identical charts. The goal is to find historically similar market environments.
⚪ Let Historical Analogs Vote
After finding the closest historical examples, the model allows them to vote.
Closer analogs receive greater influence. More distant analogs contribute less.
wg = 1.0 / (1.0 + g)
score += cls * wg
bull += cls > 0 ? wg : 0.0
bear += cls < 0 ? wg : 0.0
The weighted voting system produces:
• Analog Score
• Directional Bias
• Agreement Fraction
• Similarity Tightness
• Market Conviction
analog = total > 0 ? score / total : 0.0
dir = analog > 0.15 ? 1 : analog < -0.15 ? -1 : 0
agree = total > 0 ? (dir == 1 ? bull : dir == -1 ? bear : 0.0) / total : 0.0
tight = clamp(1.0 - avgGap / gapScale, 0.0, 1.0)
This creates a probabilistic ranking system rather than a binary signal engine.
⚪ Auto-Optimizes Feature Importance
Different markets reward different behaviors.
A feature that is extremely predictive today may become less useful tomorrow. The indicator solves this problem using adaptive Fisher-discriminant optimization.
The engine continuously measures which features best separate bullish outcomes from bearish outcomes.
f = math.pow(meanB - meanS, 2) / (varB + varS + 0.000001)
• Features with higher predictive value receive larger weights.
• Features with lower predictive value gradually lose influence.
norm = maxF > 0 ? fish.get(j) / maxF : 1.0
imp.set(j, math.max(floor, norm * 8.0))
The optimized weights are smoothed over time.
wAuto.set(j, prev + fisherSpeed * (wRaw.get(j) - prev))
This allows the model to adapt automatically without requiring manual optimization.
⚪ Adds Neural Learning
Beyond analog classification, the indicator includes an online neural learning layer.
The neural model continuously updates itself using confirmed market outcomes and adjusts internal directional bias over time.
neuralScore(t, m, mo, v, r, s) =>
nt * t + nm * m + nmo * mo + nv * v + nr * r + ns * s + nb
The neural layer evaluates:
• Trend Structure
• Mean Reversion
• Momentum
• Volatility
• Range Position
• Slope Behavior
Training is performed using an Adam-style optimizer.
adam(weight, grad, mom, vel, step) =>
newMom = beta1 * mom + (1.0 - beta1) * grad
newVel = beta2 * vel + (1.0 - beta2) * grad * grad
mHat = newMom / (1.0 - math.pow(beta1, step))
vHat = newVel / (1.0 - math.pow(beta2, step))
newWeight = weight - learnRate * mHat / (math.sqrt(vHat) + eps)
This creates a second intelligence layer that works alongside the analog engine.
⚪ Ranks All Four Sources
Every bar receives independent scores for:
• Open
• High
• Low
• Close
rO = rankSource(oT, oM, oMo, oV, oR, oS, oAnalog, oAgree, oTight, oK)
rH = rankSource(hT, hM, hMo, hV, hR, hS, hAnalog, hAgree, hTight, hK)
rL = rankSource(lT, lM, lMo, lV, lR, lS, lAnalog, lAgree, lTight, lK)
rC = rankSource(cT, cM, cMo, cV, cR, cS, cAnalog, cAgree, cTight, cK)
The ranking combines:
• Analog Classification Strength
• Historical Agreement
• Similarity Quality
• Feature Separation
• Neural Confidence
rankSource(t, m, mo, v, r, s, analog, agree, tight, k) =>
neural = useNeural ? neuralScore(t, m, mo, v, r, s) : 0.0
directional = math.abs(analog) / 3.0
raw = directional * 0.35 + agree * 0.25 + tight * 0.20 + normScore(neural) * neuralInfluence + (k >= kNeighbors ? 0.10 : 0.0)
clamp(raw, 0.0, 1.0)
The highest-ranked source becomes the active source for both the moving average and Supertrend.
bestId = safeRO >= safeRH and safeRO >= safeRL and safeRO >= safeRC ? 0 :
safeRH >= safeRL and safeRH >= safeRC ? 1 :
safeRL >= safeRC ? 2 : 3
This means the indicator can dynamically switch between Open, High, Low, and Close depending on which source currently demonstrates the strongest historical edge.
⚪ Builds An Adaptive AI Moving Average
After selecting the best source, the indicator calculates a moving average using that dynamically chosen input.
hardSrc = bestId == 0 ? open :
bestId == 1 ? high :
bestId == 2 ? low : close
The selected source is then smoothed and passed into the moving-average engine.
aiSourceRaw = hardSrc
aiSource = ta.ema(aiSourceRaw, srcSmoothLen)
aiMA = ma(aiSource, maLen, maType)
Unlike traditional averages that remain tied to a fixed source, the AI MA continuously adapts to changing market conditions.
The result is a smoother and more context-aware trend representation.
█ Main Weakness
The indicator is not deep learning.
It does not train a large neural network.
Instead, it operates as an online analog classifier enhanced by adaptive feature weighting and lightweight neural optimization.
Because it learns from historical analogs, performance can vary depending on:
• Symbol
• Timeframe
• Market Regime
• Memory Depth
• Feature Configuration
• Learning Horizon
As with all adaptive systems, historical similarity does not guarantee future outcomes.
█ How To Use
⚪ Reading The AI Moving Average
• Rising average = bullish conditions dominate.
• Falling average = bearish conditions dominate.
• Strong slope = stronger trend conviction.
• Flat slope = weaker directional conviction.
The AI Moving Average can be used much like a traditional moving average, but with the added benefit of dynamic source selection.
Use it for:
• Identifying trend direction
• Spotting trend changes
• Confirming momentum shifts
• Dynamic support and resistance analysis
• Pullback and retest opportunities
• Trend continuation setups
In bullish conditions , traders may look for price to remain above the moving average and use pullbacks into the average as potential continuation zones.
In bearish conditions , traders may look for price to remain below the moving average and use rallies into the average as potential resistance areas.
⚪ Reading The AI Supertrend
The AI Supertrend acts as:
• Trend Filter
• Dynamic Trailing Stop
• Market Structure Guide
• Bullish flips indicate positive trend conditions.
• Bearish flips indicate negative trend conditions.
Because the band width adapts to model confidence, trend changes become more responsive during strong conditions and more tolerant during weak conditions.
Use the AI Supertrend for:
• Trend confirmation
• Trade management
• Trailing stop placement
• Exit planning
• Market structure analysis
• Trend-following systems
Many traders may choose to remain long while price stays above the bullish trail and remain short while price stays below the bearish trail.
The Supertrend can also be used as a dynamic stop-loss framework, allowing positions additional room during uncertain conditions while tightening risk management when the AI model detects stronger directional conviction.
█ Settings
MA Type: Selects the moving average formula used after source selection.
MA Length: Controls the smoothing period of the AI moving average.
AI Source Smoothing: Smooths source transitions after source switching.
Memory Depth: Controls how many historical examples are stored.
Analog Count: Controls how many historical analogs participate in voting.
Learning Horizon: Controls how far ahead outcomes are evaluated.
Analog Spacing: Controls sampling diversity within the memory bank.
Learning Sensitivity × ATR: Controls how future outcomes are classified.
Use Neural Online Training: Enables the adaptive neural learning layer.
Neural Influence: Controls neural contribution to source ranking.
Learning Rate: Controls neural adaptation speed.
Huber Delta: Controls error sensitivity during training.
Auto Optimize Feature Weights: Enables adaptive feature importance learning.
Adaptation Speed: Controls weight adjustment speed.
Weight Floor: Sets minimum feature influence.
Minimum Rows: Controls when Fisher optimization becomes active.
Show AI Supertrend: Displays the adaptive trail.
ATR Length: Controls volatility measurement.
ATR Multiplier: Controls trail width.
AI Band Adaptivity: Controls AI influence over trail width.
-----------------
Disclaimer
The content provided in my scripts, indicators, ideas, algorithms, and systems is for educational and informational purposes only. It does not constitute financial advice, investment recommendations, or a solicitation to buy or sell any financial instruments. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
Indicateur

ML Liquidity Zone Classifier [PhenLabs]📊 ML Liquidity Zone Classifier
Version: PineScript™ v6
📌 Description
ML Liquidity Zone Classifier brings machine-learning-based filtering to liquidity mapping. Instead of drawing every possible order block, equal high, equal low, or volume zone, it evaluates current market conditions and only renders zones that score above a configurable confidence threshold.
The script uses a rolling k-Nearest Neighbors (k-NN) classifier built directly in Pine Script. Each potential zone is described using three normalized features: relative volume, higher-timeframe alignment, and displacement strength. Those features are compared against a rolling training set of prior bars to estimate whether the current setup resembles historically meaningful liquidity events.
The result is a cleaner liquidity tool designed to reduce chart clutter, improve selectivity, and help traders focus on zones with stronger contextual backing.
🚀 Points of Innovation
• Built-in k-NN classifier for liquidity zone confidence scoring
• Uses normalized multi-factor features instead of binary pattern logic alone
• Non-repainting delayed labeling system for training samples
• Auto higher-timeframe alignment that scales with the chart timeframe
• Zone overlap control, mitigation logic, and max-height clamping for cleaner structure
• Confidence-gated rendering so weak setups never reach the chart
🔧 Core Components
• KNN Classifier: Measures similarity between the current setup and prior labeled setups using Euclidean distance across three features
• Feature Engine: Converts volume, HTF proximity, and candle displacement into normalized 0 to 1 inputs
• Zone Detection Layer: Detects bullish and bearish order blocks, equal highs, equal lows, and high-volume nodes
• Zone Quality Gate: Filters zones by confidence, spacing, overlap, and size constraints
• Zone Lifecycle Manager: Maintains arrays for boxes and labels, prunes old zones, and removes mitigated ones
• Dashboard: Displays last detected zone, confidence score, and higher-timeframe directional bias
🔥 Key Features
• Machine-learning confidence score from 0 to 100 for every valid setup
• Automatic higher-timeframe selection based on current chart timeframe
• Support for bullish and bearish order blocks using ATR-based displacement logic
• Equal high and equal low detection using ATR-derived tolerance bands
• High-volume node detection using rolling average volume and local peak validation
• Zone deduplication to avoid stacked boxes at the same price area
• Optional mitigation that deletes broken zones after price closes through them
• Compact dashboard for live context and last-zone tracking
🎨 Visualization
• Confidence-based zone coloring with stronger opacity and border emphasis for higher-quality zones
• Labels printed directly on each zone with the zone type and confidence percentage
• Right-extended boxes so active liquidity areas remain visible into future price action
• Dashboard in the top-right corner showing Last Zone, Confidence, and HTF Bias
• Bullish zones are displayed in green tones, bearish zones in red tones, and lower-confidence zones fade toward orange or gray
📖 Usage Guidelines
KNN Classifier Settings
• K (neighbors) — Default: 5 — Controls how many historical neighbors are used when calculating confidence. Lower values react faster; higher values smooth the model.
• Training window — Default: 100 — Sets the maximum number of historical labeled samples stored in the rolling training set. Larger values add context but may slow adaptation.
HTF Alignment Settings
• Auto HTF — Default: true — Automatically selects a higher timeframe proportional to the current chart timeframe.
• Auto HTF multiplier — Default: 12.0 — Multiplies the current chart period to estimate the target higher timeframe.
• Manual HTF — Default: D — Used only when Auto HTF is disabled.
Zone Detection Settings
• Volume spike multiplier — Default: 1.5 — Minimum volume expansion required for a high-volume node.
• Order block ATR mult — Default: 1.5 — Minimum candle body size relative to ATR required to qualify as a displacement candle.
• Equal H/L tolerance — Default: 0.1 — ATR-based tolerance used to compare pivot levels for equal highs and equal lows.
Zone Quality Settings
• Min confidence to draw a zone — Default: 65 — Minimum classifier score required before a zone is rendered.
• Min bars between zones — Default: 5 — Cooldown period between newly drawn zones.
• Merge distance (ATR) — Default: 0.75 — Distance threshold used to reject overlapping or near-duplicate zones.
• Max zone height (ATR) — Default: 2.0 — Maximum vertical size of a zone before it is clamped.
• Remove zones when price breaks them — Default: true — Deletes support or resistance zones once price closes through them.
• Max visible zones — Default: 6 — Keeps only the most recent zones visible on the chart.
Advanced Settings
• ATR length — Default: 14 — Used for displacement measurement, tolerance scaling, and size normalization.
• Volume average length — Default: 20 — Rolling baseline for relative volume calculations.
• Volume node peak window — Default: 20 — Lookback used to confirm whether a bar is a true local volume peak.
• Pivot length — Default: 5 — Controls sensitivity for equal-high and equal-low pivot detection.
• Label evaluation window — Default: 10 — Number of bars waited before assigning a training label to a past setup.
• Label move threshold (ATR) — Default: 1.0 — Required future move in ATR units for a past setup to be labeled high probability.
• Show dashboard — Default: true — Enables or disables the on-chart summary table.
✅ Best Use Cases
• Traders who want fewer but higher-quality liquidity zones
• SMC and ICT-style workflows that need stronger filtering on OB and EQH/EQL logic
• Multi-timeframe traders who value HTF context in zone selection
• Intraday traders trying to avoid clutter from weak or repeated structure levels
• Quant-minded users who prefer confidence-based rendering over raw pattern detection
⚠️ Limitations
• The classifier is still a lightweight Pine implementation, not a full external ML model
• Confidence depends on the quality of recent market history inside the selected training window
• The script needs time to build its training set before meaningful zones begin to appear
• In highly abnormal volatility regimes, recent historical neighbors may be less representative
• This tool is a probability filter, not a guaranteed reversal or continuation signal
💡 What Makes This Unique
• Applies a true rolling k-NN classification process to liquidity-zone filtering inside Pine Script
• Combines market structure logic with volume, HTF context, and ATR displacement in one scoring model
• Keeps the chart clean by combining confidence gating, overlap suppression, cooldown spacing, mitigation, and pruning
• Gives traders an interpretable probability score instead of forcing all detected zones to appear equally important
🔬 How It Works
1. Feature Extraction
Each confirmed bar is converted into a three-feature vector. The script measures relative volume versus its moving average, distance to the nearest higher-timeframe OHLC level in ATR terms, and candle displacement strength based on body size versus ATR.
2. Delayed Labeling
After a configurable number of future bars passes, the script checks whether price moved far enough from the original bar. If that move exceeds the ATR-based threshold, the historical sample is labeled as high probability; otherwise it is labeled low probability.
3. KNN Confidence Scoring
When a new liquidity event appears, the script compares its feature vector against the rolling training set. It finds the nearest historical samples using Euclidean distance and converts their votes into a 0 to 100 confidence score.
4. Zone Validation
A zone is only drawn if the confidence exceeds the minimum threshold and the candidate zone does not overlap an existing one too closely. Oversized zones are clamped, repeated zones are filtered out, and only one new zone can be placed within the cooldown window.
5. Live Zone Management
Once drawn, zones extend to the right and remain active until mitigated. If price closes through a bullish zone from above or a bearish zone from below, the zone can be automatically removed to keep the display current.
Note:
This script is designed to be selective. If you use stricter confidence thresholds, larger gap settings, and mitigation enabled, you will typically see fewer but cleaner zones. Lowering the quality filters will increase signal frequency, but also increases chart noise. Indicateur

Gold Toolkit 22 [MatsukazeAlgo]🇬🇧 ENGLISH
A modular indicator that consolidates 22 Gold-specialized analysis tools into a single script. Each module can be toggled independently — enable one or two at a time for focused analysis. The shared infrastructure provides session awareness, Dollar Index correlation, and psychological price level detection across every module. Designed exclusively for XAUUSD on intraday timeframes.
Concepts
Modular Architecture -- Most indicators serve a single purpose: one trend filter, one oscillator, one pattern detector. For Gold traders who use multiple tools, this means loading 5–10 separate indicators, each consuming chart resources and requiring independent configuration. A modular architecture solves this by housing all tools within a single script, sharing a common infrastructure layer. Each module runs its own logic but inherits the same session detection, DXY feed, and psychological level engine. The result is consistent behavior across all tools without duplicate calculations.
Session-Dependent Behavior -- Gold does not trade the same way at all hours. The Asia session (19:00–03:00 ET) is characterized by tight ranges and stop runs that reverse at the London open. The London session (03:00–09:00 ET) produces directional breakouts driven by European institutional flow. The New York session (09:00–17:00 ET) carries the highest volume and tends to either continue the London move or reverse it sharply. An indicator that applies the same parameters across all three sessions is ignoring 60% of the context. Every module in this toolkit reads the current session and adjusts its signal thresholds accordingly. Asia signals require stronger confirmation. London signals favor trend continuation. NY signals weight volume more heavily.
Inverse Dollar Correlation -- Gold is priced in US Dollars. When the Dollar strengthens, Gold tends to fall. When the Dollar weakens, Gold tends to rise. This inverse relationship is not perfect on every bar, but over any meaningful sample it dominates. The toolkit reads TVC:DXY (US Dollar Index) daily data on every bar. Bull signals across all modules require a weak Dollar context (DXY close below open). Bear signals require a strong Dollar context. This single filter eliminates a substantial number of false signals that would otherwise fire against the macro trend.
Psychological Price Levels -- Gold reacts consistently at $50 and $100 round numbers. Institutional orders cluster at $4,500, $4,550, $4,600, and similar levels. When price approaches these levels, the toolkit tightens sensitivity and marks signals with a ★ indicator. A Stop Run Reversal scoring 85/100 at $4,550 is qualitatively different from the same score at $4,537 — the psychological level adds an independent layer of institutional confluence.
Modules
The 22 modules are organized into five categories. Each module is a complete analysis tool.
Trend Modules
01 ML Supertrend — A Supertrend variant with a session-learning engine. Tracks flip outcomes per session and adjusts the band multiplier over time. Sessions with low win rates get wider bands (fewer signals). Sessions with high win rates get tighter bands (more signals). Volume surge filter and RSI confirmation prevent signals in thin markets. The dashboard shows per-session win rates, current adapted multiplier, and learning state.
04 Parabolic SAR — Standard SAR calculation with two additions: age-based transparency fading and momentum scoring. Fresh SAR dots are fully opaque. As the trend ages, dots fade toward transparency, giving a visual read on trend maturity without cluttering the chart. The momentum score measures the distance between price and SAR relative to ATR. A high score means price is accelerating away from the SAR. A collapsing score warns of an impending flip. Multi-timeframe alignment check confirms whether the higher timeframe SAR agrees.
05 ACN Trend — An adaptive coral noise filter that outputs a smoothed trend line with risk zones above and below. The noise score quantifies how choppy the current market is. When noise exceeds the threshold, the background shades as a warning to avoid trading. The conviction meter is the inverse of noise — a high conviction reading means clean trend conditions. Bull/Bear signal counts per session track which sessions produce the most reliable signals for your timeframe.
09 Anchored Channels — A dual-layer channel system. Macro channels connect confirmed swing pivots and project forward with band widths derived from maximum deviation. Micro channels fit a short-term linear regression to the most recent bars. When price breaks the macro channel, it is classified as BRK (breakout). When price returns to the channel boundary, it is PB (pullback). When the micro channel aligns with the macro direction, it is CONT (continuation). The MTF screener checks two higher timeframes for directional agreement. A status badge labels the overall trend bias.
18 Asymmetric Trend — Uses different thresholds for entering and exiting a trend. The entry threshold is tight — price must move strongly to flip the trend. The exit threshold is wide — the trend persists through normal retracements. This asymmetry reduces whipsaws in ranging markets while catching genuine trend changes quickly. Gradient fill between the trend line and price shows acceleration visually. Reversal diamond markers appear at flip points with session tags and trend age.
Reversal Modules
02 Stop Run Reversal — Detects when price pierces a range boundary (liquidity grab) and reverses. Each event is scored 0–100 based on wick ratio, penetration depth, volume spike, DXY alignment, and session context. Zone boxes mark the reversal area with reference, invalidation, and target lines. A pending state tracker monitors setups that have not yet confirmed, preventing premature signals. Session and DXY tags on each label provide immediate context.
06 Arc Momentum — A non-linear RSI oscillator. Instead of plotting RSI as a flat line, the oscillator curves toward price in an arc. When the arc flips direction, a signal fires. Divergence detection compares RSI pivot extremes against price pivot extremes and flags when they disagree. The momentum zone classification (Overbought / Bull / Neutral / Bear / Oversold) shades the background for a quick visual read on the current state.
11 Harmonic Patterns — Scans for five harmonic patterns: Bat, Gartley, Butterfly, Crab, and Shark. Both bullish (XABCD with D at bottom) and bearish (XABCD with D at top) configurations are detected. Each pattern is scored based on session quality, DXY alignment, and proximity to psychological levels. Fibonacci projection levels are drawn at the PRZ (Potential Reversal Zone) showing 0.382, 0.618, 1.0, 1.272, and 1.618 targets. The tolerance parameter controls how strictly the Fibonacci ratios must match the textbook definitions.
16 RSI Swing Structure — Uses RSI overbought and oversold zones to define swing points. When RSI enters OB and price makes a high, that high is labeled. When RSI enters OS and price makes a low, that low is labeled. Each swing point is classified as HH (Higher High), HL (Higher Low), LH (Lower High), or LL (Lower Low). When the classification sequence breaks — for example, a HH followed by a LL — the indicator labels it as CHoCH (Change of Character). When the sequence continues — HH followed by another HH — it labels BOS (Break of Structure). Swing connecting lines visually link the pivots. RSI value appears on each label.
Structure Modules
03 EMA Inversion — Three EMAs (21, 55, 200) with ribbon fill. The indicator tracks Fair Value Gaps that form during trend moves. When an FVG is subsequently filled from the opposite direction (inverse FVG flip), a signal fires. Built-in SL/TP management uses the most recent swing high/low for stop placement and projects a 1:1 target. A cooldown timer prevents re-entry immediately after a stop-out. The trade state label shows whether the indicator considers the current position LONG, SHORT, or FLAT.
08 SwingRegress — Anchors linear regression channels to swing pivot confirmations. When a CHoCH occurs (price breaks the previous swing extreme), a new channel begins from the most recent opposite pivot. The channel slope and deviation are calculated from all bars within the segment. Band 1 and Band 2 at configurable standard deviations define the channel width. A linefill between the bands makes the channel body visible. Psychological price levels within the channel are drawn as dotted gold lines. A Bollinger/Keltner squeeze detector highlights when volatility compresses inside the channel — often a precursor to the next directional move.
10 S/R Zones — Builds support and resistance zones from volume-weighted pivot clustering. Nearby pivots are merged into zones. Each zone receives a strength score based on the number of touches, volume at touch, and recency. When price breaks through a zone, it is flagged. When price returns to a broken zone from the other side, it is flagged as a retest. Ghost zones keep broken levels visible with faded opacity. Star ratings provide a quick strength summary. An age-based decay ensures old, untested zones gradually disappear.
12 FVG Wave — Tracks Fair Value Gaps across the chart with session-colored rendering. Asia FVGs are rose, London FVGs are teal, NY FVGs are sky blue. Each FVG has a POC (midpoint) dotted line. When price touches the POC, a detection event fires. Age-based opacity fading dims old FVGs. Mitigation tracking removes FVGs that have been completely filled. Ghost mode optionally keeps mitigated FVGs visible in muted colors for reference.
17 OB Zone Study — Detects order blocks at displacement candles that follow swing pivots. Each OB is scored with a breakdown showing trend alignment, location quality, session, DXY confluence, and psychological level proximity. Mitigation tracking monitors whether price returns to the OB. Once mitigated, the OB is removed. Age-based opacity fading gradually dims unmitigated OBs that have been on the chart for a long time.
19 Vector SMC — Smart Money Concepts with a volume gate. FVGs and order blocks are only detected when the candle's volume exceeds the average by a configurable multiplier. This filters out structural patterns formed on low participation. OBs extend forward and are automatically invalidated when price closes through them. Sweep labels mark liquidity grabs at swing highs and lows where volume confirms institutional activity.
Session Modules
13 Session Range — Tracks the OHLC of Asia, London, and NY sessions in real time. A candle panel visualizes each session's range as a mini candlestick. 25% retracement lines for the London range identify the level where NY price action tends to react. H/M/L/O reference lines project key session levels forward. Regime classification analyzes the session structure pattern (e.g., London Partial Up, London Full Range). Asia sweep detection identifies whether the Asia high or low was taken during London. A stats table shows historical percentages for session behavior patterns.
15 Session Killzones — Draws boxes for Asia, London, NY AM, and NY PM killzone periods. When a killzone closes, its high and low are recorded as levels. These levels extend forward as dashed lines until price sweeps through them. Anticipation bars project the levels further for planning. When a sweep occurs, a detection label marks the bar. Session name labels identify each killzone box.
20 AlgoPath — Plots previous day high and low as horizontal lines. The equilibrium level (midpoint of PDH and PDL) is drawn as a dashed line. London session open and NY session open are drawn when each session begins. New day background shading marks the daily boundary. Whale candle detection flags abnormally large candles — those with body size exceeding a configurable ATR multiple — with session-colored labels showing the session name and exact time.
Volume and Correlation Modules
07 Minicharts — Displays Silver (XAG/USD), Dollar Index (DXY), and Gold Futures (GC1!) in a correlation panel. Each symbol shows EMA position (above/below). SMT (Smart Money Technique) divergence detection flags when Gold moves in the opposite direction to a correlated asset — a potential early warning of reversal.
14 Institutional Volume — Identifies accumulation and distribution phases using volume clustering analysis. When multiple high-volume candles with consistent directional bias appear within a lookback window, the indicator flags the zone. Climax volume detection identifies bars where volume × range reaches the highest level in the lookback period. Zone boxes mark the accumulation or distribution area on the chart.
21 Swing TPO — Builds Time Price Opportunity distributions anchored to swing points. The price range between swing pivots is divided into bins, and each TPO period assigns a letter to every visited bin. Gradient-colored boxes range from cool (low activity) to warm (high activity). The POC (Point of Control) line marks the highest-activity price. Psychological level detection flags when the POC lands near a $50/$100 round number.
22 VWAP — Dual-anchor Volume Weighted Average Price. The primary anchor resets on Session, Week, or Month boundaries. An optional second anchor provides a longer-term VWAP for confluence. Standard deviation bands at 1σ and 2σ show statistical extremes. Previous period VWAP, VAH (Value Area High), and VAL (Value Area Low) levels persist as reference lines with price labels. Band touch signals flag when price reaches the 2σ extreme. Slope direction indicates whether the VWAP is rising, falling, or flat.
How to Use
1. Open indicator settings. Under "Module Select," enable 1–2 modules.
2. Configure "Gold Settings" for session filtering, DXY, and psychological levels.
3. Apply to XAUUSD on your preferred intraday timeframe (5m–4h recommended).
4. Use the Style tab to show/hide individual signal shapes.
5. The module panel (top right) shows all 22 modules with the active one highlighted in gold.
Shared Infrastructure
Session Detection — Automatically identifies Asia (19:00–03:00 ET), London (03:00–09:00 ET), and New York (09:00–17:00 ET). Each module reads the current session for parameter adjustment and signal filtering.
DXY Feed — Pulls TVC:DXY daily open and close. Determines whether the Dollar is strengthening or weakening on the day. All modules use this for macro alignment.
ATR Normalization — All distance calculations (band widths, displacement thresholds, target projections) are normalized to the 14-period ATR. This ensures consistent behavior across timeframes and volatility regimes.
Psychological Level Engine — Configurable interval ($25, $50, or $100). Detects proximity to round numbers and flags signals near these levels with ★ markers. Multiple modules use this for confluence scoring.
Signal Bus — When any active module generates a Buy or Sell signal, it writes to a shared signal bus. The unified output shapes fire from this bus, providing a consistent visual regardless of which module produced the signal.
Module Panel — The top-right panel lists all 22 modules. The active module is highlighted in gold. Inactive modules are dimmed. Session, DXY, and daily range are displayed in the header and footer.
Input Reference
Module Select — 22 boolean toggles, one per module. Default: Module 01 ON, all others OFF.
Gold Settings — Session Filter (ON), Asia Signals (OFF), London Signals (ON), NY Signals (ON), Show DXY (ON), Psych $50/$100 (ON), Psych Interval (50), Show Panel (ON).
Each module has its own parameter group accessible when that module is enabled.
---
🇯🇵 日本語
22のゴールド専用分析モジュールを1つのインジケーターに統合したモジュラー型ツール。各モジュールは設定パネルから個別にON/OFF可能 — 1〜2個ずつ有効にして使用。共通インフラがセッション認識、ドルインデックス相関、心理的価格帯検出を全モジュールに提供。XAUUSD日中足専用設計。
コンセプト
モジュラーアーキテクチャ -- 多くのインジケーターは単一目的。複数ツールを使うゴールドトレーダーは5〜10個のインジを個別にロードする必要がある。モジュラーアーキテクチャはすべてのツールを単一スクリプトに収容し、共通インフラ層を共有することで解決。各モジュールは独自ロジックを実行しつつ、同一のセッション検出、DXYフィード、心理的価格帯エンジンを継承。
セッション依存型動作 -- ゴールドは時間帯によって異なる動きをする。アジア(19:00–03:00 ET)はタイトレンジとストップラン。ロンドン(03:00–09:00 ET)は欧州機関投資家フローによる方向性ブレイクアウト。ニューヨーク(09:00–17:00 ET)は最大ボリュームでロンドンの継続か急反転。全セッションに同じパラメータを適用するインジケーターは文脈の60%を無視している。本ツールキットの全モジュールは現在のセッションを読み取り、シグナル閾値を調整。
ドル逆相関 -- ゴールドはUSドル建て。ドル高→ゴールド下落、ドル安→ゴールド上昇の逆相関が支配的。TVC:DXY日足データを毎バー読み取り、Bullシグナルはドル安文脈、Bearシグナルはドル高文脈を要求。このフィルターだけでマクロトレンドに逆行する偽シグナルの大部分を排除。
心理的価格帯 -- ゴールドは$50/$100刻みのラウンドナンバーで一貫して反応。機関投資家の注文が$4,500、$4,550、$4,600等に集中。価格がこれらのレベルに接近すると感度を引き締め、★マーカーでシグナルを強調。
モジュール一覧
トレンド系 — 01 ML Supertrend:セッション学習エンジン搭載、勝率追跡・自動調整。04 Parabolic SAR:経過時間フェード、モメンタムスコア、MTFアライメント。05 ACN Trend:適応型コーラルノイズフィルター、ノイズスコア、コンビクションメーター。09 Anchored Channels:マクロ+マイクロ二層チャネル、BRK/PB/CONT分類、MTFスクリーナー。18 Asymmetric Trend:非対称閾値フィルター、グラデーション塗り、リバーサルダイヤ。
リバーサル系 — 02 Stop Run Reversal:流動性奪取検出、0–100スコアリング、ゾーンボックス。06 Arc Momentum:非線形アーク型RSI、ダイバージェンス検出、ゾーン背景表示。11 Harmonic Patterns:5種パターン(Bull+Bear)、フィボナッチ投影。16 RSI Swing Structure:HH/HL/LH/LL分類、CHoCH/BOS検出。
ストラクチャー系 — 03 EMA Inversion:3本EMAリボン+FVG追跡+iFVGフリップ。08 SwingRegress:ピボット固定LRC、CHoCH/BOS、スクイーズ検出。10 S/R Zones:出来高加重クラスタリング、強度スコア、リテスト追跡。12 FVG Wave:セッション色分けFVG、POC、ミティゲーション追跡。17 OB Zone Study:OB検出+スコア内訳+経過フェード。19 Vector SMC:出来高ゲート付きSMC。
セッション系 — 13 Session Range:Asia/London/NY OHLC、キャンドルパネル、25%ライン、レジーム分類。15 Session Killzones:キルゾーンボックス+未スイープレベル追跡。20 AlgoPath:前日高安、イクイリブリアム、ホエールキャンドル。
ボリューム・相関系 — 07 Minicharts:Silver/DXY/GC相関パネル、SMT検出。14 Institutional Volume:蓄積/分配検出、クライマックス出来高。21 Swing TPO:グラデーションTPO分布、POC。22 VWAP:デュアルアンカー、σバンド、前期間レベル。
使い方
1. 設定の「Module Select」で1〜2個を有効化。
2. 「Gold Settings」でセッションフィルター、DXY、心理的価格帯を設定。
3. XAUUSD日中足(5分〜4時間推奨)に適用。
4. 右上のモジュールパネルで全22モジュールの状態を確認。有効モジュールはゴールドで表示。
共通インフラ — セッション検出(Asia/London/NY自動識別)、DXYフィード($の強弱判定)、ATR正規化、心理的価格帯エンジン($25/$50/$100)、シグナルバス(統一Buy/Sell出力)、モジュールパネル(全22モジュール一覧表示)。 Indicateur

Indicateur

Machine Learning RSI | AI Classification & Ranking (Zeiierman)█ Overview
The Machine Learning RSI | AI Classification & Ranking (Zeiierman) is an adaptive RSI intelligence system that combines momentum analysis, historical analog recognition, machine learning classification, confidence scoring, and dynamic trend management into a single framework.
Rather than interpreting RSI solely through traditional overbought and oversold thresholds, the indicator examines how similar RSI environments have behaved historically and uses those observations to classify current market conditions.
The script transforms RSI into a multi-dimensional feature space, stores historical market behavior, identifies the closest historical analogs, and allows those analogs to vote on future directional bias.
An adaptive feature-optimization engine then continuously learns which RSI characteristics provide the greatest predictive value under current market conditions.
The result is a hybrid system that blends:
• Multi-dimensional RSI analysis
• Historical analog matching
• Machine learning classification
• Adaptive feature weighting
• Rank & confidence scoring
• AI-driven trend management
█ Why is this one unique
This is not a normal RSI. It is a full analog classification engine built in Pine Script v6. It turns RSI behavior into an 8-feature market fingerprint, stores historical examples, labels them by future outcome, finds the closest past situations, lets those analogs vote, then converts the result into an adaptive ML RSI, rank/confidence scores, signals, and an ML-modulated Supertrend.
⚪ What it does
At a high level:
1. Builds 8 RSI-derived features
It does not only use the RSI value. It models:
RSI level, slope, acceleration, distance from 50, percentile rank, RSI volatility, fast/slow RSI spread, and smoothed RSI regime.
That means each bar becomes a multi-dimensional “state” of momentum, not just “RSI is 63.”
2. Creates a memory bank
Each confirmed bar is stored with its feature snapshot and a future outcome label. The label is based on whether price moved up or down after a fixed horizon, scaled by ATR. That is the learning dataset.
3. Uses K-nearest-neighbor analog matching
For the current bar, the script scans the historical bank and finds the closest past examples. It uses a Lorentzian-style compressed distance:
log(1 + abs(feature difference))
That is good because it reduces the impact of outliers. Huge feature mismatches do not completely dominate the model.
4. Lets analogs vote
Nearest neighbors vote bull or bear, weighted by distance. Closer matches matter more. The output becomes: analogScore, bias direction, agreement fraction, and gap tightness.
5. Auto-optimizes feature weights
This is one of the most sophisticated parts. The script uses a Fisher-discriminant-style calculation to determine which RSI features currently best separate bullish vs. bearish outcomes. Then it rescales those weights and smooths them over time.
So the model can learn that, for example, RSI slope matters more on one instrument, while RSI percentile or regime matters more on another.
6. Builds rank and confidence
Signals are not triggered just because the model flips bullish or bearish. They must pass a quality system:
Rank blends agreement, distance tightness, trend alignment, volatility health, regime fit, slope fit, smoothness, persistence, and penalties for chop or early flips.
Confidence focuses more on analog agreement, tightness, persistence, and slope fit.
This is much better than a simple buy/sell oscillator because it asks: “Is this setup actually supported?”
7. Adds adaptive Supertrend
The Supertrend is not static. Its band width changes based on ML conviction. High conviction tightens the trailing stop. Low conviction or chop widens it. That makes the trend system responsive without being blindly reactive.
⚪ Why it is good
The strongest part is that it combines machine learning logic, technical architecture, and trade-quality filtering into a single system.
Most TradingView indicators are fixed formulas: RSI crosses 30, MACD crosses, Supertrend flips, moving average slope changes. This code differs because it creates a small local learning model directly in Pine.
The unique edge is the combination of:
• Feature engineering: RSI is transformed into 8 separate behavioral dimensions.
• Historical analog learning: Current market conditions are compared to past similar conditions.
• Distance-weighted voting: Closer historical examples have more influence.
• Auto feature weighting: The system adapts which features matter most.
• ATR-based outcome labeling: Learning is normalized by volatility, not just raw price movement.
• Quality scoring: Signals require both rank and confidence.
• Adaptive trend logic: The ML engine not only generates oscillator signals but also modifies Supertrend behavior.
That combination is rare in Pine Script. TradingView supports advanced data structures such as arrays, matrices, and user-defined types, but many public scripts still use simpler procedural indicator logic. This script uses those advanced structures as a true modeling framework.
⚪ What makes it sophisticated
The code actually implements an AI-style classification workflow:
Input features → labeled memory → nearest-neighbor search → weighted classification → confidence scoring → adaptive output.
That is a real machine-learning pattern.
But this script goes further than a basic KNN signal tool because it adds:
• Auto-optimized feature weights using class separation.
• Rank/confidence gates instead of raw prediction signals.
• Chop, volatility, and trend filters to reduce bad market conditions.
• ML-driven Supertrend adaptivity rather than using ML only for arrows.
• Non-repainting signal discipline by firing on confirmed bars only.
⚪ Why It’s Marketable
Most RSI indicators treat every reading the same. This tool takes a different approach by analyzing how similar RSI conditions performed in the past and evaluating the current setup against those historical patterns. It only generates signals when multiple factors align, including confidence, trend direction, volatility, and market structure.
What makes it valuable is that it transforms RSI from a simple momentum oscillator into a context-aware decision framework. Rather than reacting to fixed overbought and oversold levels, it identifies recurring market behaviors, measures the similarity of current conditions to historical examples, and assigns a quality score to each opportunity. It then filters out low-probability environments and dynamically adjusts its trend management based on the strength of the model's conviction.
The result is a more selective, adaptive, and intelligent signal engine that helps traders focus on higher-quality setups instead of every RSI fluctuation. This moves well beyond the capabilities of a conventional TradingView RSI indicator.
⚪ Main weakness
It is not deep learning, and it does not train a neural network. It is an online analog classifier. That is still legitimate AI-style logic. Also, because it learns from historical analogs inside the chart, performance depends heavily on market regime, symbol, timeframe, memory depth, and filters.
█ How It Works
⚪ Machine Learning Feature Engine
Most RSI indicators analyze a single value.
The Machine Learning RSI transforms RSI into a complete momentum fingerprint, consisting of eight independent characteristics that describe how momentum behaves beneath the surface.
The model analyzes:
• RSI Value
• RSI Slope
• RSI Acceleration
• Distance From Neutral (50)
• RSI Percentile Rank
• RSI Volatility
• Fast vs Slow RSI Spread
• RSI Regime Structure
Features cur = Features.new(
rOsc / 100.0,
scale01(rOsc - rOsc , winLen),
scale01(rOsc - rOsc -
(rOsc - rOsc ), winLen),
math.abs(rOsc - 50.0) / 50.0,
ta.percentrank(rOsc, winLen) / 100.0,
scale01(ta.stdev(rOsc, 14), winLen),
scale01(rOscF - rOscS, winLen),
scale01(ta.ema(rOsc, 20) - 50.0, winLen)
)
Together these features create a much richer representation of market behavior than traditional RSI calculations.
Instead of asking:
“Where is RSI?”
The model asks:
“What type of momentum behavior is currently occurring?”
⚪ Historical Analog Memory
The indicator continuously builds a memory bank of historical market behavior.
Every confirmed bar is stored together with its RSI fingerprint and the future outcome that followed.
row = array.from(
fVal, fSlp, fAcc, fMid,
fPct, fChn, fSpr, fReg,
float(outcome)
)
bank.add_row(0, row)
Over time the model accumulates hundreds or even thousands of historical observations.
Each observation becomes a real market example the system can reference later.
Rather than relying entirely on fixed formulas, the indicator learns from historical market behavior.
⚪ AI Classification Engine
Once the memory bank has been built, the Machine Learning RSI begins searching for historical situations that closely resemble the current market.
The comparison is performed across all eight RSI features simultaneously.
g = cur.gapTo(row, wts)
Similarity is measured using a weighted Lorentzian distance function.
compress(float d) =>
math.log(1.0 + math.abs(d))
Unlike traditional distance calculations, logarithmic compression reduces the influence of extreme outliers and prevents a single feature from dominating the comparison process.
This creates a more stable and robust analog matching system.
The objective is not to find identical charts.
The objective is to find historical momentum environments that behaved similarly.
⚪ Historical Analog Voting
After locating the closest historical matches, the system allows them to vote on the current market direction.
Closer analogs receive greater influence while weaker matches contribute less.
float w = 1.0 / (1.0 + n.gap)
v.score := v.score + n.cls * w
The weighted votes are combined into a final classification score.
eng.analogScore :=
vote.total > 0
? vote.score / vote.total
: 0.0
This process produces:
• Directional Bias
• Analog Agreement
• Classification Strength
• Similarity Quality
• Market Conviction
Rather than attempting to predict the future directly, the model asks:
“How did the most similar momentum environments behave when they occurred previously?”
⚪ Adaptive Feature Optimizer
Markets are constantly changing.
Features that are highly predictive in one environment may become less useful in another.
To solve this problem, the Machine Learning RSI includes an adaptive feature optimization engine.
The model continuously evaluates which RSI characteristics are doing the best job separating bullish outcomes from bearish outcomes.
float f =
math.pow(mB - mBe, 2)
/
(vB + vBe + 1e-6)
This process is based on Fisher Discriminant Analysis.
Features that consistently separate winning conditions from losing conditions receive larger weights.
Features that lose predictive power gradually receive less influence.
wts.value := wAuto.get(0)
wts.slope := wAuto.get(1)
wts.accel := wAuto.get(2)
wts.mid := wAuto.get(3)
This allows the model to adapt automatically to changing market conditions without requiring constant manual optimization.
⚪ Rank & Confidence Engine
Most indicators generate signals immediately after a condition is met.
The Machine Learning RSI goes several steps further. Every setup receives two independent evaluations.
• Rank → Measures setup quality.
• Confidence → Measures model conviction.
Rank evaluates:
• Historical agreement
• Analog quality
• Trend alignment
• Volatility conditions
• Regime structure
• Momentum consistency
• Market stability
Confidence evaluates:
• Historical consensus
• Analog clustering
• Directional consistency
• Signal persistence
• Structural confirmation
setup.rank := rankScore(…)
setup.conf := confScore(…)
Signals are only generated once both quality and confidence requirements have been satisfied.
This helps filter weaker market conditions while prioritizing stronger opportunities.
⚪ AI-Driven Learning System
The Machine Learning RSI does not simply memorize historical outcomes.
It learns what constitutes a meaningful outcome.
Each historical observation is classified based on future movement relative to current volatility.
outcome =
moveFwd > 2 * bandFwd ? 3 :
moveFwd > bandFwd ? 2 :
moveFwd > 0 ? 1 :
moveFwd < -2 * bandFwd ? -3 :
moveFwd < -bandFwd ? -2 :
moveFwd < 0 ? -1 : 0
• Large bullish moves receive stronger bullish labels.
• Large bearish moves receive stronger bearish labels.
• Small movements receive weaker classifications.
This allows the model to distinguish meaningful market behavior from ordinary noise.
⚪ ML Supertrend System
The indicator includes an adaptive Machine Learning Supertrend that responds to model conviction.
Unlike traditional Supertrends that rely on a fixed ATR multiplier, the ML Supertrend dynamically adjusts its sensitivity based on classification strength.
mlDrive =
math.abs(convSmoothed) * 0.5 +
eng.gapTight * 0.3 +
eng.agreeFrac * 0.2
As conviction increases:
• Bands tighten
• Trend changes become faster
• Stops become more responsive
As conviction decreases:
• Bands widen
• Noise tolerance increases
• Whipsaws are reduced
adaptMult =
stMultBase *
(1.0 + stMlResp * (1.0 - mlDrive))
This creates a trend-following system that adapts to the strength of the model’s conviction rather than relying solely on volatility.
█ How To Use
⚪ Reading The ML RSI
The Machine Learning RSI ranges from 0 to 100.
• Values above 50 suggest bullish momentum conditions dominate the market.
• Values below 50 suggest bearish momentum conditions dominate the market.
• Readings above 70 typically indicate strong bullish conditions, while readings below 30 suggest strong bearish pressure.
⚪ Reading The Signals
The Machine Learning RSI generates signals when the model detects a meaningful shift in market conditions and that shift passes both its quality and confidence requirements.
• Long signals indicate that the classification engine has identified a bullish market environment supported by historical analog agreement, trend structure, and market conditions.
• Short signals indicate that the classification engine has identified a bearish market environment supported by historical analog agreement, trend structure, and market conditions.
⚪ Using The ML Supertrend
The ML Supertrend acts as both a trend filter and a dynamic trailing stop.
• When the Supertrend flips bullish, the model considers the market to be operating in an uptrend regime.
• When the Supertrend flips bearish, the model considers the market to be operating in a downtrend regime.
█ Settings
Price Source: controls the price data used to build every RSI feature inside the learning engine.
Base RSI Length: controls the main RSI period used to create the ML RSI and its feature set.
Memory Depth: controls how many historical bars the model stores and searches when looking for similar market conditions.
Analog Count (k): controls how many closest historical matches are allowed to vote on the current market direction.
Show Signal Markers: toggles the Long and Short signal markers on the chart.
Candle Coloring: colors candles based on the current ML Supertrend regime.
Min Rank to Signal: controls the minimum setup-quality score required before a signal can appear.
Min Confidence to Signal: controls the minimum model conviction required before a signal can appear.
Trend Gate: requires signals to align with the ML Supertrend direction.
Volatility Band: filters signals so they only appear in healthier volatility conditions.
Min Vol Rank: controls the lower volatility threshold required for signals.
Chop Filter: blocks signals during choppy, range-bound market conditions.
Learning Sensitivity: controls how large a future move must be before the model treats it as a meaningful historical outcome.
Auto-Optimize Weights: allows the model to automatically learn which RSI features are most important.
Adaptation Speed: controls how quickly the learned feature weights adjust to changing market behavior.
Feature Weights: manually control the importance of each RSI feature when Auto-Optimize Weights is disabled.
Show ML Supertrend: toggles the adaptive ML Supertrend line, cloud, and trend visuals.
Supertrend Source: controls the price source used to build the ML Supertrend bands.
ATR Multiplier: controls the base distance of the ML Supertrend from price.
ML Band Adaptivity: controls how strongly model conviction adjusts the Supertrend band width.
RSI Signal Line Type: selects the moving average style displayed on the ML RSI.
RSI Signal Line Length: controls the smoothing length of the RSI signal line.
BB StdDev: controls the Bollinger Band width when using SMA + Bollinger Bands.
Colors: customize signal markers, candle coloring, ML RSI colors, Supertrend colors, cloud colors, and signal line visuals.
-----------------
Disclaimer
The content provided in my scripts, indicators, ideas, algorithms, and systems is for educational and informational purposes only. It does not constitute financial advice, investment recommendations, or a solicitation to buy or sell any financial instruments. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
Indicateur

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 TradingView 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. Indicateur

KNN Market Regime Engine [Dots3Red]█ OVERVIEW
Most market regime tools work in a pretty simple way: we set a threshold and call it a day. ADX above 25? Trending. Below 20? Ranging.
But that threshold is basically just our assumption baked into code. It doesn’t adapt, it doesn’t learn, and it’s treated the same whether we’re looking at Bitcoin, EUR/USD, or any other market — even though they behave completely differently.
This script takes a different approach . It uses a K-Nearest Neighbors (KNN) machine learning algorithm to estimate the probability that the current market is in one of three regimes: Trending , Ranging , or Volatile Trend . Rather than comparing today's readings against a fixed number, it searches the past 700 bars for the moments that looked most like right now - and asks what the market did after each of those moments. The result is a live probability for each regime, not a hard categorical label.
The output is three things simultaneously:
a background color telling you the dominant regime
a dashboard showing live probability bars for all three states
change markers appearing only when the classifier is genuinely confident a shift has occurred.
█ THE FOUR REGIMES
🔵 TRENDING — price is moving directionally with efficiency. Momentum strategies belong here. Mean reversion strategies get punished here.
🟣 RANGING — price is oscillating between levels with no net directional movement. Mean reversion strategies and fade-the-extreme setups have edge here. Trend-following generates whipsaws.
🟡 VOLATILE TREND — price is trending and ATR has expanded sharply beyond its baseline. This captures earnings gaps, macro shocks, and post-breakout expansion. It is a distinct fourth state — not simply "a strong trend." Reduce size or trail very tightly.
⬛ UNCERTAIN — the dominant probability did not clear the minimum confidence threshold. The market's character is genuinely ambiguous. The best action is observation, not engagement.
█ HOW IT WORKS — THE FULL PIPELINE
Step 1 — Six features, measured every bar
Each bar is described by six measurements, each capturing a different dimension of market character:
• ADX — trend strength. Not direction — only how strongly price is committed to any direction.
• ATR ratio — current ATR divided by its own long-term average. Measures whether volatility is elevated or compressed relative to its own history.
• Choppiness Index — measures how much of the price movement was wasted going sideways. Near 100 = pure chop. Near 38 = perfectly directional.
• Bollinger Band width — how expanded or compressed the bands are relative to price. A compression often precedes volatile expansion.
• Normalized slope — linear regression slope over N bars, divided by ATR. A scale-free measure of directional momentum.
• Kaufman Efficiency Ratio — how directly did price move from A to B? If price traveled 100 points total but only net-moved 20, ER is 0.20. High ER = trending cleanly. Low ER = zigzagging.
Step 2 — Z-score normalization
ADX runs 0–100. ATR ratio runs 0.5–3.0. BB width might be 0.01–0.08 on forex. Using raw values in a distance calculation means the largest-scale feature dominates by sheer magnitude. All six features are standardized: z = (value − rolling mean) / rolling stdev . This puts every feature on equal footing — a reading of +2.0 means " two standard deviations above normal " on any feature. Critically, the mean and stdev are computed on prior bars only ( src offset), which eliminates look-ahead bias from the normalization step.
Step 3 — Labeling historical bars
For every historical bar, the script evaluates what happened over the following Forward Bars window:
• If the net price move exceeded Trend Threshold × average ATR over the window → labeled TRENDING (1)
• If the ATR ratio exceeded Volatility Threshold → labeled VOLATILE TREND (3)
• If trending AND volatile simultaneously → labeled VOLATILE TREND (3), because risk context takes priority
• Otherwise → labeled RANGING (2)
This label is only ever read at an offset of at least Forward Bars bars into the past, so the current bar carries no label — there is no look-ahead in the training data.
Step 4 — KNN search and Gaussian-weighted voting
On each bar, the algorithm scans the historical window (default 700 bars) and computes the Minkowski distance between today's six Z-scored features and every historical bar's six features. The K nearest matches are selected. Closer neighbors receive exponentially higher voting weight via a Gaussian kernel : w = exp(−d² / 2σ²) . This means a bar at distance 0.1 vastly outweighs one at distance 0.5. The votes produce three probabilities — P(trending), P(ranging), P(volatile trend) — that always sum to 1.
Step 5 — Three-stage noise filtering
A single KNN output can flicker bar to bar. Three filters eliminate this:
• Mode filter — selects the most common regime over the last smooth_len bars. Removes 1-3 bar flickers entirely.
• Confirmation filter — the smoothed regime must hold steady for confirm_bars consecutive bars before being accepted. Kills false starts.
• Signal gap — regime change markers only appear once per signal_gap bars minimum, and only when the dominant probability exceeds 65%. This eliminates cluttered charts entirely.
█ DESIGN DECISIONS — WHAT WAS INITIALLY, WHAT CHANGED AND WHY
From 3 regimes to 4
The first idea used three regimes with a simple override: if volatility was high, VOLATILE replaced TRENDING regardless of whether price was actually moving directionally. Testing on stocks showed this caused problems — an earnings-day spike during a clear uptrend was collapsing the trend signal entirely. We realized volatile trending markets are qualitatively different from volatile ranging markets. A fast trend during an OPEC announcement is not the same as a gap-down in a sideways consolidation. VOLATILE TREND became its own regime, and the distinction turned out to be the most practically useful change in the entire script.
From stride = fwd_bars to stride = 3
The early idea for the script we had sampled the training window with a stride equal to Forward Bars (30 by default). This gave roughly 23 training samples — barely enough for KNN to make a meaningful comparison. Reducing the stride to 3 gives approximately 230 samples. The regime classification became dramatically more stable and consistent, especially in quieter markets where the 23-sample version frequently returned UNCERTAIN. The trade-off is slightly more computation, which Pine handles comfortably within its limits.
From a single volatile threshold to a combined trend + volatile check
Originally we labeled VOLATILE based purely on ATR ratio exceeding a threshold. This correctly flagged high-volatility periods but was labeling slow low-ATR trends as RANGING instead of TRENDING during prolonged low-volatility bull markets. The label logic was reworked to check directionality and volatility independently and then combine them: a trending move is TRENDING unless ATR is also elevated, in which case it becomes VOLATILE TREND. This made the label logic honest about what the market was actually doing.
The Efficiency Ratio addition
The original five features (ADX, ATR ratio, Choppiness, BB width, Slope) left a gap: two markets can have identical ADX and slope but very different directional efficiency — one moves in a clean staircase, the other zigzags the same distance. Kaufman's Efficiency Ratio fills this gap. ER = 0.85 on a bar means 85% of all price movement went in the net direction. ER = 0.20 means price was thrashing around and barely net-moved. It proved particularly valuable for distinguishing true trending from noisy ranging in crypto and high-beta stocks.
The regime change marker clutter problem
Early testing produced charts covered in triangles, circles, and diamonds — a new marker on almost every regime flicker. Three parameters were added to solve this: the mode filter, the confirmation bars requirement, and the signal gap. Together they ensure a marker only appears when (a) the majority of recent bars agree on the new regime, (b) it has held for at least N bars, and (c) the KNN confidence is above 65%. The result is 2–6 meaningful markers per year on a daily chart rather than dozens of noisy ones.
█ WHAT YOU SEE ON THE CHART
Background color — the dominant confirmed regime, colored continuously. Cyan = Trending. Magenta = Ranging. Amber = Volatile Trend. No color = Uncertain.
Bar coloring — individual bars colored by the same regime. Toggle off if you prefer your own candle coloring scheme.
Regime change markers — small shapes at confirmed, high-confidence regime transitions only. ▲ below bar = shift to Trending. ● below bar = shift to Ranging. ◆ above bar = shift to Volatile Trend.
Dashboard (top right) — shows the confirmed regime label, confidence percentage, three probability meters (▰▰▰▱▱▱ format), and six live feature readings. The bottom row shows Raw → Smooth (e.g. "T → R") so you can see what the raw KNN output is before the filters process it — useful for understanding when the classifier is about to change state.
█ SETTINGS REFERENCE
🧠 KNN Engine
• K Neighbors — how many historical bars vote. Lower = faster reaction, higher = more stable. Default 25.
• Lookback Window — how many bars to search for neighbors. Larger = more training data. Default 700.
• Minkowski p — distance exponent. 1 = Manhattan (robust to outliers), 2 = Euclidean (standard). Default 2.
• Gaussian bandwidth — how steeply neighbor weight falls with distance. Lower = only the closest neighbors matter. Default 1.5.
• Minimum confidence — probability threshold below which the regime shows as UNCERTAIN. Default 0.45.
🏷️ Labeling
• Forward bars — how many bars ahead define a historical bar's regime label. Match your typical hold time. Default 30.
• Trend threshold — net move must exceed this × avg ATR to label TRENDING. Lower = more bars labeled trending. Default 1.2.
• Volatility threshold — ATR ratio must exceed this to label VOLATILE TREND. Higher = only extreme events qualify. Default 1.5.
📐 Features
• ADX Length — period for the directional movement index. Longer = smoother. Default 20.
• ATR Length — period for average true range. Default 14.
• ATR Baseline — SMA period for the ATR ratio denominator. Longer = more stable baseline. Default 100.
• Choppiness / BB / Slope lengths — feature calculation periods. All default to 20–30.
• Efficiency Ratio Length — Kaufman ER lookback. Default 30.
🧹 Filtering
• Regime Smoothing Lookback — mode filter window. Higher = fewer false regime changes. Default 11.
• Bars to confirm regime — consecutive bars required before a new regime is accepted. Default 4.
• Min bars between signals — minimum spacing between regime change markers. Default 20.
█ SETTINGS BY ASSET CLASS
📈 Large-cap stocks — daily (AMZN, AAPL, NVDA)
Stocks trend slowly over weeks to months, with sharp one-day volatility spikes on earnings. All feature lengths should be longer to resolve the slower regime pace.
• Forward bars: 20–30 | Trend threshold: 0.8–1.2 | Volatility threshold: 2.0–2.5
• ATR Baseline: 100 | ADX / Chop / Slope lengths: 20 | BB length: 30 | EffR: 30
• Smoothing: 11 | Confirm bars: 4–5 | Signal gap: 20
• Note: use 0.8 trend threshold for slow defensive stocks (JNJ, KO), 1.2 for high-beta tech (NVDA, TSLA)
₿ Crypto — daily (BTC, ETH, large caps)
Crypto regimes flip in days, not months. ATR is 3–7× higher than stocks. Shorter windows, lower thresholds, less smoothing.
• Forward bars: 10–14 | Trend threshold: 1.5–2.5 | Volatility threshold: 1.5–2.0
• ATR Baseline: 50–70 | All feature lengths: 14 | EffR: 14–20
• Smoothing: 5–7 | Confirm bars: 2–3 | Signal gap: 7–10
• Note: for altcoins use trend threshold 2.0–2.5; for BTC use 1.5–2.0
💱 Forex — daily (EUR/USD, GBP/USD, USD/JPY)
Forex trends are driven by central bank divergence and last months. Daily ATR is tiny (0.4–0.7% of price). Everything needs to be longer and slower.
• Forward bars: 30–45 | Trend threshold: 0.6–0.8 | Volatility threshold: 2.5–3.0
• ATR Baseline: 120–150 | ADX length: 20–25 | Slope / EffR: 40–50
• Smoothing: 15–21 | Confirm bars: 5–7 | Signal gap: 30–45
• Note: exotic pairs (USD/TRY, USD/ZAR) behave like crypto — use crypto settings instead
🛢️ Commodities — daily (Gold XAU, Oil WTI)
Gold is slow and stable like equities. Oil is fast and event-driven like crypto. Use different profiles.
• Gold: Forward bars 20, Trend 0.8, Vol 2.5, ATR Base 100, Smooth 11, Confirm 4, Gap 20
• Oil: Forward bars 15, Trend 1.2, Vol 2.0, ATR Base 70, Smooth 7, Confirm 2–3, Gap 10
• Note: OPEC events and geopolitical shocks will correctly fire VOLATILE TREND on oil — this is intended behavior
🌐 Indices — daily (SPX, NDX, DAX)
Indices are the most regime-stable asset class. They trend 65–75% of the time and have the cleanest feature signals of any asset.
• Forward bars: 20–30 | Trend threshold: 0.8–1.0 | Volatility threshold: 2.0–2.5
• ATR Baseline: 120 | ADX length: 20 | Smoothing: 11–15 | Confirm bars: 4–5 | Signal gap: 20–30
• Note: NDX is ~30% more volatile than SPX — use trend threshold 1.0 for NDX, 0.8 for SPX
EXAMPLE
█ HOW TO USE WITH OTHER INDICATORS
This script does not generate buy or sell signals. It tells you which type of strategy has edge right now . The intended workflow:
1 — Add your momentum or mean reversion indicator alongside this one.
2 — Only take momentum / trend-following entries when the background is cyan (TRENDING) .
3 — Only take mean reversion / fade entries when the background is magenta (RANGING) .
4 — Reduce position size or step aside entirely when the background is amber (VOLATILE TREND) .
5 — Do nothing when there is no background color — the regime is UNCERTAIN.
Used this way, the classifier acts as a strategy mode selector rather than a signal generator. It is the foundation of a multi-strategy system where the same chart hosts different logic depending on detected conditions.
█ LIMITATIONS
• KNN is a lazy learner — it reflects patterns in its training window. If the current market regime has no historical analog in the lookback window (e.g. a once-in-a-decade crash), the classifier will misclassify or return UNCERTAIN.
• The script requires a warm-up period equal to Lookback Window + Forward Bars bars before producing output. On instruments with limited history this may delay the first valid reading.
• Computation scales with window size and stride. Very large windows (2000+) may slow chart rendering on lower-end machines.
• The reversion probability reflects historical frequency, not a guarantee of future behavior. All market regimes can and do fail.
Human vs Machine 🧠vs 🤖
And most importantly, checking the chart with the HUMAN EYE is different from using the raw ML KNN method - something we agreed on checking the charts, as we, traders-developers, had different opinions of the market regime for an asset price. But the Script might yield results we can all agree upon.
█ DISCLAIMER
This indicator is a decision-support tool, not a trading system. It does not constitute financial advice. Past regime patterns do not guarantee future behavior. Always apply proper risk management.
Algorithm: K-Nearest Neighbors (KNN)
Distance metric: Minkowski Distance (p=2, Euclidean default)
Kernel: Gaussian (distance-weighted voting)
Normalization: Z-Score (look-ahead free)
Regimes: Trending | Ranging | Volatile Trend | Uncertain Indicateur

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. Indicateur

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. Indicateur

KNN Machine Learning Mean Reversion Probability [Dots3Red]█ OVERVIEW
This script applies a K-Nearest Neighbors (KNN) machine learning algorithm to estimate the probability that price will revert to its moving average within a defined number of bars. Rather than predicting momentum direction, it asks a more specific question: how likely is it that this extension snaps back?
The model searches historical bars for situations that looked like the current one — same degree of stretch, same RSI exhaustion profile, same volume behavior — and measures how often those situations ended in a reversion to the basis MA. That proportion becomes the live probability shown on your chart.
█ METHODOLOGY
The indicator follows a supervised machine-learning pipeline with five distinct stages.
1 — Labeling (what we are predicting)
Each historical bar receives a label based on what actually happened next. If price was extended above the basis MA and touched it within the Reversion Window — that bar is labeled a successful reversion. If it did not touch — labeled as no reversion. The same logic applies from below. This is the core distinction from momentum KNN indicators: the target is reversion to fair value , not directional price movement.
2 — Feature engineering (what we measure)
Five features capture how stretched current price conditions are, each Z-score normalized to remove scale bias:
• MA Distance — signed % distance of close from the basis MA. The primary extension signal.
• Bollinger Band position — where price sits within the bands, normalizing extension relative to current volatility.
• RSI deviation — how far RSI has moved from neutral (50). Captures momentum exhaustion.
• Body compression — ratio of candle body to total range. Small bodies near extremes signal hesitation and loss of directional conviction.
• Volume fade — declining volume during an extension is a classic exhaustion signature.
3 — Z-score normalization
All five features are standardized using a rolling mean and standard deviation computed on prior bars only (look-ahead free). This ensures the KNN distance calculation is not biased by features of different scales.
4 — KNN engine
The algorithm scans the historical lookback window for the K most similar past bars, measured by Minkowski Distance across all five features simultaneously. Closer neighbors receive exponentially higher voting weight via a Gaussian Kernel , so the prediction is driven by the most relevant historical analogs — not a simple majority vote.
5 — Dual probability output
Two independent probabilities are maintained and tracked separately:
• P(reversion from above) — for overbought / extended-high setups.
• P(reversion from below) — for oversold / extended-low setups.
They are kept separate because bear-side extensions and bull-side extensions have statistically different behavior — bear moves are typically faster and sharper. A signal fires when the relevant probability crosses the user-defined threshold, and only when price is actually extended (see Extension Gate below).
█ WHAT MAKES THIS DIFFERENT
Most published KNN indicators predict momentum direction — will price go up or down next bar? This indicator predicts something more specific: will price return to its average?
The distinction matters for several reasons:
1 — A high momentum reading can persist for many bars. A stretched reading has a natural gravity pulling it back, and measuring the historical probability of that snap is a more tractable problem than direction forecasting.
2 — The two probability channels are trained on separate populations, accounting for the asymmetry between bull and bear extensions.
3 — The Extension Gate ensures signals only appear when there is actually something to revert from — no signals in flat, choppy, low-volatility conditions.
█ EXTENSION GATE
Even if the KNN model outputs a high reversion probability, no signal appears unless price is beyond Gate Multiplier × ATR from the basis MA. This prevents false signals in low-volatility or ranging conditions where mean reversion setups carry no statistical edge.
█ HOW TO USE
Signal shapes (▲ Rev / ▼ Rev)
Fire when P(reversion) crosses the threshold AND price passes the extension gate. The label at the signal bar shows the exact probability at the moment of firing.
Snap zone fill
When a signal is active, the region between current price and the basis MA is shaded. This is the reversion target zone — where price is statistically expected to return. The fill deactivates automatically once price reverts back through the basis.
Bar colors
• Bright green/red — active probability above the threshold on the current price side.
• Dimmed green/red — probability elevated but below threshold, approaching signal territory.
• No color — neutral or low reversion probability.
Background flash
A faint background confirms the exact bar on which a signal fired.
Recommended workflow
1 — Set the Basis MA to your preferred mean reversion average. EMA 20 is a common starting point for intraday and swing setups.
2 — Tune the Reversion Window to match your typical trade hold time in bars.
3 — Adjust the Extension Gate multiplier to the asset's volatility profile. Crypto typically requires higher values than forex or equities.
4 — Use the Probability Threshold to control signal frequency. 0.65 gives moderate frequency; 0.75 and above is more selective.
5 — Combine with volume analysis or candlestick confirmation at signal bars for additional confluence before entering a position.
█ SETTINGS REFERENCE
KNN Engine
• K Neighbors — how many historical analogs vote. Higher = smoother, slower to react.
• Lookback Window — size of the historical search space in bars.
• Reversion Window — bars within which price must touch the MA to count as a reversion.
• Minkowski p — distance metric exponent. 1 = Manhattan, 2 = Euclidean.
• Gaussian Bandwidth — controls how steeply neighbor weight falls with distance.
• Probability Threshold — minimum confidence required to show a signal.
Feature Settings
• Basis MA type / length — the fair value line all features are measured against.
• Bollinger Band mult — standard deviation multiplier for the BB position feature.
• RSI length — period for the RSI exhaustion feature.
• Volume MA length — baseline for the volume fade feature.
Extension Gate
• Require extension gate — toggle the ATR-based signal filter on/off.
• Gate band multiplier — how many ATRs from basis price must be before signaling.
• Gate ATR length — period for the ATR used in the gate calculation.
█ LIMITATIONS
• KNN is a lazy learner — it does not generalize beyond historical patterns in the lookback window. Strong trending regimes or structural breaks can produce elevated false signals.
• The reversion probability reflects historical frequency, not a guarantee of future behavior.
• On low-bar-count charts (e.g. weekly on newer assets), the lookback window may not contain enough samples to produce stable probability estimates.
• Computation scales with lookback window size. Very large windows may slow chart rendering.
█ DISCLAIMER
This indicator is a decision-support tool, not a trading system. It does not constitute financial advice. Always apply proper risk management and combine with your own analysis.
Algorithm: K-Nearest Neighbors (KNN)
Distance metric: Minkowski Distance
Preprocessing: Z-Score Normalization
Target: Probabilistic Mean Reversion Indicateur
