I have a serious problem merging Take profit and Stop loss in one script.
I'm using this script for TP https://kodify.net/tradingview/orders/percentage-profit/
and this one for SL https://kodify.net/tradingview/orders/percentage-stop/
I came up with the below script which doesn't look to SL. Hence, the order will remain open until TP % is reached. I need your help to fix it and activate SL same as TP.
//@version=3
strategy(title="Take profit (% of instrument price)",
overlay=true, pyramiding=1)
// STEP 1:
// Make inputs that set the take profit % (optional)
longProfitPerc = input(title="Long Take Profit (%)",
type=float, minval=0.0, step=0.1, defval=3) * 0.01
longLossPerc = input(title="Long Stop Loss (%)",
type=float, minval=0.0, step=0.1, defval=1) * 0.01
// Calculate moving averages
fastSMA = sma(close, 20)
slowSMA = sma(close, 60)
// Calculate trading conditions
enterLong = crossover(fastSMA, slowSMA)
// Plot moving averages
plot(series=fastSMA, color=green)
plot(series=slowSMA, color=red)
// STEP 2:
// Figure out take profit price
longExitPrice = strategy.position_avg_price * (1 + longProfitPerc)
longStopPrice = strategy.position_avg_price * (1 - longLossPerc)
// Plot take profit values for confirmation
plot(series=(strategy.position_size > 0) ? longExitPrice : na,
color=green, style=circles,
linewidth=3, title="Long Take Profit")
plot(series=(strategy.position_size > 0) ? longStopPrice : na,
color=red, style=cross,
linewidth=2, title="Long Stop Loss")
// Submit entry orders
if (enterLong)
strategy.entry(id="EL", long=true)
// STEP 3:
// Submit exit orders based on take profit price
if (strategy.position_size > 0)
strategy.exit(id="TP", limit=longExitPrice)
if (strategy.position_size > 0)
strategy.exit(id="SL", stop=longStopPrice)