Yes, you can create a trailing stop-loss in Pine Script using the strategy.exit() function.
For example, if you want to trail the stop by a fixed number of points, you can use the trail_points parameter.
//@version=6
strategy("Trailing Stop Example", overlay = true)
fastEMA = ta.ema(close, 9)
slowEMA = ta.ema(close, 21)
buyCondition = ta.crossover(fastEMA, slowEMA)
if buyCondition
strategy.entry("Long", strategy.long)
strategy.exit("Trailing Stop", from_entry = "Long", trail_points = 100, trail_offset = 100)
Here:
trail_points defines the trailing distance.
trail_offset defines the distance from the entry before the trailing stop starts.
Once the trade moves in your favor, the stop-loss automatically follows the price. If the price reverses and reaches the trailing stop, the position is closed.
You can change the trailing values according to your strategy and the instrument you are trading.
I hope this helps!