Indicator · Pine Script v6 · On the chart

kNN Classifier

by jayadevrana

This indicator implements a k-nearest neighbours classification model to forecast price direction several bars ahead.

View on GitHub

GitHub stars1on the repository
Pine versionv6current
Lines of code103
Settings5inputs
LicenceMPL-2.0
Last update2 days ago26 Oct 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

103 lines of Pine Script v6 from scripts/knn-classifier.pine.txt, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.

knn-classifier.pine.txt
//@version=6
indicator("kNN Classifier", overlay = true, max_bars_back = 500)

horizon = input.int(4, "Bars ahead to predict", minval = 1, maxval = 50)
k = input.int(9, "Neighbours (k)", minval = 1, maxval = 50)
maxTrain = input.int(500, "Training memory", minval = 50, maxval = 1000)
window = input.int(1500, "Predict window", minval = 100, maxval = 3000)
useLorentz = input.bool(true, "Lorentzian distance")

clamp(x) => math.max(-1.0, math.min(1.0, x))
atr = ta.atr(14)
f1 = (ta.rsi(close, 14) - 50) / 50
f2 = clamp((ta.ema(close, 8) - ta.ema(close, 34)) / (2 * atr))
f3 = clamp((high - low) / atr - 1)

type Sample
    float a
    float b
    float c
    float entry
    int bar
    int pred
    int label

var array<Sample> pending = array.new<Sample>()
var array<Sample> train = array.new<Sample>()
var int scored = 0
var int hits = 0
var int ups = 0

while array.size(pending) > 0
    if array.first(pending).bar > bar_index - horizon
        break
    Sample s = array.shift(pending)
    s.label := close > s.entry ? 1 : 0
    array.push(train, s)
    if s.pred != 0
        scored += 1
        hits += (s.pred == 1) == (s.label == 1) ? 1 : 0
        ups += s.label
while array.size(train) > maxTrain
    array.shift(train)

dist(Sample s, float a, float b, float c) =>
    da = math.abs(s.a - a)
    db = math.abs(s.b - b)
    dc = math.abs(s.c - c)
    useLorentz ? math.log(1 + da) + math.log(1 + db) + math.log(1 + dc) :
      math.sqrt(da * da + db * db + dc * dc)

int pred = 0
float conf = 0.0
ok = not na(f1) and not na(f2) and not na(f3)
live = bar_index > last_bar_index - window
if ok and live and array.size(train) >= k
    kd = array.new<float>()
    kl = array.new<int>()
    for s in train
        d = dist(s, f1, f2, f3)
        if array.size(kd) < k
            array.push(kd, d)
            array.push(kl, s.label)
        else if d < array.max(kd)
            w = array.indexof(kd, array.max(kd))
            array.set(kd, w, d)
            array.set(kl, w, s.label)
    up = array.sum(kl)
    pred := up * 2 > k ? 1 : up * 2 < k ? -1 : 0
    conf := math.abs(up * 2 - k) / float(k)

if ok
    array.push(pending, Sample.new(f1, f2, f3, close, bar_index, pred, na))

transp = 92 - conf * 50
bgcolor(pred == 1 ? color.new(color.green, transp) :
  pred == -1 ? color.new(color.red, transp) : na, title = "Prediction")
flipUp = pred == 1 and pred[1] == -1
flipDn = pred == -1 and pred[1] == 1
plotshape(flipUp, "Flip up", shape.triangleup, location.belowbar,
  color.new(color.green, 0), size = size.tiny)
plotshape(flipDn, "Flip down", shape.triangledown, location.abovebar,
  color.new(color.red, 0), size = size.tiny)

var table t = table.new(position.top_right, 2, 6,
  bgcolor = color.new(color.black, 15), border_width = 1)
row(r, name, val, col) =>
    table.cell(t, 0, r, name, text_color = color.white)
    table.cell(t, 1, r, val, text_color = col)

if barstate.islast
    modelHit = scored > 0 ? 100.0 * hits / scored : na
    baseHit = scored > 0 ? 100.0 * ups / scored : na
    edge = modelHit - baseHit
    now = pred == 1 ? "UP" : pred == -1 ? "DOWN" : "none"
    row(0, "Scored predictions", str.tostring(scored), color.white)
    row(1, "k-NN hit rate", str.tostring(modelHit, "#.0") + "%", color.white)
    row(2, "Always up hit rate", str.tostring(baseHit, "#.0") + "%",
      color.white)
    row(3, "Edge vs baseline", str.tostring(edge, "+#.0;-#.0") + " pts",
      edge > 0 ? color.lime : color.red)
    row(4, "Training points", str.tostring(array.size(train)), color.white)
    row(5, "Prediction now", now + str.format(" ({0,number,percent})", conf),
      color.yellow)

Overview

kNN Classifier extracts three normalized technical features: RSI, an EMA spread scaled by ATR, and normalized candle range volatility. Historical samples are matched using either Lorentzian or Euclidean distance metrics. The indicator colors the chart background green for bullish forecasts and red for bearish forecasts, adjusting opacity according to model confidence, and plots triangle markers on directional flips. A corner dashboard table displays evaluated prediction counts, hit rate, and edge over baseline.

Details

Published by

jayadevrana on GitHub

Type

Indicator, Pine Script v6

Draws

On the price chart

Category

AI / machine learning, Trend, Oscillators & momentum

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

algorithmic-tradingbacktestingema-crossoverpine-scriptpine-script-v6pinescriptrsitechnical-analysistrading-automationtrading-indicators

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Bars ahead to predictint4horizon
Neighbours (k)int9k
Training memoryint500maxTrain
Predict windowint1500window
Lorentzian distancebooltrueuseLorentz
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

257 stars

This indicator uses a Lorentzian distance k-nearest neighbors classification algorithm to predict market direction based on up to five technical features, such as RSI, WaveTrend, CCI, and ADX. It compares current feature values against historical bar patterns

Indicator v5 AI / machine learningOscillators & momentum
Updated 6 weeks ago · None stated GitHub repository of Donald - Machine Learning Options

This indicator applies a k-nearest neighbours (kNN) classification algorithm using Aroon indicator lags and momentum as feature inputs to forecast market direction. It compares current values against historical feature sets to classify bars into buy, hold, or

Indicator v4 AI / machine learningTrend Repaints
Updated 1 year ago · None stated GitHub repository of Machine Learning: kNN-based Strategy (aroon)

Machine Learning: Lorentzian Classification

by artificial-intelligence-edge
75 stars

An overlay indicator that applies a k-nearest-neighbors machine learning classifier using Lorentzian distance to predict price movement. It evaluates historical market features, such as RSI, WaveTrend, CCI, and ADX, to identify similar price-time patterns and

Indicator v6 AI / machine learningOscillators & momentum
Updated 2 days ago · MIT GitHub repository of Machine Learning: Lorentzian Classification

ML Decision Tree Classifier

by haydarkadioglu
1 stars

The ML Decision Tree Classifier uses rule-based decision tree logic to evaluate trend, momentum, volume, and MACD indicators for market direction classification. It calculates exponential moving averages, relative strength index values, volume relative to a mo

Indicator v5 AI / machine learningTrend
Updated 8 months ago · None stated GitHub repository of ML Decision Tree Classifier

This indicator plots an oscillator in a separate pane. It builds several SuperTrend series across a user-defined factor range and step, using ATR as the band width. On each bar it measures the distance between the close and each SuperTrend output, then groups

Indicator v5 TrendVolatility & bands
Updated 2 years ago · GPL-3.0 GitHub repository of AI SuperTrend Clustering Oscillator [LuxAlgo]

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers