Strategy · Pine Script v5 · On the chart

BankNifty 5min Supertrend Based Strategy

by hasnocool

This strategy overlays Supertrend on the price chart and trades only inside a set session and backtest date range.

View on GitHub

GitHub stars106on the repository
Pine versionv5runs as is
Lines of code73
Settings14inputs
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 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

73 lines of Pine Script v5 from BankNifty 5min Supertrend Based Strategy.pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

BankNifty 5min Supertrend Based Strategy.pine
//@version=5
strategy("BankNifty 5min Supertrend Based Strategy, 09:15 Entry with Date Range and Risk Management",overlay=true)
// Session and date range input variables
session = input("0915-1510", "Session", group="Indian Session Time")
start_date = input.time(title="Start Date", defval=timestamp("01 Jan 2022 00:00:00"), group="Backtest Specific Range")
end_date = input.time(title="End Date", defval=timestamp("01 Dec 2023 23:59:59"))
atrPeriod = input(50, "ATR Length", group="SuperTrend Setting")
factor = input.float(3.0, "Factor", step=0.1)
//Delay N numbers of candles
useDelay = input(true, "Use Delay?", group="Delay at Session Start")
Delay = useDelay ? input(10, title="Delay N numbers of candle", group="Delay at Session Start") : na
//reentry option
Take_ReEntry = input(true, "Take ReEntry After Delay/SL/Target?", group="Delay at Session Start")
D1 = Take_ReEntry ? 100 : 0
//stoploss and target
useDelay_stopLoss = input(true, "Use Stoploss Fixed Points?", group="Fixed Point SL/TG")
stopLoss = useDelay_stopLoss ? input(100, "Stop Loss Fixed Points", group="Fixed Point SL/TG"): na
useTarget = input(true, "Use Target Fixed Points?", group="Fixed Point SL/TG")
target = useTarget? input(200, "Use Target Fixed Points", group="Fixed Point SL/TG"): na
stopLoss1 = 100
// trailing stop loss
useDelay_stopLossPerc1 = input(true, "Use Stoploss Trail?", group="Trailing")
stopLossPerc1 =useDelay_stopLossPerc1 ? input.float(0.1, "Stop Loss Trail%", step=0.1,maxval = 1, group="Trailing"): na
// Check if current time is within the specified session and date range
inSession = time("1", session) and time >= start_date and time <= end_date
//suprtrend
[supertrend, direction] = ta.supertrend(factor, atrPeriod)
// Wait for n candles to form at the start of every session
var candlesFormed = 0
if inSession and not inSession[1]
    candlesFormed := 1
else if inSession and candlesFormed > 0
    candlesFormed := candlesFormed + 1
else
    candlesFormed := 0
//get entry price
entryPrice = strategy.opentrades.entry_price(strategy.opentrades - 1)
//stop and target based on entry price
StopCE=entryPrice - stopLoss
StopPE= entryPrice + stopLoss
targetCE= entryPrice + target
targetPE=entryPrice - target
// long, short and close condition
entryce = (ta.change(direction) < 0) or (candlesFormed >= Delay and candlesFormed <= Delay+D1 and direction < 0)
exitce = ta.change(direction) > 0 or close < StopCE or close > targetCE
entrype = (ta.change(direction) > 0) or (candlesFormed >= Delay and candlesFormed <= Delay+D1 and direction > 0)
exitpe = ta.change(direction) < 0 or close > StopPE or close < targetPE
// entry price variable for defining stoploss
var entryPrice1 = 0.0
// Enter long trade
if entryce and inSession
    onePercent = strategy.position_avg_price *stopLossPerc1
    entryPrice1 := close   
    strategy.entry("My Long Entry Id", strategy.long, comment="long" )
    strategy.exit("My Long Exit Id", "My Long Entry Id", stop=(entryPrice1 - stopLoss1),trail_points=onePercent )
//close long trade
if exitce and inSession
    strategy.close("My Long Entry Id", comment="close" )
// Enter short trade   
if entrype and inSession
    onePercent1 = strategy.position_avg_price *stopLossPerc1
    entryPrice1 := close
    strategy.entry("My Short Entry Id", strategy.short, comment="short")
    strategy.exit("My Short Exit Id", "My Short Entry Id", stop=(entryPrice1 + stopLoss1),trail_points=onePercent1)
//close short trade
if exitpe and inSession
    strategy.close ("My Short Entry Id", comment="close" )
// Close all trades at end of session
if not inSession and strategy.opentrades > 0
    strategy.close_all()
// Plot Supertrend with changing colors
plot(supertrend, title="Supertrend", color=direction == 1 ? color.red : color.green, linewidth=2)
Expand (87 lines)

Overview

BankNifty 5min Supertrend Based Strategy enters long when Supertrend turns up, or after a chosen candle delay while the trend is up, and enters short on the opposite conditions. It closes on a trend flip, a fixed-point stop, or a fixed-point target, and can add a percentage trail and later re-entry. ATR length, factor, delay, stop, target, and trail inputs change the signals. It is written for a five-minute Bank Nifty chart.

Details

Published by

hasnocool on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Volatility & bands, Sessions & time

Markets

Indices

Timeframes

M1-M5

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
Sessionstring0915-1510session
Start Datetimetimestamp("01 Jan 2022 00:00:00")start_date
End Datetimetimestamp("01 Dec 2023 23:59:59")end_date
ATR Lengthint50atrPeriod
Factorfloat3.0factor
Use Delay?booltrueuseDelay
Delay N numbers of candleint10Delay N numbers of candle
Take ReEntry After Delay/SL/Target?booltrueTake_ReEntry
Use Stoploss Fixed Points?booltrueuseDelay_stopLoss
Stop Loss Fixed Pointsint100Stop Loss Fixed Points
Use Target Fixed Points?booltrueuseTarget
Use Target Fixed Pointsint200Use Target Fixed Points
Show all 14 settings
SettingTypeDefaultVariable
Use Stoploss Trail?booltrueuseDelay_stopLossPerc1
Stop Loss Trail%float0.1Stop Loss Trail%
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

ORION: Hybrid Strategy

by eddiebelaval
7 stars

This strategy identifies volatility breakout opportunities by constructing dynamic ATR-based price boxes and detecting volatility squeezes. Trades are filtered using an exponential moving average trend condition and designated session hours. Entries trigger up

Strategy v5 Volatility & bandsBreakout
Updated 3 months ago · None stated GitHub repository of ORION: Hybrid Strategy
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]

This overlay strategy offers two selectable entry modes: a Bollinger squeeze on typical price and a simple moving-average cross. It filters trades by weekday, session, date range, and an optional news window, and can restrict direction or invert the side. Risk

Strategy v5 Volatility & bandsMoving averages
Updated today · None stated GitHub repository of Boilerplate Configurable Strategy [Yosiet]
257 stars

Donald - Test Logic Futures is an overlay strategy designed for intraday futures trading. It combines kernel regression functions with exponential moving averages to evaluate price retracements and entry timing. Trades are filtered by session execution windows

Strategy v5 TrendMoving averages Repaints
Updated 6 weeks ago · None stated GitHub repository of Donald - Test Logic Futures

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

Daily Bias + FVG Strategy

by TradersPost
218 stars

This overlay strategy plots previous-day high and low, the daily open, and fair value gap zones on the price chart. It takes entries on a selectable timeframe when the FVG requirement and an optional session window allow them, then uses an ATR or fixed pip sto

Strategy v6 SMC / ICT / price actionSupport & resistance Repaints
Updated 3 months ago · None stated GitHub repository of Daily Bias + FVG Strategy

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