Bmaloney
Pine Script Scholar
Pine Script Scholar
Posts: 4
Joined: November 3rd, 2023
Contact: TradingView Profile

Applying Trailing Stop Indicator to STrategy

Hi Steve,
sorry for last post,

I am having a similar problem but i cant see where the fix is sorry. im very new and half way through mastery course. might be getting a bit ahead of myself but id really like your help.

the plot doesnt seem to be correct in my code?

//@version=5
strategy("My strategy btc", overlay=true, margin_long=100, margin_short=100)

// EMA Input variables
length1 = input.int(20, title="EMA 1 Length", minval=1)
length2 = input.int(50, title="EMA 2 Length", minval=1)
src = input(close, title="Source")
timeframe1 = input.timeframe("5", title="Timeframe for EMA 1")
timeframe2 = input.timeframe("15", title="Timeframe for EMA 2")

// Get user input
tradeType = input.string(title="Trade Direction", defval="Long", options=["Long", "Short"], confirm=true)
trailSource = input.string(title="Trail Source", defval="Lows/Highs", options=["Lows/Highs", "Close", "Open"], confirm=true)
trailMethod = input.string(title="Trail Method", defval="ATR", options=["ATR", "Percent"], confirm=true)
trailPercent = input.float(title="Trail Percent", defval=10, minval=0.1, confirm=true)
swingLookback = input.int(title="Lookback", defval=7, confirm=true)
atrPeriod = input.int(title="ATR Period", defval=14, confirm=true)
atrMultiplier = input.float(title="ATR Multiplier", defval=1.0, confirm=true)

// Calculate EMAs based on the selected timeframes for another symbol (e.g., BTCUST.P)
ema1 = request.security("BTCUSDT.P", timeframe1, ta.ema(src, length1))
ema2 = request.security("BTCUSDT.P", timeframe2, ta.ema(src, length2))

// Plot EMAs on the chart
plot(ema1, color=ema1 > ema2 ? color.green : color.red, title="EMA 1", linewidth=4)
plot(ema2, color=color.gray, title="EMA 2", linewidth=4)

longCondition = ta.crossover(ema1, ema2)
if (longCondition)
strategy.entry("Long", strategy.long)

shortCondition = ta.crossunder(ema1, ema2)
if (shortCondition)
strategy.entry("Short", strategy.short)

// Declare trailing price variable (stores our trail stop value)
var float trailPrice = na
float next_trailPrice = na

// Get required trailing stop variables
atrValue = ta.atr(atrPeriod) * atrMultiplier
float swingLow = ta.lowest(low, swingLookback)
float swingHigh = ta.highest(high, swingLookback)

// Get trailing stop price
if trailMethod == "ATR" // Determine ATR trailing stop price based on price source
next_trailPrice := switch trailSource
"Close" => strategy.position_size > 0 ? close - atrValue : close + atrValue
"Open" => strategy.position_size > 0 ? open - atrValue : open + atrValue
=> strategy.position_size > 0 ? swingLow - atrValue : swingHigh + atrValue
else if trailMethod == "Percent" // Determine percentage trailing stop price based on price source
float percentMulti = strategy.position_size > 0 ? (100 - trailPercent) / 100 : (100 + trailPercent) / 100
next_trailPrice := switch trailSource
"Close" => close * percentMulti
"Open" => open * percentMulti
=> strategy.position_size > 0 ? swingLow * percentMulti : swingHigh * percentMulti

// Check for trailing stop update
if strategy.position_size != 0 and barstate.isconfirmed
// Trail long stop ONLY IF temp trailPrice is not set or is a higher price
if (next_trailPrice > trailPrice or na(trailPrice)) and strategy.position_size > 0
trailPrice := next_trailPrice
// Trigger alert
alert(message="Trailing Stop updated for " + syminfo.tickerid + ": " + str.tostring(trailPrice, "#.#####"), freq=alert.freq_once_per_bar_close)
// Trail short stop ONLY IF temp trailPrice is not set or is a lower price
if (next_trailPrice < trailPrice or na(trailPrice)) and strategy.position_size < 0
trailPrice := next_trailPrice
// Trigger alert
alert(message="Trailing Stop updated for " + syminfo.tickerid + ": " + str.tostring(trailPrice, "#.#####"), freq=alert.freq_once_per_bar_close)

// Draw data to chart
plot(trailPrice != 0 ? trailPrice : na, color=color.red, title="Trailing Stop")

// Exit trade if stop is hit
strategy.exit(id="Trail Exit", from_entry="Trade", limit=na, stop=trailPrice)

if (strategy.position_size > 0 and close < trailPrice) or (strategy.position_size < 0 and close > trailPrice)
strategy.close("Long")

if (strategy.position_size < 0 and close > trailPrice) or (strategy.position_size > 0 and close < trailPrice)
strategy.close("Short")


thanks in advance

Steve Burman
Moderator
Moderator
Posts: 109
Joined: January 13th, 2023

Re: Applying Trailing Stop Indicator to STrategy

No worries, I'll check it out shortly when I can

Steve Burman
Moderator
Moderator
Posts: 109
Joined: January 13th, 2023

Re: Applying Trailing Stop Indicator to STrategy

Bmaloney, I'm having a challenging time on this script. For some reason the changes I made aren't working although logically they should be. This happens from time to time when programming!

Bmaloney
Pine Script Scholar
Pine Script Scholar
Posts: 4
Joined: November 3rd, 2023
Contact: TradingView Profile

Re: Applying Trailing Stop Indicator to STrategy

Hey Steve,
thank you so much for taking the time to look at it. i think it may be working but not plotting correctly and its makng it hard to debug. i will keep having a play with it.

thanks again much appreciated.

Wesley7104
Pine Script Rookie
Pine Script Rookie
Posts: 1
Joined: January 4th, 2024
Contact: TradingView Profile

Re: Applying Trailing Stop Indicator to STrategy

I ran into this problem as well with the provided code on the website under the trailing stop example.
The fix is to simply add "style=plot.style_linebr" within your plot parameters. This setting plots the data when it is valid and omits the data when it is "na" or not available.
for example:
plot(trailPrice != 0.0 ? trailPrice : na, color=color.red, title="Trailing Stop", style=plot.style_linebr)

Hope this helps everyone.

Return to “Pine Script Q&A”