Conversion of indicator Volume SuperTrend AI from the TradingView platform

Viewing 15 posts - 1 through 15 (of 26 total)
  • Author
    Posts
  • #228735 quote
    Ξ3
    Participant
    Average

    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 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.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”)
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}

    SuperTrendAI.png SuperTrendAI.png
    #229004 quote
    Iván González
    Moderator
    Master

    Hi!
    Here it’s.

    //inputs
    // ~~ Input settings for K and N values
    k = 3 // Neighbors 1 to 100
    m = 10 // Data
    n = max(k,m)
    // ~~ Input settings for prediction values
    KNNPriceLen = 20 // Price Trend 2 - 500 step 10
    KNNSTlen = 100 // Prediction Trend 2 - 500 step 10
    aisignals = 1 // Boolean AI Trend Signals
    // ~~ Define SuperTrend parameters
    len = 10 // Length
    factor = 3.0 // step 0.1
    maSrc = 0 // MaType
    // ~~ Calculate the SuperTrend based on the user's choice
    vwma = average[len,maSrc](close*volume)/average[len,maSrc](volume)
    atr = averagetruerange[len](close)
    
    upperband = vwma + factor*atr
    lowerband = vwma - factor*atr
    
    if barindex < len then
    upperband = close
    lowerband = close
    direction = 1
    else
    //Redefine upperband
    if upperband < upperband[1] or close[1] > upperband[1] then
    upperband = upperband
    else
    upperband = upperband[1]
    endif
    //Redefine lowerband
    if lowerband > lowerband[1] or close[1] < lowerband[1] then
    lowerdband = lowerband
    else
    lowerband = lowerband[1]
    endif
    //Define upperband
    prevSupertrend = mysuperTrend[1]
    if prevSupertrend = upperband[1] then
    if close > upperband then
    direction = -1
    else
    direction = 1
    endif
    else
    if close < lowerband then
    direction = 1
    else
    directon = -1
    endif
    endif
    endif
    
    if direction = -1 then
    mysupertrend = lowerband
    else
    mysupertrend = upperband
    endif
    // ~~ Collect data points and their corresponding labels
    myprice = 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] = 1
    else
    $labels[i] = 0
    endif
    next
    
    // ~~ Classify the current data point
    currentsuperTrend = mysuperTrend
    //label = knn_weighted(data, labels, k, current_superTrend)
    
    // Compute distances from the current point to all other points
    n1 = lastset($data)
    for i = 0 to n1-1 do
    $distances[i] = abs(currentsuperTrend[i]-$data[i])
    $indices[i] = i
    next
    // Sort distances and corresponding indices in ascending order
    // Bubble sort method
    for i=0 to n1-2 do
    for j=0 to n1-i-2 do
    if $distances[j]>$distances[j+1] then
    tempDist = $distances[j]
    $distances[j]=$distances[j+1]
    $distances[j+1]=tempDist
    tempindex = $indices[j]
    $indices[j]=$indices[j+1]
    $indices[j+1]=tempindex
    endif
    next
    next
    // Compute weighted sum of labels of the k nearest neighbors
    weightedsum=0
    totalweight=0
    for i=0 to k-1 do
    myindex = $indices[i]
    labeli = $labels[i]
    weighti = 1 / ($distances[i]+pow(10,-6) )
    weightedsum = weighti*labeli+weightedsum
    totalweight = weighti+totalweight
    next
    
    label = floor(weightedsum / totalweight,2)
    
    // ~~ Plot
    if label = 1 then
    r=0
    g=250
    b=0
    elsif label = 0 then
    r=250
    g=0
    b=0
    else
    r=0
    g=0
    b=250
    endif
    
    middleprice = (open+close)/2
    colorbetween(middleprice,mysupertrend,r,g,b,40)
    
    // ~~ Ai Super Trend Signals
    starttrendup = label = 1 and label[1]<>1 and aisignals
    starttrenddn = label = 0 and label[1]<>0 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
    
    if starttrendup or starttrenddn then
    drawpoint(barindex,currentsuperTrend,2)coloured(r,g,b)
    elsif Trendup then
    drawtext("▲",barindex,currentsuperTrend)coloured(r,g,b)
    elsif Trenddn then
    drawtext("▼",barindex,currentsuperTrend)coloured(r,g,b)
    endif
    
    return currentsuperTrend as "SuperTrend" coloured(r,g,b)style(line,2)
    
    Ξ3 and MobiusGrey thanked this post
    #229107 quote
    WhyAskOZ
    Participant
    New

    Hi, 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 :

     

    https://nrby.in/

    #229108 quote
    WhyAskOZ
    Participant
    New

    I 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.

    #229210 quote
    Acivi90
    Participant
    New

    Hi Ivan

    i am trying to make a stratgy of this Code but it doesnt trade the whole intervall only one year on 1 min TF.
    Is there a candel or calcution limit in the code.  If yes hos do i change it?

    #229256 quote
    Iván González
    Moderator
    Master

    hi
    check it. Maybe you haven`t copied all code. I’ve done and everything is ok.

    #229257 quote
    Iván González
    Moderator
    Master

    Hi,
    there is no limitation on the code.
    I don’t know what the problem is…

    WhyAskOZ thanked this post
    #229272 quote
    PeterSt
    Participant
    Master

    I 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.

    WhyAskOZ thanked this post
    image_2024-03-05_155802107.png image_2024-03-05_155802107.png
    #229293 quote
    WhyAskOZ
    Participant
    New

    Thanks 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?

    #229294 quote
    WhyAskOZ
    Participant
    New

    Ivan

    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,

    Supertrend-AI_PRT.jpg Supertrend-AI_PRT.jpg
    #229297 quote
    PeterSt
    Participant
    Master

    Hi again OZ,

    Hopefully Iván will hand you a version that can act as Indicator. But the general idea is :

    1. 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.
    2. 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.
    3. 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 a

      GraphOnPrice 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.

    4. 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 !
    Peter

    WhyAskOZ thanked this post
    #229305 quote
    Iván González
    Moderator
    Master

    Hi!
    Yes, it´s an indicator…
    If you want to add an indicator overlaying price you should click add on price (check the attached screenshot).

    PeterSt thanked this post
    Captura-de-pantalla-2024-03-06-093921.png Captura-de-pantalla-2024-03-06-093921.png
    #229315 quote
    PeterSt
    Participant
    Master

    Yep, misinterpretation on my part. Apologies.

    Iván González thanked this post
    #229360 quote
    Acivi90
    Participant
    New

    Hi 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.

    Test-Supertrend-AI.itf Test-Supertrend-AI.jpg Test-Supertrend-AI.jpg
    #229363 quote
    PeterSt
    Participant
    Master

    Hello @Acivi90,

    I can’t let it go wrong. What instrument do you use ? (seems DAX ?). What TimeFrame ? And is it IG or IB ? How many bars do you use for the backtest ?

    Regards,
    Peter

Viewing 15 posts - 1 through 15 (of 26 total)
  • You must be logged in to reply to this topic.

Conversion of indicator Volume SuperTrend AI from the TradingView platform


ProBuilder: Indicators & Custom Tools

New Reply
Author
author-avatar
Ξ3 @cbeukes Participant
Summary

This topic contains 25 replies,
has 8 voices, and was last updated by Ξ3
1 year ago.

Topic Details
Forum: ProBuilder: Indicators & Custom Tools
Language: English
Started: 02/26/2024
Status: Active
Attachments: 7 files
Logo Logo
Loading...