QuantEdge Momentum ML [PRO]🟦 QuantEdge Momentum ML PRO is a k-Nearest Neighbors driven momentum oscillator built on an adaptive machine-learning core. Unlike RSI, Stochastic, or MACD — which apply the same static formula to every asset — QE-ML PRO learns the dual-horizon RSI fingerprints that have historically led to bullish versus bearish outcomes on the exact instrument being traded, then scores the current bar against the N closest historical matches. The result is a non-parametric, self-calibrating oscillator whose decision boundary is shaped by the asset's own behaviour rather than a hard-coded curve.
The indicator integrates nine independent layers — feature engine, training sampler, k-NN predictor, WMA signal line, stdev-adjusted OB/OS bands, filtered signal dots, gradient channel, theme-adaptive dashboard, and a nine-theme palette — all rendered on a single, clean oscillator panel.
🟦 HOW THE CORE ENGINE WORKS
**Dual-Horizon RSI Feature Vector**
Each bar, the Feature Engine computes two RSI values at different lookback windows and smooths both through a shared trend-length WMA:
- `rsiFast = WMA(RSI(close, FastPeriod), TrendLength)` — reactive short-term momentum
- `rsiSlow = WMA(RSI(close, SlowPeriod), TrendLength)` — structural mid-term momentum
The pair `(rsiSlow, rsiFast)` is a 2-dimensional point in RSI feature space. Every training sample stores one such point along with a ±1 label that records whether price rose or fell since the previous sample. Over time the dataset accumulates a cloud of labelled points that maps which RSI states historically preceded up-moves versus down-moves on this exact asset.
**Training Sampler — Multi-Trigger Collector**
Three collection modes decide when to append a new labelled sample:
| Mode | Trigger | Use Case |
|---|---|---|
| **MA Crossover** | Fast WMA crosses Slow WMA | Clean, sparse samples — classic single-trigger behaviour |
| **Periodic** | Every N bars (user-set) | Fills dataset fast on new / low-history charts |
| **Hybrid** | MA crossover **OR** every N bars | Richest training set — recommended for fresh assets |
Sampling is gated by `barstate.isconfirmed` so the dataset never absorbs unconfirmed values from a flickering live bar.
**k-NN Predictor with Adaptive k**
On every bar, the predictor computes Euclidean distance in the 2D RSI feature space between the live `(rsiSlow, rsiFast)` point and every historical sample:
```
d = sqrt((rsiSlow_now - rsiSlow_hist)² + (rsiFast_now - rsiFast_hist)²)
```
The K closest historical points vote by summing their ±1 labels. The effective K is resolved adaptively using the classical statistical heuristic:
```
kEff = max(3, min(kMax, floor(sqrt(N))))
```
This means early bars — when only a handful of samples exist — use a small K, and the value stabilises as the dataset fills. On a fresh chart you never get a noisy prediction from an undersized neighborhood, and on a mature dataset K automatically scales up for smoother output.
**Bias Correction — Label-Mean Recentering**
Raw k-NN output is biased whenever the label distribution is skewed. On a trending asset, Periodic sampling fills the dataset with mostly +1 (or mostly −1) labels, pushing every prediction off zero. QE-ML PRO subtracts the expected value from the raw sum:
```
prediction = neighborLabelSum − (kEff × meanLabelAcrossDataset)
```
This keeps the mid-level visually centred at zero regardless of how trending the underlying asset has been. The correction is applied on every bar and is what makes the oscillator read cleanly on both sideways and strongly trending markets.
**Minimum Sample Gate**
Until the dataset has reached the user-defined Minimum Training Samples threshold, the predictor outputs exactly zero. This prevents unreliable readings during the warm-up phase on fresh charts.
**FIFO Rotation**
The dataset is hard-capped at Max Dataset Size. Once the cap is reached, the oldest sample is discarded on every new insertion — classical rolling window memory that keeps the k-NN scan bounded and the indicator fast on long histories.
🟦 PREDICTION LINE — FIVE VISUAL STYLES
All five styles are line-based. Only the visual effect differs — the underlying k-NN math is identical across styles.
| Style | Character |
|---|---|
| **Stratum** | Thick adaptive line with zone-based opacity: solid in extreme zones, semi-transparent in the mid zone. Layered intensity aesthetic — default |
| **Neon** | Bright core line with an outer glow halo. Cyberpunk luminous effect, best on dark backgrounds |
| **Resonance** | LRI-style gradient line that fades near the midline and brightens toward the rolling extremes |
| **Pulse** | Adaptive bull/bear color (above midline = bull, below = bear) plus the WMA signal line. The QE-ML PRO classic look |
| **Mono** | Single flat theme-bull line, no gradient, no adaptive coloring. Minimalist single-color silhouette |
🟦 SIGNAL LINE
A WMA of the raw prediction output, used as a crossover trigger line in the MACD convention. Crossovers between the prediction and signal line mark momentum regime changes.
**Two Visual Styles**
| Style | Rendering |
|---|---|
| **Neon** | Bright core line wrapped in a wider semi-transparent glow halo — cyberpunk aesthetic |
| **Flat** | Plain single-color line, no halo, no gradient — minimalist clean look |
🟦 SIGNAL DOTS — FILTERED CROSSOVER MARKERS
A two-layer neon cross-dot renderer fires on every Prediction × Signal crossover that survives the active filter mode. Four progressive filters decide which raw crosses reach the chart:
| Filter Mode | Behaviour | Signal Count |
|---|---|---|
| **All Crosses** | Every cross becomes a dot | Highest — noisy on choppy assets |
| **Zone Only** | Only crosses inside an OB or OS strip | Mean-reversion triggers — strongest reversal setups |
| **Mid Aligned** | Bull dots only above mid, bear dots only below | Trend-following — keeps you on regime side |
| **Strict** | Zone Only + Mid Aligned + extra strength multiplier on mid-zone crosses | Fewest signals, highest conviction — default |
Two additional gates filter out whipsaws:
- **Cooldown (bars)** — minimum spacing between consecutive dots, prevents cluster spam in ranges
- **Min Strength** — minimum `|prediction − signal|` separation at the moment of the cross, drops razor-thin crossovers that close back on themselves
Each dot is a two-layer plot: an outer glow halo with user-adjustable size and opacity, and a bright solid core on top — independently sized and opacity-controlled so users can dial in the exact visual weight they want.
The dot is placed at the actual cross point: bull dots at `min(prediction, signalLine)`, bear dots at `max(prediction, signalLine)`.
🟦 DYNAMIC BANDS — STDEV-ADJUSTED OB / OS ZONES
QE-ML PRO does not use fixed 80 / 20 overbought / oversold levels. Instead, the bands adapt to the actual historical range of the prediction output:
- **Channel Extremes** — rolling highest / lowest of the prediction over a user-configurable lookback
- **Stdev Band** — EMA of rolling standard deviation of the prediction, multiplied by the user's stdev length
- **OB Level** = `rangeHi − stdevBand` (inner boundary of the overbought strip)
- **OS Level** = `rangeLo + stdevBand` (inner boundary of the oversold strip)
The result is a pair of mean-reversion zones that tighten during quiet markets and widen during volatile ones — no manual recalibration needed across assets.
The strips are rendered as gradient fills anchored on the live prediction plot, so they only appear visually while the prediction is actually inside the zone.
🟦 CHANNEL GRADIENT
Two symmetric gradient fills bracket the mid line. The upper fill stretches from `midValue` to `rangeHi`, the lower fill from `midValue` to `rangeLo`. Opacity fades from full intensity at the extremes to fully transparent at the midline — a visual range meter showing how close the prediction is sitting to its historical boundaries.
Colors are pulled from the active Theme. A single opacity slider controls the gradient intensity.
🟦 DASHBOARD — LIVE DATA PANEL
A compact 2-column × 7-row monospace panel drawn on the last bar only (zero historical overhead). Every field updates in real time on the live bar.
| Row | Left | Right |
|---|---|---|
| Header | QE-ML PRO | Regime (▲ BULL / ▼ BEAR / ■ NEUTRAL) |
| Row 1 | Prediction | Raw value + trend arrow vs previous bar |
| Row 2 | Signal | WMA trigger line value |
| Row 3 | Strength | 10-block gauge of `|prediction − signal|` normalised against rolling channel |
| Row 4 | Zone | OB / MID / OS tag |
| Row 5 | Dataset | Sample count / effective k |
| Row 6 | Mode | Active Learning Mode (MA Cross / Periodic / Hybrid) |
**Theme-Aware Auto-Invert**
The panel background scaffolds auto-switch:
- **Tropic / Amber / Pastel / Cyber / Gold / Electric / Candy** → dark panel with bright theme accent text
- **Midnight / Graphite** → light panel with dark theme accent text
This guarantees legibility on every theme without breaking the theme's color identity — because Midnight and Graphite use deep dark bull tones that would drown against a black panel.
**Direction via Glyphs, Not Color**
Both columns share the same full-strength theme tone. Regime direction is conveyed by `▲ ▼ ■` glyphs rather than color shifts, which keeps the panel reading cleanly even on the most minimal themes.
🟦 NINE COLOR THEMES
One theme selector drives every colored component — Prediction line, Signal line, Channel fill, OB / OS strips, Mid-level line, Signal Dots, and Dashboard panel. No per-color manual inputs.
| Theme | Character | Bull | Bear |
|---|---|---|---|
| **Tropic** | Cyan steel + deep orange — electric contrast (default) | Cyan | Deep Orange |
| **Amber** | Warm amber + indigo blue — fire tones | Amber | Red |
| **Pastel** | Sky blue + soft lavender — cool arctic glow | Sky Blue | Lavender |
| **Cyber** | Neon lime + hot crimson — cyber terminal | Neon Green | Crimson |
| **Gold** | Bright gold + scarlet — solar warmth | Yellow Gold | Red |
| **Electric** | Electric aqua + magenta — high-voltage neon | Aqua | Magenta |
| **Candy** | Neon green + hot pink — dark energy pop | Mint Green | Hot Pink |
| **Midnight** | Deep navy + dark crimson — dark depth (auto light dashboard) | Navy Blue | Dark Red |
| **Graphite** | Near-black + silver grey — monochrome minimal (auto light dashboard) | Near Black | Grey |
🟦 ALERT SYSTEM — TEN CONDITIONS
Every alert is gated by its matching "Show X" visibility toggle — if a component is hidden from the chart, its alerts are automatically suppressed. This eliminates the mismatch between visual signals and alert signals that plagues many indicators.
| Alert | Condition | Gated By |
|---|---|---|
| Crossover OB | Prediction crosses above the overbought boundary | Show OB/OS Fill |
| Crossunder OB | Prediction crosses back down through OB | Show OB/OS Fill |
| Crossover OS | Prediction crosses up through oversold boundary | Show OB/OS Fill |
| Crossunder OS | Prediction crosses below the oversold boundary | Show OB/OS Fill |
| Crossover Mid | Prediction crosses above the mid line — bullish regime flip | Show Mid Level |
| Crossunder Mid | Prediction crosses below the mid line — bearish regime flip | Show Mid Level |
| Crossover Signal | Prediction crosses above its WMA signal line (MACD bullish) | Show Signal Line |
| Crossunder Signal | Prediction crosses below its WMA signal line (MACD bearish) | Show Signal Line |
| Bull Signal Dot | A filtered Bull Signal Dot is plotted (uses Filter Mode + Cooldown + Min Strength) | Show Signal Dots |
| Bear Signal Dot | A filtered Bear Signal Dot is plotted (uses Filter Mode + Cooldown + Min Strength) | Show Signal Dots |
🟦 SETTINGS REFERENCE
**Visual**
- Theme — nine cohesive palettes. Default: Tropic
**Machine Learning**
- Neighbors (k) — upper bound on neighbors used by the predictor. Default: 100
- Adaptive k — scales k with dataset size using the `floor(sqrt(N))` heuristic. Default: ON
- Learning Mode — MA Crossover / Periodic / Hybrid. Default: MA Crossover
- Sample Every (bars) — bar interval for the Periodic / Hybrid trigger. Default: 5
- Minimum Training Samples — warm-up gate, predictor outputs zero until reached. Default: 30
- Max Dataset Size — hard FIFO cap. Default: 500 (safe on all timeframes)
**Feature Engine**
- Trend Length — WMA smoothing applied to both RSI features. Default: 20
- RSI Fast Period — first feature dimension. Default: 5
- RSI Slow Period — second feature dimension. Default: 20
- MA Fast Period — fast WMA for the crossover training trigger. Default: 5
- MA Slow Period — slow WMA for the crossover training trigger. Default: 20
**Prediction Line**
- Show Prediction Line — master toggle. Default: ON
- Prediction Style — Stratum / Neon / Resonance / Pulse / Mono. Default: Stratum
- Prediction Width — 1 to 5. Default: 2
**Signal Line**
- Show Signal Line — toggle. Default: ON
- Signal Style — Neon / Flat. Default: Neon
- Signal Period — WMA length of the signal line. Default: 20
- Signal Width — 1 to 5. Default: 1
**Signal Dots**
- Show Signal Dots — toggle. Default: ON
- Filter Mode — All Crosses / Zone Only / Mid Aligned / Strict. Default: Strict
- Cooldown (bars) — minimum spacing between dots. Default: 5
- Min Strength — minimum `|prediction − signal|` at the cross. Default: 0.5
- Core Dot Size — 1 to 8. Default: 3
- Core Dot Opacity — 0 to 100. Default: 100
- Glow Dot Size — 1 to 12. Default: 8
- Glow Dot Opacity — 0 to 100. Default: 30
**Channel Fill**
- Show Channel Fill — toggle. Default: ON
- Channel Opacity — 0 to 100. Default: 25
- Channel Lookback — rolling highest / lowest window. Default: 500
**OB / OS Fill**
- Show OB/OS Fill — toggle. Default: ON
- Zone Stdev Length — stdev window that offsets the OB / OS boundaries inward. Default: 20
**Mid Level**
- Show Mid Level — toggle. Default: ON
- Mid Level Value — Y-value of the reference line. Default: 0
- Mid Level Style — Solid / Dashed / Dotted. Default: Dashed
**Dashboard**
- Show Dashboard — toggle. Default: ON
- Panel Position — six slots (Top/Middle/Bottom × Right/Left). Default: Middle Right
- Panel Text Size — Tiny / Small / Normal / Large. Default: Small
**Alerts**
- Ten opt-in toggles, one per alert condition. All default: ON
🟦 TRADER PRESETS — SETTINGS BY STYLE
QE-ML PRO is volatility-agnostic thanks to the adaptive bands and bias correction, but the reactivity of the predictor scales directly with the feature and sampler parameters. The four presets below are tested starting points you can drop straight into the settings panel — adjust by ±20% to taste.
---
** SCALPER — 1m / 3m / 5m**
High-frequency entries, tight stops, many signals per session. Priority is reaction speed — you want the predictor to flip states within a handful of bars of an actual move.
| Setting | Value |
|---|---|
| Trend Length | 10 |
| RSI Fast Period | 3 |
| RSI Slow Period | 14 |
| MA Fast Period | 3 |
| MA Slow Period | 10 |
| Signal Period | 8 |
| Neighbors (k) | 40 |
| Adaptive k | ON |
| Learning Mode | **Hybrid** |
| Sample Every | 2 |
| Minimum Training Samples | 20 |
| Max Dataset Size | **300** (keeps 1m charts fast) |
| Filter Mode | **All Crosses** or Zone Only |
| Cooldown | 2 |
| Min Strength | 0.3 |
| Channel Lookback | 200 |
| Zone Stdev Length | 10 |
| Prediction Style | Neon or Stratum |
**Why:** Low smoothing (Trend=10) + short RSI pair (3/14) keeps the features razor-sharp. Hybrid learning means you never wait for an MA crossover during quiet 1m sessions. Max Dataset capped at 300 protects you from the TradingView per-bar calculation limit on long 1m histories.
---
** DAY TRADER — 15m / 30m / 1H**
Balanced reactivity and conviction — the default profile. You want clean crosses without noise spam, and signals that survive the open / close volatility spikes.
| Setting | Value |
|---|---|
| Trend Length | 20 (default) |
| RSI Fast Period | 5 (default) |
| RSI Slow Period | 20 (default) |
| MA Fast Period | 5 (default) |
| MA Slow Period | 20 (default) |
| Signal Period | 20 (default) |
| Neighbors (k) | 100 (default) |
| Adaptive k | ON |
| Learning Mode | **MA Crossover** (default) |
| Minimum Training Samples | 30 (default) |
| Max Dataset Size | 500 (default) |
| Filter Mode | **Strict** (default) |
| Cooldown | 5 (default) |
| Min Strength | 0.5 (default) |
| Channel Lookback | 500 (default) |
| Zone Stdev Length | 20 (default) |
| Prediction Style | Stratum (default) |
**Why:** Every default value was tuned for this range. Strict filter + 5-bar cooldown keeps the dot count honest on a 30m chart. MA Crossover sampling gives you clean sparse data since 15m+ charts already have enough crossover events.
---
** SWING TRADER — 4H / 1D**
Lower signal frequency, higher conviction per signal. You're holding for days or weeks — every dot needs to mean something.
| Setting | Value |
|---|---|
| Trend Length | 30 |
| RSI Fast Period | 7 |
| RSI Slow Period | 30 |
| MA Fast Period | 7 |
| MA Slow Period | 30 |
| Signal Period | 30 |
| Neighbors (k) | 150 |
| Adaptive k | ON |
| Learning Mode | MA Crossover |
| Minimum Training Samples | 50 |
| Max Dataset Size | 800 |
| Filter Mode | **Strict** |
| Cooldown | 10 |
| Min Strength | 0.8 |
| Channel Lookback | 800 |
| Zone Stdev Length | 30 |
| Prediction Style | Stratum or Mono |
**Why:** Longer feature periods mean the predictor only moves on genuine structural shifts. Larger k (150) + bigger dataset (800) gives the k-NN vote a wider base so outliers don't flip the sign. Cooldown of 10 bars on a 4H chart = 40 hours minimum between dots — exactly what a swing trader wants.
---
** POSITION / LONG-TERM — 1D / 1W / 1M**
Macro regime detection. You're looking for the handful of generational setups per year — noise is the enemy.
| Setting | Value |
|---|---|
| Trend Length | 50 |
| RSI Fast Period | 10 |
| RSI Slow Period | 40 |
| MA Fast Period | 10 |
| MA Slow Period | 40 |
| Signal Period | 40 |
| Neighbors (k) | 200 |
| Adaptive k | ON |
| Learning Mode | **Hybrid** |
| Sample Every | 3 |
| Minimum Training Samples | 40 |
| Max Dataset Size | 1000 |
| Filter Mode | **Strict** |
| Cooldown | 15 |
| Min Strength | 1.0 |
| Channel Lookback | 1000 |
| Zone Stdev Length | 40 |
| Prediction Style | Mono or Pulse |
**Why:** Weekly and monthly charts have few crossover events per year — without Hybrid mode the dataset starves. Sample Every = 3 on a weekly chart means one sample every 3 weeks, which is plenty of structural density. Min Strength 1.0 filters out every shallow cross — you only see dots on generational momentum inflections.
---
**Tuning Tip**
If the predictor feels **too reactive** → increase Trend Length and Signal Period by 25%, raise Cooldown.
If the predictor feels **too sluggish** → switch Learning Mode to Hybrid, decrease Min Samples, lower Trend Length.
If the dashboard shows **Dataset N is stuck low** → switch Learning Mode from MA Crossover to Hybrid — crossover events are too rare on your current settings.
If you see **runtime / timeout errors** on long histories → drop Max Dataset Size to 300 and Channel Lookback to 300.
🟦 COMPATIBILITY
Works on all asset classes and all timeframes in TradingView Pine Script v6.
- **Crypto** — Spot, futures, perpetual contracts
- **Forex** — All pairs
- **Equities** — Stocks, ETFs, indices
- **Commodities** — Metals, energy, agriculture
- **Timeframes** — 1m through Monthly
The k-NN engine learns each asset's own RSI fingerprint distribution, and the stdev-adjusted bands auto-scale to the volatility of that distribution, so the indicator is truly self-calibrating across assets and timeframes — no manual recalibration required.
🟦 TECHNICAL NOTES
- Pine Script v6
- No repainting — training samples are gated by `barstate.isconfirmed` so the dataset never absorbs unconfirmed live-bar values
- Dataset is hard-capped via FIFO rotation; no unbounded memory growth
- Dashboard renders only on `barstate.islast` — zero historical overhead
- All drawing objects are stateless plots (no label / box / line object pools), so `max_*_count` limits cannot be exceeded
- k-NN distance pass is O(N), sort is O(N log N), both bounded by Max Dataset Size
- Default Max Dataset Size of 500 is tuned to stay within TradingView's per-bar calculation budget on histories up to ~50,000 bars
- Bias correction uses a single extra accumulator pass during the distance sweep — no performance penalty
🟦 DISCLAIMER
This indicator is provided for educational and informational purposes only. It does not constitute financial advice. Past performance does not guarantee future results. The k-NN engine learns from historical patterns, but markets do not guarantee that historical patterns will repeat. Always conduct your own analysis and apply proper risk management.
Pine Script® インジケーター






















