kNN Machine Learning EA
k-Nearest Neighbors classification in MQL5. Four features. Majority vote. No black box.
A fully automated MT5 port of capissimo's Machine Learning: kNN-based Strategy TradingView indicator. The EA constructs a 2D feature space from four classic technical indicators — RSI, CCI, ROC, and Volume — tags every historical bar with the direction that followed it, then on each closed bar finds the k most similar historical conditions by Euclidean distance and takes a majority vote of their directional labels. Trades are entered or reversed only when the consensus flips, preventing overtrading during sustained moves. Ships with volatility and session filters, comprehensive trade management, and five tuned preset profiles.
What makes it different.
- Real k-Nearest Neighbors classifier — not a rebranded moving-average crossover. Euclidean distance in a 2D feature space, majority vote, no-repaint closed-bar logic
- Four diversified features — RSI (momentum), CCI (mean reversion), ROC (trend change), Volume (participation) — captures a richer slice of market state than single-indicator systems
- Bar-close logic — all distances, votes, and signals are computed exclusively on closed bars; backtest and live performance match tightly across brokers
- Transparent prediction score — on-chart dashboard displays the live neighbor vote, per-feature values, training sample count, and current signal confidence
- Volatility filter — blocks entries during ATR-collapse regimes where pattern-matching loses edge
- Session filter — configurable Asia/London/NY gates with custom hour ranges and per-weekday flags
- Full trade management — percent-risk or fixed-lot sizing, fixed or ATR-based stops, R:R-multiple take-profit, break-even trigger, optional trailing stop
- Five ready-to-trade .set profiles — M15 Scalper, H1 Swing (recommended), H4 Position, D1 Long-Term, XAUUSD Specialist
- Prop-firm compatible — daily-loss circuit breaker, max-DD kill switch, and a built-in evaluation-account preset that caps risk at 0.5%
- Works across forex, metals, indices, and crypto — the algorithm is non-parametric and makes no distributional assumptions about the underlying market
Simulated on $10k starting equity at the stated CAGR. Past performance does not guarantee future results. See risk disclosure.
Every input, documented.
| Parameter | Default | What it controls |
|---|---|---|
| K_Neighbors | 5 | Number of nearest neighbors used in the majority vote. Odd values avoid tie handling. |
| TrainingBars | 500 | How many historical bars form the training set for each new prediction. |
| RSIPeriod | 14 | Lookback for the RSI feature axis. |
| CCIPeriod | 20 | Lookback for the CCI feature axis. |
| ROCPeriod | 10 | Lookback for the Rate-of-Change feature axis. |
| VolumePeriod | 20 | Smoothing length for the normalized volume feature. |
| UseVolatilityFilter | true | Blocks new entries when ATR falls below a rolling threshold — pattern matching weakens in dead markets. |
| VolatilityATRPeriod | 14 | ATR lookback used by the volatility filter. |
| RiskPerTradePct | 1.0 | Equity fraction risked per trade. 0.5 recommended for prop-firm evaluations. |
| StopLossMode | ATR | Fixed points or ATR multiple. ATR is recommended for symbols with variable volatility (XAUUSD, indices, crypto). |
| ATRStopMult | 2.0 | Stop distance as a multiple of ATR when ATR mode is active. |
| RRRatio | 2.0 | Take-profit as a multiple of the stop. 2.0 is the prop-firm-friendly default. |
| UseBreakEven | true | Move stop to entry once price reaches the configured R-multiple. |
| UseTrailingStop | false | Optional ATR-based trailing stop. Off by default — the classifier's reverse signal usually exits first. |
| DailyLossCapPct | 3.0 | Kill-switch: halts trading for the rest of the day if equity drops this much. |
| UseSessionFilter | false | Restricts entries to a configured server-time window. |
| MaxSpreadPoints | 25 | Blocks entries when the spread exceeds this threshold. |
| MagicNumber | 20260422 | Unique identifier for this instance. Change per chart for multi-symbol deployment. |
Full parameter reference in the PDF user guide included with your license.
Frequently asked.
Is this actually machine learning?
Yes. k-Nearest Neighbors is a non-parametric supervised classifier. On every closed bar, the EA builds a fresh training set of the last N bars, tags each one with the direction of the bar that followed, then finds the k Euclidean-nearest examples to the current feature vector. The predicted direction is the majority vote of those neighbors. No curve fitting, no black box, no neural network mystery.
Why only four features?
Curse of dimensionality. kNN performance degrades rapidly as feature count grows — at 10+ dimensions, nearly every point is equidistant and the vote becomes random. Four carefully-chosen features (one per behavioral regime: momentum, mean reversion, trend change, participation) gives the best signal-to-noise on financial time series.
Does it repaint?
No. All features are computed on closed bars, all distance calculations use closed-bar values, and the vote is locked at bar close. Signals never move once printed.
How often does it trade?
A signal is produced every bar, but trades are only placed on direction changes. On H1 EURUSD you typically see 3-7 trades per week. On M15 XAUUSD, 15-25 per week. Frequency scales with volatility, not with time.
Which profile should I start with?
H1 Swing is the best starting point — clean feature signals without M15 noise or H4 lag. XAUUSD Specialist is tuned with larger ATR multiples for gold's fat tails.
Is it prop-firm safe?
Yes. The daily-loss kill switch, max-spread filter, and 0.5% risk preset are designed for FTMO-style challenges. The classifier's natural trade frequency fits within typical minimum-trading-days rules.
What is the difference between this and the Lorentzian Classification EA?
Distance metric and feature set. Lorentzian uses five features (RSI, WT, CCI, ADX, second RSI) with a log-transformed L1 distance, plus a kernel regression filter. kNN ML uses four features (RSI, CCI, ROC, Volume) with standard Euclidean distance. Lorentzian is more sensitive and has a tighter kernel filter; kNN is simpler, more transparent, and easier to reason about. Both are valid — Lorentzian wins on ranging instruments, kNN tends to win on trending crypto and indices.
Does it work on MT4?
No — MT5 only.
Ready to run kNN Machine Learning EA?
Lifetime license. All presets included. Direct developer support.