PINE SCRIPT CODE FOR ATR TRAILING STOP-LOSS
Several years ago I came across a website as I was searching for coding a trailing stop-loss on MetaStock. A website called Trader Nexus helped me to better understand what a Chandelier Exit is with several great examples and some sort of a plug in DLL specifically designed for MetaStock formula language. Over the years I made some modifications to the ATR based trailing stop-loss.
Recently I spent couple of long hours on Trading View to understand and formulate the similar ATR based trailing stop by using their formula language, pine script. I think I was able to plot the indicator and I’m sharing it here with out members. I plan to integrate more and more Trading View functionalities to Tech Charts reports and website.
If you are interested in giving the platform a try here is your discounted link (Try Trading View with an initial discount)
I named it Simplified ATR Trailing Stop because so much more can be done with it by adding different calculations, such as price projections based on the initial risk etc. I will continue to build on this in the following posts. Let’s look at the below box for parameters.
The Simplified ATR Trailing Stop will start calculating on a set date that you specify. This is great because you want to trail the price from the breakout day or even after exceeding specific price level (can be your breakeven level or even to capture more of the upside after the price target is met).
Entry price: If you act at the close of the day, you can leave this value as 0 and it will take the close of the day for the initial protective stop-loss calculation. You can choose to add a value such as the pattern boundary and in that case it will subtract the initial protective stop-loss from the pattern boundary and not the close of the day. If you use a scaling in tactic during the day (buying in tranches intraday as the breakout takes place) and your average purchase price is different than the close of the day, you can also plug that number in to calculate the initial protective stop-loss.
ATR period: You can select the ATR period. It can be 10 day, 14 day or 30 day or any ATR period of your choice.
ATR Multiplier for Stop-loss: This is the multiplier that you want to trail the price with. From the highest level price reached it will trail the price with a 3 x ATR () distance. The higher the number, the wider the trailing stop-loss. (Short video on ATR based trailing stop-loss). A multiplier of 1 will trail the price so close that and adverse movement can result in triggering the stop-loss.
Custom Value for First day Trailing Stop: This is my favorite part. For aggressive risk management, your initial protective stop can be smaller than what the ATR Trailing Stop will use in its calculation after entry day. In this case you can take 1xATR () or even with FX and Futures you can apply 0.5xATR() as the first day to calculate initial protective stop. The protective stop turns into a trailing stop after the first day.
The chart below is a recent breakout alert that was featured in the Global Equity Markets report. The pattern boundary is at 1,128 levels. The simplified ATR Trailing Stop-Loss subtracts 1x ATR(10) from the pattern boundary to calculate the first value as the initial protective stop-loss. As the price resumes higher, it shifts to 3x ATR(10) and trails the price until the low of the day hits the trailing stop-loss of the previous day’s calculation. At that point the trailing stop will stop plotting on the chart.
Below is the pine script code for Trading View. I am sure many of you will build on this and make it better. But I think it is a good starting point as a floating trailing stop where you can enter custom values for calculation. You need to copy and paste the below code to the Pine Editor section of the Trading View charting platform (image below the code). Note that pine editor can be a premium functionality on Trading View and you might need a premium version.
Note: When you copy and paste the below code, the website formatting changes the ” ” quotation marks. So I’m adding here a text document with unformatted text for copying and pasting without issues.
Simplified ATR Trailing Stop Unformatted Text
Also here is the link that will direct you to the published script on Trading View. You can copy the source code from this link as well.
//@version=5
indicator(“Simplified ATR Trailing Stop”, overlay=true)
// === Inputs ===
entryDateYear = input.int(2023, title=”Entry Year”, minval=1900, maxval=2100)
entryDateMonth = input.int(1, title=”Entry Month”, minval=1, maxval=12)
entryDateDay = input.int(1, title=”Entry Day”, minval=1, maxval=31)
entryPrice = input.float(0, title=”Entry Price (Set to 0 for Close of the Day)”, minval=0, maxval=5000)
atrLength = input.int(14, title=”ATR Period”, minval=1)
atrMultiplier = input.float(2.0, title=”ATR Multiplier for Stop Loss”, minval=0.1)
customValueForFirstDay = input.float(2.0, title=”Custom Value for First Day Trailing Stop”, minval=0.1, maxval=100)
// === ATR Calculation ===
atrValue = ta.atr(atrLength)
// === Entry Timestamp ===
entryDate = timestamp(entryDateYear, entryDateMonth, entryDateDay, 00, 00)
// === Entry Level ===
var float entryLevel = na
if (na(entryLevel) and time >= entryDate)
entryLevel := (entryPrice > 0) ? entryPrice : close
// === Start Condition ===
startCalculating = (time >= entryDate)
// === Trailing Stop Logic ===
initialStop = entryLevel – atrMultiplier * atrValue
var float trailingStop = na
var bool firstDayCalculated = false
var bool stopPlotting = false // NEW
if (startCalculating and not stopPlotting)
if (na(trailingStop[1]))
if (not firstDayCalculated)
trailingStop := entryLevel – (atrValue * customValueForFirstDay)
firstDayCalculated := true
else
trailingStop := initialStop
else
trailingStop := math.max(trailingStop[1], high – atrMultiplier * atrValue)
// === NEW: Stop plotting if low < yesterday’s trailing stop
if (not na(trailingStop[1]) and low < trailingStop[1])
stopPlotting := true
// === Plotting ===
plot(startCalculating and not stopPlotting ? trailingStop : na, color=color.red, title=”Trailing Stop”, linewidth=2)
