A trailing stop loss is a dynamic stop loss that moves with the price, protecting profits while allowing the trade to remain open as long as the price is moving favorably. The SuperTrend indicator can be used as a basis for setting a trailing stop loss because it moves with the trend and reacts to changes in volatility.
Below is an example of a Pine Script strategy using the SuperTrend indicator to determine entry points, and then applying a trailing stop loss to manage the position. This script is based on Pine Script version 5:
//@version=5
strategy("SuperTrend Trailing Stop", overlay=true)
// SuperTrend settings
atrPeriod = input(10, title="ATR Period")
multiplier = input(3.0, title="ATR Multiplier")
// Get the ATR and calculate the SuperTrend
atr = ta.atr(atrPeriod)
upperBand = ta.hline(high - (multiplier * atr))
lowerBand = ta.hline(low + (multiplier * atr))
var float superTrend = na
var int trendDirection = 1
// Determine the SuperTrend value and the trend direction
if not na(superTrend[1])
if close[1] > superTrend[1]
superTrend := max(upperBand, superTrend[1])
trendDirection := 1
else
superTrend := min(lowerBand, superTrend[1])
trendDirection := -1
else
superTrend := upperBand
trendDirection := 1
if trendDirection == -1 and close > superTrend
superTrend := upperBand
trendDirection := 1
else if trendDirection == 1 and close < superTrend
superTrend := lowerBand
trendDirection := -1
// Plot SuperTrend
plot(superTrend, color=(trendDirection > 0 ? color.green : color.red), linewidth=2, title="SuperTrend")
// Strategy order conditions based on SuperTrend
longCondition = trendDirection == 1 and close > superTrend
if longCondition
strategy.entry("Long", strategy.long)
shortCondition = trendDirection == -1 and close < superTrend
if shortCondition
strategy.close("Long")
// Set up trailing stop using the SuperTrend
if strategy.position_size > 0
strategy.exit("Trailing Stop", "Long", stop=superTrend)
The script defines the parameters for the SuperTrend calculation and then calculates the upper and lower bands based on the ATR and multiplier. The core of the strategy is the trailing stop logic:
- If in a long position, the strategy uses the SuperTrend value as the stop loss level.
- If the price crosses the SuperTrend and closes on the other side, it either takes a new position (if not already in one) or exits the current position.
Remember to test this script thoroughly in a simulated environment before considering it for live trading. This strategy does not include risk management considerations, such as position sizing or capping losses, nor does it provide an exit strategy other than the trailing stop. You should modify it to fit your trading plan and risk management rules.
Trading involves risk, and a trading strategy's past performance does not guarantee future results. Always ensure you fully understand the risks involved and consider seeking advice from a qualified professional if uncertain.