Strategy · Pine Script v5 · On the chart

ATR trailing SL tight to slack [Takazudo]

by hasnocool

This strategy executes breakout trades based on historical high and low entry bands and manages risk using adaptive ATR trailing stop-loss levels.

View on GitHub

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

100 lines of Pine Script v5 from ATR trailing Stop Loss tight to slack [Takazudo].pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

ATR trailing Stop Loss tight to slack [Takazudo].pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
//@version=5
//@author=Takazudo
strategy("ATR trailing SL tight to slack [Takazudo]",
  overlay=true,
  default_qty_type=strategy.fixed,
  initial_capital=0,
  currency=currency.USD)
posSize = strategy.position_size
hasNoPos = posSize == 0
hasLongPos = posSize > 0
hasShortPos = posSize < 0
//============================================================================
// consts, inputs
//============================================================================
// colors
var COLOR_SL_LINE = color.new(#e0f64d, 20)
var COLOR_SL_LINE_THIN = color.new(#e0f64d, 90)
var COLOR_ENTRY_BAND = color.new(#43A6F5, 30)
var COLOR_TRANSPARENT = color.new(#000000, 100)
// Entry strategy
_g1 = 'Entry strategy'
var config_entryBandBars = input.int(defval = 100, title = "Entry band bar count",  minval=1, group=_g1)
_g2 = 'ATR SL'
var config_slAtr_length = input.int(24, title = "Trailing stop ATR Length", group=_g2)
var config_slAtr_multi1 = input.float(1.5, title = "Trailing stop ATR Multiple on tight", step=0.1, group=_g2)
var config_slAtr_multi2 = input.float(4, title = "Trailing stop ATR Multiple on slack", step=0.1, group=_g2)
_g3 = 'Backtesting range'
var config_fromYear  = input.int(defval = 2016, title = "From Year",  minval = 1970, group=_g3)
var config_fromMonth = input.int(defval = 1,    title = "From Month", minval = 1, maxval = 12, group=_g3)
var config_fromDay   = input.int(defval = 1,    title = "From Day",   minval = 1, maxval = 31, group=_g3)
var config_toYear  = input.int(defval = 2021, title = "To Year",  minval = 1970, group=_g3)
var config_toMonth = input.int(defval = 4,    title = "To Month", minval = 1, maxval = 12, group=_g3)
var config_toDay   = input.int(defval = 5,    title = "To Day",   minval = 1, maxval = 31, group=_g3)
//============================================================================
// Range Edge calculation
//============================================================================
f_calcEntryBand_high() =>
    _highest = math.max(open[3], close[3])
    for i = 4 to (config_entryBandBars - 1)
        _highest := math.max(_highest, open[i], close[i])
    _highest
f_calcEntryBand_low() =>
    _lowest = math.min(open[3], close[3])
    for i = 4 to (config_entryBandBars - 1)
        _lowest := math.min(_lowest, open[i], close[i])
    _lowest
entryBand_high = f_calcEntryBand_high()
entryBand_low = f_calcEntryBand_low()
entryBand_height = entryBand_high - entryBand_low
plot(entryBand_high, color=COLOR_ENTRY_BAND, linewidth=1)
plot(entryBand_low, color=COLOR_ENTRY_BAND, linewidth=1)
rangeBreakDetected_long = entryBand_high < close
rangeBreakDetected_short = entryBand_low > close
shouldMakeEntryLong = (strategy.position_size == 0) and rangeBreakDetected_long
shouldMakeEntryShort = (strategy.position_size == 0) and rangeBreakDetected_short
//============================================================================
// ATR based stuff
//============================================================================
sl_atrHeight_tight = ta.atr(config_slAtr_length) * config_slAtr_multi1
sl_atrHeight_slack = ta.atr(config_slAtr_length) * config_slAtr_multi2
sl_tight_bull = math.min(open, close) - sl_atrHeight_tight
sl_tight_bear = math.max(open, close) + sl_atrHeight_tight
sl_slack_bull = math.min(open, close) - sl_atrHeight_slack
sl_slack_bear = math.max(open, close) + sl_atrHeight_slack
plot(sl_tight_bull, color=COLOR_SL_LINE_THIN, linewidth=1)
plot(sl_tight_bear, color=COLOR_SL_LINE_THIN, linewidth=1)
plot(sl_slack_bull, color=COLOR_SL_LINE_THIN, linewidth=1)
plot(sl_slack_bear, color=COLOR_SL_LINE_THIN, linewidth=1)
//============================================================================
// Sl
//============================================================================
var trailingSl_long = hl2
var trailingSl_short = hl2
trailingSl_long := if hasLongPos
    math.max(trailingSl_long, sl_slack_bull)
else
    sl_tight_bull
trailingSl_short := if hasShortPos
    math.min(trailingSl_short, sl_slack_bear)
else
    sl_tight_bear
color_sl_long = hasLongPos ? COLOR_SL_LINE : COLOR_TRANSPARENT
color_sl_short = hasShortPos ? COLOR_SL_LINE : COLOR_TRANSPARENT
plot(trailingSl_long, color=color_sl_long, linewidth=2)
plot(trailingSl_short, color=color_sl_short, linewidth=2)
//============================================================================
// make entries
//============================================================================
// Calculate start/end date and time condition
startDate  = timestamp(config_fromYear, config_fromMonth, config_fromDay, 00, 00)
finishDate = timestamp(config_toYear,   config_toMonth,   config_toDay,   00, 00)
if (time >= startDate and time <= finishDate)
    if shouldMakeEntryLong
        strategy.entry(id="Long", direction=strategy.long, stop=close, qty=1000)
    if shouldMakeEntryShort
        strategy.entry(id="Short", direction=strategy.short, stop=close, qty=1000)
strategy.exit('Long-SL/TP', 'Long', stop=trailingSl_long)
strategy.exit('Short-SL/TP', 'Short', stop=trailingSl_short)
Expand (135 lines)

Overview

ATR trailing SL tight to slack [Takazudo] enters long positions when the close breaks above the lookback band and short positions when it breaks below. Stop loss levels transition between tight and slack multiples of the ATR. Plots include the entry channel levels and trailing stop-loss values directly on the price chart. Backtesting can be bounded by a specific date window.

Details

Published by

hasnocool on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Breakout, Volatility & bands

Markets

Any symbol

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.

Topics

analysisbtcusdtcryptocurrencydatapandaspythonsimulationtradingtradingview

Settings

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

SettingTypeDefaultVariable
Entry band bar countint100config_entryBandBars
Trailing stop ATR Lengthint24config_slAtr_length
Trailing stop ATR Multiple on tightfloat1.5config_slAtr_multi1
Trailing stop ATR Multiple on slackfloat4config_slAtr_multi2
From Yearint2016config_fromYear
From Monthint1config_fromMonth
From Dayint1config_fromDay
To Yearint2021config_toYear
To Monthint4config_toMonth
To Dayint5config_toDay
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

257 stars

This strategy plots VWMA-based Bollinger bands on the 1-minute ES futures price chart for volatility analysis and potential breakout identification. It calculates dynamic long and short stop loss and take profit levels using percentage inputs relative to entry

Strategy v6 Volatility & bandsSupport & resistance
Updated 6 weeks ago · None stated GitHub repository of V1.6 ES - Futures 1M No Repaint
218 stars

This strategy detects price breakouts above rolling highest highs or below lowest lows over a customizable lookback period. It includes optional volume spike and ATR volatility threshold filters, along with bar confirmation rules. Positions are taken upon conf

Strategy v6 BreakoutVolatility & bands
Updated 3 months ago · None stated GitHub repository of Breakout Strategy Template

Bollinger Breakout

by hackingthemarkets
189 stars

This price-chart strategy plots a simple moving average and upper and lower bands built from the standard deviation of close, scaled by separate offset inputs. It enters a fixed quantity long when close crosses above the upper band and a fixed quantity short w

Strategy v4 Volatility & bandsBreakout
Updated 3 years ago · None stated GitHub repository of Bollinger Breakout

均线突破交易系统

by tangly1024
76 stars

This strategy trades long breakouts of a fast and a slow moving average on the price chart. It opens a long position when price crosses above either average, using a percentage of equity as size. It reduces the position by a set share when the high reaches the

Strategy v5 TrendMoving averages
Updated 4 months ago · None stated GitHub repository of 均线突破交易系统

Bollinger bands examples

by tradingstrategy-ai
53 stars

This strategy plots exponential-moving-average Bollinger bands on the price chart and calculates RSI. It opens a long position when close crosses above the upper band while RSI is at or above a threshold, the date filter allows trading, and no position is open

Strategy v5 Volatility & bandsOscillators & momentum
Updated 3 years ago · None stated GitHub repository of Bollinger bands examples

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