//This demonstrates various methods we can use to code trailing stop losses in Pine Script to lock in profits in strategy scripts - including ATR and Percentage-based variants with several parameters.
/// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @version=5
strategy("www.PineScriptMastery.com", overlay=true)
// Get user input
tradeType = input.string(title="Trade Direction", defval="Long", options=["Long", "Short"], 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=1.0, confirm=true)
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")
// Exit trade if stop is hit
strategy.exit(id="Trail Exit", from_entry="Trade", limit=na, stop=trailPrice)
//if (strategy.position_size > 0 and close < trailPrice) or (strategy.position_size < 0 and close > trailPrice)
// strategy.close("Trade")
Overview
PineScriptMastery executes a single mock trade in the chosen direction starting at a user-defined timestamp. The trailing stop is calculated using either Average True Range or percentage offsets anchored to swing highs and lows, candle opens, or closes. Stop levels only ratchet in a favorable direction as price advances. The script plots levels directly on the price chart. It serves as an implementation template rather than an automated entry signal generator.
ATR and percentage trailing stop calculation methods
Anchor options using swing points, close, or open prices
The inputs you can change from the gear icon on the chart. Defaults are the author's.
Setting
Type
Default
Variable
Trade Direction
string
Long
tradeType
Trail Source
string
Lows/Highs
trailSource
Trail Method
string
ATR
trailMethod
Trail Percent
float
10
trailPercent
Lookback
int
7
swingLookback
ATR Period
int
14
atrPeriod
ATR Multiplier
float
1.0
atrMultiplier
Bar Time
time
timestamp("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.
This overlay strategy is built for ES futures on the one-minute chart. It plots a volume-weighted moving average of price opens and standard-deviation bands at Fibonacci ratios, plus a second longer volume-weighted average from a higher-timeframe open. Call an
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
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
KC15 is a price-chart strategy that configures two moving averages, a Bollinger Band Width Percentile filter, and PMARP entry and exit thresholds for long and short trades. Users can switch each average between SMA and EMA, set lengths and colors, and toggle l
This strategy implements a multi-stage trend following system inspired by John W. Seykota. It generates long and short entries when price breaks above or below Donchian channels of specified length. Each entry adds a unit sized to risk a fixed percentage of cu
Calculates upper and lower Donchian Channel bands over a customizable lookback length and plots them on the main price chart. At a specified exchange hour, the strategy places a long buy stop order at the upper Donchian Channel level. Unfilled pending orders a