Yes, you can create a Supertrend indicator in Pine Script very easily using the built-in ta.supertrend() function.
The code below creates a Supertrend with an ATR Multiplier of 3 and an ATR Length of 10. It returns two values:
–supertrend โ The Supertrend line.
–direction โ The current trend direction.
The plot() functions then display the Supertrend on the chart. When the trend is bullish, the line is plotted in green, and when the trend is bearish, it is plotted in red.
The script also includes a custom function named pine_supertrend(). This function manually calculates the Supertrend using ATR, upper band, lower band, and trend direction. It produces the same result as the built-in ta.supertrend() function and is useful if you want to understand or customize the Supertrend calculation.
You can simply copy the code below into the Pine Script Editor and click Add to Chart to see the Supertrend indicator in action.
//@version=6
indicator("My super trend", overlay = true)
[supertrend, direction] = ta.supertrend(3, 10)
plot(direction < 0 ? supertrend : na, "Up direction", color = color.green, style = plot.style_linebr)
plot(direction > 0 ? supertrend : na, "Down direction", color = color.red, style = plot.style_linebr)
// The same on Pine Scriptยฎ
pine_supertrend(factor, atrPeriod) =>
src = hl2
atr = ta.atr(atrPeriod)
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]
[Pine_Supertrend, pineDirection] = pine_supertrend(3, 10)
plot(pineDirection < 0 ? Pine_Supertrend : na, "Up direction", color = color.green, style = plot.style_linebr)
plot(pineDirection > 0 ? Pine_Supertrend : na, "Down direction", color = color.red, style = plot.style_linebr)
Also, if you want the code of tradingview provided for the supertrend then just visit the refrance manual and search for the supertrend in that example you will find the code of the supertrend.
I hope this helps! If you have any questions about the code or want to customize the Supertrend settings, feel free to ask in the comments.