Strong KNN Classifier | ProjectSyndicateStrong KNN Classifier reads the order flow underneath each bar and asks one question: is the current move more likely to CONTINUE or to REVERSE? Instead of guessing, it learns from the market's own history. Every bar is turned into a five-part order-flow fingerprint, stored with the outcome it actually produced, and the live bar is matched against the closest past situations using Lorentzian distance — the outlier-robust metric built for noisy market data. The nearest neighbours vote, that vote is calibrated into an honest probability, and only genuinely confident reads near structural zones are printed as signals. Every prediction that resolves is scored on a live hit-rate panel — winners and misses alike — so you see exactly how the logic behaves on the symbol and timeframe you trade, not a number typed into a description.
🧠 Lorentzian Core — the core idea, expressed as a lifecycle: OBSERVE ▸ LABEL ▸ LEARN ▸ CLASSIFY ▸ CALIBRATE. Each bar is reduced to five order-flow features and z-scored so they share one scale. A rolling library of past feature vectors is kept, and each one is labelled only after its outcome is fully known — a vector formed H bars ago is tagged CONTINUATION or REVERSAL using bars that have already printed, never future ones. The live bar is then compared to that resolved library with Lorentzian-distance k-nearest-neighbours, the closest matches vote, and the result is turned into a probability. Because every label is resolved from past bars and every signal confirms on the bar's close, the classifier does not repaint.
🔋 Feature Anatomy — the fingerprint is not one number; it is five breakout-native ingredients fused into a single distance. Net delta (reconstructed buy-minus-sell pressure), bid/ask imbalance (which side dominated the bar), absorption (heavy volume that produces little price progress — a stalled push), CVD slope (the direction and steepness of cumulative delta), and price location versus VWAP in ATR units (where the bar sits inside its structural range). Each feature is independently z-scored over a rolling window, so no single raw scale can dominate the match. Order-flow components are reconstructed from lower-timeframe intrabar data and are labelled as estimates, not exchange tick prints.
🎯 Calibrated Probability Engine — this is the part most "AI" scripts get wrong. A raw k-vote can only land on a handful of fractions, so it slams to 88% or 100% and lies about its own confidence. Strong KNN Classifier instead weights each neighbour by distance, collapses the vote into a signed margin, shrinks that margin toward a neutral 0.5 prior by how much trustworthy neighbour mass actually agreed, and passes it through a logistic curve. The output is a smooth, continuous Reversal Probability and a 0–100 Confidence read that reflect genuine neighbour agreement — high only when many close matches concur, honestly near the middle when they don't.
🧲 Structural-Zone Context — a classification matters most where decisions are made: at the levels where price interacts with resting structure. The engine only promotes a read to a signal when price is inside a structural zone — within an ATR band of VWAP or of the most recent confirmed swing pivot. Away from structure the model still reports its read on the dashboard, but it holds its fire, keeping orbs anchored to the moments that carry context rather than scattering them mid-range.
🎚️ Conviction Controls — a compact set of dials sets how serious a read must be before it prints: the Minimum Confidence to signal, the number of Neighbours (k) that vote, the Prior Strength that shrinks weak agreement toward neutral, the Probability Sharpness that scales the confidence spread, the Distance Temperature that softens or sharpens neighbour weighting, the minimum sample count before any signal is allowed, and a cooldown. Tighten them for fewer, cleaner classifications; loosen them for more activity. Together with the zone gate, this is your main control over conviction versus frequency.
🧭 No-Lookahead Discipline — a read is not allowed to cheat. Training labels are resolved purely from bars that have already closed, the live bar is only ever compared against fully-resolved neighbours, and signals confirm on the closed candle. Until the library holds enough resolved samples the panel shows TRAINING and stays silent, and a cooldown stops a single chaotic session from stacking overlapping orbs. The hit-rate tracker is held to the same standard — every prediction whose horizon resolves is counted, correct or not, with nothing dropped to flatter the number.
⭐ 0–100 Confidence Read — every classification carries a numeric Reversal Probability, a Confidence score, and the count of neighbours that actually contributed. Treat Confidence as a relative cleanliness and agreement read for ranking and thinning signals — it describes how textbook the current situation is versus the model's memory, not a guaranteed outcome. The confidence threshold restricts what is displayed and alerted, while the dashboard keeps reporting the live read in the background even when no signal fires.
📊 Live Statistics Dashboard — a non-intrusive panel tracks, in real time on your chart: model status (TRAINING or LIVE) with the current training-pool size, the order-flow source in use, each of the five features as a live z-score, the current Prediction (continuation / reversal / neutral), the Reversal Probability, the Confidence, the number of neighbours used, whether price is currently inside a structural zone, and a rolling Hit-Rate computed over every resolved prediction. The hit-rate counts winners and misses in full, so the number is built live from the real signals on your current symbol and timeframe — not printed here in advance.
🎨 Clean Themed Visuals — four coherent palettes (Aurora default, plus Neon, Plasma, and Solar) shade the probability ribbon, the class-tinted candles, the signal orbs and their chips, and the dashboard to one look, so direction and quality read at a glance on a dark chart. A background ribbon graduates between the continuation and reversal colours by probability; confirmed signals print a sized circular orb with a clean, non-overlapping chip showing direction, probability, and the neighbour/confidence read. Signal dot size is adjustable, and the chip offset scales with it so labels never collide with the orb.
🔔 Detailed Alerts — fires on a continuation signal, on a reversal signal, and on any high-confidence classification, formatted for manual or automated use. The confidence threshold and the in-zone gate restrict alerts to higher-conviction reads.
🔧 Fully Customizable — every component is exposed: the number of neighbours, the outcome horizon, the trend-reference length, the outcome threshold in ATR, and the maximum and minimum training-pool sizes; the distance temperature, prior strength, and probability sharpness that govern calibration; the normalisation window, CVD slope length, and absorption reference of the feature engine; the intrabar resolution and volume weighting of the order-flow reconstruction; the VWAP and swing-pivot zones, pivot length, and zone width; the confidence threshold, in-zone requirement, and cooldown; all four themes and every ribbon, candle-tint, orb, dot-size, neighbour-chip, and dashboard toggle, plus dashboard position and size.
🎯 Why this is different — most "machine learning" indicators are black boxes that restyle an oscillator and claim to call the top, and most kNN scripts publish a confidence that is really just a vote fraction in disguise. This one engineers inspectable order-flow features, matches them with an outlier-robust Lorentzian metric, and then does the part that is usually skipped: it calibrates the probability so confidence reflects real, distance-weighted neighbour agreement instead of a coarse vote artefact. It resolves every training label with no lookahead, gates signals to structural context, and reports a live, honest hit-rate that counts misses in full — so you judge it on your own current data rather than on a marketing figure.
🚀 Where to use it — the engine is symbol-agnostic and built on universal order-flow behaviour, so it can be applied to FX majors and crosses, metals, indices, and crypto on intraday timeframes. It is strongest where lower-timeframe order-flow reconstruction carries information — liquid intraday futures and crypto — and the normalisation and ATR scaling adapt to each instrument automatically. One practical check: if the five features all read 0σ, your chart's symbol is not exposing intrabar data and the model is running on the coarse bar-level fallback — set the Intrabar Resolution explicitly and confirm the features come alive before relying on signals. Because the classifier is symmetric, let the dashboard's hit-rate tell you whether the logic genuinely suits the pair and timeframe before you commit.
🎯 How to trade it
1 Apply it to a liquid symbol on an intraday timeframe and let the panel move from TRAINING to LIVE as the library fills. Read the live Hit-Rate for your symbol and timeframe first — if the logic doesn't suit that market, you'll see it.
2 Wait for an orb — it marks a confirmed close, above your confidence threshold, inside a structural zone, with the direction, probability, and neighbour/confidence read already labelled.
3 Read the dashboard alongside it: the Prediction, the Reversal Probability, the Confidence, and how many of the k neighbours actually agreed.
4 Use the confidence threshold, neighbour count, prior strength, and sharpness to set your tempo — stricter for fewer, cleaner reads; looser for more activity.
5 Combine the classification with your own structure and risk management — it is a read on the next move's character, not an entry-and-exit system on its own.
⚠️ Important — this is a decision-support tool, not a standalone buy/sell system, and it makes no performance guarantees. The probability is calibrated to reflect genuine neighbour agreement, but the underlying edge varies by market, session, and configuration, and on some symbols and timeframes it will be close to neutral — the displayed probability and the dashboard hit-rate are historical and descriptive, not a forecast. Order-flow features are reconstructed from lower-timeframe data and are estimates, not true tick prints; where intrabar data is unavailable the model falls back to a coarser delta. Signals confirm on the closed bar, so always wait for the orb on a closed candle. Because the classifier is symmetric and contrarian-capable, a strong one-way trend or a regime shift can run straight through a high-confidence read — combine it with your own analysis, and test it on your market before trading it live. Indicator

AI SuperTrend [PickMyTrade]THE PROBLEM WITH A FIXED MULTIPLIER
Every standard SuperTrend applies the same ATR multiplier across all market conditions — the same constant during a strong trending breakout, a narrow choppy range, and a volatility spike. A value calibrated for one regime is miscalibrated for the others. Most traders compensate by manually switching timeframes or parameters. This script automates that decision.
The question it asks: what if the ATR multiplier were selected from historical bars that most resembled the current market regime — matched by Hurst state and volatility rank — rather than set by the user as a fixed constant?
────────────────────────────────────────
THREE AI LAYERS
Layer 1 — Hurst Exponent (Regime Gate)
The Hurst Exponent is computed via Rescaled Range (R/S) Analysis. It measures the degree of long-range dependence (memory) in the price series:
H ≥ 0.55 → Persistent (trending) — SuperTrend active, signals enabled
H ≈ 0.50 → Random walk — candles turn gray, no signal generated
H ≤ 0.45 → Anti-persistent (mean-reverting) — signals suppressed
The Hurst gate is the first filter. Signals only fire when market structure is historically associated with persistence — not randomness or mean-reversion.
Layer 2 — Garman-Klass Volatility Rank
Garman-Klass (1980) estimates realized volatility from OHLC prices rather than close-to-close returns, capturing intrabar price range and making it more sensitive to volatility changes. The current reading is percentile-ranked against recent history (0–100%) and used as the second feature dimension for the KNN search.
Layer 3 — KNN Multiplier Optimizer
K-Nearest Neighbors searches a rolling memory bank of feature pairs from previous bars. For each current bar it finds the K most similar historical bars by Euclidean distance in that 2D feature space. From those neighbors it retrieves the ATR multipliers that were in effect — weighted by the profitability of the bar that followed. The result is the AI Multiplier: a context-aware value drawn from the most similar past conditions, not a fixed constant.
────────────────────────────────────────
WHAT YOU SEE ON THE CHART
Candle color — the defining visual. Orange = bull trend regime, blue = bear trend regime, gray = random walk or mean-reverting. The regime state is readable on every bar without checking the table.
Signals — ● (circle) marks trend flips with Hurst ≥ 0.65, the high-conviction threshold. ▲▼ (triangle) marks standard threshold crossings. No signal fires in gray (random or mean-reverting) regimes.
SL / TP lines — dashed lines drawn automatically at each signal bar, sized from current ATR × the AI Multiplier active at that bar.
Info table (top right) — live display of Hurst value, Regime label, Direction, AI Multiplier, Vol Rank, and KNN memory bar count. Shows WARMUP until KNN has stored enough bars to begin optimizing.
────────────────────────────────────────
HOW TO USE
A signal requires all three conditions to be true simultaneously:
KNN is warmed up (table shows ● LIVE)
Hurst confirms a trending regime (H ≥ Trend Threshold input)
Price is on the correct side of the EMA filter
Circle signals (●) indicate Hurst has exceeded 0.65 — stronger persistence than the standard threshold. Triangle signals (▲▼) are at the user-defined threshold. Gray candles indicate the market is not in a trending regime; reducing exposure or standing aside is appropriate during those periods.
The regime background shading (faint orange or blue fill) shows when the SuperTrend is in an active directional state.
────────────────────────────────────────
INPUTS
AI Engine — Hurst Lookback, KNN Neighbors (K), KNN Memory (bars), Trend Threshold, Mean-Revert Threshold
SuperTrend — ATR Length, Base Multiplier, Volatility Window, EMA Period
Visual — Bull/Bear colors, SL/TP lines toggle, SL ATR Multiplier, Risk:Reward ratio, Regime Background
Display — Zen Mode (hides labels and table), Show Info Table
ALERTS
Three alert conditions: Long Signal, Short Signal, Any Signal.
────────────────────────────────────────
NOTES
KNN requires warmup equal to the KNN Memory setting before the AI Multiplier activates. During warmup the base multiplier scaled by Hurst and volatility rank is used instead.
No repainting. All signals are confirmed on bar close. KNN stores lagged values only.
Garman-Klass citation: Garman, M. & Klass, M. (1980). On the Estimation of Security Price Volatilities from Historical Data. Journal of Business , 53(1), 67–78.
Indicator

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

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

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

Artemis Oscillator PROArtemis Oscillator PRO is a momentum oscillator built on a custom Directional Range Momentum (DRM) engine — an original algorithm that measures signed range impulse, not price distance. Unlike RSI or Stochastic, DRM scores the direction and force of range expansion relative to its own history, normalized to 0–100. The result is an oscillator that reacts cleanly to structural momentum shifts without the lag inherent in traditional smoothed-ratio oscillators.
The indicator integrates five analytical layers — oscillator core, volume pressure, momentum state scoring, divergence detection, and KNN machine learning bias — each operating independently and rendered on a single, clean oscillator panel.
🟦 HOW THE CORE ENGINE WORKS
**Directional Range Momentum (DRM)**
Each bar, the engine measures the current highest high and lowest low over the lookback period. It then assigns a signed range force:
- If the range is expanding to the upside → positive force (full range span)
- If the range is expanding to the downside → negative force (negative full span)
- If range is stable → raw tick delta (neutral)
This signed force is split into two smoothed components:
- `sUp` — smoothed directed force (can be positive or negative)
- `sAbs` — smoothed absolute force (always positive, represents total activity)
The oscillator value is: `(sUp / sAbs) * 50 + 50`
This produces a 0–100 scale where 50 is neutral, above 50 means upward range pressure dominates, and below 50 means downward range pressure dominates. Division by the absolute component normalizes the output regardless of asset volatility.
**Signal Line**
A second independently configurable smoothing pass over the oscillator value. Crossovers between the oscillator and signal line mark momentum regime changes.
**Smoothing Methods**
Four algorithms available for both oscillator and signal line:
- RMA — Wilder's Moving Average (default, most stable, minimal overreaction)
- EMA — Exponential, faster response
- SMA — Simple, equal weight across all bars
- TMA — Double-smoothed SMA, maximum smoothness
🟦 VOLUME PRESSURE
**Dual MFI Architecture**
Volume Pressure uses two Money Flow Index calculations simultaneously:
- Fast MFI: `Period / 1.33` (shorter window, more reactive)
- Slow MFI: `Period * 1.33` (longer window, structural bias)
These are blended 50/50, then passed through a power-curve compression function (`x^0.75`) that reduces extreme readings while preserving directional accuracy. The result is mapped to 0–100 and rendered as fill areas anchored at the midline:
- Above 50: Inflow fill (buying pressure dominates)
- Below 50: Outflow fill (selling pressure dominates)
The MFI price source is configurable: HLC3 (default), Close, HL2, or OHLC4.
🟦 MOMENTUM STATE SCORING
A composite score from 0 to 3 is calculated each bar using three independent binary conditions:
| Condition | +1 Point |
|---|---|
| Oscillator > Signal Line | Momentum direction |
| Oscillator > 50 | Oscillator position |
| Volume Pressure > 50 | Volume confirmation |
**Score interpretation:**
- Score 3 → Full overbought state fill (all three conditions bull-aligned)
- Score 2 → Partial overbought fill (two conditions)
- Score 1 → Partial oversold fill (one condition)
- Score 0 → Full oversold state fill (all three conditions bear-aligned)
Fills render inside the oscillator panel at adjustable opacity. The scoring is continuous — it updates every bar without look-ahead.
🟦 MOMENTUM EXHAUSTION
Exhaustion labels (`✦ OB` / `✦ OS`) fire when the oscillator is inside a zone but weakening consecutively. Specifically:
✦ OB — oscillator is at or above the OB threshold AND has closed lower for N consecutive bars
✦ OS — oscillator is at or below the OS threshold AND has closed higher for N consecutive bars
N (Confirmation Bars) is configurable from 1 to 4. Higher values produce fewer but more structurally confirmed signals. This is not a predictive signal — it marks the process of momentum fading, not the reversal itself.
🟦 DIVERGENCE DETECTION
Pivots are calculated using `ta.pivothigh` and `ta.pivotlow` with an arm of `Period / 2`. All divergence results appear `Period / 2` bars late — this is standard Pine Script pivot behavior, not a bug.
**Four divergence types:**
| Type | Price | Oscillator | Signal |
|---|---|---|---|
| Regular Bull (D▲) | Lower Low | Higher Low | Potential reversal up |
| Regular Bear (D▼) | Higher High | Lower High | Potential reversal down |
| Hidden Bull (H▲) | Higher Low | Lower Low | Uptrend continuation |
| Hidden Bear (H▼) | Lower High | Higher High | Downtrend continuation |
Regular divergence uses solid lines. Hidden divergence uses dashed lines. Labels use clean symbol-only style with no background box.
**Smart Divergence Filter (AI)**
An optional pre-filter that rejects low-quality divergence signals before they render. Three conditions must pass (each configurable independently):
1. Minimum oscillator swing between the two pivot points (default: 5 units)
2. Minimum price swing as a percentage of recent range (default: 0.3%)
3. Volume Pressure confirmation — VP must agree with divergence direction
When the filter is OFF, all detected divergences render. When ON, only structurally significant divergences pass. The filter applies identically to both chart rendering and alert conditions — no mismatch between visual and alert signals.
🟦 KNN BIAS PANEL
**What KNN Does**
K-Nearest Neighbors (KNN) is a non-parametric machine learning algorithm. Each bar, the indicator stores the current market state as a point in 3-dimensional feature space. When making a prediction, it finds the K historically most similar states and votes on the likely outcome.
**The Three Features**
| Feature | Calculation | Signal |
|---|---|---|
| O (Oscillator) | `oscVal / 100` | O+ = above 50 (bull zone) |
| V (Volume) | `vpMid / 100` | V+ = above 50 (inflow) |
| S (Signal gap) | `(oscVal - sigVal + 100) / 200` | S+ = oscillator above trigger |
**ATR-Normalized Output Label**
The classification target uses ATR-adjusted thresholds rather than a raw `close > close ` comparison. A bar is labeled bullish only if close moved more than `0.1 × ATR(14)` upward, bearish if it moved more than `0.1 × ATR(14)` downward, otherwise the previous label is carried forward. This eliminates noise-driven label flips caused by micro price movements.
**Distance Calculation**
Euclidean distance in 3D feature space:
```
d = sqrt((kf1_now - kf1_hist)^2 + (kf2_now - kf2_hist)^2 + (kf3_now - kf3_hist)^2)
```
The K nearest historical points vote. If majority voted bullish → BULL bias. Result thresholds: ≥60% bull vote = BULL, ≤40% = BEAR, between = NEUTRAL.
**Panel Display**
| Row | Left | Right |
|---|---|---|
| Header | KNN AI | Direction (▲ BULL / ▼ BEAR / ◈ NEUTRAL) |
| Row 1 | Confidence | Percentage (0–100%) |
| Row 2 | Progress bar (█░) | Bars in training memory |
| Row 3 | O± V± S± feature states | K= neighbor count |
Panel renders with monospace font, theme-aware backgrounds, and a single accent color derived from the active theme.
🟦 COLOR THEMES
Eight complete palettes, each defining five independently tuned colors (bull, bear, signal, VP buy, VP sell):
| Theme | Character | Bull Color | Bear Color |
|---|---|---|---|
| Aurora | Dark mode, high contrast | Cyan | Violet |
| Ember | Dark mode, warm | Amber | Steel Blue |
| Cyber | Dark mode, neon | Lime Green | Crimson |
| Arctic | Dark mode, cool | Sky Blue | Soft Purple |
| Solar | Dark mode, warm gold | Yellow Gold | Salmon |
| Obsidian | Dark mode, pro trader | Emerald | Scarlet |
| Classic | Light mode | Navy Blue | Crimson |
| Mono | Light mode, minimal | Near Black | Gray |
All five color roles (bull/bear/signal/VP buy/VP sell) change simultaneously when the theme changes. No per-color manual adjustment required.
🟦 ALERT SYSTEM
Twelve alert conditions, all using `alert.freq_once_per_bar`:
| Alert | Condition |
|---|---|
| Bullish Cross | Oscillator crosses above signal while below midline |
| Bearish Cross | Oscillator crosses below signal while above midline |
| Exit Oversold | Oscillator crosses above OS level |
| Exit Overbought | Oscillator crosses below OB level |
| Regular Bull Divergence | Price LL + oscillator HL (+ Smart Filter if enabled) |
| Regular Bear Divergence | Price HH + oscillator LH (+ Smart Filter if enabled) |
| Hidden Bull Divergence | Price HL + oscillator LL (+ Smart Filter if enabled) |
| Hidden Bear Divergence | Price LH + oscillator HH (+ Smart Filter if enabled) |
| VP Inflow | Volume Pressure crosses above 50 |
| VP Outflow | Volume Pressure crosses below 50 |
| Exhaustion OB | Oscillator weakening N bars while above OB level |
| Exhaustion OS | Oscillator strengthening N bars while below OS level |
Divergence alerts respect the Smart Divergence Filter — if the filter is ON and a divergence is rejected visually, the alert will also not fire.
🟦 SETTINGS REFERENCE
**Oscillator**
- Period — DRM lookback window. Also controls divergence pivot arm (Period / 2). Default: 14
- Smoothing — EMA / SMA / RMA / TMA. Default: RMA
- Source — Price input for the range engine. Default: Close
- Adaptive Color — Oscillator line shifts between bull/bear colors based on position. Default: ON
**Signal Line**
- Period — Signal smoothing window. Default: 7
- Smoothing — EMA / SMA / RMA / TMA. Default: EMA
- Show Cross Dots — Dot on signal line at each crossover. Default: ON
**Zones & Fills**
- Overbought level — Default: 80
- Oversold level — Default: 20
- Zone fill opacity — Configurable per zone. Default: 20
**Volume Pressure**
- Show Volume Pressure — Toggle. Default: ON
- MFI Source — HLC3 / Close / HL2 / OHLC4. Default: HLC3
- Opacity — Default: 18
**Momentum State**
- Show Momentum State — Toggle. Default: ON
- OB Opacity / OS Opacity — Default: 35 each
**Divergence**
- Regular / Hidden — Independent toggles and opacity controls
- Label Size — Tiny / Small / Normal / Large. Default: Tiny
- Smart Divergence Filter — ON/OFF. Default: OFF
- Min Oscillator Swing — Default: 5.0
- Min Price Swing % — Default: 0.3%
- Require VP Confirmation — Default: ON
**Momentum Exhaustion**
- Show Labels — Toggle. Default: ON
- Confirmation Bars — 1 to 4. Default: 4
**KNN Bias**
- Show KNN Panel — Toggle. Default: ON
- Neighbors (K) — 3 to 10. Default: 5
- Training Window — 50 to 300 bars. Default: 100
- Panel Position — Four corners. Default: Bottom Right
- Panel Text Size — Tiny / Small / Normal / Large. Default: Small
🟦 COMPATIBILITY
Works on all asset classes and all timeframes in PulseWire Pine Script v6.
- Crypto: Spot, futures, perpetual contracts
- Forex: All pairs
- Equities: Stocks, ETFs, indices
- Commodities: Metals, energy, agriculture
- Timeframes: 1m through Monthly
The DRM engine normalizes by its own absolute smoothed component, making it volatility-agnostic across assets and timeframes without manual recalibration.
🟦 TECHNICAL NOTES
- Pine Script v6
- max_lines_count = 500`, `max_labels_count = 500` (divergence drawings)
- No repainting — all values calculated on bar close. Pivot-based divergence results appear `Period / 2` bars late by design
- KNN training updates only after `bar_index > 1` to avoid cold-start artifacts
- Volume Pressure fill anchors use `color = na` (not `display.none`) to maintain Pine v6 `fill()` compatibility
- OB/OS state fills render outside the 0–100 oscillator range (104–110 and −10 to −4) to avoid visual overlap
🟦 DISCLAIMER
This indicator is provided for educational and informational purposes only. It does not constitute financial advice. Past performance does not guarantee future results. Always conduct your own analysis and apply proper risk management.
Indicator

Indicator

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

kNN Market Architecture [LuxAlgo]The kNN Market Architecture indicator is a professional-grade market structure framework that utilizes a k-nearest neighbors (kNN) machine learning classifier to validate price pivots across multiple time horizons. By integrating a dynamic detection engine, cumulative volume delta analysis, and a range-based volume profile, this tool provides a multi-layered hierarchical view of price action to identify high-probability reversal and breakout zones.
🔶 USAGE
The indicator identifies and classifies market structure into three distinct layers: Short-Term (ST), Medium-Term (MT), and Long-Term (LT). Unlike traditional pivot indicators that rely on static lookbacks, each point must pass a kNN similarity test based on relative volatility and volume features to be validated and plotted.
🔹 Multi-Scale Bias Analysis
Users can define which structural layer (ST, MT, or LT) dictates the overall market bias. When price is trading above the most recent validated high of the selected term, the candles and dashboard will reflect a bullish bias. Conversely, trading below the recent validated low indicates a bearish bias. This allows for seamless "top-down" analysis within a single chart view.
🔹 The Delta Tank
When a structural level is active (not yet breached), a "Delta Tank" label appears at the price line. This tool tracks the cumulative volume and delta (buying vs. selling pressure) since the level was formed.
A green icon with a high fill percentage indicates aggressive buying defending a support level or attacking resistance.
A red icon suggests selling pressure is mounting, potentially signaling an upcoming Break of Structure (BOS).
The percentage value represents the delta-to-total-volume ratio, providing a metric for the "exhaustion" or "strength" of a specific level.
🔹 Anchor Volume Profile
The indicator includes a dynamic Volume Profile that anchors itself specifically to the current active structural range. This profile calculates volume distribution between the most recent validated High and Low of your chosen Bias Source, allowing you to see exactly where the most "fair value" was traded within the current trading range.
🔶 ADVANTAGES OVER TRADITIONAL METHODS
The kNN Market Architecture offers several significant improvements over standard market structure indicators:
Noise Filtering via Machine Learning: Traditional pivot indicators plot every mathematical high/low within a window. The kNN classifier filters these by comparing the "signature" (volatility and volume) of the current point against historical successful pivots. If a pivot lacks the necessary confidence, it is ignored, leading to much cleaner charts.
Volatility-Adjusted Detection: Most indicators use a fixed lookback (e.g., 10 bars). This script uses a dynamic engine that expands during high volatility and contracts during low volatility, ensuring the structure remains relevant regardless of market speed.
Contextual Volume Data: While standard indicators only show price, this tool layers Volume Delta and Volume Profiles directly onto the structure points, providing the "why" behind price movements.
🔶 DETAILS
🔹 Auto-Adjust Sensitivity
The core of the detection engine is its ability to adapt to changing market conditions. When "Auto-Adjust Sensitivity" is enabled, the script calculates a volatility ratio by comparing the current ATR to its long-term average. During periods of high volatility, the engine automatically expands the detection window. This ensures that the indicator requires more significant price movement to confirm a new structure point, preventing "false positives" during erratic price swings. In low-volatility environments, the window contracts, making the engine more sensitive to subtle structural shifts.
🔹 kNN Validation Engine
For every potential price pivot, the engine analyzes features such as Relative ATR and Relative Volume. It compares these features against a historical database of previous pivots. If the current point does not meet the "Confidence Threshold" (the average score of its k-nearest neighbors), it is discarded.
🔶 SETTINGS
🔹 Dynamic Engine
Structure Sensitivity: Controls the base lookback for pivot detection.
Auto-Adjust Sensitivity: Enables volatility-based scaling of the detection engine.
🔹 kNN Classifier
k-Nearest Neighbors: The number of historical neighbors to compare against the current pivot.
Confidence Threshold: The minimum similarity score required to validate a structure point.
🔹 Visual Hierarchy
ST/MT/LT Toggles: Enables or disables the visibility of Short, Medium, and Long-term structures.
Bias Source: Choose which term (Auto, LT, MT, ST) governs candle coloring and the Volume Profile.
Color Candles by Bias: Toggles the gradient candle coloring based on the current range position.
🔹 Volume Profile
Show Volume Profile: Toggles the structural range-based profile.
Profile Rows: Adjusts the vertical granularity (price bins) of the profile.
Profile Width (%): Controls the horizontal scale of the profile.
Indicator

Cluster Money Flow Index [UAlgo]Cluster Money Flow Index is a zone based MFI structure tool designed to detect repeated Money Flow Index turning points and group them into meaningful reaction areas. Instead of treating every isolated MFI pivot as a standalone event, the script searches for clusters of nearby pivots that occur around similar MFI levels. When enough touches accumulate in the same area, the indicator promotes that region into a live zone.
The main idea is simple. If MFI repeatedly turns down from a similar high region, that area can behave like an overbought supply style zone inside the oscillator. If MFI repeatedly turns up from a similar low region, that area can behave like an oversold demand style zone. By clustering these repeated reactions, the script attempts to map oscillator structure in the same way traders often map support and resistance on price.
What makes this indicator especially useful is that the zones are not static. They can expand when fresh touches appear, they gain visual strength as more reactions accumulate, and they can later be invalidated if MFI decisively breaks beyond them. This creates a much more dynamic view than a simple overbought line, oversold line, or ordinary pivot marker.
The script also includes a smoothed MFI reference, optional center lines, zone labels, a live dashboard, and alert conditions when MFI enters active cluster zones. This makes the indicator useful both for structural oscillator analysis and for workflow monitoring.
In practical use, Cluster Money Flow Index can help highlight repeated MFI rejection areas, repeated MFI support areas, transition zones near the middle range, and regions where oscillator behavior has historically clustered before reversal or pause.
🔹 Features
🔸 Pivot Based MFI Structure Detection
The script detects confirmed MFI pivot highs and pivot lows using user defined left and right pivot settings. This means clusters are built only from confirmed oscillator turning points rather than from every small fluctuation.
🔸 Cluster Logic Instead of Single Pivot Logic
A new pivot does not automatically create a new zone. The script first checks whether that pivot is close enough to an existing valid cluster. If it is, the cluster gains another touch. If it is not, a new cluster is created.
🔸 Adaptive Proximity Threshold
Cluster sensitivity is based on MFI volatility. The script calculates the standard deviation of raw MFI and multiplies it by the user selected proximity multiplier. This makes zone grouping adapt to the current oscillator environment.
🔸 Minimum Touch Confirmation
A cluster is displayed only after it reaches the required minimum number of touches. This helps filter out weak one time reactions and focuses attention on repeated oscillator behavior.
🔸 Optional Zone Expansion
When enabled, the zone can expand with each new retest. If a fresh pivot extends beyond the current cluster boundary, the top or bottom is updated and the center is recalculated. This allows the zone to evolve naturally as more data arrives.
🔸 Dynamic Zone Strength Visualization
Zones become slightly more visible as touch count increases. This gives stronger clusters more visual weight and helps the user quickly distinguish weak from strong oscillator regions.
🔸 Overbought, Oversold, and Mid Context
Zone color is chosen from the zone center. Clusters centered high in the MFI range use the overbought color, clusters centered low use the oversold color, and clusters near the middle range use the mid color.
🔸 Optional Center Line and Labels
Each displayed cluster can include a center line and an information label showing whether the zone is an upper or lower type cluster, its approximate center level, and its total touch count.
🔸 Invalidation Logic
A zone remains valid until MFI breaks clearly beyond it. Upper clusters are invalidated if MFI pushes decisively above the zone. Lower clusters are invalidated if MFI drops decisively below it.
🔸 Dashboard Summary
A built in dashboard can show current MFI state, number of active upper and lower zones, strongest cluster strength, and the nearest upper and lower cluster centers.
🔸 Alert Support
Alerts are provided for:
MFI entering an upper cluster zone,
MFI entering a lower cluster zone,
MFI crossing above 80,
and MFI crossing below 20.
🔹 Calculations
1) Calculating Raw and Smoothed MFI
float rawMFI = ta.mfi(hlc3, mfiLen)
float smoothedMFI = ta.ema(rawMFI, mfiSmooth)
This is the starting point of the indicator.
The script first calculates the standard Money Flow Index from hlc3 using the selected MFI length. Then it applies an EMA smoothing pass to create a softer reference line.
The raw MFI is used for all pivot detection, clustering, invalidation, zone interaction, and alerts. The smoothed MFI is mainly a visual aid that helps the user see the broader oscillator path more clearly.
So the indicator always builds its logic from raw MFI structure while also giving the user a smoother secondary guide.
2) Defining the Cluster Object
type MFICluster
float top
float bottom
float center
bool isOB
int touches
int firstBarTime
int lastTouchTime
int firstBarIdx
bool isValid
bool isDisplayed
box zoneBox
line centerLine
label infoLabel
This object stores the full lifecycle of one MFI cluster zone.
It contains:
the zone top,
the zone bottom,
the center level,
whether the zone came from an upper pivot or lower pivot,
how many touches it has,
when it first formed,
when it was last touched,
whether it is still valid,
whether it has already been drawn,
and its visual objects.
So the script is not just plotting shapes. It is managing structured oscillator zones that have state, memory, and display properties.
3) Calculating the Adaptive Proximity Threshold
float mfiStd = ta.stdev(rawMFI, 50)
float proximity = math.max(2.0, mfiStd * proxMult)
This is the sensitivity engine of the clustering logic.
The script measures the standard deviation of raw MFI over the last fifty bars. It then multiplies that volatility measure by the user selected proximity multiplier. Finally, it enforces a minimum threshold of 2.0.
This means a new pivot is considered close enough to an existing cluster only if it lies within a volatility adjusted distance from the cluster center.
So the zone grouping automatically adapts to how noisy or how compressed the MFI environment currently is.
4) Detecting Confirmed MFI Pivot Highs and Lows
float mfiPH = ta.pivothigh(rawMFI, pivotLeft, pivotRight)
float mfiPL = ta.pivotlow(rawMFI, pivotLeft, pivotRight)
This is the pivot discovery step.
The script finds confirmed pivot highs and pivot lows directly on the raw MFI series. A pivot high becomes an upper type candidate cluster. A pivot low becomes a lower type candidate cluster.
Because the pivots are confirmed using both left and right bars, the script avoids reacting too early to temporary oscillator wiggles.
So all clustering logic is based on confirmed structure rather than live unconfirmed turns.
5) Checking Whether a Pivot Belongs to an Existing Cluster
method checkProximity(MFICluster this, float pivotVal, bool isOB, float threshold) =>
bool result = false
if this.isOB == isOB and this.isValid
if math.abs(pivotVal - this.center) <= threshold
result := true
result
This method decides whether a new pivot should strengthen an existing cluster.
A pivot can only join a cluster if:
the cluster is of the same type,
the cluster is still valid,
and the distance between the pivot value and the cluster center is less than or equal to the current threshold.
This is important because upper pivot highs are never mixed with lower pivot lows, and stale invalidated clusters are ignored.
So this method is the actual grouping filter that turns repeated nearby pivots into one shared zone.
6) Adding a New Touch to a Cluster
method addTouch(MFICluster this, float pivotVal, int pTime, bool shouldExpand) =>
this.touches += 1
this.lastTouchTime := pTime
if shouldExpand
if pivotVal > this.top
this.top := pivotVal
if pivotVal < this.bottom
this.bottom := pivotVal
this.center := (this.top + this.bottom) / 2.0
int(na)
Once a pivot is assigned to a cluster, this method updates the cluster state.
The touch count is incremented and the last touch time is refreshed. If zone expansion is enabled, the script also checks whether the new pivot extends above the current top or below the current bottom. If it does, the cluster boundaries are widened and the center is recalculated.
So clusters do not have to remain frozen. They can evolve as new oscillator reactions appear.
7) Creating a New Cluster When No Match Exists
if not wasClustered
float zoneHalf = math.max(proximity * 0.15, 0.8)
float zTop = pVal + zoneHalf
float zBot = pVal - zoneHalf
MFICluster newCl = MFICluster.new(
top = zTop,
bottom = zBot,
center = pVal,
isOB = isOB,
touches = 1,
firstBarTime = pTime,
lastTouchTime= pTime,
firstBarIdx = pBarIdx,
isValid = true,
isDisplayed = false)
If the new pivot does not belong to any existing valid cluster, the script creates a fresh cluster.
The initial zone width is determined from the current proximity threshold. Specifically, the script takes fifteen percent of that threshold and applies it equally above and below the pivot center, while enforcing a minimum half size of 0.8.
So every new cluster begins as a compact seed zone around one confirmed pivot and can later grow through repeated touches.
8) Minimum Touch Display Rule
if this.touches >= minT
This is the first major visual gate inside the drawing logic.
A cluster is not drawn just because it exists internally. It becomes visible only when its touch count reaches the user selected minimum touches threshold.
This helps reduce noise by hiding weak single touch or low confidence zones until repeated oscillator interaction has been proven.
So display is based on structural repetition, not just first occurrence.
9) Zone Strength and Opacity Calculation
f_calcOpacity(int touches, int baseOp) =>
float strength = math.min((touches - 1) / 8.0, 1.0)
int result = int(baseOp + (strength * 15))
math.min(result, 40)
This function converts touch count into visual intensity.
The script measures strength from the number of touches relative to a capped scale. Then it adds that strength bonus to the base opacity setting, while also imposing an upper limit.
This means zones with more touches appear slightly stronger and easier to notice than weaker zones.
So touch count influences not only logic, but also visual emphasis.
10) Zone Color Selection
f_zoneColor(float center) =>
center >= 70 ? obColor : center <= 30 ? osColor : midColor
This is the color classification rule.
If the cluster center is at or above 70, the zone uses the overbought color.
If the cluster center is at or below 30, the zone uses the oversold color.
Anything in between uses the mid color.
This is important because a cluster may come from an upper or lower pivot, but its actual center still determines how extreme its oscillator location really is.
So the visual color reflects where the cluster sits inside the MFI range.
11) Drawing the Zone Box
this.zoneBox := box.new(
left=this.firstBarTime, top=this.top, right=time, bottom=this.bottom,
border_color=borderCol, border_width=bWidth, bgcolor=fillCol,
xloc=xloc.bar_time)
Once the cluster qualifies for display, the script draws a box from the first touch time to the current bar time, with the cluster’s top and bottom as boundaries.
So the zone is not a single point marker. It becomes a persistent horizontal oscillator region that extends over time.
This makes the MFI structure much easier to interpret as a live area rather than isolated pivot dots.
12) Drawing the Optional Center Line
if drawCenter
this.centerLine := line.new(
x1=this.firstBarTime, y1=this.center, x2=time, y2=this.center,
color=color.new(baseCol, zoneOpacity - 5), style=line.style_dotted,
width=1, xloc=xloc.bar_time)
If enabled, the script also draws a center line through the middle of the cluster.
This gives the user a clean reference for the average reaction level inside the zone, which can be useful when the zone expands and becomes wider over time.
So the center line acts like an equilibrium guide inside the cluster.
13) Drawing the Info Label
string typeStr = this.isOB ? "OB" : "OS"
string lblText = typeStr + " · " + str.tostring(math.round(this.center, 1)) + " | ×" + str.tostring(this.touches)
this.infoLabel := label.new(
x=time, y=this.isOB ? this.top : this.bottom,
text=lblText, textcolor=textCol,
style=label.style_none, size=f_labelSize(lSize),
xloc=xloc.bar_time, textalign=text.align_right)
The label contains three pieces of information:
the cluster type,
the approximate center level,
and the touch count.
This means a user can immediately see whether the zone is an upper or lower cluster, where it is centered, and how strong it is based on repeated reactions.
So the label turns the zone into an interpretable structural object instead of only a colored band.
14) Updating Existing Displayed Zones
box.set_right(this.zoneBox, time)
box.set_bgcolor(this.zoneBox, fillCol)
box.set_border_color(this.zoneBox, borderCol)
box.set_border_width(this.zoneBox, bWidth)
box.set_top(this.zoneBox, this.top)
box.set_bottom(this.zoneBox, this.bottom)
Once a zone is already displayed and still valid, the script updates it on every bar.
It extends the right edge to the latest time, refreshes the fill and border styling, and updates the top and bottom in case the zone expanded after new touches.
So visible zones remain live and adaptive rather than remaining frozen in their original shape.
15) Zone Invalidation Logic
method invalidate(MFICluster this, float mfiVal) =>
bool broken = false
if this.isOB
if mfiVal > this.top + 2
broken := true
else
if mfiVal < this.bottom - 2
broken := true
if broken
this.isValid := false
broken
This method decides when a cluster has failed.
For upper type clusters, invalidation occurs if MFI pushes clearly above the zone top by more than two MFI points.
For lower type clusters, invalidation occurs if MFI falls clearly below the zone bottom by more than two MFI points.
This extra buffer is important because it avoids invalidating zones on tiny marginal touches.
So the script requires a decisive break beyond the zone before it stops treating that cluster as active structure.
16) Visual Handling of Invalidated Zones
else
box.set_bgcolor(this.zoneBox, color.new(baseCol, math.max(zoneOpacity + 20, 95)))
box.set_border_color(this.zoneBox, color.new(baseCol, math.max(zoneOpacity + 20, 95)))
if not na(this.centerLine)
line.set_style(this.centerLine, line.style_dashed)
line.set_color(this.centerLine, color.new(baseCol, 80))
When a cluster becomes invalid, the script does not delete it immediately. Instead, it fades the zone heavily and softens the center line.
This allows the user to keep the historical context of where the zone existed while also clearly seeing that it is no longer considered valid.
So invalidated zones remain on the pane as context, but not as active structure.
17) Detecting Whether MFI Is Inside an Active Cluster
if cl.isValid and cl.touches >= minTouches
if cl.isOB and rawMFI >= cl.bottom and rawMFI <= cl.top + 5
inOBZone := true
if not cl.isOB and rawMFI <= cl.top and rawMFI >= cl.bottom - 5
inOSZone := true
This block checks whether the current raw MFI value has entered a valid displayed cluster zone.
For upper clusters, the script allows a small tolerance above the zone.
For lower clusters, it allows a small tolerance below the zone.
This produces the conditions used by the entry alerts. So the alerts are not tied merely to MFI crossing 80 or 20. They can also trigger when MFI enters historically clustered oscillator reaction areas.
18) Dashboard Metrics
int obZoneCount = 0
int osZoneCount = 0
int strongMax = 0
float nearOB = na
float nearOS = na
if cl.touches > strongMax
strongMax := cl.touches
if cl.touches >= minTouches
if cl.center >= 70
obZoneCount += 1
else if cl.center <= 30
osZoneCount += 1
The dashboard summarizes the live structure.
It counts how many active displayed zones are centered in overbought and oversold territory, finds the highest touch count among all clusters, and tracks the nearest upper and lower cluster centers relative to current MFI.
So the dashboard gives a quick structural overview without requiring the user to visually inspect every zone one by one.
19) MFI State Classification for the Dashboard
string mfiState = rawMFI >= 80 ? "OVERBOUGHT" : rawMFI <= 20 ? "OVERSOLD" : rawMFI >= 50 ? "BULLISH" : "BEARISH"
This line classifies the current oscillator state into four broad conditions.
At or above 80 is treated as overbought.
At or below 20 is treated as oversold.
Between 50 and 80 is treated as bullish.
Between 20 and 50 is treated as bearish.
This gives the dashboard an easy to read directional context in addition to the cluster statistics.
20) Alert Conditions
alertcondition(inOBZone, title="MFI Entered OB Cluster Zone", message="Cluster MFI: Price entered an overbought cluster zone — watch for reversal")
alertcondition(inOSZone, title="MFI Entered OS Cluster Zone", message="Cluster MFI: Price entered an oversold cluster zone — watch for reversal")
alertcondition(ta.crossover(rawMFI, 80), title="MFI Crossed Above 80", message="Cluster MFI: MFI crossed above 80 — overbought territory")
alertcondition(ta.crossunder(rawMFI, 20), title="MFI Crossed Below 20", message="Cluster MFI: MFI crossed below 20 — oversold territory")
The script provides four alert types.
Two alerts are structural cluster alerts:
entering an upper cluster,
and entering a lower cluster.
Two alerts are classic threshold alerts:
crossing above 80,
and crossing below 20.
So the user can monitor both traditional MFI extremes and the more advanced cluster based structure. Indicator

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

EDUVEST Lorentzian ClassificationEDUVEST Lorentzian Classification - Machine Learning Signal Detection
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ ORIGINALITY
This indicator enhances the original Lorentzian Classification concept by jdehorty with EduVest's visual modifications and alert system integration. The core innovation is using Lorentzian distance instead of Euclidean distance for k-NN classification, providing more robust pattern recognition in financial markets.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ WHAT IT DOES
- Generates BUY/SELL signals using machine learning classification
- Displays kernel regression estimate for trend visualization
- Shows prediction values on each bar
- Provides trade statistics (Win Rate, W/L Ratio)
- Includes multiple filter options (Volatility, Regime, ADX, EMA, SMA)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ HOW IT WORKS
【Lorentzian Distance Calculation】
Unlike Euclidean distance, Lorentzian distance uses logarithmic transformation:
d = Σ log(1 + |xi - yi|)
This provides:
- Better handling of outliers
- More stable distance measurements
- Reduced sensitivity to extreme values
【Feature Engineering】
The classifier uses up to 5 configurable features:
- RSI (Relative Strength Index)
- WT (WaveTrend)
- CCI (Commodity Channel Index)
- ADX (Average Directional Index)
Each feature is normalized using the n_rsi, n_wt, n_cci, or n_adx functions.
【k-Nearest Neighbors Classification】
1. Calculate Lorentzian distance between current bar and historical bars
2. Find k nearest neighbors (default: 8)
3. Sum predictions from neighbors
4. Generate signal based on prediction sum (>0 = Long, <0 = Short)
【Kernel Regression】
Uses Rational Quadratic kernel for smooth trend estimation:
- Lookback Window: 8
- Relative Weighting: 8
- Regression Level: 25
【Filters】
- Volatility Filter: Filters signals during extreme volatility
- Regime Filter: Identifies market regime using threshold
- ADX Filter: Confirms trend strength
- EMA/SMA Filter: Trend direction confirmation
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ HOW TO USE
【Recommended Settings】
- Timeframe: 15M, 1H, 4H, Daily
- Neighbors Count: 8 (default)
- Feature Count: 5 for comprehensive analysis
【Signal Interpretation】
- Green BUY label: Long entry signal
- Red SELL label: Short entry signal
- Bar colors: Green (bullish) / Red (bearish) prediction strength
【Trade Statistics Panel】
- Winrate: Historical win percentage
- Trades: Total (Wins|Losses)
- WL Ratio: Win/Loss ratio
- Early Signal Flips: Premature signal changes
【Filter Recommendations】
- Enable Volatility Filter for ranging markets
- Enable Regime Filter for trend confirmation
- Use EMA Filter (200) for higher timeframes
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ CREDITS
Original Lorentzian Classification concept and MLExtensions library by jdehorty.
Enhanced with visual modifications and alert integration by EduVest.
License: Mozilla Public License 2.0 Indicator

Adaptive ML Trailing Stop [BOSWaves]Adaptive ML Trailing Stop – Regime-Aware Risk Control with KAMA Adaptation and Pattern-Based Intelligence
Overview
Adaptive ML Trailing Stop is a regime-sensitive trailing stop and risk control system that adjusts stop placement dynamically as market behavior shifts, using efficiency-based smoothing and pattern-informed biasing.
Instead of operating with fixed ATR offsets or rigid trailing rules, stop distance, responsiveness, and directional treatment are continuously recalculated using market efficiency, volatility conditions, and historical pattern resemblance.
This creates a live trailing structure that responds immediately to regime change - contracting during orderly directional movement, relaxing during rotational conditions, and applying probabilistic refinement when pattern confidence is present.
Price is therefore assessed relative to adaptive, condition-aware trailing boundaries rather than static stop levels.
Conceptual Framework
Adaptive ML Trailing Stop is founded on the idea that effective risk control depends on regime context rather than price location alone.
Conventional trailing mechanisms apply constant volatility multipliers, which often results in trend suppression or delayed exits. This framework replaces static logic with adaptive behavior shaped by efficiency state and observed historical outcomes.
Three core principles guide the design:
Stop distance should adjust in proportion to market efficiency.
Smoothing behavior must respond to regime changes.
Trailing logic benefits from probabilistic context instead of fixed rules.
This shifts trailing stops from rigid exit tools into adaptive, regime-responsive risk boundaries.
Theoretical Foundation
The indicator combines adaptive averaging techniques, volatility-based distance modeling, and similarity-weighted pattern analysis.
Kaufman’s Adaptive Moving Average (KAMA) is used to quantify directional efficiency, allowing smoothing intensity and stop behavior to scale with trend quality. Average True Range (ATR) defines the volatility reference, while a K-Nearest Neighbors (KNN) process evaluates historical price patterns to introduce directional weighting when appropriate.
Three internal systems operate in tandem:
KAMA Efficiency Engine : Evaluates directional efficiency to distinguish structured trends from range conditions and modulate smoothing and stop behavior.
Adaptive ATR Stop Engine : Expands or contracts ATR-derived stop distance based on efficiency, tightening during strong trends and widening in low-efficiency environments.
KNN Pattern Influence Layer : Applies distance-weighted historical pattern outcomes to subtly influence stop placement on both sides.
This design allows stop behavior to evolve with market context rather than reacting mechanically to price changes.
How It Works
Adaptive ML Trailing Stop evaluates price through a sequence of adaptive processes:
Efficiency-Based Regime Identification : KAMA efficiency determines whether conditions favor trend continuation or rotational movement, influencing stop sensitivity.
Volatility-Responsive Scaling : ATR-based stop distance adjusts automatically as efficiency rises or falls.
Pattern-Weighted Adjustment : KNN compares recent price sequences to historical analogs, applying confidence-based bias to stop positioning.
Adaptive Stop Smoothing : Long and short stop levels are smoothed using KAMA logic to maintain structural stability while remaining responsive.
Directional Trailing Enforcement : Stops advance only in the direction of the prevailing regime, preserving invalidation structure.
Gradient Distance Visualization : Gradient fills reflect the relative distance between price and the active stop.
Controlled Interaction Markers : Diamond markers highlight meaningful stop interactions, filtered through cooldown logic to reduce clustering.
Together, these elements form a continuously adapting trailing stop system rather than a fixed exit mechanism.
Interpretation
Adaptive ML Trailing Stop should be interpreted as a dynamic risk envelope:
Long Stop (Green) : Acts as the downside invalidation level during bullish regimes, tightening as efficiency improves.
Short Stop (Red) : Serves as the upside invalidation level during bearish regimes, adjusting width based on efficiency and volatility.
Trend State Changes : Regime flips occur only after confirmed stop breaches, filtering temporary price spikes.
Gradient Depth : Deeper gradient penetration indicates increased extension from the stop rather than imminent reversal.
Pattern Influence : KNN weighting affects stop behavior only when historical agreement is strong and remains neutral otherwise.
Distance, efficiency, and context outweigh isolated price interactions.
Signal Logic & Visual Cues
Adaptive ML Trailing Stop presents two primary visual signals:
Trend Transition Circles : Display when price crosses the opposing trailing stop, confirming a regime change rather than anticipating one.
Stop Interaction Diamonds : Indicate controlled contact with the active stop, subject to cooldown filtering to avoid excessive signals.
Alert generation is limited to confirmed trend transitions to maintain clarity.
Strategy Integration
Adaptive ML Trailing Stop fits within trend-following and risk-managed trading approaches:
Dynamic Risk Framing : Use adaptive stops as evolving invalidation levels instead of fixed exits.
Directional Alignment : Base execution on confirmed regime state rather than speculative reversals.
Efficiency-Based Tolerance : Allow greater price fluctuation during inefficient movement while enforcing tighter control during clean trends.
Pattern-Guided Refinement : Let KNN influence adjust sensitivity without overriding core structure.
Multi-Timeframe Context : Apply higher-timeframe efficiency states to inform lower-timeframe stop responsiveness.
Technical Implementation Details
Core Engine : KAMA-based efficiency measurement with adaptive smoothing
Volatility Model : ATR-derived stop distance scaled by regime
Machine Learning Layer : Distance-weighted KNN with confidence modulation
Visualization : Directional trailing stops with layered gradient fills
Signal Logic : Regime-based transitions and controlled interaction markers
Performance Profile : Optimized for real-time chart execution
Optimal Application Parameters
Timeframe Guidance:
1 - 5 min : Tight adaptive trailing for short-term momentum control
15 - 60 min : Structured intraday trend supervision
4H - Daily : Higher-timeframe regime monitoring
Suggested Baseline Configuration:
KAMA Length : 20
Fast/Slow Periods : 15 / 50
ATR Period : 21
Base ATR Multiplier : 2.5
Adaptive Strength : 1.0
KNN Neighbors : 7
KNN Influence : 0.2
These suggested parameters should be used as a baseline; their effectiveness depends on the asset volatility, liquidity, and preferred entry frequency, so fine-tuning is expected for optimal performance.
Parameter Calibration Notes
Use the following adjustments to refine behavior without altering the core logic:
Excessive chop or overreaction : Increase KAMA Length, Slow Period, and ATR Period to reinforce regime filtering.
Stops feel overly permissive : Reduce the Base ATR Multiplier to tighten invalidation boundaries.
Frequent false regime shifts : Increase KNN Neighbors to demand stronger historical agreement.
Delayed adaptation : Decrease KAMA Length and Fast Period to improve responsiveness during regime change.
Adjustments should be incremental and evaluated over multiple market cycles rather than isolated sessions.
Performance Characteristics
High Effectiveness:
Markets exhibiting sustained directional efficiency
Instruments with recurring structural behavior
Trend-oriented, risk-managed strategies
Reduced Effectiveness:
Highly erratic or event-driven price action
Illiquid markets with unreliable volatility readings
Integration Guidelines
Confluence : Combine with BOSWaves structure or trend indicators
Discipline : Follow adaptive stop behavior rather than forcing exits
Risk Framing : Treat stops as adaptive boundaries, not forecasts
Regime Awareness : Always interpret stop behavior within efficiency context
Disclaimer
Adaptive ML Trailing Stop is a professional-grade adaptive risk and regime management tool. It does not forecast price movement and does not guarantee profitability. Results depend on market conditions, parameter selection, and disciplined execution. BOSWaves recommends deploying this indicator within a broader analytical framework that incorporates structure, volatility, and contextual risk management. Indicator

Machine Learning RSI ║ BullVisionOverview:
Introducing the Machine Learning RSI with KNN Adaptation – a cutting-edge momentum indicator that blends the classic Relative Strength Index (RSI) with machine learning principles. By leveraging K-Nearest Neighbors (KNN), this indicator aims at identifying historical patterns that resemble current market behavior and uses this context to refine RSI readings with enhanced sensitivity and responsiveness.
Unlike traditional RSI models, which treat every market environment the same, this version adapts in real-time based on how similar past conditions evolved, offering an analytical edge without relying on predictive assumptions.
Key Features:
🔁 KNN-Based RSI Refinement
This indicator uses a machine learning algorithm (K-Nearest Neighbors) to compare current RSI and price action characteristics to similar historical conditions. The resulting RSI is weighted accordingly, producing a dynamically adjusted value that reflects historical context.
📈 Multi-Feature Similarity Analysis
Pattern similarity is calculated using up to five customizable features:
RSI level
RSI momentum
Volatility
Linear regression slope
Price momentum
Users can adjust how many features are used to tailor the behavior of the KNN logic.
🧠 Machine Learning Weight Control
The influence of the machine learning model on the final RSI output can be fine-tuned using a simple slider. This lets you blend traditional RSI and machine learning-enhanced RSI to suit your preferred level of adaptation.
🎛️ Adaptive Filtering
Additional smoothing options (Kalman Filter, ALMA, Double EMA) can be applied to the RSI, offering better visual clarity and helping to reduce noise in high-frequency environments.
🎨 Visual & Accessibility Settings
Custom color palettes, including support for color vision deficiencies, ensure that trend coloring remains readable for all users. A built-in neon mode adds high-contrast visuals to improve RSI visibility across dark or light themes.
How It Works:
Similarity Matching with KNN:
At each candle, the current RSI and optional market characteristics are compared to historical bars using a KNN search. The algorithm selects the closest matches and averages their RSI values, weighted by similarity. The more similar the pattern, the greater its influence.
Feature-Based Weighting:
Similarity is determined using normalized values of the selected features, which gives a more refined result than RSI alone. You can choose to use only 1 (RSI) or up to all 5 features for deeper analysis.
Filtering & Blending:
After the machine learning-enhanced RSI is calculated, it can be optionally smoothed using advanced filters to suppress short-term noise or sharp spikes. This makes it easier to evaluate RSI signals in different volatility regimes.
Parameters Explained:
📊 RSI Settings:
Set the base RSI length and select your preferred smoothing method from 10+ moving average types (e.g., EMA, ALMA, TEMA).
🧠 Machine Learning Controls:
Enable or disable the KNN engine
Select how many nearest neighbors to compare (K)
Choose the number of features used in similarity detection
Control how much the machine learning engine affects the RSI calculation
🔍 Filtering Options:
Enable one of several advanced smoothing techniques (Kalman Filter, ALMA, Double EMA) to adjust the indicator’s reactivity and stability.
📏 Threshold Levels:
Define static overbought/oversold boundaries or reference dynamically adjusted thresholds based on historical context identified by the KNN algorithm.
🎨 Visual Enhancements:
Select between trend-following or impulse coloring styles. Customize color palettes to accommodate different types of color blindness. Enable neon-style effects for visual clarity.
Use Cases:
Swing & Trend Traders
Can use the indicator to explore how current RSI readings compare to similar market phases, helping to assess trend strength or potential turning points.
Intraday Traders
Benefit from adjustable filters and fast-reacting smoothing to reduce noise in shorter timeframes while retaining contextual relevance.
Discretionary Analysts
Use the adaptive OB/OS thresholds and visual cues to supplement broader confluence zones or market structure analysis.
Customization Tips:
Higher Volatility Periods: Use more neighbors and enable filtering to reduce noise.
Lower Volatility Markets: Use fewer features and disable filtering for quicker RSI adaptation.
Deeper Contextual Analysis: Increase KNN lookback and raise the feature count to refine pattern recognition.
Accessibility Needs: Switch to Deuteranopia or Monochrome mode for clearer visuals in specific color vision conditions.
Final Thoughts:
The Machine Learning RSI combines familiar momentum logic with statistical context derived from historical similarity analysis. It does not attempt to predict price action but rather contextualizes RSI behavior with added nuance. This makes it a valuable tool for those looking to elevate traditional RSI workflows with adaptive, research-driven enhancements. Indicator

Indicator

AI SuperTrend x Pivot Percentile - Strategy [PresentTrading]█ Introduction and How it is Different
The AI SuperTrend x Pivot Percentile strategy is a sophisticated trading approach that integrates AI-driven analysis with traditional technical indicators. Combining the AI SuperTrend with the Pivot Percentile strategy highlights several key advantages:
1. Enhanced Accuracy in Trend Prediction: The AI SuperTrend utilizes K-Nearest Neighbors (KNN) algorithm for trend prediction, improving accuracy by considering historical data patterns. This is complemented by the Pivot Percentile analysis which provides additional context on trend strength.
2. Comprehensive Market Analysis: The integration offers a multi-faceted approach to market analysis, combining AI insights with traditional technical indicators. This dual approach captures a broader range of market dynamics.
BTC 6H L/S Performance
Local
█ Strategy: How it Works - Detailed Explanation
🔶 AI-Enhanced SuperTrend Indicators
1. SuperTrend Calculation:
- The SuperTrend indicator is calculated using a moving average and the Average True Range (ATR). The basic formula is:
- Upper Band = Moving Average + (Multiplier × ATR)
- Lower Band = Moving Average - (Multiplier × ATR)
- The moving average type (SMA, EMA, WMA, RMA, VWMA) and the length of the moving average and ATR are adjustable parameters.
- The direction of the trend is determined based on the position of the closing price in relation to these bands.
2. AI Integration with K-Nearest Neighbors (KNN):
- The KNN algorithm is applied to predict trend direction. It uses historical price data and SuperTrend values to classify the current trend as bullish or bearish.
- The algorithm calculates the 'distance' between the current data point and historical points. The 'k' nearest data points (neighbors) are identified based on this distance.
- A weighted average of these neighbors' trends (bullish or bearish) is calculated to predict the current trend.
For more please check: Multi-TF AI SuperTrend with ADX - Strategy
🔶 Pivot Percentile Analysis
1. Percentile Calculation:
- This involves calculating the percentile ranks for high and low prices over a set of predefined lengths.
- The percentile function is typically defined as:
- Percentile = Value at (P/100) × (N + 1)th position
- Where P is the desired percentile, and N is the number of data points.
2. Trend Strength Evaluation:
- The calculated percentiles for highs and lows are used to determine the strength of bullish and bearish trends.
- For instance, a high percentile rank in the high prices may indicate a strong bullish trend, and vice versa for bearish trends.
For more please check: Pivot Percentile Trend - Strategy
🔶 Strategy Integration
1. Combining SuperTrend and Pivot Percentile:
- The strategy synthesizes the insights from both AI-enhanced SuperTrend and Pivot Percentile analysis.
- It compares the trend direction indicated by the SuperTrend with the strength of the trend as suggested by the Pivot Percentile analysis.
2. Signal Generation:
- A trading signal is generated when both the AI-enhanced SuperTrend and the Pivot Percentile analysis agree on the trend direction.
- For instance, a bullish signal is generated when both the SuperTrend is bullish, and the Pivot Percentile analysis shows strength in bullish trends.
🔶 Risk Management and Filters
- ADX and DMI Filter: The strategy uses the Average Directional Index (ADX) and the Directional Movement Index (DMI) as filters to assess the trend's strength and direction.
- Dynamic Trailing Stop Loss: Based on the SuperTrend indicator, the strategy dynamically adjusts stop-loss levels to manage risk effectively.
This strategy stands out for its ability to combine real-time AI analysis with established technical indicators, offering traders a nuanced and responsive tool for navigating complex market conditions. The equations and algorithms involved are pivotal in accurately identifying market trends and potential trade opportunities.
█ Usage
To effectively use this strategy, traders should:
1. Understand the AI and Pivot Percentile Indicators: A clear grasp of how these indicators work will enable traders to make informed decisions.
2. Interpret the Signals Accurately: The strategy provides bullish, bearish, and neutral signals. Traders should align these signals with their market analysis and trading goals.
3. Monitor Market Conditions: Given that this strategy is sensitive to market dynamics, continuous monitoring is crucial for timely decision-making.
4. Adjust Settings as Needed: Traders should feel free to tweak the input parameters to suit their trading preferences and to respond to changing market conditions.
█Default Settings and Their Impact on Performance
1. Trading Direction (Default: "Both")
Effect: Determines whether the strategy will take long positions, short positions, or both. Adjusting this setting can align the strategy with the trader's market outlook or risk preference.
2. AI Settings (Neighbors: 3, Data Points: 24)
Neighbors: The number of nearest neighbors in the KNN algorithm. A higher number might smooth out noise but could miss subtle, recent changes. A lower number makes the model more sensitive to recent data but may increase noise.
Data Points: Defines the amount of historical data considered. More data points provide a broader context but may dilute recent trends' impact.
3. SuperTrend Settings (Length: 10, Factor: 3.0, MA Source: "WMA")
Length: Affects the sensitivity of the SuperTrend indicator. A longer length results in a smoother, less sensitive indicator, ideal for long-term trends.
Factor: Determines the bandwidth of the SuperTrend. A higher factor creates wider bands, capturing larger price movements but potentially missing short-term signals.
MA Source: The type of moving average used (e.g., WMA - Weighted Moving Average). Different MA types can affect the trend indicator's responsiveness and smoothness.
4. AI Trend Prediction Settings (Price Trend: 10, Prediction Trend: 80)
Price Trend and Prediction Trend Lengths: These settings define the lengths of weighted moving averages for price and SuperTrend, impacting the responsiveness and smoothness of the AI's trend predictions.
5. Pivot Percentile Settings (Length: 10)
Length: Influences the calculation of pivot percentiles. A shorter length makes the percentile more responsive to recent price changes, while a longer length offers a broader view of price trends.
6. ADX and DMI Settings (ADX Length: 14, Time Frame: 'D')
ADX Length: Defines the period for the Average Directional Index calculation. A longer period results in a smoother ADX line.
Time Frame: Sets the time frame for the ADX and DMI calculations, affecting the sensitivity to market changes.
7. Commission, Slippage, and Initial Capital
These settings relate to transaction costs and initial investment, directly impacting net profitability and strategy feasibility. Strategy

Multi-TF AI SuperTrend with ADX - Strategy [PresentTrading]
## █ Introduction and How it is Different
The trading strategy in question is an enhanced version of the SuperTrend indicator, combined with AI elements and an ADX filter. It's a multi-timeframe strategy that incorporates two SuperTrends from different timeframes and utilizes a k-nearest neighbors (KNN) algorithm for trend prediction. It's different from traditional SuperTrend indicators because of its AI-based predictive capabilities and the addition of the ADX filter for trend strength.
BTC 8hr Performance
ETH 8hr Performance
## █ Strategy, How it Works: Detailed Explanation (Revised)
### Multi-Timeframe Approach
The strategy leverages the power of multiple timeframes by incorporating two SuperTrend indicators, each calculated on a different timeframe. This multi-timeframe approach provides a holistic view of the market's trend. For example, a 8-hour timeframe might capture the medium-term trend, while a daily timeframe could capture the longer-term trend. When both SuperTrends align, the strategy confirms a more robust trend.
### K-Nearest Neighbors (KNN)
The KNN algorithm is used to classify the direction of the trend based on historical SuperTrend values. It uses weighted voting of the 'k' nearest data points. For each point, it looks at its 'k' closest neighbors and takes a weighted average of their labels to predict the current label. The KNN algorithm is applied separately to each timeframe's SuperTrend data.
### SuperTrend Indicators
Two SuperTrend indicators are used, each from a different timeframe. They are calculated using different moving averages and ATR lengths as per user settings. The SuperTrend values are then smoothed to make them suitable for KNN-based prediction.
### ADX and DMI Filters
The ADX filter is used to eliminate weak trends. Only when the ADX is above 20 and the directional movement index (DMI) confirms the trend direction, does the strategy signal a buy or sell.
### Combining Elements
A trade signal is generated only when both SuperTrends and the ADX filter confirm the trend direction. This multi-timeframe, multi-indicator approach reduces false positives and increases the robustness of the strategy.
By considering multiple timeframes and using machine learning for trend classification, the strategy aims to provide more accurate and reliable trade signals.
BTC 8hr Performance (Zoom-in)
## █ Trade Direction
The strategy allows users to specify the trade direction as 'Long', 'Short', or 'Both'. This is useful for traders who have a specific market bias. For instance, in a bullish market, one might choose to only take 'Long' trades.
## █ Usage
Parameters: Adjust the number of neighbors, data points, and moving averages according to the asset and market conditions.
Trade Direction: Choose your preferred trading direction based on your market outlook.
ADX Filter: Optionally, enable the ADX filter to avoid trading in a sideways market.
Risk Management: Use the trailing stop-loss feature to manage risks.
## █ Default Settings
Neighbors (K): 3
Data points for KNN: 12
SuperTrend Length: 10 and 5 for the two different SuperTrends
ATR Multiplier: 3.0 for both
ADX Length: 21
ADX Time Frame: 240
Default trading direction: Both
By customizing these settings, traders can tailor the strategy to fit various trading styles and assets. Strategy

Machine Learning: VWAP [YinYangAlgorithms]Machine Learning: VWAP aims to use Machine Learning to Identify the best location to Anchor the VWAP at. Rather than using a traditional fixed length or simply adjusting based on a Date / Time; by applying Machine Learning we may hope to identify crucial areas which make sense to reset the VWAP and start anew. VWAP’s may act similar to a Bollinger Band in the sense that they help to identify both Overbought and Oversold Price locations based on previous movements and help to identify how far the price may move within the current Trend. However, unlike Bollinger Bands, VWAPs have the ability to parabolically get quite spaced out and also reset. For this reason, the price may never actually go from the Lower to the Upper and vice versa (when very spaced out; when the Upper and Lower zones are narrow, it may bounce between the two). The reason for this is due to how the anchor location is calculated and in this specific Indicator, how it changes anchors based on price movement calculated within Machine Learning.
This Indicator changes the anchor if the Low < Lowest Low of a length of X and likewise if the High > Highest High of a length of X. This logic is applied within a Machine Learning standpoint that likewise amplifies this Lookback Length by adding a Machine Learning Length to it and increasing the lookback length even further.
Due to how the anchor for this VWAP changes, you may notice that the Basis Line (Orange) may act as a Trend Identifier. When the Price is above the basis line, it may represent a bullish trend; and likewise it may represent a bearish trend when below it. You may also notice what may happen is when the trend occurs, it may push all the way to the Upper or Lower levels of this VWAP. It may then proceed to move horizontally until the VWAP expands more and it may gain more movement; or it may correct back to the Basis Line. If it corrects back to the basis line, what may happen is it either uses the Basis Line as a Support and continues in its current direction, or it will change the VWAP anchor and start anew.
Tutorial:
If we zoom in on the most recent VWAP we can see how it expands. Expansion may be caused by time but generally it may be caused by price movement and volume. Exponential Price movement causes the VWAP to expand, even if there are corrections to it. However, please note Volume adds a large weighted factor to the calculation; hence Volume Weighted Average Price (VWAP).
If you refer to the white circle in the example above; you’ll be able to see that the VWAP expanded even while the price was correcting to the Basis line. This happens due to exponential movement which holds high volume. If you look at the volume below the white circle, you’ll notice it was very large; however even though there was exponential price movement after the white circle, since the volume was low, the VWAP didn’t expand much more than it already had.
There may be times where both Volume and Price movement isn’t significant enough to cause much of an expansion. During this time it may be considered to be in a state of consolidation. While looking at this example, you may also notice the color switch from red to green to red. The color of the VWAP is related to the movement of the Basis line (Orange middle line). When the current basis is > the basis of the previous bar the color of the VWAP is green, and when the current basis is < the basis of the previous bar, the color of the VWAP is red. The color may help you gauge the current directional movement the price is facing within the VWAP.
You may have noticed there are signals within this Indicator. These signals are composed of Green and Red Triangles which represent potential Bullish and Bearish momentum changes. The Momentum changes happen when the Signal Type:
The High/Low or Close (You pick in settings)
Crosses one of the locations within the VWAP.
Bullish Momentum change signals occur when :
Signal Type crosses OVER the Basis
Signal Type crosses OVER the lower level
Bearish Momentum change signals occur when:
Signal Type crosses UNDER the Basis
Signal Type Crosses UNDER the upper level
These signals may represent locations where momentum may occur in the direction of these signals. For these reasons there are also alerts available to be set up for them.
If you refer to the two circles within the example above, you may see that when the close goes above the basis line, how it mat represents bullish momentum. Likewise if it corrects back to the basis and the basis acts as a support, it may continue its bullish momentum back to the upper levels again. However, if you refer to the red circle, you’ll see if the basis fails to act as a support, it may then start to correct all the way to the lower levels, or depending on how expanded the VWAP is, it may just reset its anchor due to such drastic movement.
You also have the ability to disable Machine Learning by setting ‘Machine Learning Type’ to ‘None’. If this is done, it will go off whether you have it set to:
Bullish
Bearish
Neutral
For the type of VWAP you want to see. In this example above we have it set to ‘Bullish’. Non Machine Learning VWAP are still calculated using the same logic of if low < lowest low over length of X and if high > highest high over length of X.
Non Machine Learning VWAP’s change much quicker but may also allow the price to correct from one side to the other without changing VWAP Anchor. They may be useful for breaking up a trend into smaller pieces after momentum may have changed.
Above is an example of how the Non Machine Learning VWAP looks like when in Bearish. As you can see based on if it is Bullish or Bearish is how it favors the trend to be and may likewise dictate when it changes the Anchor.
When set to neutral however, the Anchor may change quite quickly. This results in a still useful VWAP to help dictate possible zones that the price may move within, but they’re also much tighter zones that may not expand the same way.
We will conclude this Tutorial here, hopefully this gives you some insight as to why and how Machine Learning VWAPs may be useful; as well as how to use them.
Settings:
VWAP:
VWAP Type: Type of VWAP. You can favor specific direction changes or let it be Neutral where there is even weight to both. Please note, these do not apply to the Machine Learning VWAP.
Source: VWAP Source. By default VWAP usually uses HLC3; however OHLC4 may help by providing more data.
Lookback Length: The Length of this VWAP when it comes to seeing if the current High > Highest of this length; or if the current Low is < Lowest of this length.
Standard VWAP Multiplier: This multiplier is applied only to the Standard VWMA. This is when 'Machine Learning Type' is set to 'None'.
Machine Learning:
Use Rational Quadratics: Rationalizing our source may be beneficial for usage within ML calculations.
Signal Type: Bullish and Bearish Signals are when the price crosses over/under the basis, as well as the Upper and Lower levels. These may act as indicators to where price movement may occur.
Machine Learning Type: Are we using a Simple ML Average, KNN Mean Average, KNN Exponential Average or None?
KNN Distance Type: We need to check if distance is within the KNN Min/Max distance, which distance checks are we using.
Machine Learning Length: How far back is our Machine Learning going to keep data for.
k-Nearest Neighbour (KNN) Length: How many k-Nearest Neighbours will we account for?
Fast ML Data Length: What is our Fast ML Length? This is used with our Slow Length to create our KNN Distance.
Slow ML Data Length: What is our Slow ML Length? This is used with our Fast Length to create our KNN Distance.
If you have any questions, comments, ideas or concerns please don't hesitate to contact us.
HAPPY TRADING! Indicator

Machine Learning: Optimal RSI [YinYangAlgorithms]This Indicator, will rate multiple different lengths of RSIs to determine which RSI to RSI MA cross produced the highest profit within the lookback span. This ‘Optimal RSI’ is then passed back, and if toggled will then be thrown into a Machine Learning calculation. You have the option to Filter RSI and RSI MA’s within the Machine Learning calculation. What this does is, only other Optimal RSI’s which are in the same bullish or bearish direction (is the RSI above or below the RSI MA) will be added to the calculation.
You can either (by default) use a Simple Average; which is essentially just a Mean of all the Optimal RSI’s with a length of Machine Learning. Or, you can opt to use a k-Nearest Neighbour (KNN) calculation which takes a Fast and Slow Speed. We essentially turn the Optimal RSI into a MA with different lengths and then compare the distance between the two within our KNN Function.
RSI may very well be one of the most used Indicators for identifying crucial Overbought and Oversold locations. Not only that but when it crosses its Moving Average (MA) line it may also indicate good locations to Buy and Sell. Many traders simply use the RSI with the standard length (14), however, does that mean this is the best length?
By using the length of the top performing RSI and then applying some Machine Learning logic to it, we hope to create what may be a more accurate, smooth, optimal, RSI.
Tutorial:
This is a pretty zoomed out Perspective of what the Indicator looks like with its default settings (except with Bollinger Bands and Signals disabled). If you look at the Tables above, you’ll notice, currently the Top Performing RSI Length is 13 with an Optimal Profit % of: 1.00054973. On its default settings, what it does is Scan X amount of RSI Lengths and checks for when the RSI and RSI MA cross each other. It then records the profitability of each cross to identify which length produced the overall highest crossing profitability. Whichever length produces the highest profit is then the RSI length that is used in the plots, until another length takes its place. This may result in what we deem to be the ‘Optimal RSI’ as it is an adaptive RSI which changes based on performance.
In our next example, we changed the ‘Optimal RSI Type’ from ‘All Crossings’ to ‘Extremity Crossings’. If you compare the last two examples to each other, you’ll notice some similarities, but overall they’re quite different. The reason why is, the Optimal RSI is calculated differently. When using ‘All Crossings’ everytime the RSI and RSI MA cross, we evaluate it for profit (short and long). However, with ‘Extremity Crossings’, we only evaluate it when the RSI crosses over the RSI MA and RSI <= 40 or RSI crosses under the RSI MA and RSI >= 60. We conclude the crossing when it crosses back on its opposite of the extremity, and that is how it finds its Optimal RSI.
The way we determine the Optimal RSI is crucial to calculating which length is currently optimal.
In this next example we have zoomed in a bit, and have the full default settings on. Now we have signals (which you can set alerts for), for when the RSI and RSI MA cross (green is bullish and red is bearish). We also have our Optimal RSI Bollinger Bands enabled here too. These bands allow you to see where there may be Support and Resistance within the RSI at levels that aren’t static; such as 30 and 70. The length the RSI Bollinger Bands use is the Optimal RSI Length, allowing it to likewise change in correlation to the Optimal RSI.
In the example above, we’ve zoomed out as far as the Optimal RSI Bollinger Bands go. You’ll notice, the Bollinger Bands may act as Support and Resistance locations within and outside of the RSI Mid zone (30-70). In the next example we will highlight these areas so they may be easier to see.
Circled above, you may see how many times the Optimal RSI faced Support and Resistance locations on the Bollinger Bands. These Bollinger Bands may give a second location for Support and Resistance. The key Support and Resistance may still be the 30/50/70, however the Bollinger Bands allows us to have a more adaptive, moving form of Support and Resistance. This helps to show where it may ‘bounce’ if it surpasses any of the static levels (30/50/70).
Due to the fact that this Indicator may take a long time to execute and it can throw errors for such, we have added a Setting called: Adjust Optimal RSI Lookback and RSI Count. This settings will automatically modify the Optimal RSI Lookback Length and the RSI Count based on the Time Frame you are on and the Bar Indexes that are within. For instance, if we switch to the 1 Hour Time Frame, it will adjust the length from 200->90 and RSI Count from 30->20. If this wasn’t adjusted, the Indicator would Timeout.
You may however, change the Setting ‘Adjust Optimal RSI Lookback and RSI Count’ to ‘Manual’ from ‘Auto’. This will give you control over the ‘Optimal RSI Lookback Length’ and ‘RSI Count’ within the Settings. Please note, it will likely take some “fine tuning” to find working settings without the Indicator timing out, but there are definitely times you can find better settings than our ‘Auto’ will create; especially on higher Time Frames. The Minimum our ‘Auto’ will create is:
Optimal RSI Lookback Length: 90
RSI Count: 20
The Maximum it will create is:
Optimal RSI Lookback Length: 200
RSI Count: 30
If there isn’t much bar index history, for instance, if you’re on the 1 Day and the pair is BTC/USDT you’ll get < 4000 Bar Indexes worth of data. For this reason it is possible to manually increase the settings to say:
Optimal RSI Lookback Length: 500
RSI Count: 50
But, please note, if you make it too high, it may also lead to inaccuracies.
We will conclude our Tutorial here, hopefully this has given you some insight as to how calculating our Optimal RSI and then using it within Machine Learning may create a more adaptive RSI.
Settings:
Optimal RSI:
Show Crossing Signals: Display signals where the RSI and RSI Cross.
Show Tables: Display Information Tables to show information like, Optimal RSI Length, Best Profit, New Optimal RSI Lookback Length and New RSI Count.
Show Bollinger Bands: Show RSI Bollinger Bands. These bands work like the TDI Indicator, except its length changes as it uses the current RSI Optimal Length.
Optimal RSI Type: This is how we calculate our Optimal RSI. Do we use all RSI and RSI MA Crossings or just when it crosses within the Extremities.
Adjust Optimal RSI Lookback and RSI Count: Auto means the script will automatically adjust the Optimal RSI Lookback Length and RSI Count based on the current Time Frame and Bar Index's on chart. This will attempt to stop the script from 'Taking too long to Execute'. Manual means you have full control of the Optimal RSI Lookback Length and RSI Count.
Optimal RSI Lookback Length: How far back are we looking to see which RSI length is optimal? Please note the more bars the lower this needs to be. For instance with BTC/USDT you can use 500 here on 1D but only 200 for 15 Minutes; otherwise it will timeout.
RSI Count: How many lengths are we checking? For instance, if our 'RSI Minimum Length' is 4 and this is 30, the valid RSI lengths we check is 4-34.
RSI Minimum Length: What is the RSI length we start our scans at? We are capped with RSI Count otherwise it will cause the Indicator to timeout, so we don't want to waste any processing power on irrelevant lengths.
RSI MA Length: What length are we using to calculate the optimal RSI cross' and likewise plot our RSI MA with?
Extremity Crossings RSI Backup Length: When there is no Optimal RSI (if using Extremity Crossings), which RSI should we use instead?
Machine Learning:
Use Rational Quadratics: Rationalizing our Close may be beneficial for usage within ML calculations.
Filter RSI and RSI MA: Should we filter the RSI's before usage in ML calculations? Essentially should we only use RSI data that are of the same type as our Optimal RSI? For instance if our Optimal RSI is Bullish (RSI > RSI MA), should we only use ML RSI's that are likewise bullish?
Machine Learning Type: Are we using a Simple ML Average, KNN Mean Average, KNN Exponential Average or None?
KNN Distance Type: We need to check if distance is within the KNN Min/Max distance, which distance checks are we using.
Machine Learning Length: How far back is our Machine Learning going to keep data for.
k-Nearest Neighbour (KNN) Length: How many k-Nearest Neighbours will we account for?
Fast ML Data Length: What is our Fast ML Length? This is used with our Slow Length to create our KNN Distance.
Slow ML Data Length: What is our Slow ML Length? This is used with our Fast Length to create our KNN Distance.
If you have any questions, comments, ideas or concerns please don't hesitate to contact us.
HAPPY TRADING! Indicator

Machine Learning: SuperTrend Strategy TP/SL [YinYangAlgorithms]The SuperTrend is a very useful Indicator to display when trends have shifted based on the Average True Range (ATR). Its underlying ideology is to calculate the ATR using a fixed length and then multiply it by a factor to calculate the SuperTrend +/-. When the close crosses the SuperTrend it changes direction.
This Strategy features the Traditional SuperTrend Calculations with Machine Learning (ML) and Take Profit / Stop Loss applied to it. Using ML on the SuperTrend allows for the ability to sort data from previous SuperTrend calculations. We can filter the data so only previous SuperTrends that follow the same direction and are within the distance bounds of our k-Nearest Neighbour (KNN) will be added and then averaged. This average can either be achieved using a Mean or with an Exponential calculation which puts added weight on the initial source. Take Profits and Stop Losses are then added to the ML SuperTrend so it may capitalize on Momentum changes meanwhile remaining in the Trend during consolidation.
By applying Machine Learning logic and adding a Take Profit and Stop Loss to the Traditional SuperTrend, we may enhance its underlying calculations with potential to withhold the trend better. The main purpose of this Strategy is to minimize losses and false trend changes while maximizing gains. This may be achieved by quick reversals of trends where strategic small losses are taken before a large trend occurs with hopes of potentially occurring large gain. Due to this logic, the Win/Loss ratio of this Strategy may be quite poor as it may take many small marginal losses where there is consolidation. However, it may also take large gains and capitalize on strong momentum movements.
Tutorial:
In this example above, we can get an idea of what the default settings may achieve when there is momentum. It focuses on attempting to hit the Trailing Take Profit which moves in accord with the SuperTrend just with a multiplier added. When momentum occurs it helps push the SuperTrend within it, which on its own may act as a smaller Trailing Take Profit of its own accord.
We’ve highlighted some key points from the last example to better emphasize how it works. As you can see, the White Circle is where profit was taken from the ML SuperTrend simply from it attempting to switch to a Bullish (Buy) Trend. However, that was rejected almost immediately and we went back to our Bearish (Sell) Trend that ended up resulting in our Take Profit being hit (Yellow Circle). This Strategy aims to not only capitalize on the small profits from SuperTrend to SuperTrend but to also capitalize when the Momentum is so strong that the price moves X% away from the SuperTrend and is able to hit the Take Profit location. This Take Profit addition to this Strategy is crucial as momentum may change state shortly after such drastic price movements; and if we were to simply wait for it to come back to the SuperTrend, we may lose out on lots of potential profit.
If you refer to the Yellow Circle in this example, you’ll notice what was talked about in the Summary/Overview above. During periods of consolidation when there is little momentum and price movement and we don’t have any Stop Loss activated, you may see ‘Signal Flashing’. Signal Flashing is when there are Buy and Sell signals that keep switching back and forth. During this time you may be taking small losses. This is a normal part of this Strategy. When a signal has finally been confirmed by Momentum, is when this Strategy shines and may produce the profit you desire.
You may be wondering, what causes these jagged like patterns in the SuperTrend? It's due to the ML logic, and it may be a little confusing, but essentially what is happening is the Fast Moving SuperTrend and the Slow Moving SuperTrend are creating KNN Min and Max distances that are extreme due to (usually) parabolic movement. This causes fewer values to be added to and averaged within the ML and causes less smooth and more exponential drastic movements. This is completely normal, and one of the perks of using k-Nearest Neighbor for ML calculations. If you don’t know, the Min and Max Distance allowed is derived from the most recent(0 index of data array) to KNN Length. So only SuperTrend values that exhibit distances within these Min/Max will be allowed into the average.
Since the KNN ML logic can cause these exponential movements in the SuperTrend, they likewise affect its Take Profit. The Take Profit may benefit from this movement like displayed in the example above which helped it claim profit before then exhibiting upwards movement.
By default our Stop Loss Multiplier is kept quite low at 0.0000025. Keeping it low may help to reduce some Signal Flashing while not taking extra losses more so than not using it at all. However, if we increase it even more to say 0.005 like is shown in the example above. It can really help the trend keep momentum. Please note, although previous results don’t imply future results, at 0.0000025 Stop Loss we are currently exhibiting 69.27% profit while at 0.005 Stop Loss we are exhibiting 33.54% profit. This just goes to show that although there may be less Signal Flashing, it may not result in more profit.
We will conclude our Tutorial here. Hopefully this has given you some insight as to how Machine Learning, combined with Trailing Take Profit and Stop Loss may have positive effects on the SuperTrend when turned into a Strategy.
Settings:
SuperTrend:
ATR Length: ATR Length used to create the Original Supertrend.
Factor: Multiplier used to create the Original Supertrend.
Stop Loss Multiplier: 0 = Don't use Stop Loss. Stop loss can be useful for helping to prevent false signals but also may result in more loss when hit and less profit when switching trends.
Take Profit Multiplier: Take Profits can be useful within the Supertrend Strategy to stop the price reverting all the way to the Stop Loss once it's been profitable.
Machine Learning:
Only Factor Same Trend Direction: Very useful for ensuring that data used in KNN is not manipulated by different SuperTrend Directional data. Please note, it doesn't affect KNN Exponential.
Rationalized Source Type: Should we Rationalize only a specific source, All or None?
Machine Learning Type: Are we using a Simple ML Average, KNN Mean Average, KNN Exponential Average or None?
Machine Learning Smoothing Type: How should we smooth our Fast and Slow ML Datas to be used in our KNN Distance calculation? SMA, EMA or VWMA?
KNN Distance Type: We need to check if distance is within the KNN Min/Max distance, which distance checks are we using.
Machine Learning Length: How far back is our Machine Learning going to keep data for.
k-Nearest Neighbour (KNN) Length: How many k-Nearest Neighbours will we account for?
Fast ML Data Length: What is our Fast ML Length?? This is used with our Slow Length to create our KNN Distance.
Slow ML Data Length: What is our Slow ML Length?? This is used with our Fast Length to create our KNN Distance.
If you have any questions, comments, ideas or concerns please don't hesitate to contact us.
HAPPY TRADING! Strategy

Machine Learning: Trend Lines [YinYangAlgorithms]Trend lines have always been a key indicator that may help predict many different types of price movements. They have been well known to create different types of formations such as: Pennants, Channels, Flags and Wedges. The type of formation they create is based on how the formation was created and the angle it was created. For instance, if there was a strong price increase and then there is a Wedge where both end points meet, this is considered a Bull Pennant. The formations Trend Lines create may be powerful tools that can help predict current Support and Resistance and also Future Momentum changes. However, not all Trend Lines will create formations, and alone they may stand as strong Support and Resistance locations on the Vertical.
The purpose of this Indicator is to apply Machine Learning logic to a Traditional Trend Line Calculation, and therefore allowing a new approach to a modern indicator of high usage. The results of such are quite interesting and goes to show the impacts a simple KNN Machine Learning model can have on Traditional Indicators.
Tutorial:
There are a few different settings within this Indicator. Many will greatly impact the results and if any are changed, lots will need ‘Fine Tuning’. So let's discuss the main toggles that have great effects and what they do before discussing the lengths. Currently in this example above we have the Indicator at its Default Settings. In this example, you can see how the Trend Lines act as key Support and Resistance locations. Due note, Support and Resistance are a relative term, as is their color. What starts off as Support or Resistance may change when the price crosses over / under them.
In the example above we have zoomed in and circled locations that exhibited markers of Support and Resistance along the Trend Lines. These Trend Lines are all created using the Default Settings. As you can see from the example above; just because it is a Green Upwards Trend Line, doesn’t mean it’s a Support Line. Support and Resistance is always shifting on Trend Lines based on the prices location relative to them.
We won’t go through all the Formations Trend Lines make, but the example above, we can see the Trend Lines formed a Downward Channel. Channels are when there are two parallel downwards Trend Lines that are at a relatively similar angle. This means that they won’t ever meet. What may happen when the price is within these channels, is it may bounce between the upper and lower bounds. These Channels may drive the price upwards or downwards, depending on if it is in an Upwards or Downwards Channel.
If you refer to the example above, you’ll notice that the Trend Lines are formed like traditional Trend Lines. They don’t stem from current Highs and Lows but rather Machine Learning Highs and Lows. More often than not, the Machine Learning approach to Trend Lines cause their start point and angle to be quite different than a Traditional Trend Line. Due to this, it may help predict Support and Resistance locations at are more uncommon and therefore can be quite useful.
In the example above we have turned off the toggle in Settings ‘Use Exponential Data Average’. This Settings uses a custom Exponential Data Average of the KNN rather than simply averaging the KNN. By Default it is enabled, but as you can see when it is disabled it may create some pretty strong lasting Trend Lines. This is why we advise you ZOOM OUT AS FAR AS YOU CAN. Trend Lines are only displayed when you’ve zoomed out far enough that their Start Point is visible.
As you can see in this example above, there were 3 major Upward Trend Lines created in 2020 that have had a major impact on Support and Resistance Locations within the last year. Lets zoom in and get a closer look.
We have zoomed in for this example above, and circled some of the major Support and Resistance locations that these Upward Trend Lines may have had a major impact on.
Please note, these Machine Learning Trend Lines aren’t a ‘One Size Fits All’ kind of thing. They are completely customizable within the Settings, so that you can get a tailored experience based on what Pair and Time Frame you are trading on.
When any values are changed within the Settings, you’ll likely need to ‘Fine Tune’ the rest of the settings until your desired result is met. By default the modifiable lengths within the Settings are:
Machine Learning Length: 50
KNN Length:5
Fast ML Data Length: 5
Slow ML Data Length: 30
For example, let's toggle ‘Use Exponential Data Averages’ back on and change ‘Fast ML Data Length’ from 5 to 20 and ‘Slow ML Data Length’ from 30 to 50.
As you can in the example above, all of the lines have changed. Although there are still some strong Support Locations created by the Upwards Trend Lines.
We will conclude our Tutorial here. Hopefully you’ve learned how to use Machine Learning Trend Lines and will be able to now see some more unorthodox Support and Resistance locations on the Vertical.
Settings:
Use Machine Learning Sources: If disabled Traditional Trend line sources (High and Low) will be used rather than Rational Quadratics.
Use KNN Distance Sorting: You can disable this if you wish to not have the Machine Learning Data sorted using KNN. If disabled trend line logic will be Traditional.
Use Exponential Data Average: This Settings uses a custom Exponential Data Average of the KNN rather than simply averaging the KNN.
Machine Learning Length: How strong is our Machine Learning Memory? Please note, when this value is too high the data is almost 'too' much and can lead to poor results.
K-Nearest Neighbour (KNN) Length: How many K-Nearest Neighbours are allowed with our Distance Clustering? Please note, too high or too low may lead to poor results.
Fast ML Data Length: Fast and Slow speed needs to be adjusted properly to see results. 3/5/7 all seem to work well for Fast.
Slow ML Data Length: Fast and Slow speed needs to be adjusted properly to see results. 20 - 50 all seem to work well for Slow.
If you have any questions, comments, ideas or concerns please don't hesitate to contact us.
HAPPY TRADING! Indicator

Double AI Super Trend Trading - Strategy [PresentTrading]█ Introduction and How It is Different
The Double AI Super Trend Trading Strategy is a cutting-edge approach that leverages the power of not one, but two AI algorithms, in tandem with the SuperTrend technical indicator. The strategy aims to provide traders with enhanced precision in market entry and exit points. It is designed to adapt to market conditions dynamically, offering the flexibility to trade in both bullish and bearish markets.
*The KNN part is mainly referred from @Zeiierman.
BTCUSD 8hr performance
ETHUSD 8hr performance
█ Strategy, How It Works: Detailed Explanation
1. SuperTrend Calculation
The SuperTrend is a popular indicator that captures market trends through a combination of the Volume-Weighted Moving Average (VWMA) and the Average True Range (ATR). This strategy utilizes two sets of SuperTrend calculations with varying lengths and factors to capture both short-term and long-term market trends.
2. KNN Algorithm
The strategy employs k-Nearest Neighbors (KNN) algorithms, which are supervised machine learning models. Two sets of KNN algorithms are used, each focused on different lengths of historical data and number of neighbors. The KNN algorithms classify the current SuperTrend data point as bullish or bearish based on the weighted sum of the labels of the k closest historical data points.
3. Signal Generation
Based on the KNN classifications and the SuperTrend indicator, the strategy generates signals for the start of a new trend and the continuation of an existing trend.
4. Trading Logic
The strategy uses these signals to enter long or short positions. It also incorporates dynamic trailing stops for exit conditions.
Local picture
█ Trade Direction
The strategy allows traders to specify their trading direction: long, short, or both. This enables the strategy to be versatile and adapt to various market conditions.
█ Usage
ToolTips: Comprehensive tooltips are provided for each parameter to guide the user through the customization process.
Inputs: Traders can customize numerous parameters including the number of neighbors in KNN, ATR multiplier, and types of moving averages.
Plotting: The strategy also provides visual cues on the chart to indicate bullish or bearish trends.
Order Execution: Based on the generated signals, the strategy will execute buy or sell orders automatically.
█ Default Settings
The default settings are configured to offer a balanced approach suitable for most scenarios:
Initial Capital: $10,000
Default Quantity Type: 10% of equity
Commission: 0.1%
Slippage: 1
Currency: USD
These settings can be modified to suit various trading styles and asset classes.
Strategy

Machine Learning: Support and Resistance [YinYangAlgorithms]Overview:
Support and Resistance is normally based upon Pivot Points and Highest Highs and Lowest Lows. Many times coders even incorporate Volume, RSI and other factors into the equation. However there may be a downside to doing a pure technical approach based on historical levels. We live in a time where Machine Learning is becoming more and more used; thus we have decided to create a Machine Learning Support and Resistance Projection based Indicator. Rather than using traditional Support and Resistance calculations using historical data, we have taken a rather different approach. This Indicator instead attempts to Predict and Project where Support and Resistance locations will be based on a Machine Learning Model using a form of KNN (k-Nearest Neighbors).
Since this indicator creates a Projection of where it deems Support and Resistance will be, it has the ability to move its Support and Resistance before the price even gets to it if it believes it will surpass its projections. This may create a more accurate placement of Support and Resistance as they’re not based on historical levels.
This Indicator does not Repaint.
How it works:
This Indicator makes its projections based on the source you provide (by default close) of the previous bar and submits the source, RSI and EMA to our Projection Function to get its projection of the current bar.
The Projection function essentially calculates potential movement after finding the differences between the source the MA from the current bar, previous bar and average over the span of Machine Learning Length.
Potential movement is defined as:
Average Difference + Average(Machine Learning Average, Average Last Distance)
Average Difference: (Absolute value of Current Source - Current MA) - (Absolute value of Machine Learning Average - Machine Learning MA)
Average Last Distance: Average(Current Source - Current MA, Previous Source - Previous MA)
It then predicts the next bars directional movement (bullish or bearish bar) using several factors:
Previous Source > Previous MA
Current Source - Current MA > Average Source - Average MA
Current RSI > Previous RSI
Current RSI > 30 and Previous RSI <= 30
Current RSI < 70 and Previous RSI >= 70
This helps us to predict the direction the next bar may move.
We then calculate a multiplier that we apply to our Potential Movement value to get our final result which is our Current Bars Close Projection.
Our multiplier is calculated using:
(Current RSI > 30 and Previous RSI <= 30) OR (Current RSI < 70 and Previous RSI >= 70)
Current Source - Current MA > Previous Source - Previous MA
We then create an array and fill it with the previous X projections (Machine Learning Length) and send it to another function. This function, if told to, will sort the data accordingly and then output the KNN average of the length given.
We calculate and plot various KNN lengths to create different Zones:
Strong Support: Length of 2 but sort the data Ascending (low to high)
Strong Resistance: Length of 2 but sort the data Descending (high to low)
Support: Length of Machine Length Length / 10 or Min of 2 sorted by Ascending
Resistance: Length of Machine Length Length / 10 or Min of 2 sorted by Descending
There are also 4 other plots you may be wondering what they are, there is your AVG, VWMA, Long Term Memory and Current Projection.
By default your Current Projection is disabled in settings but you can enable it if you are curious to see how the projections for each close are calculated. It is, however, not a crucial point of interest (white line).
The average is simply the average value of the Machine Learning Data (purple line).
The VWMA is a VWMA calculation applied to our Data over a length specified in settings (by default 1)(blue line). The VWMA is crucial when combined with the Avg as they can cross over and under each other. These crosses represent potential Bullish and Bearish zones.
Lastly, but certainly not least, we have the Long Term Memory (maroon line). The Long Term Memory can be displayed either as an ‘Average’, ‘Hard Line’ or ‘None’. The Long Term Average is only updated every Machine Learning Length Bar Index’s and is populated with the average of the Machine Learning Data. For Instance, if Machine Learning Length is set to 100, the Long Term Memory is only updated every 100 bars, and since its length is the same as the Machine Learning Length, that means its data is composed of 10,000 bars worth of data. The Long Term Memory may be very beneficial for determining where Support and Resistance lie over the Long Term within a Machine Learning Algorithm. When set to ‘Average’ it plots the connection lines diagonally, and although they may be more visually appealing, they’re less useful when it comes to actually seeing support and resistance as generally speaking, support and resistance lie on the horizontal. When set to ‘Hard Line’ the Long Term Memory is connected with hard lines and holds the price value until the next time it is updated. This makes it much more useful for potentially identifying Support and Resistance.
Tutorial:
Here is an overview of what the Indicator looks like, now let's start to dissect it.
In the example above we can see how all of the lines between the Major Support and Resistance zones may act as BOTH Support and Resistance depending on which side the price is currently on. In the circle on the left, we can see how it can fluctuate between the two. If you look at the circle on the right, we can see how the Average line acts as a strong support before it fails to maintain it. Generally speaking, most Support and Resistance locations may potentially fail to hold after 3 tests, as the Average did in this example.
As you can see, the Support and Resistance doesn’t wait to be tested before adjusting, which is why there are 2 lines which create their zones. The inner line is the Support/Resistance and the outer line is the Strong Support/Resistance. The Yellow Circle shows the inner line was able to calculate the moving resistance correctly and then adjusted accordingly as it was projecting the price to keep increasing. However, if you look at the White Circle, you can see that since there was first a crash, and then parabolic movement, that the inner zone could not move and predict the resistance as well as the outer zone could.
We consider the price to be ‘Overvalued’ when it is above the VWMA (blue line) and ‘Undervalued’ when it is below the VWMA. It is considered ‘fair’ price when it is within the VWMA to Average zone (between the blue and purple lines). If you look at the example above, you’ll notice where the two yellow circles are, it is not only considered ‘Overvalued’, but it then proceeds to ride the inner resistance line upwards. This is common when the market is overly bullish and vice versa when it is bearish. Please keep in mind, although it is common, it doesn’t mean a correction can’t happen.
In this example above we look at the last bull run that may have started due to the halving. This bull run was very bullish as you can see in the example above. The price was constantly sitting within the Resistance Zone and the VWMA that was very close to it was constantly acting as a Support. Naturally, due to the Algorithm used in this Indicator, as the momentum starts to slow down, the VWMA (blue line) will start to space out more and more from the Resistance Zone. This doesn’t mean the momentum is gone, it just means it may be slowing down.
Unfortunately we have to study the Bear Market with a different perspective than the Bull Market. However, there are still some similarities within the two. If you refer to the example above and the previous example, you can clearly see that the Bull Market loves to stay with the Resistance Zone and use the VWMA as a Support. However, the Bear Market does not. This is a normal occurrence, however we can see from the example above you may see a correction / horizontal movement when the Outer Support Line is touched. If you look at all 3 yellow circles, the Outer Support Line was touched, then either a small correction or horizontal consolidation occurred.
We will conclude our Tutorial here, hopefully you’ll be able to benefit from a moving Support and Resistance calculated with Machine Learning that projects its locations, rather than using traditional calculations.
Settings:
Source: This source is the base for all our calculations
Machine Learning Length: How much projection data are we storing and using to make calculations.
Smoothing Length: We need to smooth calculations such as RSI, EMA and VWMA. What length are we smoothing it with?
VWMA ML Projection Length: How far into our Machine Learning data should we average for our VWMA. Please note the 'Smoothing Length' is still applied here after getting the Projection Average.
Long Term Memory: Long term memory has the same storage length but is only updated once per Machine Learning Length. For instance, if Machine Learning Length is 100, it will save the Average of our data once every 100 bars. This means its memory is an average of 10,000 bars of Machine Learning. 'Average' connects its values diagonally whereas 'Hard Line' holds its value until it changes.
Use Average Last Distance In Potential Movement: This can help accuracy but generally also displaces the Support and Resistance by projecting it further.
Show Current Projection: Projections occur for each bar, and our Machine Learning utilizes these projections by storing and evaluating them. This toggle will display the Current Projection Line which is used to create all our Projections.
If you have any questions, comments, ideas or concerns please don't hesitate to contact us.
HAPPY TRADING! Indicator
