Strategy · Pine Script v5 · On the chart

TSL

by riegodavid-git· code credited to ZenAndTheArtOfTrading / PineScriptMastery.com

A strategy that tests trailing stop methods on a single mock trade.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code65
Settings9inputs
LicenceNone statedfile: MPL-2.0
Last update4 months ago25 Jun 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

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

tsl_atr.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ZenAndTheArtOfTrading / PineScriptMastery.com
// @version=5
strategy("TSL", overlay=true)

// Get user input
tradeType           = input.string(title="Trade Direction", defval="Long", options=["Long", "Short"], confirm=true)
exit_type = input.string(title="Exit Type", defval="Wick", options=["Close", "Wick"], confirm=true)
trailSource         = input.string(title="Trail Source", defval="Lows/Highs", options=["Lows/Highs", "Close", "Open"], confirm=true)
trailMethod         = input.string(title="Trail Method", defval="ATR", options=["ATR", "Percent"], confirm=true)
trailPercent        = input.float(title="Trail Percent", defval=10, minval=0.1, confirm=true)
swingLookback       = input.int(title="Lookback", defval=7, confirm=true)
atrPeriod           = input.int(title="ATR Period", defval=14, confirm=true)
atrMultiplier       = input.float(title="ATR Multiplier", defval=0.5, confirm=true, step = 0.5)
barTime             = input.time(title="Bar Time", defval=timestamp("01 Jan 2021 13:30 +0000"), confirm=true)

// Enter mock trade (if bar is the one we clicked on and we have no open trades or previous trades)
if time >= barTime and strategy.position_size == 0 and strategy.closedtrades == 0
    strategy.entry("Trade", direction = (tradeType == "Long" ? strategy.long : strategy.short))

// Declare trailing price variable (stores our trail stop value)
var float trailPrice    = na
float next_trailPrice   = na

// Get required trailing stop variables
atrValue                = ta.atr(atrPeriod) * atrMultiplier
float swingLow          = ta.lowest(low, swingLookback)
float swingHigh         = ta.highest(high, swingLookback)

// Get trailing stop price
if trailMethod == "ATR" // Determine ATR trailing stop price based on price source
    next_trailPrice := switch trailSource
        "Close"     => strategy.position_size > 0 ? close - atrValue : close + atrValue
        "Open"      => strategy.position_size > 0 ? open - atrValue : open + atrValue
        => strategy.position_size > 0 ? swingLow - atrValue : swingHigh + atrValue
else if trailMethod == "Percent" // Determine percentage trailing stop price based on price source
    float percentMulti = strategy.position_size > 0 ? (100 - trailPercent) / 100 : (100 + trailPercent) / 100
    next_trailPrice := switch trailSource
        "Close"     => close * percentMulti
        "Open"      => open * percentMulti
        => strategy.position_size > 0 ? swingLow * percentMulti : swingHigh * percentMulti

// Check for trailing stop update
if strategy.position_size != 0 and barstate.isconfirmed
    // Trail long stop ONLY IF temp trailPrice is not set or is a higher price
    if (next_trailPrice > trailPrice or na(trailPrice)) and strategy.position_size > 0
        trailPrice := next_trailPrice
        // Trigger alert
        alert(message="Trailing Stop updated for " + syminfo.tickerid + ": " + str.tostring(trailPrice, "#.#####"), freq=alert.freq_once_per_bar_close)
    // Trail short stop ONLY IF temp trailPrice is not set or is a lower price
    if (next_trailPrice < trailPrice or na(trailPrice)) and strategy.position_size < 0
        trailPrice := next_trailPrice
        // Trigger alert
        alert(message="Trailing Stop updated for " + syminfo.tickerid + ": " + str.tostring(trailPrice, "#.#####"), freq=alert.freq_once_per_bar_close)

// Draw data to chart
plot(strategy.position_size != 0 ? trailPrice : na, color=color.red, title="Trailing Stop")


if exit_type == "Wick"
// Exit trade if stop is hit
    strategy.exit(id="Trail Exit", from_entry="Trade", limit=na, stop=trailPrice)
else if exit_type == "Close"
    if (strategy.position_size > 0 and close < trailPrice) or (strategy.position_size < 0 and close > trailPrice)
        strategy.close("Trade")

Overview

TSL opens one long or short position at a chosen start time and then trails a stop behind price. The trail can use ATR with a multiplier or a percentage, anchored to swing lows and highs, closes or opens over a lookback, and exits can trigger on a close or on a wick. Alerts fire when the stop moves. Direction, source, method and start time are set by the user. There is no signal logic.

Details

Published by

riegodavid-git on GitHub

Code credit

ZenAndTheArtOfTrading / PineScriptMastery.com, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

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.

Settings

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

SettingTypeDefaultVariable
Trade DirectionstringLongtradeType
Exit TypestringWickexit_type
Trail SourcestringLows/HighstrailSource
Trail MethodstringATRtrailMethod
Trail Percentfloat10trailPercent
Lookbackint7swingLookback
ATR Periodint14atrPeriod
ATR Multiplierfloat0.5atrMultiplier
Bar Timetimetimestamp("01 Jan 2021 13:30 +0000")barTime
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

Alert BB + RSI [Alorse] is a multi-symbol mean-reversion strategy designed for cryptocurrency trading. It evaluates Bollinger Bands and the Relative Strength Index (RSI) across up to 20 user-defined ticker symbols simultaneously. The strategy enters long posit

Strategy v4 Oscillators & momentumVolatility & bands
Updated 2 months ago · None stated GitHub repository of Alert BB + RSI [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 yesterday · None stated GitHub repository of Boilerplate Configurable Strategy [Yosiet]
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
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

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