Conversion of indicator Volume SuperTrend AI from the TradingView platform
Forums › ProRealTime English forum › ProBuilder support › Conversion of indicator Volume SuperTrend AI from the TradingView platform
- This topic has 23 replies, 7 voices, and was last updated 7 months ago by jacquesgermain.
-
-
02/26/2024 at 8:10 AM #228735
Hi Nicholas,
Would it be possible to convert the Volume SuperTrend AI indicator to ProRealTime code? It would be greatly appreciated.
The details of this indicator can be found at: https://www.tradingview.com/script/eTgP2ymK-Volume-SuperTrend-AI-Expo/
█ Overview
The Volume SuperTrend AI is an advanced technical indicator used to predict trends in price movements by utilizing a combination of traditional SuperTrend calculation and AI techniques, particularly the k-nearest neighbors (KNN) algorithm.
The Volume SuperTrend AI is designed to provide traders with insights into potential market trends, using both volume-weighted moving averages (VWMA) and the k-nearest neighbors (KNN) algorithm. By combining these approaches, the indicator aims to offer more precise predictions of price trends, offering bullish and bearish signals.Many thanks.
——-TRADINGVIEW CODE BELOW—————————————————————————————–
// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © Zeiierman//@version=5
indicator(“Volume SuperTrend AI (Expo)”, overlay=true)// ~~ ToolTips {
t1=”Number of nearest neighbors in KNN algorithm (k): Increase to consider more neighbors, providing a more balanced view but possibly smoothing out local patterns. Decrease for fewer neighbors to make the algorithm more responsive to recent changes. \n\nNumber of data points to consider (n): Increase for more historical data, providing a broader context but possibly diluting recent trends. Decrease for less historical data to focus more on recent behavior.”
t2=”Length of weighted moving average for price (KNN_PriceLen): Higher values create a smoother price line, influencing the KNN algorithm to be more stable but less sensitive to short-term price movements. Lower values enhance responsiveness in KNN predictions to recent price changes but may lead to more noise. \n\nLength of weighted moving average for SuperTrend (KNN_STLen): Higher values lead to a smoother SuperTrend line, affecting the KNN algorithm to emphasize long-term trends. Lower values make KNN predictions more sensitive to recent SuperTrend changes but may result in more volatility.”
t3=”Length of the SuperTrend (len): Increase for a smoother trend line, ideal for identifying long-term trends but possibly ignoring short-term fluctuations. Decrease for more responsiveness to recent changes but risk of more false signals. \n\nMultiplier for ATR in SuperTrend calculation (factor): Increase for wider bands, capturing larger price movements but possibly missing subtle changes. Decrease for narrower bands, more sensitive to small shifts but risk of more noise.”
t4=”Type of moving average for SuperTrend calculation (maSrc): Choose based on desired characteristics. SMA is simple and clear, EMA emphasizes recent prices, WMA gives more weight to recent data, RMA is less sensitive to recent changes, and VWMA considers volume.”
t5=”Color for bullish trend (upCol): Select to visually identify upward trends. \n\nColor for bearish trend (dnCol): Select to visually identify downward trends.\n\nColor for neutral trend (neCol): Select to visually identify neutral trends.”
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}// ~~ Input settings for K and N values
k = input.int(3, title = “Neighbors”, minval=1, maxval=100,inline=”AI”, group=”AI Settings”)
n_ = input.int(10, title =”Data”, minval=1, maxval=100,inline=”AI”, group=”AI Settings”, tooltip=t1)
n = math.max(k,n_)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}// ~~ Input settings for prediction values
KNN_PriceLen = input.int(20, title=”Price Trend”, minval=2, maxval=500, step=10,inline=”AITrend”, group=”AI Trend”)
KNN_STLen = input.int(100, title=”Prediction Trend”, minval=2, maxval=500, step=10, inline=”AITrend”, group=”AI Trend”, tooltip=t2)
aisignals = input.bool(true,title=”AI Trend Signals”,inline=”signal”, group=”AI Trend”)
Bullish_col = input.color(color.lime,””,inline=”signal”, group=”AI Trend”)
Bearish_col = input.color(color.red,””,inline=”signal”, group=”AI Trend”)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}// ~~ Define SuperTrend parameters
len = input.int(10, “Length”, minval=1,inline=”SuperTrend”, group=”Super Trend Settings”)
factor = input.float(3.0,step=.1,inline=”SuperTrend”, group=”Super Trend Settings”, tooltip=t3)
maSrc = input.string(“WMA”,”Moving Average Source”,[“SMA”,”EMA”,”WMA”,”RMA”,”VWMA”],inline=””, group=”Super Trend Settings”, tooltip=t4)
upCol = input.color(color.lime,”Bullish Color”,inline=”col”, group=”Super Trend Coloring”)
dnCol = input.color(color.red,”Bearish Color”,inline=”col”, group=”Super Trend Coloring”)
neCol = input.color(color.blue,”Neutral Color”,inline=”col”, group=”Super Trend Coloring”, tooltip=t5)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}// ~~ 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)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}// ~~ 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,90)
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 aisignalsplotshape(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.small, color=Bullish_col, title=”AI Bullish Trend Signal”)
plotshape(TrendDn?superTrend:na, location=location.absolute, style= shape.triangledown,size=size.small, color=Bearish_col, title=”AI Bearish Trend Signal”)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}// ~~ Alerts {
alertcondition(Start_TrendUp, title =”1 Bullish Trend Start”, message = “AI Bullish Trend Start”)
alertcondition(Start_TrendDn, title =”2 Bearish Trend Start”, message = “AI Bearish Trend Start”)
alertcondition((Start_TrendUp or Start_TrendDn), title =”3 Any Trend Start”, message=”Any AI Trend Start”)
alertcondition(TrendUp, title = “4 Bullish Trend Signal”, message = “AI Bullish Trend Signal”)
alertcondition(TrendDn, title = “5 Bearish Trend Signal”, message = “AI Bearish Trend Signal”)
alertcondition((TrendUp or TrendDn),title = “6 Any Trend Signal”, message =”Any AI Trend Signal”)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}02/29/2024 at 5:33 PM #229004Hi!
Here it’s.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142//inputs// ~~ Input settings for K and N valuesk = 3 // Neighbors 1 to 100m = 10 // Datan = max(k,m)// ~~ Input settings for prediction valuesKNNPriceLen = 20 // Price Trend 2 - 500 step 10KNNSTlen = 100 // Prediction Trend 2 - 500 step 10aisignals = 1 // Boolean AI Trend Signals// ~~ Define SuperTrend parameterslen = 10 // Lengthfactor = 3.0 // step 0.1maSrc = 0 // MaType// ~~ Calculate the SuperTrend based on the user's choicevwma = average[len,maSrc](close*volume)/average[len,maSrc](volume)atr = averagetruerange[len](close)upperband = vwma + factor*atrlowerband = vwma - factor*atrif barindex < len thenupperband = closelowerband = closedirection = 1else//Redefine upperbandif upperband < upperband[1] or close[1] > upperband[1] thenupperband = upperbandelseupperband = upperband[1]endif//Redefine lowerbandif lowerband > lowerband[1] or close[1] < lowerband[1] thenlowerdband = lowerbandelselowerband = lowerband[1]endif//Define upperbandprevSupertrend = mysuperTrend[1]if prevSupertrend = upperband[1] thenif close > upperband thendirection = -1elsedirection = 1endifelseif close < lowerband thendirection = 1elsedirecton = -1endifendifendifif direction = -1 thenmysupertrend = lowerbandelsemysupertrend = upperbandendif// ~~ Collect data points and their corresponding labelsmyprice = WeightedAverage[KNNPriceLen](close)sT = WeightedAverage[kNNSTlen](mysupertrend)for i=0 to n-1 do$data[i]=mysupertrend[i]if myprice[i] > sT[i] then$labels[i] = 1else$labels[i] = 0endifnext// ~~ Classify the current data pointcurrentsuperTrend = mysuperTrend//label = knn_weighted(data, labels, k, current_superTrend)// Compute distances from the current point to all other pointsn1 = lastset($data)for i = 0 to n1-1 do$distances[i] = abs(currentsuperTrend[i]-$data[i])$indices[i] = inext// Sort distances and corresponding indices in ascending order// Bubble sort methodfor i=0 to n1-2 dofor j=0 to n1-i-2 doif $distances[j]>$distances[j+1] thentempDist = $distances[j]$distances[j]=$distances[j+1]$distances[j+1]=tempDisttempindex = $indices[j]$indices[j]=$indices[j+1]$indices[j+1]=tempindexendifnextnext// Compute weighted sum of labels of the k nearest neighborsweightedsum=0totalweight=0for i=0 to k-1 domyindex = $indices[i]labeli = $labels[i]weighti = 1 / ($distances[i]+pow(10,-6) )weightedsum = weighti*labeli+weightedsumtotalweight = weighti+totalweightnextlabel = floor(weightedsum / totalweight,2)// ~~ Plotif label = 1 thenr=0g=250b=0elsif label = 0 thenr=250g=0b=0elser=0g=0b=250endifmiddleprice = (open+close)/2colorbetween(middleprice,mysupertrend,r,g,b,40)// ~~ Ai Super Trend Signalsstarttrendup = label = 1 and label[1]<>1 and aisignalsstarttrenddn = label = 0 and label[1]<>0 and aisignalsTrendUp = direction = -1 and direction[1] = 1 and label = 1 and aisignalsTrendDn = direction = 1 and direction[1] = -1 and label = 0 and aisignalsif starttrendup or starttrenddn thendrawpoint(barindex,currentsuperTrend,2)coloured(r,g,b)elsif Trendup thendrawtext("▲",barindex,currentsuperTrend)coloured(r,g,b)elsif Trenddn thendrawtext("▼",barindex,currentsuperTrend)coloured(r,g,b)endifreturn currentsuperTrend as "SuperTrend" coloured(r,g,b)style(line,2)2 users thanked author for this post.
03/02/2024 at 9:23 PM #229107Hi, Ivan
You and some other poster here are exceptionally smart and helpful volunteers. How about you guys open account with below website and keep it as a signature under your name so i would like to buy you a coffee as well.. !
https://www.buymeacoffee.com/signup
see below, how people use this website :
03/02/2024 at 9:32 PM #229108I copied above strategy and it gives error on line 132 which is for ” colorbetween ” .
it also give error on line 1 saying ” character missing. suggestion : end of the code”. Now there is nothing on line one so not sure why it keep giving error and preventing to run the code.
03/04/2024 at 7:37 PM #22921003/05/2024 at 2:39 PM #22925603/05/2024 at 2:41 PM #22925703/05/2024 at 3:58 PM #229272I copied above strategy and it gives error on line 132 which is for ” colorbetween ” .
Hi there,
Did you put that code to an Indicator ?
In Strategy code this will not work.1 user thanked author for this post.
03/06/2024 at 4:52 AM #229293Thanks Peter,
I did copied it in the strategy but when I put it into indicator then it worked. Just need to verify if it works same or not.
is there shortcut to make it a strategy so we can see if it is worthwhile using this indicator? i mean that’s the only way we know if the indicator is worth using?
03/06/2024 at 4:57 AM #229294Ivan
Code works now as initially I put it into strategy but after reading Peter’s response above I changed it to indicator and it worked.
Is there a way to have this indicator on price chart ? as currently it is coming out as separate window see attached the screenshot.
thanks,
03/06/2024 at 5:26 AM #229297Hi again OZ,
Hopefully Iván will hand you a version that can act as Indicator. But the general idea is :
- Remove all what “draws” because that can not work in Strategy Code (like the ColorBetween example).
Thus, just comment it out (//) so it won’t do anything. - Change the Return command (last line) in actually also a commented out line, but *know* that (in this example) CurrentSupertrend is the variable you will need. This now needs to be incorporated in your Strategy Code somewhere. See #3 and #4 below.
- Somewhere under the code which is now in your Strategy Code, put a
Graph CurrentSuperTrend
command. You will now see the same as what the Indicator showed or shows (you can just let the Indicator be active as well for comparison).
Also notice that if you make that aGraphOnPrice CurrentSuperTrend
command, the line of the supertrend will now be projected on the Price area. It is not said that this will always work for each Indicator you convert to Strategy Code, but withhout really looking into it, this one should work regarding that.
- Now you see the line on your screen, you will be able to envision how to use that line in your code. Think like
If Close Crosses Over CurrentSuperTrend then
or, you make a second of such “indicator” line like ShortTrend and have an
If ShortTrend Crosses Under CurrentSuperTrend then
In all events it is clear that you need some programming skills. 🙂
Hope this helps !
Peter1 user thanked author for this post.
03/06/2024 at 9:43 AM #22930503/06/2024 at 10:08 AM #22931503/07/2024 at 7:55 AM #229360Hi Ivan,
I am attaching 1 itf and a picture of the problem.
Never had this before and am not very good at coding.
Can you understand why it doesn’t trade all the way to the end?
If i use it as a indicator it appears from start to end.
I want to se this how this indicator works on diffrent timeframes and index to know where it gets the best resultat for manuelly trading.
03/07/2024 at 8:43 AM #229363 - Remove all what “draws” because that can not work in Strategy Code (like the ColorBetween example).
-
AuthorPosts
Find exclusive trading pro-tools on