Trailing Stop in Pine Script
A stop that follows price in the trade's favour and never retreats, defined by a trail distance, an activation point and a unit, ATR or percent, so winners run and reversals get cut.
Definition
A trailing stop is a stop order whose level follows price as the trade moves into profit and never moves back. For a long it sits a set distance below the highest price reached since it started trailing; for a short, the same distance above the lowest. It belongs to the volatility stops family when the distance is set in ATR, and to fixed rules when it is set in percent or ticks. Every trailing stop is defined by three choices: the trail distance, the point at which trailing starts, and whether the reference is the best high or the best close.
The stop turns an open gain into a defined exit level, so the decision to leave a trend becomes a rule rather than a judgement made in the moment. The cost is built into the design: the exit is always below the peak by at least the trail distance, and a pullback larger than that distance ends the trade even if the trend then resumes. A tight trail locks in more of a short move and is shaken out of a long one; a wide trail rides pullbacks and gives back more at the end. Setting the distance in ATR keeps the trade-off constant as volatility changes.
There is no single inventor; the trailing stop is an order type that brokers have offered for decades, and the ATR version came with Wilder's volatility work. The usual settings are 2 to 3 ATR for swing trades and 5 to 10 percent for daily stock positions, with an activation threshold so the stop starts trailing only once the trade shows a profit. The library strategy enters on a 9 and 21 EMA cross and exits with a trail of 3 ATR that activates after 1 ATR of profit, the ATR measured over 14 bars at the time of entry.
On the chart the stop stairs up behind a long trade, level during pullbacks and rising as price makes new highs, until a pullback of the trail distance hits it. In a strong trend that happens near the end, and the trade gives back roughly the trail distance from the peak. In a choppy market it happens early and often. The library strategy also leaves a trade on the opposite EMA cross, which is the exit in the cases where the trail was never activated; until price has moved the activation distance there is no stop at all, so the strategy's followup to add a fixed stop is worth taking.
Reading the chart
Set a trailing stop by choosing its unit, its distance, its activation and its reference, then watch it stair behind price.
- Choose the unit. ATR makes the distance match the instrument's volatility and travels across markets; percent is simple for daily stock positions; ticks only suit one instrument at one time.
- Set the distance from the pullbacks the trend produces. If the average pullback in the trends you want to hold is 2 ATR, a 2 ATR trail will be hit by most of them; 3 ATR survives them.
- Set the activation. Trailing from the first tick turns small dips into break-even exits; waiting for 1 ATR of profit lets the trade breathe before the stop follows.
- Pick the reference. Trailing the highest high reacts to every wick and holds the stop higher; trailing the highest close ignores spikes and leaves the stop a little lower.
- Watch the stop on a chart. It should rise in steps and never fall; the distance between price and the stop after a new high is the trail distance, and it shrinks in each pullback.
- Test the distance on history. Compare 2, 3 and 4 ATR on the same entries and look at how much each gives back at the end of trends against how often each is shaken out.
The maths
The stop trails the best price by the trail distance once the activation profit has been reached, and it only moves in the trade's favour.
In the library strategy the trail distance and the activation are converted from ATR into ticks on the entry bar, so both are fixed for the life of the trade at the ATR value at entry.
A percent trail grows in price terms as price rises; an ATR trail changes only when volatility does. The two behave very differently in a long trend.
Platform trailing orders update on every tick, so the exit can fire intrabar; a rule that only checks the close exits later and a little lower.
Before activation the library strategy has no stop other than the opposite EMA cross. A fixed initial stop can be added alongside the trail.
Inputs that matter
| Input | Typical | What changing it does |
|---|---|---|
| Trail distance (ATR multiples) | 3 | Tighter locks in more of a short move but is hit by ordinary pullbacks; wider rides through pullbacks and gives back more at the turn. |
| Activation profit (ATR multiples) | 1 | 0 starts trailing at once; higher waits for the trade to prove itself before the stop follows, leaving the early risk to the opposite signal. |
| Fast and slow EMA | 9 and 21 | The entry rule of the library strategy; longer lengths give fewer, slower entries and longer trades for the trail to work on. |
In practice
- As the exit of a trend-following entry: the library strategy enters on the EMA cross and lets the 3 ATR trail decide how long the trade lasts, which is the classic use.
- As protection after a partial exit: a partial-exit rule takes part of the position at a target and trails the rest, so the remainder can ride a trend without the whole position depending on it.
- As a percent rule on daily stock positions: a 7 to 10 percent trail below the highest close is a common position-trading exit that needs no chart reading.
- As a break-even device: activation at 1 ATR with a trail of 1 ATR moves the stop to about the entry price once the trade has moved 1 ATR, a rules-based break-even stop.
- As a comparison tool: run the same entries with 2, 3 and 4 ATR trails and read the difference in give-back and shake-outs, which is the test the library's backtest makes easy.
- As a replacement for discretionary exits: a trader who tends to leave winners early can hand the exit to the trail and act only on the entry.
Where it goes wrong
- Trailing too tightly. A 1 ATR trail is inside normal noise and turns most trends into small wins; 2 to 3 ATR is the usual range for swing trades.
- Running without an initial stop. Until the trail activates the library strategy has only the opposite cross; add a fixed stop for the entries that fail at once.
- Setting the trail in ticks or points. A fixed distance is right for one instrument in one volatility regime and wrong everywhere else; set it in ATR or percent.
- Expecting to exit near the top. By construction the exit is at least the trail distance below the peak; the give-back is the price of holding the trend.
Compared with
Chandelier Exit. The Chandelier is a specific trailing stop: an ATR multiple below the highest high of a lookback, with a ratchet. The generic trailing stop lets you choose the unit, the distance and the activation, and the library strategy applies it to EMA cross entries.
Parabolic SAR. The parabolic SAR is a trailing stop that accelerates as the trend ages, so it tightens with time whether or not price moves. A plain trailing stop keeps its distance and tightens only when price makes new extremes.
ATR Stop & Target. A fixed ATR stop and target set the exit at entry and leave it there. A trailing stop replaces the target with an exit that follows the trend, so the trade can run further and gives back some of the run at the end.
SuperTrend. SuperTrend is an ATR band that flips and can serve as a trailing stop at a fixed multiple from each bar. A trailing stop measures from the best price since entry, so it is anchored to the trade rather than to the bar.
Build it in Quant
Type one of these in the Quant desk, or click it. A request that fits a checked template is assembled on the spot without a credit; anything beyond the blanks goes to the copilot, which edits on top of the checked script.
Questions
ATR or percent?
ATR for anything traded across instruments or timeframes, because the distance then matches each market's noise and the rule carries over. Percent for daily stock positions held for weeks, where a 7 to 10 percent trail is easy to manage and volatility differences matter less. Never ticks, unless the rule lives on one instrument and is revisited when volatility changes.
How far should the trail be?
Far enough to survive the pullbacks the trend produces. For swing trades that is usually 2 to 3 ATR; for long-term trend following 3 to 4. Measure the pullbacks in the trends you want to hold and set the trail beyond most of them. The give-back at the end of the trend is roughly the trail distance, and that is the price of the rule.
What is the activation for?
It delays the trail until the trade has shown some profit. Without it a trade that dips before running is stopped near the entry by a stop that started trailing at once. The library strategy activates after 1 ATR of profit and then trails at 3 ATR; set activation to 0 to trail from the first bar.
Why does my backtest exit long before the top?
Because a pullback larger than the trail distance ended the trade before the final leg. That is the design, and a wider trail would have held the trade at the cost of more give-back in every other trade. Compare distances on the same entries and choose by total expectancy, not by the one trade that got away.
Should I trail on highs or closes?
Highs react to every wick, so the stop rises on spikes and is then closer to price; closes ignore spikes and give a steadier line. Platform trailing orders track the traded price, which is what the library strategy uses through its tick-based trail. For a calmer rule on wicky instruments, trail the close and exit on a close through the level.
Does the library strategy have an initial stop?
No. It enters on the 9 and 21 EMA cross, activates the trail after 1 ATR of profit and trails at 3 ATR, and it leaves on the opposite cross. Before activation the opposite cross is the only exit, so an entry that fails at once can lose more than a fixed stop would allow. Adding a fixed stop is the first followup the strategy offers.