Understanding Pine Script Trailing Take Profit: A Comprehensive Guide
You know that feeling when you're in a winning trade and you're not sure when to get out? Too early and you miss out on bigger profits. Too late and you watch your gains evaporate. That's where trailing take profit comes in - it's like having a smart assistant that follows your trade and locks in profits for you.
Let me walk you through how to set this up in Pine Script, because honestly, it took me way too long to figure this out when I first started.

What is Trailing Take Profit?
Think of trailing take profit like a loyal dog that follows you on a walk. As you move forward (price goes up in your favor), it stays a fixed distance behind you. But if you stop or turn around (price reverses), it stops too and won't go backwards.
Here's what makes it so useful:
- You don't have to babysit your trades constantly
- You can ride trends for bigger profits
- It automatically protects your gains when things turn south
The beauty is that it removes the emotional guesswork from exits. No more "should I close now?" anxiety.

The No-Code Approach (If You're Not Into Coding)
Look, I get it. Not everyone wants to spend hours debugging Pine Script code. If you just want to build strategies without the headache, there are visual tools out there like Pineify that let you drag and drop your way to a working strategy.

It's pretty neat - you can set up complex trailing stops without touching code. But since you're here reading about Pine Script, I'm guessing you want to understand how it actually works under the hood.
Website: Pineify
Check out what Pineify can do.Building Your Own Trailing Take Profit
Alright, let's get our hands dirty. Here's a basic setup that actually works:
//@version=5
strategy("My Trailing Stop", overlay=true)
// Simple entry - when price crosses above the 20-period moving average
longCondition = ta.crossover(close, ta.sma(close, 20))
// These are the knobs you can turn
trailPercentage = input.float(1, "How far to trail (%)", minval=0.1) * 0.01
activationPercentage = input.float(1.5, "When to start trailing (%)", minval=0.1) * 0.01
// Jump in when conditions are met
if (longCondition)
strategy.entry("Long", strategy.long)
// Figure out our key levels
entryPrice = strategy.opentrades.entry_price(strategy.opentrades - 1)
activationLevel = entryPrice * (1 + activationPercentage)
trailDistance = entryPrice * trailPercentage
// The magic happens here
strategy.exit("Trail Stop", "Long", trail_points=trailDistance, trail_offset=0,
when=high >= activationLevel)
The Stuff That'll Drive You Crazy (And How to Fix It)
Backtesting Lies to You
Here's something that frustrated me for months: your backtest results might be completely wrong. Pine Script processes data bar by bar, so if a trade opens and closes within the same candle, it might show you exiting at the perfect wick high minus your trail distance. In reality? Good luck with that execution.
Even TradingView's "Bar Magnifier" feature (which costs extra, by the way) doesn't always fix this.
The Workaround That Actually Works
What I do now is run my strategy on a much lower timeframe but calculate my signals on the higher timeframe. So if I'm trading a 4-hour strategy:
- Set the chart to 2 minutes
- Use
request.security()
to get my 4-hour indicators - Only trade when both timeframes align
It's like zooming in on each 4-hour candle to see what really happened inside. Your backtests become way more realistic.
Making It Smarter
Dynamic Trailing Based on Volatility
Instead of using a fixed percentage, you can make your trailing distance adapt to how crazy the market is:
// Use ATR to measure market craziness
atrPeriod = input.int(14, "ATR Period")
atrMultiplier = input.float(2, "ATR Multiplier")
dynamicTrailDistance = ta.atr(atrPeriod) * atrMultiplier
// Apply it to your exit
strategy.exit("Smart Trail", "Long", trail_points=dynamicTrailDistance,
trail_offset=0, when=high >= activationLevel)
This way, in choppy markets your trail stays further back, and in smooth trends it follows closer.
When to Start Trailing
Don't start trailing immediately after entry - that's usually a mistake. Wait until you have some cushion:
- Breakeven start: Only start trailing once you're at least at breakeven
- Minimum profit: Wait until you have a decent profit before the trailing kicks in
Mistakes That'll Bite You
The Instant Exit Bug
I've seen this so many times (and did it myself): you set up your trailing logic, run it, and boom - it exits immediately after every entry.
Here's a classic example of broken code:
// DON'T DO THIS
long_trailing_percentage = input.float(title="Trailing %", defval=.01) * 0.01
long_previous_close_price = math.max(close, close, close) // This is always just 'close'
long_trailing_price := long_previous_close_price * (1 - long_trailing_percentage)
// This condition is ALWAYS true!
if long_trailing_price < long_previous_close_price
strategy.close("EL", comment="Oops", immediately = true)
The Right Way to Do It
Track the highest price since you entered, not just the current price:
var float highestPrice = na
if (strategy.position_size > 0)
// Keep track of the highest high since entry
highestPrice := na(highestPrice) ? high : math.max(highestPrice, high)
trailPrice = highestPrice * (1 - trailPercentage)
// Only exit if price drops below our trail
if (close < trailPrice)
strategy.close("Long", comment="Trailed out")
Wrapping Up
Trailing take profit isn't magic, but it's pretty close. Once you get it working properly, it takes a lot of the stress out of trading. You can actually sleep at night knowing your profits are protected.
The key is starting simple, testing thoroughly (with realistic expectations about backtest accuracy), and gradually adding complexity as you understand how it behaves in different market conditions.
Don't get discouraged if your first attempts don't work perfectly - this stuff takes time to get right. But once you do, it's a game changer.