Machine Learning - Lorentzian KNN Classifier (Update) — Strategy by Mark_Novak
By Mark_Novak
Performance Metrics
- Author: Mark_Novak
- Symbol: OANDA:XAGUSD
- Timeframe: 1 hour
- Net P&L: +41,305.67 USD (+4.13%)
- Win Rate: 65.7%
- Profit Factor: 1.417
- Max Drawdown: 15,162.11 USD (1.44%)
- Total Trades: 207
Description
══════════════════════════════════════════TRADINGVIEW DESCRIPTION══════════════════════════════════════════SHORT DESCRIPTION:Non-repainting ML classifier using Lorentzian distance metric with 4-feature KNN, kernel regression envelope, multi-layer confluence scoring, and AI Trade Quality Grade. Updated v2.0.══════════════════════════════════════════FULL DESCRIPTION:══════════════════════════════════════════█ UPDATE v2.0 — CRITICAL IMPROVEMENTSThis is a major update to the Lorentzian KNN Classifier strategy. The previous version contained a repainting issue that inflated backtest results. This has been fully resolved:✦ calc_on_every_tick disabled — all calculations on confirmed (closed) bars only✦ Entry conditions gated by barstate.isconfirmed — no mid-bar decisions✦ Trailing stop values properly converted to ticks via syminfo.mintick✦ Backtest results now reflect realistic, achievable performanceIf you were using the previous version, please update immediately. Live trading results will now match what the backtest shows.█ WHAT IS THIS?A machine learning classification strategy that uses the Lorentzian distance metric — a non-Euclidean measure better suited for financial time series than traditional Euclidean distance. The classifier analyzes 4 normalized features across a sliding training window and predicts short-term price direction using inverse-distance-weighted K-Nearest Neighbors voting.█ HOW THE KNN CLASSIFIER WORKSThe Lorentzian distance between two points is calculated as:d(x, y) = Σ log(1 + |xᵢ − yᵢ|)Unlike Euclidean distance, Lorentzian distance is less sensitive to outliers in individual features — a property that makes it more robust for noisy financial data.The classifier uses 4 features, each z-score normalized over 50 bars:• RSI (default 14) — momentum oscillator• WaveTrend (LazyBear, channel 10, average 21) — cycle detection• CCI (default 20) — mean reversion pressure• ADX (default 14) — trend strengthFor each bar, the algorithm scans a training window (default 50 bars back) and computes the Lorentzian distance to every historical bar. Each neighbor casts a weighted vote (weight = 1/distance) based on its 5-bar forward return label. The aggregate bull vs bear vote produces a score smoothed by EMA(3).KNN Score > +0.1 → BULL classificationKNN Score < −0.1 → BEAR classificationOtherwise → NEUTRAL█ NEW: AI TRADE QUALITY GRADEEvery signal receives a letter grade from A+ to F, calculated from three components:• KNN Confidence (40%) — how decisive the classifier vote was• Confluence Score (35%) — how many independent filters agree (MTF, Ribbon, Order Flow, Smart Money, ADX)• Regime Fitness (25%) — whether market conditions match the strategy type (trending market + trend signal = high fitness)Grade interpretation:A+ / A → High-conviction setup, all systems alignedB → Good setup, minor disagreementsC → Marginal, proceed with cautionD / F → Weak setup, consider skippingThe grade appears on entry labels ("BUY A+", "SELL B") and in alert messages, giving you an instant read on trade quality without analyzing the dashboard.█ MULTI-LAYER CONFLUENCE ENGINEThe strategy combines 3 entry types with 5 institutional-grade filters:Entry Types:• Trend Following — EMA 21/50 crossover + EMA 200 direction + volume spike• Breakout — Donchian channel break + volume confirmation• Mean Reversion — Bollinger Band extreme + RSI reversal (ranging markets only)Filters (each independently toggleable):• MTF Filter — higher timeframe EMA alignment (default 4H)• MA Ribbon — 8-layer Fibonacci ribbon (8/13/21/34/55/89/144/233) with alignment threshold• Order Flow — VWAP position + CVD divergence + volume delta analysis• Smart Money Concepts — Order blocks, fair value gaps, liquidity sweeps, BOS/CHoCH, demand/supply zones• Volatility Regime — Bollinger Band width expansion/contraction + ATR percentile rankingConfluence score: 0–5.55 (5 base filters + KNN weight 0.55)█ KERNEL REGRESSION ENVELOPEVisual overlay showing an EMA-based kernel center with ATR-scaled bands (±0.5σ to ±3σ). Green gradient above center, red gradient below. Provides instant visual context for where price sits relative to the statistical envelope.█ RISK MANAGEMENT• ATR-based stop loss (default 2.0x ATR)• ATR-based take profit (default 3.0x ATR)• Optional trailing stop (default 1.5x ATR activation)• Session time filter• All values properly tick-normalized for accurate backtesting█ DASHBOARDLight-themed panel (bottom-right) showing:• AI Trade Quality Grade (prominent, color-coded)• KNN classification + confidence %• Feature values (RSI/WT/CCI/ADX)• Win rate, profit factor, R:R ratio• Multi-timeframe trend alignment (15m/1h/4h)• Ribbon, Smart Money, Volatility status• Volume pressure analysis• Demand/Supply zone count• Current session indicator• Active signal with SL/TP levels█ USAGE NOTES• Works on any instrument and timeframe• Best results on 15m–4H for intraday/swing trading• All filters can be individually enabled/disabled• KNN lookback window (20–100) trades off speed vs accuracy• Gradient candle coloring provides additional visual momentum context• The strategy does NOT repaint — what you see in backtest is what you get live█ CHANGELOGv2.0 (current):— Fixed repainting: calc_on_every_tick=false + barstate.isconfirmed gate— Fixed trailing stop tick conversion (/ syminfo.mintick)— Added AI Trade Quality Grade (A+/A/B/C/D/F)— Light dashboard theme, repositioned to bottom-right— Compact layout (18 rows vs 22)— Grade shown on entry labels and alerts— barstate.islast → barstate.islastconfirmedhistory for dashboardv1.0:— Initial release with Lorentzian KNN, kernel envelope, SMC, order flow