OPEN-SOURCE SCRIPT

Strong KNN Classifier | ProjectSyndicate

3 450
Strong KNN Classifier reads the order flow underneath each bar and asks one question: is the current move more likely to CONTINUE or to REVERSE? Instead of guessing, it learns from the market's own history. Every bar is turned into a five-part order-flow fingerprint, stored with the outcome it actually produced, and the live bar is matched against the closest past situations using Lorentzian distance — the outlier-robust metric built for noisy market data. The nearest neighbours vote, that vote is calibrated into an honest probability, and only genuinely confident reads near structural zones are printed as signals. Every prediction that resolves is scored on a live hit-rate panel — winners and misses alike — so you see exactly how the logic behaves on the symbol and timeframe you trade, not a number typed into a description.

🧠 Lorentzian Core — the core idea, expressed as a lifecycle: OBSERVE ▸ LABEL ▸ LEARN ▸ CLASSIFY ▸ CALIBRATE. Each bar is reduced to five order-flow features and z-scored so they share one scale. A rolling library of past feature vectors is kept, and each one is labelled only after its outcome is fully known — a vector formed H bars ago is tagged CONTINUATION or REVERSAL using bars that have already printed, never future ones. The live bar is then compared to that resolved library with Lorentzian-distance k-nearest-neighbours, the closest matches vote, and the result is turned into a probability. Because every label is resolved from past bars and every signal confirms on the bar's close, the classifier does not repaint.

🔋 Feature Anatomy — the fingerprint is not one number; it is five breakout-native ingredients fused into a single distance. Net delta (reconstructed buy-minus-sell pressure), bid/ask imbalance (which side dominated the bar), absorption (heavy volume that produces little price progress — a stalled push), CVD slope (the direction and steepness of cumulative delta), and price location versus VWAP in ATR units (where the bar sits inside its structural range). Each feature is independently z-scored over a rolling window, so no single raw scale can dominate the match. Order-flow components are reconstructed from lower-timeframe intrabar data and are labelled as estimates, not exchange tick prints.

🎯 Calibrated Probability Engine — this is the part most "AI" scripts get wrong. A raw k-vote can only land on a handful of fractions, so it slams to 88% or 100% and lies about its own confidence. Strong KNN Classifier instead weights each neighbour by distance, collapses the vote into a signed margin, shrinks that margin toward a neutral 0.5 prior by how much trustworthy neighbour mass actually agreed, and passes it through a logistic curve. The output is a smooth, continuous Reversal Probability and a 0–100 Confidence read that reflect genuine neighbour agreement — high only when many close matches concur, honestly near the middle when they don't.

🧲 Structural-Zone Context — a classification matters most where decisions are made: at the levels where price interacts with resting structure. The engine only promotes a read to a signal when price is inside a structural zone — within an ATR band of VWAP or of the most recent confirmed swing pivot. Away from structure the model still reports its read on the dashboard, but it holds its fire, keeping orbs anchored to the moments that carry context rather than scattering them mid-range.

🎚️ Conviction Controls — a compact set of dials sets how serious a read must be before it prints: the Minimum Confidence to signal, the number of Neighbours (k) that vote, the Prior Strength that shrinks weak agreement toward neutral, the Probability Sharpness that scales the confidence spread, the Distance Temperature that softens or sharpens neighbour weighting, the minimum sample count before any signal is allowed, and a cooldown. Tighten them for fewer, cleaner classifications; loosen them for more activity. Together with the zone gate, this is your main control over conviction versus frequency.

🧭 No-Lookahead Discipline — a read is not allowed to cheat. Training labels are resolved purely from bars that have already closed, the live bar is only ever compared against fully-resolved neighbours, and signals confirm on the closed candle. Until the library holds enough resolved samples the panel shows TRAINING and stays silent, and a cooldown stops a single chaotic session from stacking overlapping orbs. The hit-rate tracker is held to the same standard — every prediction whose horizon resolves is counted, correct or not, with nothing dropped to flatter the number.

⭐ 0–100 Confidence Read — every classification carries a numeric Reversal Probability, a Confidence score, and the count of neighbours that actually contributed. Treat Confidence as a relative cleanliness and agreement read for ranking and thinning signals — it describes how textbook the current situation is versus the model's memory, not a guaranteed outcome. The confidence threshold restricts what is displayed and alerted, while the dashboard keeps reporting the live read in the background even when no signal fires.

📊 Live Statistics Dashboard — a non-intrusive panel tracks, in real time on your chart: model status (TRAINING or LIVE) with the current training-pool size, the order-flow source in use, each of the five features as a live z-score, the current Prediction (continuation / reversal / neutral), the Reversal Probability, the Confidence, the number of neighbours used, whether price is currently inside a structural zone, and a rolling Hit-Rate computed over every resolved prediction. The hit-rate counts winners and misses in full, so the number is built live from the real signals on your current symbol and timeframe — not printed here in advance.

🎨 Clean Themed Visuals — four coherent palettes (Aurora default, plus Neon, Plasma, and Solar) shade the probability ribbon, the class-tinted candles, the signal orbs and their chips, and the dashboard to one look, so direction and quality read at a glance on a dark chart. A background ribbon graduates between the continuation and reversal colours by probability; confirmed signals print a sized circular orb with a clean, non-overlapping chip showing direction, probability, and the neighbour/confidence read. Signal dot size is adjustable, and the chip offset scales with it so labels never collide with the orb.

🔔 Detailed Alerts — fires on a continuation signal, on a reversal signal, and on any high-confidence classification, formatted for manual or automated use. The confidence threshold and the in-zone gate restrict alerts to higher-conviction reads.

🔧 Fully Customizable — every component is exposed: the number of neighbours, the outcome horizon, the trend-reference length, the outcome threshold in ATR, and the maximum and minimum training-pool sizes; the distance temperature, prior strength, and probability sharpness that govern calibration; the normalisation window, CVD slope length, and absorption reference of the feature engine; the intrabar resolution and volume weighting of the order-flow reconstruction; the VWAP and swing-pivot zones, pivot length, and zone width; the confidence threshold, in-zone requirement, and cooldown; all four themes and every ribbon, candle-tint, orb, dot-size, neighbour-chip, and dashboard toggle, plus dashboard position and size.

🎯 Why this is different — most "machine learning" indicators are black boxes that restyle an oscillator and claim to call the top, and most kNN scripts publish a confidence that is really just a vote fraction in disguise. This one engineers inspectable order-flow features, matches them with an outlier-robust Lorentzian metric, and then does the part that is usually skipped: it calibrates the probability so confidence reflects real, distance-weighted neighbour agreement instead of a coarse vote artefact. It resolves every training label with no lookahead, gates signals to structural context, and reports a live, honest hit-rate that counts misses in full — so you judge it on your own current data rather than on a marketing figure.

🚀 Where to use it — the engine is symbol-agnostic and built on universal order-flow behaviour, so it can be applied to FX majors and crosses, metals, indices, and crypto on intraday timeframes. It is strongest where lower-timeframe order-flow reconstruction carries information — liquid intraday futures and crypto — and the normalisation and ATR scaling adapt to each instrument automatically. One practical check: if the five features all read 0σ, your chart's symbol is not exposing intrabar data and the model is running on the coarse bar-level fallback — set the Intrabar Resolution explicitly and confirm the features come alive before relying on signals. Because the classifier is symmetric, let the dashboard's hit-rate tell you whether the logic genuinely suits the pair and timeframe before you commit.

🎯 How to trade it

1 Apply it to a liquid symbol on an intraday timeframe and let the panel move from TRAINING to LIVE as the library fills. Read the live Hit-Rate for your symbol and timeframe first — if the logic doesn't suit that market, you'll see it.

2 Wait for an orb — it marks a confirmed close, above your confidence threshold, inside a structural zone, with the direction, probability, and neighbour/confidence read already labelled.

3 Read the dashboard alongside it: the Prediction, the Reversal Probability, the Confidence, and how many of the k neighbours actually agreed.

4 Use the confidence threshold, neighbour count, prior strength, and sharpness to set your tempo — stricter for fewer, cleaner reads; looser for more activity.

5 Combine the classification with your own structure and risk management — it is a read on the next move's character, not an entry-and-exit system on its own.

⚠️ Important — this is a decision-support tool, not a standalone buy/sell system, and it makes no performance guarantees. The probability is calibrated to reflect genuine neighbour agreement, but the underlying edge varies by market, session, and configuration, and on some symbols and timeframes it will be close to neutral — the displayed probability and the dashboard hit-rate are historical and descriptive, not a forecast. Order-flow features are reconstructed from lower-timeframe data and are estimates, not true tick prints; where intrabar data is unavailable the model falls back to a coarser delta. Signals confirm on the closed bar, so always wait for the orb on a closed candle. Because the classifier is symmetric and contrarian-capable, a strong one-way trend or a regime shift can run straight through a high-confidence read — combine it with your own analysis, and test it on your market before trading it live.

Haftungsausschluss

Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.