Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

improve //@version=5 strategy("Machine Learning Adaptive SuperTrend [AlgoAlpha]",…

  1. User

    improve

    //@version=5 strategy("Machine Learning Adaptive SuperTrend [AlgoAlpha]", "AlgoAlpha - 🤖 Adaptive SuperTrend", overlay = true, max_labels_count = 500)

    import TradingView/ta/7

    atr_len = input.int(10, "ATR Length", group = "SuperTrend Settings") fact = input.float(3, "SuperTrend Factor", group = "SuperTrend Settings") training_data_period = input.int(100, "Training Data Length", group = "K-Means Settings") highvol = input.float(0.75, "Initial High volatility Percentile Guess", maxval = 1, group = "K-Means Settings", tooltip = "The initial guess of where the potential 'high volatility' area is, a value of 0.75 will take the 75th percentile of the range of ATR values over the training data period") midvol = input.float(0.5, "Initial Medium volatility Percentile Guess", maxval = 1, group = "K-Means Settings", tooltip = "The initial guess of where the potential 'medium volatility' area is, a value of 0.5 will take the 50th percentile of the range of ATR values over the training data period") lowvol = input.float(0.25, "Initial Low volatility Percentile Guess", maxval = 1, group = "K-Means Settings", tooltip = "The initial guess of where the potential 'low volatility' area is, a value of 0.25 will take the 25th percentile of the range of ATR values over the training data period") green = input.color(#00ffbb, "Bullish Color", group = "Appearance") red = input.color(#ff1100, "Bearish Color", group = "Appearance")

    pine_supertrend(factor, atr) => src = hl2 upperBand = src + factor * atr lowerBand = src - 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
    [superTrend, _direction]
    

    volatility = ta.atr(atr_len)

    upper = ta.highest(volatility, training_data_period) lower = ta.lowest(volatility, training_data_period)

    high_volatility = lower + (upper-lower) * highvol medium_volatility = lower + (upper-lower) * midvol low_volatility = lower + (upper-lower) * lowvol

    iterations = 0

    size_a = 0 size_b = 0 size_c = 0

    hv = array.new_float() mv = array.new_float() lv = array.new_float() amean = array.new_float(1,high_volatility) bmean = array.new_float(1,medium_volatility) cmean = array.new_float(1,low_volatility)

    if nz(volatility) > 0 and bar_index >= training_data_period-1

    while ((amean.size() == 1 ? true : (amean.first() != amean.get(1))) or (bmean.size() == 1 ? true : (bmean.first() != bmean.get(1))) or (cmean.size() == 1 ? true : (cmean.first() != cmean.get(1)))):
        hv.clear()
        mv.clear()
        lv.clear()
        for i = training_data_period-1 to 0
            if math.abs(volatility[i] - amean.first()) < math.abs(volatility[i] - bmean.first()) and math.abs(volatility[i] - amean.first()) < math.abs(volatility[i] - cmean.first())
                hv.unshift(volatility[i])
    
            if math.abs(volatility[i] - bmean.first()) < math.abs(volatility[i] - amean.first()) and math.abs(volatility[i] - bmean.first()) < math.abs(volatility[i] - cmean.first())
                mv.unshift(volatility[i])
    
            if math.abs(volatility[i] - cmean.first()) < math.abs(volatility[i] - amean.first()) and math.abs(volatility[i] - cmean.first()) < math.abs(volatility[i] - bmean.first())
                lv.unshift(volatility[i])
        
        amean.unshift(hv.avg())
        bmean.unshift(mv.avg())
        cmean.unshift(lv.avg())
        size_a := hv.size()
        size_b := mv.size()
        size_c := lv.size()
        iterations := iterations + 1
    

    hv_new = amean.first() mv_new = bmean.first() lv_new = cmean.first() vdist_a = math.abs(volatility - hv_new) vdist_b = math.abs(volatility - mv_new) vdist_c = math.abs(volatility - lv_new)

    distances = array.new_float() centroids = array.new_float()

    distances.push(vdist_a) distances.push(vdist_b) distances.push(vdist_c)

    centroids.push(hv_new) centroids.push(mv_new) centroids.push(lv_new)

    cluster = distances.indexof(distances.min()) // 0 for high, 1 for medium, 2 for low assigned_centroid = cluster == -1 ? na : centroids.get(cluster)

    [ST, dir] = pine_supertrend(fact, assigned_centroid)

    // Define buy and sell conditions longCondition = ta.crossunder(dir, 0) shortCondition = ta.crossover(dir, 0)

    // Execute buy and sell orders if (longCondition) strategy.entry("Long", strategy.long)

    if (shortCondition) strategy.entry("Short", strategy.short)

    // Stop Loss and Take Profit based on ATR atrVal = ta.atr(14) strategy.exit("Exit Long", from_entry = "Long", stop = close - 1.5 * atrVal, limit = close + 2 * atrVal) strategy.exit("Exit Short", from_entry = "Short", stop = close + 1.5 * atrVal, limit = close - 2 * atrVal)

    t1 = 70 t2 = 95

    upTrend = plot(close > ST ? ST : na, color = color.new(green, t1), style = plot.style_linebr) downTrend = plot(close < ST ? ST : na, color = color.new(red, t1), style = plot.style_linebr, force_overlay = false) bodyMiddle = plot(barstate.isfirst ? na : (open + close) / 2, "Body Middle", display = display.none)

    fill(bodyMiddle, upTrend, (open + close) / 2, ST, color.new(green, t2), color.new(green, t1)) fill(bodyMiddle, downTrend, ST, (open + close) / 2, color.new(red, t1), color.new(red, t2))

    plotshape(ta.crossunder(dir, 0) ? ST : na, "Bullish Trend", shape.labelup, location.absolute, green, text = "▲", textcolor = chart.fg_color, size = size.small) plotshape(ta.crossover(dir, 0) ? ST : na, "Bearish Trend", shape.labeldown, location.absolute, red, text = "▼", textcolor = chart.fg_color, size = size.small)

  2. Assistant

    To improve your Pine Script, we'll address several key issues:

    1. K-Means Implementation Errors: The current K-Means clustering implementation has logic errors that prevent it from functioning correctly. Specifically, the data points aren't being assigned exclusively to one cluster, and there's no handling for empty clusters.

    2. Performance Optimization: The script can be optimized for better performance by reducing unnecessary calculations and iterations, which is crucial given Pine Script's resource limitations.

    3. Code Readability and Maintainability: By refactoring and commenting on the code, we can make it more readable and easier to maintain.

    Here's an improved version of your script with these considerations in mind:

    //@version=5
    strategy("Improved Machine Learning Adaptive SuperTrend", overlay = true, max_labels_count = 500)
    
    // Inputs
    atr_len = input.int(10, "ATR Length", group = "SuperTrend Settings")
    fact = input.float(3, "SuperTrend Factor", group = "SuperTrend Settings")
    training_data_period = input.int(100, "Training Data Length", group = "K-Means Settings")
    highvol = input.float(0.75, "Initial High Volatility Percentile Guess", maxval = 1, group = "K-Means Settings")
    midvol = input.float(0.5, "Initial Medium Volatility Percentile Guess", maxval = 1, group = "K-Means Settings")
    lowvol = input.float(0.25, "Initial Low Volatility Percentile Guess", maxval = 1, group = "K-Means Settings")
    green = input.color(#00ffbb, "Bullish Color", group = "Appearance")
    red = input.color(#ff1100, "Bearish Color", group = "Appearance")
    
    // Functions
    pine_supertrend(factor, atr) =>
        src = hl2
        upperBand = src + factor * atr
        lowerBand = src - 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
        _dir = 1
        _dir := nz(_dir[1])
        _dir := _dir == -1 and close > upperBand ? 1 : _dir == 1 and close < lowerBand ? -1 : _dir
        superTrend = _dir == 1 ? lowerBand : upperBand
        [superTrend, _dir]
    
    // Main Code
    var float[] volatility_history = array.new_float()
    volatility = ta.atr(atr_len)
    array.unshift(volatility_history, volatility)
    
    // Run K-Means only after enough data is collected
    var float assigned_centroid = na
    if array.size(volatility_history) >= training_data_period
        // K-Means Clustering
        float[] data = array.slice(volatility_history, 0, training_data_period)
        // Initial centroids based on percentiles
        data_sorted = array.copy(data)
        array.sort(data_sorted)
        high_centroid = array.get(data_sorted, math.round(training_data_period * highvol) - 1)
        mid_centroid = array.get(data_sorted, math.round(training_data_period * midvol) - 1)
        low_centroid = array.get(data_sorted, math.round(training_data_period * lowvol) - 1)
        centroids = array.from(high_centroid, mid_centroid, low_centroid)
        prev_centroids = array.new_float(3)
        max_iterations = 10
        iteration = 0
        stop = false
    
        while not stop and iteration < max_iterations
            iteration += 1
            // Create clusters
            clusters = array.new<array_float>(3)
            for i = 0 to 2
                array.push(clusters, array.new_float())
            // Assign data points to the nearest centroid
            for v in data
                dists = array.new_float()
                for c in centroids
                    array.push(dists, math.abs(v - c))
                min_dist = array.min(dists)
                cluster_idx = array.indexof(dists, min_dist)
                array.push(array.get(clusters, cluster_idx), v)
            // Update centroids
            stop = true
            for i = 0 to 2
                cluster = array.get(clusters, i)
                if array.size(cluster) > 0
                    new_centroid = array.avg(cluster)
                    if new_centroid != array.get(centroids, i)
                        stop := false
                        array.set(centroids, i, new_centroid)
                else
                    // Handle empty cluster by keeping the centroid unchanged
                    continue
        // Assign current volatility to the nearest centroid
        dists = array.new_float()
        for c in centroids
            array.push(dists, math.abs(volatility - c))
        min_dist = array.min(dists)
        idx = array.indexof(dists, min_dist)
        assigned_centroid := array.get(centroids, idx)
    else
        assigned_centroid := volatility  // Use current volatility if not enough data
    
    // Calculate SuperTrend
    [ST, dir] = pine_supertrend(fact, assigned_centroid)
    
    // Define buy and sell conditions
    longCondition = ta.crossunder(dir, 0)
    shortCondition = ta.crossover(dir, 0)
    
    // Execute buy and sell orders
    if (longCondition)
        strategy.entry("Long", strategy.long)
    
    if (shortCondition)
        strategy.entry("Short", strategy.short)
    
    // Stop Loss and Take Profit based on ATR
    atrVal = ta.atr(14)
    strategy.exit("Exit Long", from_entry = "Long", stop = close - 1.5 * atrVal, limit = close + 2 * atrVal)
    strategy.exit("Exit Short", from_entry = "Short", stop = close + 1.5 * atrVal, limit = close - 2 * atrVal)
    
    // Plotting
    t1 = 70
    t2 = 95
    
    upTrend = plot(close > ST ? ST : na, color = color.new(green, t1), style = plot.style_linebr)
    downTrend = plot(close < ST ? ST : na, color = color.new(red, t1), style = plot.style_linebr)
    bodyMiddle = plot(na, display = display.none)
    
    fill(bodyMiddle, upTrend, color.new(green, t2))
    fill(bodyMiddle, downTrend, color.new(red, t2))
    
    plotshape(ta.crossunder(dir, 0) ? ST : na, "Bullish Trend", shape.labelup, location.absolute, green, text = "▲", textcolor = color.white, size = size.small)
    plotshape(ta.crossover(dir, 0) ? ST : na, "Bearish Trend", shape.labeldown, location.absolute, red, text = "▼", textcolor = color.white, size = size.small)
    

    Explanation of Improvements:

    1. Corrected the K-Means Clustering Logic:

      • Exclusive Assignment: Each data point is now assigned to the nearest centroid exclusively.
      • Handling Empty Clusters: If a cluster ends up empty after an iteration, the centroid remains unchanged to avoid division by zero errors.
      • Convergence Criterion: The algorithm now stops when centroids no longer change or after a maximum number of iterations.
    2. Optimized Performance:

      • Limited Iterations: The maximum number of iterations for K-Means is set to 10 to prevent infinite loops.
      • Data Handling: The script collects volatility data only when necessary and avoids unnecessary recalculations.
    3. Enhanced Code Readability:

      • Comments: Added comments throughout the script to explain each section.
      • Structured Code Blocks: Organized the code into logical sections (inputs, functions, main code, plotting) for better readability.
      • Simplified Variable Names: Used clear and concise variable names to make the code easier to understand.
    4. Improved Plotting:

      • Removed Unnecessary Plots: Simplified the plotting by removing redundant variables.
      • Consistent Color Usage: Ensured consistent use of colors for bullish and bearish trends.
      • Clear Trend Indicators: Used plotshape to mark bullish and bearish trend changes clearly.

    Note: The K-Means algorithm in this script is a basic implementation and may not perform optimally in all market conditions. It's essential to test the strategy thoroughly and adjust the parameters (training_data_period, max_iterations, initial centroid guesses) to fit the specific financial instrument and timeframe you are trading.

    Additional Recommendations:

    • Backtesting: Before using this strategy in live trading, backtest it across different timeframes and market conditions to evaluate its performance.
    • Risk Management: Adjust the stop-loss and take-profit levels according to your risk tolerance and the volatility of the instrument.
    • Further Optimization: Consider experimenting with different clustering algorithms or machine learning techniques if you seek more advanced adaptability.

    By addressing the core issues and optimizing the script, you should now have a more reliable and efficient strategy that adapts to market volatility using K-Means clustering.

improve //@version=5 strategy("Machine Learning Adaptive… · The Chat Archive