Indicator · Pine Script v5 · On the chart

Bjorgum AutoTrail

by theonetrade

Bjorgum AutoTrail calculates and plots dynamic trailing stop levels directly on the price chart.

View on GitHub

GitHub stars34on the repository
Pine versionv5runs as is
Lines of code247
Settings18inputs
LicenceMIT
Last update2 weeks ago8 Nov 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

247 lines of Pine Script v5 from assets/indicator/bit-exact/bjorgum_autotrail_EfbdipVs.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

bjorgum_autotrail_EfbdipVs.pine
// █▀▀▄ ──▀ █▀▀█ █▀▀█ █▀▀▀ █──█ █▀▄▀█ 
// █▀▀▄ ──█ █──█ █▄▄▀ █─▀█ █──█ █─▀─█ 
// ▀▀▀─ █▄█ ▀▀▀▀ ▀─▀▀ ▀▀▀▀ ─▀▀▀ ▀───▀

//@version=5
indicator     ('Bjorgum AutoTrail', "Bj AutoTrail", overlay=true)

// ================================== //
// ------------> Tips <-------------- //
// ================================== //

barTimeTip      = "Time to start trail. Time can be interactively selected with the cursor"
priceTip        = "Price to start trail. Price can be interactively selected with the cursor"
trailTypeTip    = "4 different trail types can be used. Refer to release documentation for more info"
trailSourceTip  = "The price source for calculating trailing stop"

atrLengthTip    = "Length of the period for the ATR to average. Valid only if ATR type trail is envoked" 
atrMultTip      = "Multiplier as a function of the ATR value projected from the calculated swing high/low. ex 1 = ATR distance. Valid only if ATR type trail is envoked"
percTip         = "Percent offset from closing price. Stop will set at the cursor selected price, and trail a change in price by a factor of percent if percent trail is selected."
lookbackTip     = "Look back period to measure swing lows. A lower number brings a trail tighter to price action, where as a higher number will look back farther for significant swing points."

startTip        = "PSAR Start"
incTip          = "Step Setting (Sensitivity) - A higher step moves SAR closer to the price action, which makes a reversal more likely"
maxTip          = "PSAR Max - While the Maximum Step can influence sensitivity, the Step carries more weight"

quantityTip     = "Will fill in quantity for an alert if used"
marketTip       = "Will fill in a market for an alert if used. Ex. Spot or futures acronyms"
brokerTip       = "Will fill in a broker for a fx based alert if used"

// ================================== //
// ---------> User Input <----------- //
// ================================== //

barTime         = input.time    (0      ,   'Bar Time'      ,   group= 'Set Trade',             tooltip= barTimeTip,        inline=  '1',      confirm=true)
price           = input.price   (0      ,   'Price'         ,   group= 'Set Trade',             tooltip= priceTip,          inline=  '1',      confirm=true)
trailType       = input.string  ('Price',   'Trail Type'    ,   group= 'Set Trade',             tooltip= trailTypeTip,      options= ['ATR' , 'Percent', 'Price', 'Sar'])
trailSource     = input.string  ("High/Low","Stop Source"   ,   group= "Set Trade",             tooltip= trailSourceTip,    options= ["High/Low", "Close", "Open"])

atrLength       = input.int     (14     ,   'ATR Length'    ,   group= 'Trail Offset',          tooltip= atrLengthTip)
atrMult         = input.float   (1      ,   'ATR Multiplier',   group= 'Trail Offset',          tooltip= atrMultTip)
perc            = input.float   (2.0    ,   'Percent Trail' ,   group= 'Trail Offset',          tooltip= percTip)
lookback        = input.int     (5      ,   'Lookback'      ,   group= 'Trail Offset',          tooltip= lookbackTip)

start           = input.float   (0.043  ,   'Start'         ,   group= 'Psar Settings',         tooltip= startTip) 
inc             = input.float   (0.043  ,   'inc'           ,   group= 'Psar Settings',         tooltip= incTip)
max             = input.float   (0.34   ,   'max'           ,   group= 'Psar Settings',         tooltip= maxTip)
    
longCol         = input.color   (#64b5f6,   ''              ,   group= 'Stop Color',            inline='2')
ShortCol        = input.color   (#ef5350,   ''              ,   group= 'Stop Color',            inline='2')
lineWidth       = input.int     (2      ,   ''              ,   group= 'Stop Color',            inline='2')
transp          = input.int     (0      ,   ''              ,   group= 'Stop Color',            inline='2')

quantity        = input.float   (0.001  ,   'Quantity'      ,   group= 'Live Trade Metrics',    tooltip= quantityTip)
market          = input.string  ('usdm' ,   'Market'        ,   group= 'Live Trade Metrics',    tooltip= marketTip)
broker          = input.string  ('Test' ,   'Broker'        ,   group= 'Live Trade Metrics',    tooltip= brokerTip)

// ================================== //
// -----> Invariable Constants <----- //
// ================================== //

var color       lColor          = color.new(longCol,  transp)
var color       sColor          = color.new(ShortCol, transp)
var int         trade           = 0
var float       trailPrice      = 0.0
var float       initSrc         = 0.0
var float       initHigh        = 0.0
var float       initLow         = 0.0
var bool        long            = false
var bool        short           = false
var bool        oneTime         = true
var bool        psar            = trailType == 'Sar'
var bool        atrTrail        = trailType == 'ATR'
var bool        percTrail       = trailType == 'Percent' 
float           tTrailPrice     = 0.0
 
var float       sar             = na
var float       maxMin          = na
var float       accel           = na
var bool        isBelow         = na
var float       lsar            = 0.0
bool            isFirstTrendBar = false

// ================================== //
// ----> Variable Calculations <----- //
// ================================== //

    // PSAR Calcualtion // 

if bar_index            == 1
    if close > close[1]
        isBelow         := true
        maxMin          := high
        sar             := low[1]
    else
        isBelow         := false
        maxMin          := low
        sar             := high[1]
    isFirstTrendBar     := true
    accel               := start

sar                     := sar + accel * (maxMin - sar)
lsar                    := sar
if isBelow
    if sar > low
        isFirstTrendBar := true
        isBelow         := false
        sar             := math.max(high, maxMin)
        maxMin          := low
        accel           := start
else
    if sar < high
        isFirstTrendBar := true
        isBelow         := true
        sar             := math.min(low, maxMin)
        maxMin          := high
        accel           := start
        
if not isFirstTrendBar
    if isBelow
        if high > maxMin
            maxMin      := high
            accel       := math.min(accel + inc, max)
    else
        if low < maxMin
            maxMin      := low
            accel       := math.min(accel + inc, max)

if isBelow
    sar                 := math.min(sar, low[1])
    if bar_index > 1
        sar             := math.min(sar, low[2])
else
    sar                 := math.max(sar, high[1])
    if bar_index > 1
        sar             := math.max(sar, high[2])
    sar

// ================================== //
// ----> Conditional Parameters <---- //
// ================================== //

timeStart               = time_close[1] <= barTime and time >= barTime

if timeStart
    long                := price < close 
    short               := price > close 
    initSrc             := trailSource == "Close" ? close : trailSource == "Open"  ? open : long ? low : high
    initHigh            := high
    initLow             := low
    if long 
        trade           :=  1
    if short
        trade           := -1 

atr                     = ta.atr (atrLength)

trailSrc                = trailSource == "Close" ? close[1] : trailSource == "Open"  ? open[1] : long ? low : high

diff                    = math.abs(initSrc-price)

offset                  = percTrail ? close * (perc/100) :
                          atrTrail  ? atr   *  atrMult   : diff

swingLow                = ta.lowest  (trailSrc, lookback) - (offset)
swingHigh               = ta.highest (trailSrc, lookback) + (offset) 

sarTrail                = ((long and isBelow) or (short and not isBelow))  

levelCheck              = (long and price < swingLow) or (short and price > swingHigh)

tTrailPrice             := psar and sarTrail ? sar : 
                           timeStart and not levelCheck ? price : 
                           long ? swingLow : short ? swingHigh : 0

// ================================== //
// --------> Logical Order <--------- //
// ================================== //

if time >= barTime and (psar or barstate.isconfirmed)
    if long and trade   == 1
        if  tTrailPrice  > trailPrice or trailPrice == 0.0 
            trailPrice  := tTrailPrice
            
        if low <= trailPrice 
            trade       := 0

        if  isBelow[1] and psar and not isBelow and (trade != 0)[1]
            trade       := 0
    
    if short and trade  == -1 
        if  tTrailPrice  < trailPrice or trailPrice == 0.0 
            trailPrice  := tTrailPrice

        if high >= trailPrice 
            trade       := 0

        if isBelow and not isBelow[1] and psar and (trade != 0)[1]
            trade       := 0

// ================================== //
// ------> Graphical Display <------- //
// ================================== //

longSig     = (trade ==  1)[1] and low  <= trailPrice 
shortSig    = (trade == -1)[1] and high >= trailPrice

psarSig     = psar    and (trade !=  trade[1])  and    (trade       != 0)[1]
plotPsar    = psarSig ?   lsar   :   psar       and     trade       != 0  ?  trailPrice : na
plotTrail   = psar    ?   na     :   trailPrice != 0 ?  trailPrice  : na

longStop    = long  and psar ? psarSig : longSig
shortStop   = short and psar ? psarSig : shortSig

plotColor   = long ? lColor : sColor

plotshape   (longStop,  style= shape.xcross, size= size.tiny, text= "Long Stop",  color= lColor, textcolor= lColor, location=location.abovebar)
plotshape   (shortStop, style= shape.xcross, size= size.tiny, text= "Short Stop", color= sColor, textcolor= sColor, location=location.belowbar)

plot        (psar ? na : trailPrice != 0 ? trailPrice : na, 'Trailing Stop', color=(trade == 0)[1] ? na : plotColor, style=plot.style_linebr, linewidth=lineWidth)

plot        (plotPsar, "SAR", plotColor, style=plot.style_circles, linewidth=lineWidth)

// ================================== //
// -----> Alert Functionality <------ //
// ================================== //

if price <= initHigh and price >= initLow and time_close >= barTime and time_close[1] <= barTime
    runtime.error("Stop cannot be placed in candle range")

action      = long  ? 'sell' : 
              short ? 'buy'  : na

// Building block starter for a crypto API alert to a third party. Some assembly required.
// Triggers only on crypto pairs and autofills information from the chart and script. 
if (longStop or shortStop) and oneTime and syminfo.type == "crypto"
    alert(action + ' ' + syminfo.basecurrency + syminfo.currency + ' ' + 'q=' + str.tostring(quantity) + ' ' + 'a=' + market)
    oneTime := false

// Building block starter for a forex browser extension API alert. Batteries not included.
// Triggers only on forex pairs and autofills information from the chart and script. 
if (longStop or shortStop) and oneTime and syminfo.type == "forex"
    alert("e=" + broker + " s=" + syminfo.basecurrency + "/" + syminfo.currency + " b=" + action + " q=" + str.tostring(quantity))
    oneTime := false

// Basic alerts for manual trading
alertcondition(longStop,  "Long Trail", 'Long  Trail Trigger on {{interval}} chart. Price is {{close}}')
alertcondition(shortStop, "Short Trail",'Short Trail Trigger on {{interval}} chart. Price is {{close}}')

Overview

Bjorgum AutoTrail supports four distinct trailing stop methods: Average True Range (ATR), percentage distance, price lookback, and Parabolic SAR (PSAR). Users can set starting anchor points interactively via price and bar time chart inputs and select price sources like High/Low, Close, or Open. Settings allow fine-tuning of ATR multipliers, lookback periods, and PSAR sensitivity.

Details

Published by

theonetrade on GitHub

Draws

On the price chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

algorithmic-tradingbacktestingbitcoinccxtcrypto-tradingllm-agentoffline-backtestingopen-source-tradingpine-scriptpine-to-pythonpinescriptpynecorepythonquantquantitative-financestrategy-backtestingtechnical-analysistrading-indicatorstrading-strategiestradingview

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Bar Timetime0barTime
Priceprice0price
Trail TypestringPricetrailType
Stop SourcestringHigh/LowtrailSource
ATR Lengthint14atrLength
ATR Multiplierfloat1atrMult
Percent Trailfloat2.0perc
Lookbackint5lookback
Startfloat0.043start
incfloat0.043inc
maxfloat0.34max
longColcolor#64b5f6longCol
Show all 18 settings
SettingTypeDefaultVariable
ShortColcolor#ef5350ShortCol
lineWidthint2lineWidth
transpint0transp
Quantityfloat0.001quantity
Marketstringusdmmarket
BrokerstringTestbroker
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

[RS]Donchian Fans

by ricardosantos79
261 stars

This indicator plots Donchian Channel boundary lines along with dynamic fan projections directly on the price chart. It calculates the highest high, lowest low, and median price over a customizable lookback period. Whenever price establishes a new channel high

Indicator v4 Support & resistanceTrend
Updated 5 years ago · None stated GitHub repository of [RS]Donchian Fans

Dynamic Linear Regression

by TradersPost
228 stars

Dynamic Linear Regression calculates and plots linear regression trendlines and standard deviation channels directly on the price chart over a user-selected time period. Traders can configure static channels locked at the end time, dynamic channels that contin

Indicator v6 TrendSupport & resistance
Updated 4 months ago · None stated GitHub repository of Dynamic Linear Regression

ATR Trailing Stop

by mihakralj
99 stars

Calculates an ATR-based trailing stop overlaid on the price chart to assist with trend identification and stop placement. Using a specified ATR period and multiplier, it projects upper and lower bounds around the closing price. The stop line ratchets up during

Indicator v5 TrendVolatility & bands
Updated 8 weeks ago · Apache-2.0 GitHub repository of ATR Trailing Stop

Moon Dev Lunar Sniper

by moondevonyt
98 stars

Moon Dev Lunar Sniper is a multi-indicator overlay that scores confluence across fast and slow EMAs, RSI, MACD, DMI, and BB width to fire signals only when score meets the minimum threshold. It plots buy and sell signals on the price chart, highlights cosmic b

Indicator v6 TrendOscillators & momentum Repaints
Updated 2 months ago · Custom licence GitHub repository of Moon Dev Lunar Sniper

SuperTrend & Pivots

by dcaoyuan
55 stars

This overlay indicator plots a SuperTrend line on the price chart using a fixed ATR length of 10 and a factor of 3. When the trend direction is up it draws a green line and a light green fill toward the candle midpoint; when down it draws a red line and a ligh

Indicator v6 TrendVolatility & bands
Updated 7 months ago · Apache-2.0 GitHub repository of SuperTrend & Pivots

More Support & resistance scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers