Indicator · Pine Script v5 · On the chart

SuperTrend

by KorayGocmen

This indicator plots a SuperTrend line on the price chart to mark trend direction.

View on GitHub

Repaints

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code56
Settings4inputs
LicenceNone statedfile: MPL-2.0
Last update2 years ago4 Oct 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

56 lines of Pine Script v5 from supertrend.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

supertrend.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © koraygocmen

//@version=5
indicator("SuperTrend", overlay=true)

source = input.source(hl2, title="Source")
band = input.string("StdDev", title="Band", options=["ATR", "StdDev"])
period = input.int(20, "Period", minval = 1)
factor = input.float(1, "Factor", minval = 0.01, step = 0.01)

// The same on Pine Script®
supertrend(src, band, factor, period) =>
    atr = ta.atr(period)
    stddev = ta.stdev(src, period)

    upperBand = src + factor * (band == "ATR" ? atr : band == "StdDev" ? stddev : 0)
    lowerBand = src - factor * (band == "ATR" ? atr : band == "StdDev" ? stddev : 0)

    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]

[supertrend, direction] = supertrend(source, band, factor, period)

supertrend := barstate.isfirst ? na : supertrend
upTrend =    plot(direction < 0 ? supertrend : na, "Up Trend",   color = color.green, style = plot.style_linebr)
downTrend =  plot(direction < 0 ? na : supertrend, "Down Trend", color = color.red,   style = plot.style_linebr)
bodyMiddle = plot(barstate.isfirst ? na : (open + close) / 2, "Body Middle",display = display.none)

fill(bodyMiddle, upTrend,   color.new(color.green, 90), fillgaps = false)
fill(bodyMiddle, downTrend, color.new(color.red,   90), fillgaps = false)

// Detecting crossovers
crossedUp = direction[1] > direction
crossedDown = direction[1] < direction

alertcondition(crossedUp, title='Downtrend to Uptrend', message='The Supertrend value switched from Downtrend to Uptrend ')
alertcondition(crossedDown, title='Uptrend to Downtrend', message='The Supertrend value switched from Uptrend to Downtrend')
alertcondition(direction[1] != direction, title='Trend Change', message='The Supertrend value switched from Uptrend to Downtrend or vice versa')

Overview

SuperTrend builds upper and lower bands from a user-selected price source and either average true range or standard deviation, then trails the active band as the trend continues. A green line marks an uptrend and a red line a downtrend, with a light fill toward the candle body. Period and factor change the lookback and band distance. Alerts fire when direction flips. The signal can change on the live bar before that bar closes.

Details

Published by

KorayGocmen on GitHub

Draws

On the price chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • Signals can change on the live bar or after it closes (repainting)

Topics

pinescriptpinescript-indicatorspinescript-strategiestradingtrading-strategiestradingview-scripts

Settings

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

SettingTypeDefaultVariable
Sourcesourcehl2source
BandstringStdDevband
Periodint20period
Factorfloat1factor
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

Chandelier Exit

by everget
947 stars

This indicator plots an ATR-based Chandelier Exit trailing stop on the price chart. It tracks a long stop under recent highs and a short stop above recent lows, then switches direction when price crosses the opposite stop. Buy and sell labels mark those flips.

Indicator v6 Volatility & bandsTrend Repaints
Updated 12 days ago · GPL-3.0 GitHub repository of Chandelier Exit

The Momentum Setup is a multi-indicator visual tool designed for trend and momentum analysis directly on the price chart. It combines Relative Strength Index (RSI), Money Flow Index (MFI), Commodity Channel Index (CCI), Supertrend, and a 250-bar percentage cha

Indicator v5 Oscillators & momentumTrend
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup - Ankush Bajaj Momentum Investing Setup
330 stars

Range Filter [Alorse] is a technical indicator overlay for TradingView designed to filter market volatility and identify price trends. It calculates a smoothed range based on historical volatility using a configurable sampling period and multiplier applied to

Indicator v5 TrendVolatility & bands
Updated 2 months ago · None stated GitHub repository of Range Filter [Alorse]
318 stars

This indicator calculates an ATR trailing stop line derived from the highest high minus an average true range multiple over a specified lookback period. It plots the trailing stop line directly on the price chart and colors price bars based on whether the clos

Indicator v5 TrendVolatility & bands
Updated 2 months ago · MIT GitHub repository of ATR Trailing Stoploss

NVDA Trend Ribbon

by longsurf-ai
280 stars

This indicator plots three exponential moving averages and ATR volatility envelopes on the price chart. It compares the fast and slow EMAs to shade a trend ribbon and marks confirmed upward and downward crossovers with triangle labels. Settings change the thre

Indicator v6 TrendMoving averages
Updated 3 days ago · MIT GitHub repository of NVDA Trend Ribbon

[RS]Donchian Fans

by ricardosantos79
261 stars

This indicator plots Donchian Channel boundary lines along with dynamic fan projections directly on the price chart. It calculates the highest high, lowest low, and median price over a customizable lookback period. Whenever price establishes a new channel high

Indicator v4 Support & resistanceTrend
Updated 4 years ago · None stated GitHub repository of [RS]Donchian Fans

More Trend scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers