Indicator · Pine Script v5 · Own pane

AI SuperTrend Clustering Oscillator [LuxAlgo]

by hasnocool· code credited to LuxAlgo

This indicator plots an oscillator in a separate pane.

View on GitHub

GitHub stars106on the repository
Pine versionv5runs as is
Lines of code123
Settings12inputs
LicenceGPL-3.0
Last update2 years ago18 Sep 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

123 lines of Pine Script v5 from AI SuperTrend Clustering Oscillator [LuxAlgo].pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

AI SuperTrend Clustering Oscillator [LuxAlgo].pine
// 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/
// © LuxAlgo
//@version=5
indicator("AI SuperTrend Clustering Oscillator [LuxAlgo]", "LuxAlgo - AI SuperTrend Clustering Oscillator")
//------------------------------------------------------------------------------
//Settings
//-----------------------------------------------------------------------------{
length = input(10, 'ATR Length')
minMult = input.int(1, 'Factor Range', minval = 0, inline = 'factor')
maxMult = input.int(5, '', minval = 0, inline = 'factor')
step    = input.float(.5, 'Step', minval = 0, step = 0.1)
smooth = input.float(1, minval = 1)
//Trigger error
if minMult > maxMult
    runtime.error('Minimum factor is greater than maximum factor in the range')
//Optimization
maxIter = input.int(1000, 'Maximum Iteration Steps', minval = 0, group = 'Optimization')
maxData = input.int(10000, 'Historical Bars Calculation', minval = 0, group = 'Optimization')
//Style
bullCss = input(color.new(#5b9cf6, 50), 'Bullish', inline = 'bull', group = 'Style')
strongBullCss = input(color.new(#5b9cf6, 28), 'Strong', inline = 'bull', group = 'Style')
neutCss = input(#9598a1, 'Neutral', inline = 'neut', group = 'Style')
bearCss = input(color.new(#f77c80, 50), 'Bearish', inline = 'bear', group = 'Style')
strongBearCss = input(color.new(#f77c80, 28), 'Strong', inline = 'bear', group = 'Style')
//-----------------------------------------------------------------------------}
//UDT's
//-----------------------------------------------------------------------------{
type supertrend
    float upper = hl2
    float lower = hl2
    float output
    int trend
type vector
    array<float> out
//-----------------------------------------------------------------------------}
//Supertrend
//-----------------------------------------------------------------------------{
var holder = array.new<supertrend>(0)
var factors = array.new<float>(0)
//Populate supertrend type array
if barstate.isfirst
    for i = 0 to int((maxMult - minMult) / step)
        factors.push(minMult + i * step)
        holder.push(supertrend.new())
atr = ta.atr(length)
//Compute Supertrend for multiple factors
k = 0
for factor in factors
    get_spt = holder.get(k)
    up = hl2 + atr * factor
    dn = hl2 - atr * factor
    
    get_spt.upper := close[1] < get_spt.upper ? math.min(up, get_spt.upper) : up
    get_spt.lower := close[1] > get_spt.lower ? math.max(dn, get_spt.lower) : dn
    get_spt.trend := close > get_spt.upper ? 1 : close < get_spt.lower ? 0 : get_spt.trend
    get_spt.output := get_spt.trend == 1 ? get_spt.lower : get_spt.upper
    k += 1
//-----------------------------------------------------------------------------}
//K-means clustering
//-----------------------------------------------------------------------------{
data = array.new<float>(0)
//Populate data arrays
if last_bar_index - bar_index <= maxData
    for element in holder
        data.push(close - element.output)
//Intitalize centroids using quartiles
centroids = array.new<float>(0)
centroids.push(data.percentile_linear_interpolation(25))
centroids.push(data.percentile_linear_interpolation(50))
centroids.push(data.percentile_linear_interpolation(75))
//Intialize clusters
var array<vector> clusters = na
if last_bar_index - bar_index <= maxData
    for _ = 0 to maxIter
        clusters := array.from(vector.new(array.new<float>(0)), vector.new(array.new<float>(0)), vector.new(array.new<float>(0)))
        
        //Assign value to cluster
        for value in data
            dist = array.new<float>(0)
            for centroid in centroids
                dist.push(math.abs(value - centroid))
            idx = dist.indexof(dist.min())
            if idx != -1
                clusters.get(idx).out.push(value)
            
        //Update centroids
        new_centroids = array.new<float>(0)
        for cluster_ in clusters
            new_centroids.push(cluster_.out.avg())
        //Test if centroid changed
        if new_centroids.get(0) == centroids.get(0) and new_centroids.get(1) == centroids.get(1) and new_centroids.get(2) == centroids.get(2)
            break
        centroids := new_centroids
//-----------------------------------------------------------------------------}
//Get centroids
//-----------------------------------------------------------------------------{
//Get associated supertrend
var float bull = 0
var float neut = 0
var float bear = 0
var den = 0
if not na(clusters)
    bull += 2/(smooth+1) * nz(centroids.get(2) - bull)
    neut += 2/(smooth+1) * nz(centroids.get(1) - neut)
    bear += 2/(smooth+1) * nz(centroids.get(0) - bear)
    den += 1
//-----------------------------------------------------------------------------}
//Plots
//-----------------------------------------------------------------------------{
plot_bull = plot(math.max(bull, 0), color = na, editable = false)
plot_bull_ext = plot(math.max(bear, 0), 'Strong Bullish'
  , bear > 0 ? strongBullCss : na
  , style = plot.style_circles)
plot_bear = plot(math.min(bear, 0), color = na, editable = false)
plot_bear_ext = plot(math.min(bull, 0), 'Strong Bearish'
  , bull < 0 ? strongBearCss : na
  , style = plot.style_circles)
plot(neut, 'Consensus', neutCss)
fill(plot_bull, plot_bull_ext, bull, math.max(bear, 0), bullCss, color.new(chart.bg_color, 100))
fill(plot_bear_ext, plot_bear, math.min(bull, 0), bear, color.new(chart.bg_color, 100), bearCss)
hline(0, linestyle = hline.style_solid)
//-----------------------------------------------------------------------------}
Expand (152 lines)

Overview

AI SuperTrend Clustering Oscillator [LuxAlgo] 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 those distances with k-means clustering whose starting centroids come from the 25th, 50th, and 75th percentiles. Settings cover ATR length, factor bounds, a smoothing value, iteration count, and historical bars. Bullish, strong, neutral, and bearish colors style the result. The supplied code ends before the final cluster assignment and plot calls.

Details

Published by

hasnocool on GitHub

Code credit

LuxAlgo, as written in the script's header

Type

Indicator, Pine Script v5

Draws

Separate pane below the chart

Category

Trend, Volatility & bands, Oscillators & momentum, AI / machine learning

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.

Topics

analysisbtcusdtcryptocurrencydatapandaspythonsimulationtradingtradingview

Settings

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

SettingTypeDefaultVariable
ATR Lengthint10length
Factor Rangeint1minMult
maxMultint5maxMult
Stepfloat.5step
smoothfloat1smooth
Maximum Iteration Stepsint1000maxIter
Historical Bars Calculationint10000maxData
Bullishcolorcolor.new(#5b9cf6, 50)bullCss
Strongcolorcolor.new(#5b9cf6, 28)strongBullCss
Neutralcolor#9598a1neutCss
Bearishcolorcolor.new(#f77c80, 50)bearCss
Strongcolorcolor.new(#f77c80, 28)strongBearCss
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

147 stars

This indicator generates trade entry signals and target levels optimized for 1-hour timeframes, designed for external signal extraction. It calculates 7-period and 16-period EMAs alongside 10-period RSI and ATR filters. Long signals occur when the fast EMA cro

Indicator v5 TrendOscillators & momentum
Updated 6 weeks ago · MIT GitHub repository of Signal Strategy 100 Candles of 1H Timeframe

MultiIndicator

by capissimo
114 stars

MultiIndicator combines multiple technical indicators into a single separate pane to save chart space. It calculates and displays market regime detection based on ordinary least squares regression, a Holt exponential smoothing crossover, normalized RSI, ADX, a

Indicator v4 Oscillators & momentumTrend
Updated 1 year ago · None stated GitHub repository of MultiIndicator
29 stars

The Supertrended RSI [AlgoAlpha] indicator plots the Relative Strength Index combined with a Supertrend overlay in a separate indicator pane. It first computes standard RSI, with an optional Hull Moving Average smoothing step, and computes a secondary moving a

Indicator v5 Oscillators & momentumTrend
Updated 11 months ago · Custom licence GitHub repository of Supertrended RSI [AlgoAlpha]
24 stars

This indicator plots a smoothed stochastic oscillator in a separate pane, with K and D lines, a midsection background, and adjustable overbought and oversold levels. Optional highlights mark overbought or oversold breakouts and K/D crossovers, and ribbon filli

Indicator v5 Oscillators & momentumVolatility & bands
Updated 4 years ago · MPL-2.0 GitHub repository of Intermediate Stochastic

Manias, Panics and Crashes

by MeridianAlgo
9 stars

Manias, Panics and Crashes is a separate-pane market regime indicator that quantifies market sentiment and systemic risk. It processes technical metrics including RSI, moving averages, and volume alongside optional intermarket data such as VIX volatility and c

Indicator v6 Oscillators & momentumVolatility & bands
Updated 4 months ago · MIT GitHub repository of Manias, Panics and Crashes

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