Indicator · Pine Script v4 · On the chart

Machine Learning: kNN-based Strategy (aroon)

by capissimo

This indicator applies a k-nearest neighbours (kNN) classification algorithm using Aroon indicator lags and momentum as feature inputs to forecast market direction.

View on GitHub

Repaints

GitHub stars114on the repository
Pine versionv4older, still runs
Lines of code248
Settings9inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago7 Nov 2024

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

248 lines of Pine Script v4 from scripts/111-ML-kNN-based-Strategy-(aroon).pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

111-ML-kNN-based-Strategy-(aroon).pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © capissimo

//@version=4
study('Machine Learning: kNN-based Strategy (aroon)', '', true, precision=4, max_labels_count=200)

// kNN-based Strategy (FX and Crypto)
// Description: 
// This strategy uses a classic machine learning algorithm - k Nearest Neighbours (kNN) - 
// to let you find a prediction for the next (tomorrow's, next month's, etc.) market move. 
// Being an unsupervised machine learning algorithm, kNN is one of the most simple learning algorithms. 

// To do a prediction of the next market move, the kNN algorithm uses the historic data, 
// collected in 3 arrays - feature1, feature2 and directions, - and finds the k-nearest 
// neighbours of the current indicator(s) values. 

// The two dimensional kNN algorithm just has a look on what has happened in the past when 
// the two indicators had a similar level. It then looks at the k nearest neighbours, 
// sees their state and thus classifies the current point.

// The kNN algorithm offers a framework to test all kinds of indicators easily to see if they 
// have got any *predictive value*. One can easily add cog, wpr and others.
// Note: TradingViews's playback feature helps to see this strategy in action.
// Warning: Signals ARE repainting.

/////////////////////////////////////////////////////////////////////////////////
// This update to the popular kNN-based strategy features:
//     improvements in the business logic,
//     adjustible k value for the kNN model, 
//     one more feature (MOM),
//     streamlined filter and 
//     some other minor fixes.

// Now this script works in all timeframes and does not repaint !

/////////////////////////////////////////////////////////////////////////////////

// Style tags: Trend Following, Trend Analysis
// Asset class: Equities, Futures, ETFs, Currencies and Commodities
// Dataset: FX Minutes (1M,3M,5M - for scalpers) / Hours+++ (1H,3H,4H) / Days-

//-------------------- Inputs

K           = input(63,    'K Value for kNN Model |2..n|', minval=2)
shortlag    = input(5,     'Short Aroon Lag |1..n|',       minval=1)
longlag     = input(10,    'Long Aroon Lag |1..n|',        minval=1)
HighLevel   = input(90,    'Overbought Level |1..n|',      minval=1)
LowLevel    = input(10,    'Oversold Level |1..n|',        minval=1)
ftype       = input('Both','Filter Signals by',            options=['Volatility','Volume','Both','None'])
holding_p   = input(1,     'Holding Period |1..n|',        minval=1)

// startYear   = input(2000,  'Training Start Year',          minval=2000)
// startMonth  = input(1,     'Training Start Month',         minval=1, maxval=12)
// startDay    = input(1,     'Training Start Day',           minval=1, maxval=31)
// stopYear    = input(2021,  'Training Stop Year',           minval=2000)
// stopMonth   = input(12,    'Training Stop Month',          minval=1, maxval=12)
// stopDay     = input(31,    'Training Stop Day',            minval=1, maxval=31)

//-------------------- Global Variables

var float k          = floor(sqrt(K))  
var int   BUY        =  1
var int   SELL       = -1
var int   HOLD       =  0
var int   hp_counter =  0

//-------------------- Custom Functions

cAqua(g) =>  g>9?#0080FFff : g>8?#0080FFe5 : g>7?#0080FFcc : g>6?#0080FFb2 : g>5?#0080FF99
           : g>4?#0080FF7f : g>3?#0080FF66 : g>2?#0080FF4c : g>1?#0080FF33 : #00C0FF19
cPink(g) =>  g>9?#FF0080ff : g>8?#FF0080e5 : g>7?#FF0080cc : g>6?#FF0080b2 : g>5?#FF008099
           : g>4?#FF00807f : g>3?#FF008066 : g>2?#FF00804c : g>1?#FF008033 : #FF008019

volumeBreak(thres) =>  
    rsivol   = rsi(volume, 14)  
    osc      = hma(rsivol, 10)  
    osc > thres                     

volatilityBreak(volmin, volmax) => atr(volmin) > atr(volmax)

aroon(lag) =>
    bulls = 100 * (highestbars(high, lag+1) + lag) / lag
    bears = 100 * (lowestbars(low, lag+1)   + lag) / lag
    (bulls>HighLevel and bears<LowLevel) ? 1 : (bulls<LowLevel and bears>HighLevel) ? -1 : 0

scale(x, p) => (x - lowest(x, p)) / (highest(x, p) - lowest(x, p)) //-- scale to the range of [0..1]

//-------------------- Logic

// periodStart = timestamp(startYear, startMonth, startDay, 0, 0)
// periodStop  = timestamp(stopYear,  stopMonth,  stopDay,  0, 0)

// Predictor indicators, long and short each
f1 = scale(aroon(longlag), K) * 100
f2 = scale(aroon(shortlag), K) * 100

// Classification data, what happens on the next bar
class = close[1]<close[0] ? SELL: close[1]>close[0] ? BUY : HOLD

// Training data, normalized to the range of [0,...,100]
var feature1   = array.new_float(0)  // [0,...,100]
var feature2   = array.new_float(0)  //    ...
var directions = array.new_int(0)    // [-1; 0; +1]

// Result data
var predictions = array.new_int(0)
var prediction  = 0.
var signal      = HOLD

// Use particular training period
//if time >= periodStart and time <= periodStop

// Store everything in arrays. Features represent a square 100 x 100 matrix,
// whose row-colum intersections represent class labels, showing historic directions
array.push(feature1, f1)
array.push(feature2, f2)
array.push(directions, class)

// Ucomment the followng statement (if barstate.islast) and tab everything below
// between BOBlock and EOBlock marks to see just the recent several signals gradually 
// showing up, rather than all the preceding signals

//if barstate.islast   

//==BOBlock    

// Core logic of the algorithm

size    = array.size(directions)
maxdist = -999.

// Loop through the training arrays, getting distances and corresponding directions.
for i=0 to size-1
    // Calculate the euclidean distance of current point to all historic points,
    // here the metric used might as well be a manhattan distance or any other.
    d = sqrt(pow(f1 - array.get(feature1, i), 2) + pow(f2 - array.get(feature2, i), 2))
    
    if d > maxdist
        maxdist := d
        if array.size(predictions) > k
            array.shift(predictions)
        array.push(predictions, array.get(directions, i))
        
//==EOBlock    

// Note: in this setup there's no need for distances array (i.e. array.push(distances, d)),
//       but the drawback is that a sudden max value may shadow all the subsequent values.
// One of the ways to bypass this is to:
// 1) store d in distances array,
// 2) calculate newdirs = bubbleSort(distances, directions), and then 
// 3) take a slice with array.slice(newdirs) from the end
        
// Get the overall prediction of the k nearest neighbours model
prediction := array.sum(predictions)   
    
// Now that we got a prediction for the next market move, we need to make use of this prediction and 
// trade it. The returns then will show if everything works as predicted.
// Over here is a simple long/short interpretation of the prediction, 
// but of course one could also use the quality of the prediction (+5 or +1) in some sort of way,
// ex. for position sizing.
    
filter =   ftype=='Volatility' ? volatilityBreak(1, 10) 
         : ftype=='Volume'     ? volumeBreak(49) 
         : ftype=='Both'       ? volatilityBreak(1, 10) and volumeBreak(49)
         :                       true
         
signal := prediction > 0 and filter ? BUY : prediction < 0 and filter ? SELL : nz(signal[1])  // HOLD

changed = change(signal)

hp_counter := changed ? 0 : hp_counter + 1

startLongTrade  = changed and signal==BUY    
startShortTrade = changed and signal==SELL   
endLongTrade    = (changed and signal==SELL) or (signal==BUY  and hp_counter==holding_p and not changed) 
endShortTrade   = (changed and signal==BUY)  or (signal==SELL and hp_counter==holding_p and not changed) 

//-------------------- Rendering

plotshape(startLongTrade  ? low  : na, 'Buy',  shape.labelup,   location.belowbar, cAqua(prediction*2),  text='a', textcolor=color.white, size=size.tiny)  // color intensity correction
plotshape(startShortTrade ? high : na, 'Sell', shape.labeldown, location.abovebar, cPink(-prediction*2), text='a', textcolor=color.white, size=size.tiny)
plot(endLongTrade         ? high : na, 'StopBuy',  cAqua(6), 2, plot.style_cross)
plot(endShortTrade        ? low  : na, 'StopSell', cPink(6), 2, plot.style_cross)

//-------------------- Notification

if changed and signal==BUY 
    alert("Buy Alert", alert.freq_once_per_bar)  // alert.freq_once_per_bar_close
if changed and signal==SELL 
    alert("Sell Alert", alert.freq_once_per_bar)
    
alertcondition(startLongTrade,  "Buy Alert",  "Go Long!")
alertcondition(startShortTrade, "Sell Alert", "Go Short!")

//-------------------- Backtesting

show_info = input(true, '===Information===')
lot_size  = input(0.01,  'Lot Size', options=[0.01,0.1,0.2,0.3,0.5,1,2,3,5,10,20,30,50,100,1000]) 

tbase   = (time - time[1]) / 1000
tcurr   = (timenow - time_close[1]) / 1000
barlife = tcurr / tbase

bidask  = (open+high+low)/3

var float start_long_trade  = bidask  
var float long_trades       = 0.
var float start_short_trade = bidask  
var float short_trades      = 0.
var int   wins              = 0
var int   trade_count       = 0

if startLongTrade 
    start_long_trade := bidask 
if endLongTrade
    ldiff         = (bidask - start_long_trade)
    wins         := ldiff > 0 ? 1 : 0
    long_trades  := ldiff * lot_size   
    trade_count  := 1
if startShortTrade 
    start_short_trade := bidask
if endShortTrade
    sdiff         = (start_short_trade - bidask)
    wins         := sdiff > 0 ? 1 : 0
    short_trades := sdiff * lot_size 
    trade_count  := 1
    
cumreturn   = cum(long_trades) + cum(short_trades)  //-- cumulative return 
totaltrades = cum(trade_count)
totalwins   = cum(wins)  
totallosses = totaltrades - totalwins == 0 ? 1 : totaltrades - totalwins

//------------------- Information

var label lbl = na

info =  'K Value: '    + tostring(K, '#') + ' (' + tostring(k, '#.##') + ')'
      + '\nHPeriod: '  + tostring(holding_p,             '#') 
      + '\nCR='        + tostring(cumreturn,             '#.#') 
      + '\nTrades: '   + tostring(totaltrades,           '#')
      + '\nWin/Loss: ' + tostring(totalwins/totallosses, '#.##') 
      + '\nWinrate: '  + tostring(totalwins/totaltrades, '#.#%')       
      + '\nBar Time: ' + tostring(barlife,               '#.#%')

if show_info and barstate.islast  
    lbl := label.new(bar_index, ohlc4, info, xloc.bar_index, yloc.price, 
                     color.new(color.blue, 100), label.style_label_left, color.black, size.small, text.align_left)
    label.delete(lbl[1])

Overview

Machine Learning: kNN-based Strategy (aroon) compares current values against historical feature sets to classify bars into buy, hold, or sell signals, plotting directional markers directly on the price chart. Users can configure the kNN neighbor count, Aroon lag parameters, overbought and oversold thresholds, holding period, and optional volume or volatility signal filters. Although labeled as a strategy in its title, it functions as a study without automated order execution.

Details

Published by

capissimo on GitHub

Type

Indicator, Pine Script v4

Draws

On the price chart

Category

AI / machine learning, Trend, Oscillators & momentum

Markets

Forex, Crypto

Timeframes

M1-M5, M15-H1, H4 and above

Risk Notes

  • Signals can change on the live bar or after it closes (repainting)

Settings

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

SettingTypeDefaultVariable
K Value for kNN Model |2..n|int63K
Short Aroon Lag |1..n|int5shortlag
Long Aroon Lag |1..n|int10longlag
Overbought Level |1..n|int90HighLevel
Oversold Level |1..n|int10LowLevel
Filter Signals bystringBothftype
Holding Period |1..n|int1holding_p
===Information===booltrueshow_info
Lot Sizefloat0.01lot_size
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

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

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]
7 stars

Lorentzian Classification is a machine learning indicator that applies a k-nearest neighbors algorithm using Lorentzian distance to analyze market patterns. It processes configurable technical indicators, including RSI, WaveTrend, CCI, and ADX, as feature vect

Indicator v6 AI / machine learningOscillators & momentum
Updated 1 year ago · MPL-2.0 GitHub repository of Lorentzian Classification
948 stars

The Adaptive RSI Moving Average (ARSIMA) is an overlay indicator that dynamically adjusts its smoothing factor based on the Relative Strength Index (RSI). When the RSI moves toward extreme overbought or oversold conditions, the smoothing factor increases to ma

Indicator v4 Moving averagesOscillators & momentum
Updated 10 days ago · GPL-3.0 GitHub repository of Adaptive RSI Moving Average

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