// █▀▀▄ ──▀ █▀▀█ █▀▀█ █▀▀▀ █──█ █▀▄▀█
// █▀▀▄ ──█ █──█ █▄▄▀ █─▀█ █──█ █─▀─█
// ▀▀▀─ █▄█ ▀▀▀▀ ▀─▀▀ ▀▀▀▀ ─▀▀▀ ▀───▀
//@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.
Four trailing stop calculation modes (ATR, Percent, Price, PSAR)
Interactive chart inputs for starting price and bar time
Configurable stop sources including High/Low, Close, and Open
Customizable ATR lookback and Parabolic SAR parameters
The inputs you can change from the gear icon on the chart. Defaults are the author's.
Setting
Type
Default
Variable
Bar Time
time
0
barTime
Price
price
0
price
Trail Type
string
Price
trailType
Stop Source
string
High/Low
trailSource
ATR Length
int
14
atrLength
ATR Multiplier
float
1
atrMult
Percent Trail
float
2.0
perc
Lookback
int
5
lookback
Start
float
0.043
start
inc
float
0.043
inc
max
float
0.34
max
longCol
color
#64b5f6
longCol
Show all 18 settings
Setting
Type
Default
Variable
ShortCol
color
#ef5350
ShortCol
lineWidth
int
2
lineWidth
transp
int
0
transp
Quantity
float
0.001
quantity
Market
string
usdm
market
Broker
string
Test
broker
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.
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
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
This indicator overlays trend-following Supertrend bands on the price chart using Average True Range calculations. It plots trailing stop lines, highlights active trend directions, and prints buy or sell shape labels when price closes across band thresholds. I
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
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
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