Code Library / Trailing Stop

Pine Script Percentage Trailing Stop

Percentage-based trailing stop strategy for TradingView backtesting.

Language: Pine Script · Category: Trailing Stop · Tags: trailing stop, percentage, Pine Script, strategy, backtesting

Source code

//@version=5
strategy("Percentage Trailing Stop", overlay=true)
trailPct = input.float(2.0, "Trail %%") / 100
if ta.crossover(ta.sma(close,10), ta.sma(close,50))
    strategy.entry("Long", strategy.long)
if strategy.position_size > 0
    strategy.exit("Trail","Long",trail_price=close,trail_offset=close*trailPct/syminfo.mintick)

How to use this snippet

This is a building block, not a finished trading system. Paste it into your own Pine Script project, compile it, and test it on a demo account with your broker's real spreads before relying on it. You can convert it to MQL4 or MQL5 with the Pine Script converter.

Related snippets