Indicator · Pine Script v5 · On the chart

Tsh Arrow

by teshmi9z-beep· code credited to PresentTrading

An overlay that draws a SuperTrend-style trend line built from a volume-weighted moving average, selectable from SMA, EMA, WMA, RMA or VWMA types, with a fixed ATR factor.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code174
Settings9inputs
LicenceMIT
Last updateyesterday28 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

174 lines of Pine Script v5 from src/indicators/custom/tshArrow.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

tshArrow.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © PresentTrading
//@version=5
indicator("Tsh_Arrow", overlay = true,max_boxes_count = 1000)
// ~~ Input settings for K and N values
k  = 3
n_ = 12
n  = math.max(3,12)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
// ~~ Input settings for prediction values
KNN_PriceLen = 20
KNN_STLen    = 80

aisignals    = input.bool(true,title="Trend Signals",inline="signal", group="Super Trend Settings")
voir_fleche=input.bool(true, title="Arrow",inline="signal")
Bullish_col  = input.color(color.lime,"",inline="signal")
Bearish_col  = input.color(color.red,"",inline="signal")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ Define SuperTrend parameters
maSrc  = input.string("WMA","Moving Average Source",["SMA","EMA","WMA","RMA","VWMA"],inline="")
len    = input.int(20, "Length", minval=1,inline="SuperTrend")
factor = 4

upCol  = input.color( color.new(color.lime,80),"Up",inline="col")
dnCol  = input.color(color.new(color.red,80),"Down",inline="col")
neCol  = input.color(color.new(color.blue,80),"Neutral",inline="col")
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ Calculate the SuperTrend based on the user's choice
vwma = switch maSrc
    "SMA"  => ta.sma(close*volume, len) / ta.sma(volume, len)
    "EMA"  => ta.ema(close*volume, len) / ta.ema(volume, len)
    "WMA"  => ta.wma(close*volume, len) / ta.wma(volume, len)
    "RMA"  => ta.rma(close*volume, len) / ta.rma(volume, len)
    "VWMA" => ta.vwma(close*volume, len) / ta.vwma(volume, len)

atr = ta.atr(len)
upperBand = vwma + factor * atr
lowerBand = vwma - factor * atr
prevLowerBand = nz(lowerBand[1])
prevUpperBand = nz(upperBand[1])

lowerBand := lowerBand > prevLowerBand or close[1] < prevLowerBand ? lowerBand : prevLowerBand
upperBand := upperBand < prevUpperBand or close[1] > prevUpperBand ? upperBand : prevUpperBand
int direction = na
float superTrend = na

prevSuperTrend = superTrend[1]
if na(atr[1])
    direction := 1
else if prevSuperTrend == prevUpperBand
    direction := close > upperBand ? -1 : 1
else
    direction := close < lowerBand ? 1 : -1
superTrend := direction == -1 ? lowerBand : upperBand

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ Collect data points and their corresponding labels
price  = ta.wma(close,KNN_PriceLen)
sT     = ta.wma(superTrend,KNN_STLen)
data   = array.new_float(n)
labels = array.new_int(n)
for i = 0 to n - 1
    data.set(i, superTrend[i])
    label_i = price[i] > sT[i] ? 1 : 0
    labels.set(i, label_i)

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ Define a function to compute distance between two data points
distance(x1, x2) =>
    math.abs(x1 - x2)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ Define the weighted k-nearest neighbors (KNN) function
knn_weighted(data, labels, k, x) =>
    n1 = data.size()
    distances = array.new_float(n1)
    indices   = array.new_int(n1)
    // Compute distances from the current point to all other points
    for i = 0 to n1 - 1
        x_i = data.get(i)
        dist = distance(x, x_i)
        distances.set(i, dist)
        indices.set(i, i)
    // Sort distances and corresponding indices in ascending order
    // Bubble sort method
    for i = 0 to n1 - 2
        for j = 0 to n1 - i - 2
            if distances.get(j) > distances.get(j + 1)
                tempDist = distances.get(j)
                distances.set(j, distances.get(j + 1))
                distances.set(j + 1, tempDist)
                tempIndex = indices.get(j)
                indices.set(j, indices.get(j + 1))
                indices.set(j + 1, tempIndex)
    // Compute weighted sum of labels of the k nearest neighbors
    weighted_sum = 0.
    total_weight = 0.
    for i = 0 to k - 1
        index = indices.get(i)
        label_i = labels.get(index)
        weight_i = 1 / (distances.get(i) + 1e-6)
        weighted_sum += weight_i * label_i
        total_weight += weight_i
    weighted_sum / total_weight
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ Classify the current data point
current_superTrend = superTrend
label_             = knn_weighted(data, labels, k, current_superTrend)
label_upTrend = label_ == 1 ? 1:0
label_downTrend = label_ == 0 ? -1:0

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

// ~~ Plot
col = label_ == 1?upCol:label_ == 0?dnCol:neCol
plot(current_superTrend, color=col, title="Volume Super Trend AI")

upTrend   = plot(superTrend==lowerBand?current_superTrend:na, title="Up Volume Super Trend AI", color=col, style=plot.style_linebr)
Middle    = plot((open + close) / 2, display=display.none, editable=false)
downTrend = plot(superTrend==upperBand?current_superTrend:na, title="Down Volume Super Trend AI", color=col, style=plot.style_linebr)
fill_col  = color.new(col,95)
fill(Middle, upTrend, fill_col, fillgaps=false,title="Up Volume Super Trend AI")
fill(Middle, downTrend, fill_col, fillgaps=false, title="Down Volume Super Trend AI")


// ~~ Ai Super Trend Signals
Start_TrendUp = col==upCol and (col[1]!=upCol or col[1]==neCol) and aisignals
Start_TrendDn = col==dnCol and (col[1]!=dnCol or col[1]==neCol) and aisignals

TrendUp       = direction == -1 and direction[1] == 1  and label_ == 1 and aisignals
TrendDn       = direction == 1  and direction[1] ==-1  and label_ == 0 and aisignals

plotshape(Start_TrendUp?superTrend:na, location=location.absolute, style= shape.circle, size=size.tiny, color=Bullish_col, title="AI Bullish Trend Start")
plotshape(Start_TrendDn?superTrend:na, location=location.absolute, style= shape.circle,size=size.tiny, color=Bearish_col, title="AI Bearish Trend Start")
plotshape(TrendUp?superTrend:na, location=location.absolute, style= shape.triangleup, size=size.tiny, color=Bullish_col, title="AI Bullish Trend Signal")
plotshape(TrendDn?superTrend:na, location=location.absolute, style= shape.triangledown,size=size.tiny, color=Bearish_col, title="AI Bearish Trend Signal")

// Définir la fonction DEMA MACD
dema(src, length) =>
    ema1 = ta.ema(src, length)
    ema2 = ta.ema(ema1, length)
    2 * ema1 - ema2

// Paramètres pour DEMA
p = 12
q = 26
r = 9
// Calculer DEMA pour les différentes périodes
z1 = dema(close, p)
z2 = dema(close, q)
e = z1 - z2
z3 = dema(e, r)
f = z3
g = e - f

// Condition pour afficher une flèche verte
bullishCross = ta.crossover(e, f)
Inf0= e < 0 and f <0

// Condition pour afficher une flèche rouge
bearishCross = ta.crossunder(e, f)
Sup0= e > 0 and f>0


if (bullishCross and Inf0 and col==upCol and voir_fleche)
    label.new(bar_index, low, "▲", color=color.new(color.white,100),  textcolor=Bullish_col,  style=label.style_label_up, size=size.small)

if (bearishCross and Sup0 and col==dnCol and voir_fleche)
    label.new(bar_index, high, "▼", color=color.new(color.white,100), textcolor=Bearish_col, style=label.style_label_down, size=size.small)

Overview

A k-nearest neighbours routine compares recent prices with the smoothed trend line to produce trend signals, with arrows and background colours for up, down and neutral states. Length and colours are adjustable. The method uses a small data window, so its signals are sensitive to settings.

Details

Published by

teshmi9z-beep on GitHub

Code credit

PresentTrading, as written in the script's header

Draws

On the price chart

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.

Settings

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

SettingTypeDefaultVariable
Trend Signalsbooltrueaisignals
Arrowbooltruevoir_fleche
Bullish_colcolorcolor.limeBullish_col
Bearish_colcolorcolor.redBearish_col
Moving Average SourcestringWMAmaSrc
Lengthint20len
Upcolorcolor.new(color.lime,80)upCol
Downcolorcolor.new(color.red,80)dnCol
Neutralcolorcolor.new(color.blue,80)neCol
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

AI Trend Navigator

by hasnocool
106 stars

This indicator calculates a trend direction and smoothed moving average using a k-nearest neighbours (k-NN) classification algorithm directly on the main price chart. Users can select input price types, target values, neighborhood size, and smoothing periods.

Indicator v5 AI / machine learningTrend
Updated 2 years ago · GPL-3.0 GitHub repository of AI Trend Navigator

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 3 days ago · MIT GitHub repository of Machine Learning: Lorentzian Classification
46 stars

This indicator uses a Hidden Markov Model (HMM) framework combined with an adaptive dual moving average engine and Directional Movement Index (DMI) features to identify market regimes (bullish, bearish, or ranging/chop). It calculates regime probabilities on e

Indicator v5 AI / machine learningTrend
Updated 7 weeks ago · None stated GitHub repository of HMM Enhanced: Regime Probability

This overlay indicator plots a SuperTrend-style band on the price chart using ATR length, a selectable source, and a base factor. Optional settings enable an adaptive factor driven by rate of change, a volatility filter, K-means clustering, and an LSTM layer w

Indicator v6 TrendVolatility & bands
Updated 4 months ago · MIT GitHub repository of ML SuperTrend (Ultimate) - Auto-Optimized AI with LSTM

More Trend scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers