OPEN-SOURCE SCRIPT

AetherEdge KNN Regime Classifier

462
🖊️ Overview
AetherEdge KNN Regime Classifier is an innovative memory-based machine learning regime classifier that fully implements the k-Nearest Neighbors (k-NN) algorithm in Pine Script. It memorizes up to 2,000 historical patterns, retrieves the k most similar past patterns matching the current 8-dimensional feature vector, and classifies the market into five regimes (Trending Up / Trending Down / Range / Breakout / Reversal) in real time via majority voting. Each regime's forward returns and historical win-rate are statistically tracked, providing multi-dimensional data-driven trade support.

🔶 Key Features

True k-NN Implementation: k tunable from 3–50, odd numbers preferred
Memory Bank: Up to 2,000 patterns stored, FIFO auto-discard
3 Distance Metrics: Euclidean / Manhattan / Cosine
2 Voting Schemes: Majority / Distance-weighted (1/d)
5 Regime Classification: Trending▲ / Trending▼ / Range / Breakout / Reversal
Forward-Looking Validation: Each pattern verified against N-bar future return
8-D Feature Vector: ADX/DMI/BBW/RSI/Volume/Slope/Position/ROC
Live Win-Rate Table: Statistical edge of each regime visualized
KNN Distance Heatmap: Nearest-to-farthest distance distribution
Vote Distribution Bars: % bars showing votes per regime
Confidence Computation: Auto-derived from vote concentration
Regime Background Tinting: Instant chart-wide regime visibility
High-Confidence Regime Shift Alert: Triggered at Confidence > 85%

🧠 Technical Architecture

This indicator is a top-tier regime classification engine fully implementing k-NN, the flagship of memory-based (lazy) learning.

k-NN Algorithm:
Compute query vector q = [f1, f2, ..., f8]
Calculate distance d(q, m_i) to all memory patterns
Select top-k by ascending distance
Vote: argmax_l Σ w_i × [label_i == l]
Distance Metrics:
Euclidean: √Σ(q_i - m_i)² — standard geometric
Manhattan: Σ|q_i - m_i| — outlier-robust
Cosine: 1 - (q·m)/(|q||m|) — direction-focused
Weighting Schemes:
Majority: Plain vote
Distance-weighted: w = 1/(d + ε) — closer = stronger
Feature Engineering (8-D):
f1: ADX strength (trend presence)
f2: DMI differential (direction)
f3: BBW ratio (volatility expansion)
f4: RSI normalized (momentum)
f5: Volume z-score (liquidity)
f6: Linear Regression Slope (structural tilt)
f7: Range Position (within high-low)
f8: ROC (rate of change)
Regime Labeling Rules:
Breakout: BBW > 1.5×avg AND Volume > 1.8×avg AND |ROC| > 1.0
Reversal: RSI extreme AND ROC sign flipped
Trending Up: ADX > 25 AND DI+ > DI- AND Slope > 0
Trending Down: ADX > 25 AND DI- > DI+ AND Slope < 0
Range: ADX < 18 AND BBW < 1.2×avg
Forward-Looking Validation: Win/loss decided after N (default 5) bars
Memory Management: Staging queue → committed after forward window → FIFO once size exceeded

⚙️ Recommended Settings & Tuning Guide

Crypto Defaults:

BTC (4H–D): k=15, Memory=500, Forward=5 (standard)
ETH (1H–4H): k=11, Cosine, Forward=8
SOL (high-vol): k=21, Manhattan (outlier-robust)
XRP (range-heavy): k=9, Forward=3 for short-horizon edge
k Tuning:

k=3–7: High sensitivity, noisy
k=11–15: Balanced (recommended)
k=21–31: Smooth, may dilute rare patterns
Memory Size:

300: Lightweight, recent-trend focused
500: Standard
1000–2000: Long-term stats, heavy compute
Forward Bars:

3: Scalping
5: Standard
10–15: Swing-oriented
Distance Metric Selection:

Euclidean: Standard, balanced
Manhattan: High-vol assets, outlier-heavy
Cosine: Pattern-shape focus, magnitude-agnostic

💡 How to Use in Practice

Trending▲ + Confidence > 70%: Optimal trend-following entry
Breakout detected: Activate volatility-breakout strategies
Reversal warning: Reduce trend-follow size, consider counter-trend
Range: Range/grid strategies fit
Win-Rate Table analysis: Discover statistically dominant regimes for your asset
Avg Ret monitoring: Trending▲ with high +Avg Ret = trend-follow valid
Confidence < 50%: Vote dispersion, regime unclear—reduce size
Heatmap green-dominant: Abundant similar patterns, high prediction trust
Heatmap red-dominant: Uncharted territory—proceed cautiously
AetherEdge Synergy:
NeuraNet Predictor: KNN Trending▲ + NeuraNet > 0.7 = dual AI conviction
Self-Evolving S/R Grid: Breakout regime + line breach = strong entry
All-in-One Dashboard: HIGH-CONVICTION + high KNN confidence = ultimate alignment
Multi-TF: 4H KNN regime → 1H strategy selection → 15M precision entry

⚠️ Important Notes

Learning Reset: Memory wipes on chart reload; rebuild required
Min Samples (50): Classification disabled prior; wait phase mandatory
FIFO Memory: Old patterns auto-discarded for regime adaptation
Compute Load: Memory=2000 + k=50 is heavy; use 500/15 on low-spec
Feature NaN: Features undefined initially; accumulation starts after structLen+50 bars
Rare regimes: Reversal/Breakout occur infrequently; small N = unstable stats
Forward Window Lag: Most recent N bars not yet labeled; memory commit delayed

🚨 Disclaimer

This indicator is a machine learning demonstration provided for educational and research purposes only and does not constitute financial advice. k-NN classification results derive from statistical similarity to past patterns and do not guarantee future profits. Reliability depends on market conditions, asset, and timeframe. Combine with independent analysis and proper risk management.

คำจำกัดสิทธิ์ความรับผิดชอบ

ข้อมูลและบทความไม่ได้มีวัตถุประสงค์เพื่อก่อให้เกิดกิจกรรมทางการเงิน, การลงทุน, การซื้อขาย, ข้อเสนอแนะ หรือคำแนะนำประเภทอื่น ๆ ที่ให้หรือรับรองโดย TradingView อ่านเพิ่มเติมใน ข้อกำหนดการใช้งาน