Strategy · Pine Script v5 · On the chart

Supertrend - Dynamic Trend Follower

by Basant1Saini· code credited to TradingTools

This strategy combines two Supertrend indicators with different factors and periods to identify trend direction on the price chart.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code82
Settings10inputs
LicenceNone statedfile: MPL-2.0
Last update7 months ago4 Mar 2026

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 strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

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

12_Supertrend.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0
// © TradingTools

//@version=5
strategy("Supertrend - Dynamic Trend Follower", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// ─── Inputs ───
stFactor1       = input.float(3.0, "Supertrend Factor 1", step=0.1, group="Supertrend")
stPeriod1       = input.int(10, "Supertrend Period 1", group="Supertrend")
stFactor2       = input.float(2.0, "Supertrend Factor 2 (Fast)", step=0.1, group="Supertrend")
stPeriod2       = input.int(7, "Supertrend Period 2 (Fast)", group="Supertrend")
useDualST       = input.bool(true, "Use Dual Supertrend Confirmation", group="Supertrend")
emaLength       = input.int(200, "Trend Filter EMA", group="Filters")
useTrendFilter  = input.bool(false, "Use EMA Trend Filter", group="Filters")
atrLength       = input.int(14, "ATR Length", group="Risk Management")
atrMult         = input.float(2.0, "ATR Multiplier for SL", step=0.1, group="Risk Management")
trailAtrMult    = input.float(2.5, "Trailing Stop ATR Mult", step=0.1, group="Risk Management")

// ─── Supertrend 1 (Primary) ───
[st1, dir1] = ta.supertrend(stFactor1, stPeriod1)
bullST1 = dir1 < 0
bearST1 = dir1 > 0

// ─── Supertrend 2 (Fast) ───
[st2, dir2] = ta.supertrend(stFactor2, stPeriod2)
bullST2 = dir2 < 0
bearST2 = dir2 > 0

// ─── Trend Filter ───
emaVal = ta.ema(close, emaLength)
emaBull = useTrendFilter ? close > emaVal : true
emaBear = useTrendFilter ? close < emaVal : true

// ─── ATR ───
atrVal = ta.atr(atrLength)

// ─── Entry Conditions ───
// Dual: both supertrends must agree
// Single: only primary supertrend
stFlipLong  = bullST1 and not bullST1[1]  // primary flipped bullish
stFlipShort = bearST1 and not bearST1[1]  // primary flipped bearish

dualBull = useDualST ? (bullST1 and bullST2) : bullST1
dualBear = useDualST ? (bearST1 and bearST2) : bearST1

longCondition  = stFlipLong and (useDualST ? bullST2 : true) and emaBull
shortCondition = stFlipShort and (useDualST ? bearST2 : true) and emaBear

// ─── Execute Trades ───
if longCondition and strategy.position_size <= 0
    sl = close - atrVal * atrMult
    strategy.entry("ST Long", strategy.long)
    strategy.exit("ST Long Exit", "ST Long", stop=sl, trail_offset=atrVal * trailAtrMult, trail_points=atrVal * trailAtrMult)

if shortCondition and strategy.position_size >= 0
    sl = close + atrVal * atrMult
    strategy.entry("ST Short", strategy.short)
    strategy.exit("ST Short Exit", "ST Short", stop=sl, trail_offset=atrVal * trailAtrMult, trail_points=atrVal * trailAtrMult)

// ─── Exit on Supertrend Flip ───
if strategy.position_size > 0 and bearST1
    strategy.close("ST Long", comment="ST Flip")
if strategy.position_size < 0 and bullST1
    strategy.close("ST Short", comment="ST Flip")

// ─── Plotting ───
plot(bullST1 ? st1 : na, "Supertrend 1 Bull", color=color.new(color.green, 0), linewidth=2, style=plot.style_linebr)
plot(bearST1 ? st1 : na, "Supertrend 1 Bear", color=color.new(color.red, 0), linewidth=2, style=plot.style_linebr)

plot(useDualST and bullST2 ? st2 : na, "Supertrend 2 Bull", color=color.new(color.green, 50), linewidth=1, style=plot.style_linebr)
plot(useDualST and bearST2 ? st2 : na, "Supertrend 2 Bear", color=color.new(color.red, 50), linewidth=1, style=plot.style_linebr)

plot(useTrendFilter ? emaVal : na, "EMA Filter", color=color.new(color.gray, 40), linewidth=1)

bgcolor(dualBull ? color.new(color.green, 93) : dualBear ? color.new(color.red, 93) : na, title="Dual ST Direction")

plotshape(longCondition, title="Long", location=location.belowbar, style=shape.triangleup, color=color.green, size=size.small)
plotshape(shortCondition, title="Short", location=location.abovebar, style=shape.triangledown, color=color.red, size=size.small)

// ─── Alerts ───
alertcondition(longCondition, title="Supertrend Long", message="Supertrend: Bullish flip — Long entry")
alertcondition(shortCondition, title="Supertrend Short", message="Supertrend: Bearish flip — Short entry")

Overview

The primary Supertrend (factor 3, period 10) signals flips for entries, confirmed optionally by a faster Supertrend (factor 2, period 7). An optional 200-period EMA filters trends. ATR (length 14) sets stop loss and trailing stops. Long entries trigger on bullish flip with confirmation and EMA alignment, exiting on bearish flip or opposite signal. Short trades mirror this logic. Plots Supertrend lines for dynamic trailing. Settings control Supertrend parameters, dual confirmation, EMA filter, ATR length, and risk multipliers. No pyramiding or exit rules beyond Supertrend flips.

Details

Published by

Basant1Saini on GitHub

Code credit

TradingTools, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Volatility & bands

Markets

Stocks

Timeframes

M15-H1, H4 and above

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.

Settings

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

SettingTypeDefaultVariable
Supertrend Factor 1float3.0stFactor1
Supertrend Period 1int10stPeriod1
Supertrend Factor 2 (Fast)float2.0stFactor2
Supertrend Period 2 (Fast)int7stPeriod2
Use Dual Supertrend ConfirmationbooltrueuseDualST
Trend Filter EMAint200emaLength
Use EMA Trend FilterboolfalseuseTrendFilter
ATR Lengthint14atrLength
ATR Multiplier for SLfloat2.0atrMult
Trailing Stop ATR Multfloat2.5trailAtrMult
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

330 stars

This strategy calculates Bollinger Bands and Aroon oscillator values to identify mean-reversion opportunities. It enters a long position using full equity when the closing price crosses below the lower Bollinger Band while Aroon Up remains above a user-specifi

Strategy v5 Mean reversionVolatility & bands
Updated 2 months ago · None stated GitHub repository of Bollinger bands + Aroon [Alorse]
257 stars

This overlay strategy targets one-minute ES futures and plots volume-weighted moving-average bands from the open, scaled by a standard-deviation multiple, plus a slower band from ten-minute opens. A higher-timeframe exponential moving average can filter trades

Strategy v6 Moving averagesVolatility & bands
Updated 6 weeks ago · None stated GitHub repository of ES - Futures 1M No Repaint

STRG-BBForce

by harryguiacorn
219 stars

STRG-BBForce is a Bollinger Bands trend-following strategy. It calculates standard Bollinger Bands and tracks directional alignment across the upper, lower, and basis lines. When all three lines slope upward, it opens a long position and closes short positions

Strategy v5 TrendVolatility & bands
Updated 1 year ago · None stated GitHub repository of STRG-BBForce

Nasdaq Prop Firm Strategy

by TradersPost
218 stars

This strategy uses multiple VWAP anchors and a custom Lull indicator to generate buy and sell signals on the Nasdaq price chart. It plots the VWAP trend line and three VWAP anchors with customizable colors and mitigation methods. The Lull indicator produces si

Strategy v6 TrendSupport & resistance Repaints
Updated 3 months ago · None stated GitHub repository of Nasdaq Prop Firm Strategy

This strategy implements a single-layer perceptron machine learning model built from scratch to generate trading signals directly on the price chart. It calculates predictions based on sample size, threshold settings, and optional volatility or volume filters.

Strategy v5 AI / machine learningTrend
Updated 1 year ago · None stated GitHub repository of Machine Learning: Perceptron-Based Strategy [5] (v.3)
106 stars

This overlay strategy plots a two-timeframe Ichimoku setup on the price chart, with Tenkan, Kijun, Chikou, and Kumo from a base higher timeframe and an optional highest-timeframe cloud. It allows two entries in the same direction and uses ATR-based trailing st

Strategy v4 TrendVolatility & bands
Updated 2 years ago · GPL-3.0 GitHub repository of 2Tier Ichimoku Pyramiding [Takazudo]

More strategys

Trade Your Charts With a Regulated Broker

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

Compare brokers