'ATR Trailing Stop needs to be reset on each long/short entry

ATR Trailing Stop needs to be reset on each long/short entry because it's being updated once it reaches higher value. How do I do that?

If you add "3Commas Bot" on TradingView, I want to do the same: take profit, static stop loss and trailing stop loss.

//@version=4
strategy("Swing Strategy - Long/Short only", overlay = true)

// —————————— Constants {
// ————— Input options
var string GP1 = "Swing Settings"
var string GP2 = "Filters"
var string GP3 = "Stop Loss Settings"
var string GP4 = "Risk Management"

var string SLO1 = "High/Low"
var string SLO2 = "Close"
var string SLO3 = "Open"

// ————— Color constants
var color C_RED             = color.red
var color C_ORANGE          = color.orange
var color C_GREEN           = color.green
var color C_MAROON          = color.maroon
var color C_LIME            = color.lime
var color C_AQUA            = color.aqua
var color C_FUCHSIA         = color.fuchsia
// }

// —————————— Inputs {
// ————— Swing Settings
i_src                       = input(close, title = "Source", group = GP1)
i_samplingPeriod            = input(9, title = "Sampling Period", minval = 1, group = GP1)
i_rangeMultiplier           = input(1.9, title = "Range Multiplier", minval = 0.1, group = GP1)

// ————— Filters
i_useTimeRangeFilter        = input(false, title = "Use Time Range Filter", group = GP2)
i_startTime                 = input(timestamp("01 Jan 2021 00:00"), title = "Start Date/Time", type = input.time, group = GP2)
i_endTime                   = input(timestamp("01 Oct 2021 00:00"), title = "End Date/Time", type = input.time, group = GP2)

var bool inDate = i_useTimeRangeFilter ? (time >= i_startTime and time <= i_endTime) : true

// ————— Stop Loss Settings
i_useTrailingStop           = input(true, "Use ATR Trailing Stop", group = GP3)
i_atrLength                 = input(14, "ATR Trailing Length", group = GP3)
i_atrTrailingSource         = input(SLO1, "ATR Trailing Stop Source", options = [SLO1, SLO2, SLO3], group = GP3)
i_atrMultiplier             = input(1.5, "ATR Multiplier", step = 0.1, group = GP3)
i_swingLookback             = input(5, "Swing Lookback", group = GP3)

// ————— Risk Management
i_riskPerTrade              = input(2, "Risk Per Trade (%)", group = GP4) * 0.01
// }

// —————————— Functions {
// ————— Function used to calculate the Smooth Average Range
f_smoothAverageRange(src, t, m) =>
    wper = t * 2 - 1
    avrng = ema(abs(src - src[1]), t)
    smoothrng = ema(avrng, wper) * m
    smoothrng
    
// ————— Function used to calculate the Range Filter
f_rangeFilter(src, r) =>
    rngfilt = src
    rngfilt := src > nz(rngfilt[1]) ? src - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : src - r : 
       src + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : src + r
    rngfilt
// }
    
// —————————— Calculations {
// ————— Swing
smrng = f_smoothAverageRange(i_src, i_samplingPeriod, i_rangeMultiplier)
filt = f_rangeFilter(i_src, smrng)

// Filter Direction
var float upward = na
upward := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1])

var float downward = na
downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 : nz(downward[1])

// Target Bands
hband = filt + smrng
lband = filt - smrng
// }

// —————————— Strategy Calls {
var bool longCond = na
longCond := i_src > filt and i_src > i_src[1] and upward > 0 or 
   i_src > filt and i_src < i_src[1] and upward > 0

var bool shortCond = na
shortCond := i_src < filt and i_src < i_src[1] and downward > 0 or 
   i_src < filt and i_src > i_src[1] and downward > 0

var int condIni = na
condIni := longCond ? 1 : shortCond ? -1 : condIni[1]
longCondition = longCond and condIni[1] == -1
shortCondition = shortCond and condIni[1] == 1

// TODO
atr             = atr(i_atrLength)
lowestLow       = lowest(low, i_swingLookback)
highestHigh     = highest(high, i_swingLookback)

FLAT            = strategy.position_size == 0
LONG            = strategy.position_size > 0
SHORT           = strategy.position_size < 0
entry           = strategy.position_avg_price

var float trailingStop = na

if LONG and i_useTrailingStop and barstate.isconfirmed
    trail = lowestLow - atr * i_atrMultiplier
    needsUpdate = trail > nz(trailingStop, 0)
    trailingStop := needsUpdate ? trail : trailingStop

if SHORT and i_useTrailingStop and barstate.isconfirmed
    trail = highestHigh + atr * i_atrMultiplier
    needsUpdate = trail < nz(trailingStop, 0)
    trailingStop := needsUpdate ? trail : trailingStop

plot(entry, "Entry Price", color.gray, style = plot.style_linebr)
plot(trailingStop, "Stop Price", color.red, style = plot.style_linebr)

// Long
strategy.entry("LONG", strategy.long, when = longCondition)
// strategy.exit("EXIT LONG", "LONG", stop = i_useTrailingStop ? trailingStop : 0)

// Short
strategy.entry("SHORT", strategy.short, when = shortCondition)
// strategy.exit("EXIT SHORT", "SHORT", stop = i_useTrailingStop ? trailingStop : 0)
// }

// —————————— Plots {
// ————— Swing
barcolor = i_src > filt and i_src > i_src[1] and upward > 0 ? C_LIME : 
   i_src > filt and i_src < i_src[1] and upward > 0 ? C_GREEN : 
   i_src < filt and i_src < i_src[1] and downward > 0 ? C_RED : 
   i_src < filt and i_src > i_src[1] and downward > 0 ? C_MAROON : C_ORANGE
barcolor(barcolor)

filtcolor = upward > 0 ? C_LIME : downward > 0 ? C_RED : C_ORANGE
p_filtplot = plot(filt, title = "Range Filter", color = filtcolor, linewidth = 3)

// Target
p_hbandplot = plot(hband, title = "High Target", color = color.new(C_AQUA, 90))
p_lbandplot = plot(lband, title = "Low Target",  color = color.new(C_FUCHSIA, 90))

// Fills
fill(p_hbandplot, p_filtplot, color = color.new(C_AQUA, 90),    title = "High Target Range")
fill(p_lbandplot, p_filtplot, color = color.new(C_FUCHSIA, 90), title = "Low Target Range")

plotshape(longCondition,  title = "Buy Signal",  style = shape.labelup,   location = location.belowbar, color = color.green, text = "BE",  textcolor = color.white, size = size.normal)
plotshape(shortCondition, title = "Sell Signal", style = shape.labeldown, location = location.abovebar, color = color.red,   text = "SE",  textcolor = color.white, size = size.normal)
// }

// —————————— Backtester {
float totalTrades = strategy.closedtrades
float winrate = (strategy.wintrades / strategy.closedtrades) * 100

var table tbl = table.new(position.top_right, 1, 6, border_width = 3)

f_fillCell(_tbl, _column, _row, _text, _bgcolor, _textcolor) =>
    table.cell(_tbl, _column, _row, _text, bgcolor = _bgcolor, text_color = _textcolor)
    
if barstate.islastconfirmedhistory
    color bgcolor = color.new(color.gray, 80)
    color textcolor = color.gray
    f_fillCell(tbl, 0, 0, str.format("Total Trades\n{0,number,integer}", totalTrades), bgcolor, textcolor)
    f_fillCell(tbl, 0, 1, str.format("Win Rate\n{0,number,#.##}%", winrate), bgcolor, textcolor)
    f_fillCell(tbl, 0, 2, str.format("Return of Investment\n{0,number,#.##}%", 0), bgcolor, textcolor)
    f_fillCell(tbl, 0, 3, str.format("Risk of Ruin\n{0,number,#.##}%", 0), bgcolor, textcolor)
    f_fillCell(tbl, 0, 4, str.format("Kelly Criterion\n{0,number,#.##}%", 0), bgcolor, textcolor)
    f_fillCell(tbl, 0, 5, str.format("Start Time\n{0,date,yyyy/MM/dd hh:mm:ss}", i_startTime), bgcolor, textcolor)
// }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source