Strategy · Pine Script v5 · On the chart

SuperTrend Algomojo Trading Strategy with Target/Stoploss

by ClimberMel· code credited to tradestudio

This strategy plots SuperTrend lines on the price chart using ATR period and multiplier settings to identify trend direction and generate buy and sell signals.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code204
Settings33inputs
LicenceMIT
Last update4 years ago4 Apr 2022

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

204 lines of Pine Script v5 from code/sampleStrat.txt, published under MIT. Keep the author's credit and licence lines when you reuse it.

sampleStrat.txt
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tradestudio
// Algomojo Trading Strategy Carry Forward Strategy/Intraday Strategy with Target/Stoploss
// Supertrend Version 1.0
// Code Date : 17th Dec 2021
// Coded by Rajandran R (Founder - Marketcalls / Co-Founder - Algomojo)


//@version=5
strategy('SuperTrend Algomojo Trading Strategy with Target/Stoploss', shorttitle='Supertrend Algomojo', overlay=true)


import algomojo/automation/9

//Block 1 : API Controls + Algomojo Input Controls


//Enter Your Algomojo API Key and API Secret Key

am_client_id = input.string(title='Client ID', defval='ZZ0011', group='AlgoControls')
am_api_key = input.string(title='API Key', defval='xxxxx', group='AlgoControls')
am_api_secret = input.string(title='API Secret Key', defval='xxxxx', group='AlgoControls')
am_broker = input.string(title='Broker', defval='ALICEBLUE', options=['ALICEBLUE', 'ANGELONE', 'FIRSTOCK', 'FYERS','MASTERTRUST','SAMCO','TRADEJINI','UPSTOX','ZEBU','ZERODHA'], group='AlgoControls')
am_strategy = input.string(title='Strategy Name', defval='Supertrend Strategy', group='AlgoControls')
am_symbol = input.string(title='Trading Symbol', defval='RELIANCE-EQ', group='AlgoControls')
am_exchange = input.string(title='Exchange', defval='NSE', options=['NSE', 'NFO', 'MCX', 'BSE'], group='AlgoControls')
am_quantity = input.int(title='Quantity', defval=1, group='AlgoControls')
am_OrderType = input.string(title='Order Type', defval='MARKET', group='AlgoControls')
am_Product = input.string(title='Product', defval='NORMAL', options=['NORMAL', 'INTRADAY', 'DELIVERY', 'MARGIN'], group='AlgoControls')
am_Mode = input.string(title='Algo Mode', defval='ENABLE', options=['ENABLE', 'LONGONLY', 'SHORTONLY'], group='AlgoControls')


////////////////////////////////////////Block 1 Module Ends////////////////////////////////////////////////////////////////////////



//Block 2 : Autotrading API data configuration

[BE,SX,BSR,SE,BX,SSR] = automation.algomodule(am_client_id, am_api_key,am_api_secret,am_broker,am_strategy,am_symbol,am_exchange,am_quantity,am_OrderType, am_Product)


////////////////////////////////////////Block 2 Module Ends////////////////////////////////////////////////////////////////////////

//Block 3 : Backtesting Controls & Live Automation Purpose

FromMonth = input.int(defval=9, title='From Month', minval=1, maxval=12, group='Backtesting')
FromDay = input.int(defval=1, title='From Day', minval=1, maxval=31, group='Backtesting')
FromYear = input.int(defval=2018, title='From Year', minval=999, group='Backtesting')
ToMonth = input.int(defval=1, title='To Month', minval=1, maxval=12, group='Backtesting')
ToDay = input.int(defval=1, title='To Day', minval=1, maxval=31, group='Backtesting')
ToYear = input.int(defval=9999, title='To Year', minval=999, group='Backtesting')
start = timestamp(FromYear, FromMonth, FromDay, 00, 00)
finish = timestamp(ToYear, ToMonth, ToDay, 23, 59)
window() =>
    time >= start and time <= finish ? true : false


////////////////////////////////////////Block 3 Module Ends////////////////////////////////////////////////////////////////////////



//inputs

src = input(hl2, title='Source', group='Supertrend Controls')
Multiplier = input.float(title='ATR Multiplier', step=0.1, defval=3.0, group='Supertrend Controls')
Periods = input.int(title='ATR Period', defval=10, group='Supertrend Controls')
changeATR = input.bool(title='Change ATR Calculation Method ?', defval=true, group='Supertrend Controls')
showsignals = input.bool(title='Show Buy/Sell Signals ?', defval=true, group='Supertrend Controls')
highlighting = input.bool(title='Highlighter On/Off ?', defval=true, group='Supertrend Controls')
barcoloring = input.bool(title='Bar Coloring On/Off ?', defval=true, group='Supertrend Controls')

intraday = input.bool(title='Intraday On/Off ?', defval=false, group='Intraday Controls')
marketSession = input.session(title='Market session', defval='0915-1500', confirm=true, group='Intraday Controls')

risk = input.bool(title='Stoploss/Target On/Off', defval=false, group='Stoploss/Target Controls')
type = input.string(title='Type', defval='FIXED', options=['FIXED', 'PERCENTAGE', 'VOLATILITY'], group='Stoploss/Target Controls')
stoploss = input.float(defval=10.0, title='Stoploss', group='Stoploss/Target Controls')
target = input.float(defval=20.0, title='Target', group='Stoploss/Target Controls')
TickSz = input.float(defval=0.05, title='TickSize', group='Stoploss/Target Controls')
ATRMultiplier = input.float(title='ATR Multiplier', step=0.1, defval=1.5, group='Stoploss/Target Controls')
ATRLength = input.int(title='ATR Period', defval=20, group='Stoploss/Target Controls')

iATR = ta.atr(ATRLength)

var longCondition = false
var shortCondition = false


atr2 = ta.sma(ta.tr, Periods)
atr = changeATR ? ta.atr(Periods) : atr2
up = src - Multiplier * atr
up1 = nz(up[1], up)
up := close[1] > up1 ? math.max(up, up1) : up
dn = src + Multiplier * atr
dn1 = nz(dn[1], dn)
dn := close[1] < dn1 ? math.min(dn, dn1) : dn
trend = 1
trend := nz(trend[1], trend)
trend := trend == -1 and close > dn1 ? 1 : trend == 1 and close < up1 ? -1 : trend


//Plots
upPlot = plot(trend == 1 ? up : na, title='Up Trend', style=plot.style_linebr, linewidth=2, color=color.new(color.green, 0))
buySignal = trend == 1 and trend[1] == -1
plotshape(buySignal  ? up : na, title='UpTrend Begins', location=location.absolute, style=shape.circle, size=size.tiny, color=color.new(color.green, 0))
//plotshape(buySignal and showsignals ? up : na, title='Buy', text='Buy', location=location.absolute, style=shape.labelup, size=size.tiny, color=color.new(color.green, 0), textcolor=color.new(color.white, 0))
dnPlot = plot(trend == 1 ? na : dn, title='Down Trend', style=plot.style_linebr, linewidth=2, color=color.new(color.red, 0))
sellSignal = trend == -1 and trend[1] == 1
plotshape(sellSignal ? dn : na, title='DownTrend Begins', location=location.absolute, style=shape.circle, size=size.tiny, color=color.new(color.red, 0))
//plotshape(sellSignal and showsignals ? dn : na, title='Sell', text='Sell', location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.new(color.red, 0), textcolor=color.new(color.white, 0))
mPlot = plot(ohlc4, title='', style=plot.style_circles, linewidth=0)

longFillColor = highlighting ? trend == 1 ? color.new(color.green,90) : na : na
shortFillColor = highlighting ? trend == -1 ? color.new(color.red,90) : na : na
fill(mPlot, upPlot, title='UpTrend Highligter', color=longFillColor)
fill(mPlot, dnPlot, title='DownTrend Highligter', color=shortFillColor)


barInSession(sess) =>
    time(timeframe.period, sess) != 0
    
bool intradaySession = barInSession(marketSession)

buy = buySignal
sell = sellSignal

buy1 = buy[1]
sell1 = sell[1]

//assign signals
if(not intraday)
    longCondition := buySignal
    shortCondition := sellSignal

if(intraday)
    longCondition := buySignal and intradaySession
    shortCondition := sellSignal and intradaySession 

//Block 4 : Execution Controls
if(am_Mode=="ENABLE")
    if longCondition and strategy.position_size == 0
        strategy.entry('BUY', strategy.long, when=window(), alert_message=BE,comment='BUY')
    if longCondition and strategy.position_size < 0
        strategy.entry('BUY', strategy.long, when=window(), alert_message=BSR,comment='BUY')
    if shortCondition and strategy.position_size == 0
        strategy.entry('SELL', strategy.short, when=window(), alert_message=SE,comment='SELL')
    if shortCondition and strategy.position_size > 0
        strategy.entry('SELL', strategy.short, when=window(), alert_message=SSR,comment='SELL')
        
if(am_Mode=="LONGONLY")
    if longCondition and strategy.position_size == 0
        strategy.entry('BUY', strategy.long, when=window(), alert_message=BE,comment='BUY')
    if shortCondition and strategy.position_size > 0
        strategy.close('BUY', when=window(),  alert_message=BX,comment='BUY EXIT')    

if(am_Mode=="SHORTONLY")
    if shortCondition and strategy.position_size == 0
        strategy.entry('SELL', strategy.short, when=window(), alert_message=SE,comment='SHORT')
    if longCondition and strategy.position_size < 0
        strategy.close('SELL', when=window(), alert_message=SX,comment='SHORT EXIT')

if(intraday)
    longsquareOff = not intradaySession and strategy.position_size > 0 
    strategy.close(id='BUY', when=longsquareOff, comment='Square-off',alert_message=BX)
    shortsquareOff = not intradaySession and strategy.position_size < 0 
    strategy.close(id='SELL', when=shortsquareOff, comment='Square-off',alert_message=SX)

////////////////////////////////////////Block 4 Module Ends////////////////////////////////////////////////////////////////////////

buycount = ta.barssince(buySignal)
sellcount = ta.barssince(sellSignal)
color1 = buycount[1] < sellcount[1] ? color.green : buycount[1] > sellcount[1] ? color.red : na
barcolor(barcoloring ? color1 : na)


long_stop_level = ta.valuewhen(buy1, open - stoploss, 0)
long_profit_level = ta.valuewhen(buy1, open + target, 0)
short_stop_level = ta.valuewhen(sell1, open + stoploss, 0)
short_profit_level = ta.valuewhen(sell1, open - target, 0)

if(type=="PERCENTAGE")
    long_stop_level := ta.valuewhen(buy1, open, 0) * (100-stoploss)/100
    long_profit_level := ta.valuewhen(buy1, open, 0) * (100+target)/100
    long_stop_level := TickSz * math.round(long_stop_level/TickSz)
    long_profit_level := TickSz * math.round(long_profit_level/TickSz)
    short_stop_level := ta.valuewhen(sell1, open, 0) * (100+stoploss)/100
    short_profit_level := ta.valuewhen(sell1, open, 0) * (100-target)/100
    short_stop_level := TickSz * math.round(short_stop_level/TickSz)
    short_profit_level := TickSz * math.round(short_profit_level/TickSz)
    
if(type=="VOLATILITY")
    long_stop_level := ta.valuewhen(buy1, open - iATR*ATRMultiplier, 0)
    long_profit_level := ta.valuewhen(buy1, open + iATR*ATRMultiplier, 0)
    short_stop_level := ta.valuewhen(sell1, open + iATR*ATRMultiplier, 0)
    short_profit_level := ta.valuewhen(sell1, open - iATR*ATRMultiplier, 0)

if(risk)
    if(strategy.position_size!=0)
        strategy.exit('TP/SL', 'BUY', stop=long_stop_level, limit=long_profit_level,alert_message=BX)
        strategy.exit('TP/SL', 'SELL', stop=short_stop_level, limit=short_profit_level,alert_message=SX)
plot(strategy.position_size <= 0 or not risk ? na : long_stop_level, color=color.new(color.red, 0), style=plot.style_circles, linewidth=2)
plot(strategy.position_size <= 0 or not risk ? na : long_profit_level, color=color.new(color.green, 0), style=plot.style_circles, linewidth=2)
plot(strategy.position_size >= 0 or not risk ? na : short_stop_level, color=color.new(color.red, 0), style=plot.style_circles, linewidth=2)
plot(strategy.position_size >= 0 or not risk ? na : short_profit_level, color=color.new(color.green, 0), style=plot.style_circles, linewidth=2)

Overview

SuperTrend Algomojo Trading Strategy with Target/Stoploss integrates with Algomojo automation to automatically execute trades via API calls to supported brokers for stocks like those on NSE. Backtesting controls allow date range filtering for historical simulation while live trading respects market sessions. Users adjust ATR source calculation, enable bar coloring and signal highlighting, and optionally apply fixed stoploss or target values for risk management. The script draws exclusively on the price chart without separate panes.

Details

Published by

ClimberMel on GitHub

Code credit

tradestudio, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Volatility & bands, Moving averages

Markets

Stocks

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Settings

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

SettingTypeDefaultVariable
Client IDstringZZ0011am_client_id
API Keystringxxxxxam_api_key
API Secret Keystringxxxxxam_api_secret
BrokerstringALICEBLUEam_broker
Strategy NamestringSupertrend Strategyam_strategy
Trading SymbolstringRELIANCE-EQam_symbol
ExchangestringNSEam_exchange
Quantityint1am_quantity
Order TypestringMARKETam_OrderType
ProductstringNORMALam_Product
Algo ModestringENABLEam_Mode
From Monthint9FromMonth
Show all 33 settings
SettingTypeDefaultVariable
From Dayint1FromDay
From Yearint2018FromYear
To Monthint1ToMonth
To Dayint1ToDay
To Yearint9999ToYear
Sourcesourcehl2src
ATR Multiplierfloat3.0Multiplier
ATR Periodint10Periods
Change ATR Calculation Method ?booltruechangeATR
Show Buy/Sell Signals ?booltrueshowsignals
Highlighter On/Off ?booltruehighlighting
Bar Coloring On/Off ?booltruebarcoloring
Intraday On/Off ?boolfalseintraday
Market sessionsession0915-1500marketSession
Stoploss/Target On/Offboolfalserisk
TypestringFIXEDtype
Stoplossfloat10.0stoploss
Targetfloat20.0target
TickSizefloat0.05TickSz
ATR Multiplierfloat1.5ATRMultiplier
ATR Periodint20ATRLength
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

This mean-reversion strategy plots Bollinger Bands and a long-term moving average directly on the price chart. It enters trades when price candles penetrate the outer Bollinger Bands beyond a user-defined body percentage, anticipating a price reversal. Entries

Strategy v5 Mean reversionVolatility & bands
Updated 2 months ago · None stated GitHub repository of Bollinger Bands Winner PRO [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
106 stars

This trading strategy combines three Exponential Moving Averages (8, 14, and 50 periods by default) with Stochastic RSI and Average True Range (ATR). It enters a long position when EMA 1 is above EMA 2, EMA 2 is above EMA 3, and the Stochastic RSI %K line cros

Strategy v4 TrendOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of 3 x EMA + Stochastic RSI + ATR

Bollinger Bands Strategy

by cklose2000
105 stars

This strategy generates buy and sell signals based on Bollinger Band crossovers combined with a simple moving average trend filter. It enters a long position when price crosses above the lower band while trading above the SMA filter line, and enters a short po

Strategy v5 Volatility & bandsMoving averages
Updated 1 year ago · None stated GitHub repository of Bollinger Bands Strategy
104 stars

This overlay strategy combines a Chandelier Exit with a zero-lag least squares moving average. Although the header mentions Heikin Ashi candles, the calculations use ordinary closes. An ATR trailing stop sets long and short levels, and direction flips when pri

Strategy v5 TrendMoving averages
Updated 3 years ago · MIT GitHub repository of Chandelier Exit & ZLSMA 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