DonBastardo
Pine Script Rookie
Pine Script Rookie
Posts: 8
Joined: February 10th, 2023

Moving Stop Loss

Hi guys,

I am trying to code a breakeven/moving stop loss function but - although I feel I am close - it´s not working.
The idea is to move stop loss with each RR reached e.g: if the goal is RR 1:3 when the trade reaches RR1 then stop loss should be moved to entry price (so basically break even), if RR2 is reached, the stop loss should now be moved to RR1 and so on.
Down the line it also should work with a RR 1:X but I assume then its just a copy/paste of a few lines of code.

The Tradingview Strategy Tester says "No data" because the first trade is opened but it´s never closed.

Below the current script code:

Code: Select all

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © DonBastardo

//@version=5
strategy("Engulfing", overlay=true, pyramiding = 0, initial_capital = 1000, currency = currency.EUR, 
 process_orders_on_close = true, use_bar_magnifier = true, 
 commission_type = strategy.commission.cash_per_order, commission_value = 0.006)

RunStrategie = input(title = "RunStrategie ?" ,defval=true, group = "Main")
FixedRR = input(title = "FixedRR ?" ,defval=true, group = "FixedRR")

ema20 = request.security(syminfo.tickerid,timeframe.period,ta.ema(close, 20))
ema50 = request.security(syminfo.tickerid,timeframe.period,ta.ema(close, 50))

BarRange() =>
	high - low
Bu_Candle() =>
	open < close
Be_Candle() =>
	open > close

//EngulfingEma************************************************************************************************************************************************************
ShowEngulfingEmaBu = input(title = "EngulfingEma Bu" ,defval=true, group = "Pattern")
ShowEngulfingEmaBe = input(title = "EngulfingEma Be" ,defval=true, group = "Pattern")

EngulfingEmaBu_condition = ema20 > ema50 and Be_Candle()[1] and Bu_Candle() and close > high[1] and low < low[1]
EngulfingEmaBu = EngulfingEmaBu_condition 
plotshape(EngulfingEmaBu and ShowEngulfingEmaBu == true, style=shape.circle, text="EngulfingEma", color=color.green, textcolor=color.green, location = location.belowbar, size = size.small)

EngulfingEmaBe_condition = ema20 < ema50 and Bu_Candle()[1] and Be_Candle() and close < low[1] and high > high[1]
EngulfingEmaBe = EngulfingEmaBe_condition
plotshape(EngulfingEmaBe and ShowEngulfingEmaBe == true, style=shape.circle, text="EngulfingEma", color=color.red, textcolor=color.red, location = location.abovebar, size = size.small)

//Strategie

// Get price of last entry in position:
lastEntryPrice = strategy.opentrades.entry_price(strategy.opentrades - 1)

//Fixed Values
ProfitMultipler = input.float (title = "Profit Multipler", defval = 3, group = "Fixed RR")	
Fixedbuysl = lastEntryPrice - BarRange()
Fixedbuytp = lastEntryPrice + BarRange()*ProfitMultipler

Fixedsellsl = lastEntryPrice + BarRange()
Fixedselltp = lastEntryPrice - BarRange()*ProfitMultipler

Breakevenbuy0 = lastEntryPrice + BarRange() //RR 1
Breakevenbuy1 = lastEntryPrice + BarRange()*2 //RR 2
Breakevenbuy2 = lastEntryPrice + BarRange()*3 //RR 3

Breakevensell0 = lastEntryPrice - BarRange() //RR 1 
Breakevensell1 = lastEntryPrice - BarRange()*2 //RR 2
Breakevensell2 = lastEntryPrice - BarRange()*3 //RR 3

BuyCurrentStage() =>
	var buystage = 0
	if close < Breakevenbuy0
		buystage:= 0
	if buystage == 0 and close > Breakevenbuy1
		buystage := 1
	if buystage == 1 and close > Breakevenbuy2
		buystage := 2
		
sellCurrentStage() =>
	var sellstage = 0
	if close > Breakevensell0
		sellstage:= 0
	if sellstage == 0 and close < Breakevensell1
		sellstage := 1
	if sellstage == 1 and close < Breakevensell2
		sellstage := 2
	
buystage = BuyCurrentStage()

if EngulfingEmaBu and ShowEngulfingEmaBu == true and RunStrategie == true and strategy.opentrades == 0
	strategy.entry("Long", strategy.long )
	if FixedRR == true and buystage == 0
		strategy.exit("Exit", "Long", stop = Fixedbuysl, limit = Fixedbuytp, comment_loss = "SL Hit", comment_profit = "TP Hit" )
    if FixedRR == true and buystage == 1
		strategy.exit("Exit2", "Long", stop = lastEntryPrice, limit = Fixedbuytp, comment_loss = "Breakeven Hit", comment_profit = "TP Hit" )
    if FixedRR == true and buystage == 2
		strategy.exit("Exit3", "Long", stop = Breakevenbuy1, limit = Fixedbuytp, comment_loss = "RR1 Hit", comment_profit = "TP Hit" )

sellstage = sellCurrentStage()

if EngulfingEmaBe and ShowEngulfingEmaBe == true and RunStrategie == true and strategy.opentrades == 0
	strategy.entry("Short", strategy.short )
	if FixedRR == true and sellstage == 0
		strategy.exit("Exit", "Short", stop = Fixedsellsl, limit = Fixedselltp, comment_loss = "SL Hit", comment_profit = "TP Hit" )
    if FixedRR == true and sellstage == 1
		strategy.exit("Exit2", "Short", stop = lastEntryPrice, limit = Fixedselltp, comment_loss = "SL Hit", comment_profit = "TP Hit" )
    if FixedRR == true and sellstage == 2
		strategy.exit("Exit3", "Short", stop = Breakevensell1, limit = Fixedselltp, comment_loss = "SL Hit", comment_profit = "TP Hit" )
Where is the error in my logic/code? Thanks for any help.

Thanks, Don

RobAgrees
Pine Script Rookie
Pine Script Rookie
Posts: 3
Joined: March 17th, 2023
Contact: TradingView Profile

Re: Moving Stop Loss

Because your entry conditions have your exit conditions nested in them. Your code enters a trade the first time, but then exits the if flow because it doesn't get a sell signal until future bars. On the future bars, with an open position, strategy.opentrades == 1, so it doesn't go through the if logic to reach the exit statements. You'll want to separate out your entry and exit conditions from the nested logic and be sure the script can reach the exits on future bars.

DonBastardo
Pine Script Rookie
Pine Script Rookie
Posts: 8
Joined: February 10th, 2023

Re: Moving Stop Loss

Thanks for the Feedback i will check it out

Return to “Pine Script Q&A”