Strategy · Pine Script v6 · On the chart

Supertrend Strategy

by dharaarpan7

This strategy executes long trades based on the Supertrend indicator and candle color confirmation.

View on GitHub

GitHub stars3on the repository
Pine versionv6current
Lines of code92
Settings4inputs
LicenceMIT
Last update1 year ago15 Oct 2025

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

92 lines of Pine Script v6 from Supertrend/Supertrend.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

Supertrend.pine
//@version=6
strategy("Supertrend Strategy", overlay=true, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// Input parameters
atrPeriod = input.int(10, "ATR Length", minval=1)
factor = input.float(3.0, "Factor", minval=0.01, step=0.01)

// Risk management inputs
stopLossPercent = input.float(2.0, "Stop Loss %", minval=0.1, step=0.1)
takeProfitPercent = input.float(6.0, "Take Profit %", minval=0.1, step=0.1)

// Calculate Supertrend
[supertrend, direction] = ta.supertrend(factor, atrPeriod)
supertrend := barstate.isfirst ? na : supertrend

// Trend direction variables
isBullish = direction < 0  // Supertrend is bullish when direction < 0
isBearish = direction > 0  // Supertrend is bearish when direction > 0

// Previous bar trend
wasBullish = direction[1] < 0
wasBearish = direction[1] > 0

// Candle color conditions
isGreenCandle = close > open
isRedCandle = close < open

// Entry Logic: Fresh bullish trend after bearish trend with green candle
freshBullishTrend = wasBearish and isBullish and isGreenCandle
entryCondition = freshBullishTrend and strategy.position_size == 0

// Exit Logic: Bullish trend reverses to bearish with red candle
trendReversalExit = wasBullish and isBearish and isRedCandle
exitCondition = trendReversalExit and strategy.position_size > 0

// Calculate stop loss and take profit levels
var float entryPrice = na
var float stopLoss = na
var float takeProfit = na

if entryCondition
    entryPrice := close
    stopLoss := entryPrice * (1 - stopLossPercent / 100)
    takeProfit := entryPrice * (1 + takeProfitPercent / 100)

// Strategy execution
if entryCondition
    strategy.entry("Long", strategy.long, comment="Bullish Entry")

if exitCondition
    strategy.close("Long", comment="Bearish Exit")

// Stop loss and take profit orders
if strategy.position_size > 0
    strategy.exit("Exit", "Long", stop=stopLoss, limit=takeProfit, comment="SL/TP Exit")

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

// Background fills
fill(bodyMiddle, upTrend, title="Uptrend background", color=color.new(color.green, 90), fillgaps=false)
fill(bodyMiddle, downTrend, title="Downtrend background", color=color.new(color.red, 90), fillgaps=false)

// Plot entry and exit signals
plotshape(entryCondition, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.normal, title="Buy Signal")
plotshape(exitCondition, style=shape.triangledown, location=location.abovebar, color=color.red, size=size.normal, title="Sell Signal")

// Plot stop loss and take profit levels
plot(strategy.position_size > 0 ? stopLoss : na, color=color.red, style=plot.style_linebr, linewidth=1, title="Stop Loss")
plot(strategy.position_size > 0 ? takeProfit : na, color=color.blue, style=plot.style_linebr, linewidth=1, title="Take Profit")

// Alerts
alertcondition(entryCondition, title='Long Entry Signal', message='Supertrend: Fresh bullish trend confirmed with green candle')
alertcondition(exitCondition, title='Long Exit Signal', message='Supertrend: Bullish trend reversed to bearish with red candle')

// Strategy information table
if barstate.islast
    var table infoTable = table.new(position.top_right, 2, 6, bgcolor=color.white, border_width=1)
    table.cell(infoTable, 0, 0, "Strategy Stats", text_color=color.black, text_size=size.small)
    table.cell(infoTable, 1, 0, "", text_color=color.black, text_size=size.small)
    table.cell(infoTable, 0, 1, "Total Trades", text_color=color.black, text_size=size.small)
    table.cell(infoTable, 1, 1, str.tostring(strategy.closedtrades), text_color=color.black, text_size=size.small)
    table.cell(infoTable, 0, 2, "Win Rate", text_color=color.black, text_size=size.small)
    table.cell(infoTable, 1, 2, str.tostring(math.round(strategy.wintrades / strategy.closedtrades * 100, 2)) + "%", text_color=color.black, text_size=size.small)
    table.cell(infoTable, 0, 3, "Net Profit", text_color=color.black, text_size=size.small)
    table.cell(infoTable, 1, 3, str.tostring(math.round(strategy.netprofit, 2)), text_color=color.black, text_size=size.small)
    table.cell(infoTable, 0, 4, "Max Drawdown", text_color=color.black, text_size=size.small)
    table.cell(infoTable, 1, 4, str.tostring(math.round(strategy.max_drawdown, 2)), text_color=color.black, text_size=size.small)
    table.cell(infoTable, 0, 5, "Profit Factor", text_color=color.black, text_size=size.small)
    table.cell(infoTable, 1, 5, str.tostring(math.round(strategy.grossprofit / math.abs(strategy.grossloss), 2)), text_color=color.black, text_size=size.small)

Overview

Supertrend Strategy enters when a fresh bullish Supertrend flip occurs on a green candle and exits when the trend flips bearish on a red candle. It also places bracket orders with configurable percentage-based stop-loss and take-profit targets. Plotted directly on the price chart, it visualizes the Supertrend bands, entry and exit shapes, active stop and target levels, and an informational summary table.

Details

Published by

dharaarpan7 on GitHub

Type

Strategy, Pine Script v6

Draws

On the price chart

Category

Trend, Volatility & bands

Markets

Forex, Gold, Indices

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.

Settings

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

SettingTypeDefaultVariable
ATR Lengthint10atrPeriod
Factorfloat3.0factor
Stop Loss %float2.0stopLossPercent
Take Profit %float6.0takeProfitPercent
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