Viprasol KNN SuperTrend Engine## Overview
The KNN SuperTrend Engine combines a K-Nearest Neighbors machine learning classifier with the SuperTrend indicator to generate high-confidence trend signals. Instead of relying solely on price crossing a band, this indicator uses 12 technical features across multiple time horizons, optional PCA dimensionality reduction, and Gaussian-weighted neighbor voting to predict market direction. Only when the KNN prediction aligns with a SuperTrend direction change does a confirmed signal fire.
Built for traders who want data-driven, confidence-scored entries rather than simple crossover signals.
## How It Works
**SuperTrend as Label Generator:**
The SuperTrend indicator's direction changes serve as supervised learning labels. Each historical bar is labeled as bullish (+1), bearish (-1), or neutral (0) based on the SuperTrend state, with a 5-bar stability filter to avoid noisy labels near flip points.
**12-Feature Engineering:**
Four types of features, each calculated at three stride windows (short/medium/long), create a rich representation of current market conditions:
1. **RSI** — Momentum state at three temporal resolutions
2. **MA Deviation** — How far price deviates from its moving average (10 MA types supported)
3. **RSI-Signal Distance** — Momentum acceleration/deceleration
4. **Choppiness Index** — Whether the market is trending or ranging
All 12 features are z-score normalized to ensure equal weighting.
**PCA Compression (Optional):**
When enabled, the 12 raw features are compressed into 4 principal components with decay weighting (1.0 / 0.9 / 0.8), reducing noise while preserving the most important variance.
**KNN Classification:**
The engine searches the training window for the K most similar historical patterns using Minkowski distance (configurable — Euclidean at p=2, Manhattan at p=1). Neighbors are weighted using a Gaussian kernel, so closer matches have exponentially more influence. The weighted vote produces bullish and bearish probability scores.
**Signal Confirmation:**
A signal fires only when:
1. The KNN probability crosses above the prediction threshold (default 90%)
2. The SuperTrend direction change confirms the same direction
This dual-confirmation dramatically reduces false signals compared to either method alone.
## Key Features
- K-Nearest Neighbors classifier with Gaussian-weighted Minkowski distance
- 12 technical features across 3 stride windows (RSI, MA deviation, RSI-signal distance, Choppiness)
- 10 moving average types for feature calculation (SMA, EMA, DEMA, TEMA, LSMA, WMA, HMA, ZLSMA, SMMA, THMA)
- Optional PCA dimensionality reduction (12 features -> 4 components)
- Configurable distance metric (Minkowski p-parameter) and kernel shape
- Dual confirmation: KNN prediction + SuperTrend direction alignment
- Confidence-based dynamic bar coloring (gradient from neutral to bull/bear)
- Prediction probability labels at SuperTrend direction changes
- ATR-based TP/SL levels on confirmed signals
- Dashboard showing KNN probabilities, prediction, confidence, SuperTrend state, and feature values
- SuperTrend gradient fill with toggle
- 5 alert conditions with dynamic messages
## How to Use
**Setup:**
1. Add to any chart (works on all markets and timeframes)
2. The indicator needs sufficient historical bars to train (at least Training Window + Stride bars)
3. Default settings work well on 15m-4H timeframes
**Reading the Signals:**
- **UP/DN labels** = KNN-confirmed signals (strongest, use for entries)
- **Circles on SuperTrend line** = SuperTrend direction changes (colored by KNN agreement)
- **Prediction % labels** = KNN confidence at each SuperTrend flip
- **Bar colors** = Real-time confidence gradient (blue = bullish, pink = bearish, gray = neutral)
**Dashboard:**
Shows real-time KNN bull/bear probabilities, prediction state, confidence level, SuperTrend direction, RSI, Choppiness, and model settings.
**Tuning Guide:**
- More K-Neighbors = smoother predictions, slower to react
- Higher Prediction Threshold = fewer but more confident signals
- Larger Training Window = more historical data for pattern matching
- PCA ON = cleaner signals in noisy markets
- PCA OFF = more responsive in clean trending markets
**Recommended Settings:**
- Scalping (1m-5m): K=5, Threshold=0.85, Window=500, Stride=5
- Intraday (15m-1H): K=10, Threshold=0.90, Window=1000, Stride=10
- Swing (4H-1D): K=15, Threshold=0.90, Window=1000, Stride=15
## Settings
**SuperTrend:** ATR length and factor for the base SuperTrend calculation.
**KNN Engine:** K-neighbors count, training window size, sampling stride, prediction threshold.
**Feature Engineering:** MA type, RSI/MA/signal/choppiness periods, normalization window, distance exponent, kernel shape.
**Dimensionality Reduction:** Toggle PCA compression on/off.
**Risk Management:** TP/SL toggle, SL ATR multiplier, TP1/TP2 risk-reward ratios.
**Visuals:** Bar coloring, prediction labels, SuperTrend fill, signal markers — all individually toggleable.
**Dashboard:** Show/hide, position, font size.
## Alerts
1. **KNN Confirmed Long** — Fires when KNN + SuperTrend both confirm bullish
2. **KNN Confirmed Short** — Fires when KNN + SuperTrend both confirm bearish
3. **Any KNN Confirmed Signal** — Fires on either confirmed direction
4. **KNN Bullish Prediction** — Fires when KNN alone predicts bullish (before SuperTrend confirmation)
5. **KNN Bearish Prediction** — Fires when KNN alone predicts bearish (before SuperTrend confirmation)
All alerts include {{ticker}}, {{close}}, and {{interval}} for dynamic notification messages.
## Limitations & Disclaimer
- The KNN engine requires sufficient historical data to produce meaningful predictions — early bars and newly listed instruments may have unreliable output
- Machine learning on financial data does not guarantee predictive accuracy; markets are non-stationary and patterns may not persist
- The training window uses past data; the model cannot predict novel market regimes it hasn't seen
- Computational load increases with larger training windows and more K-neighbors — very large settings may cause slow chart loading
- PCA compression uses simplified linear combinations, not true eigenvector decomposition
- TP/SL levels are visual guides — they do not execute trades automatically
- This indicator is for educational and analytical purposes only — it is not financial advice. Always use proper risk management.
---
*Based on a concept by SatohK. Upgraded to Pine Script v6 and significantly enhanced with TP/SL management, full dashboard, visual toggles, 5 alert conditions, tooltips on all inputs, and complete code restructuring by Viprasol.*
Indicador Pine Script®






















