title: Tradingview - pine script for Take profit and Stop loss by percentage
body: <p>I have a serious problem merging Take profit and Stop loss in one script.</p>
  <p>I'm using this script for TP
  <a href="https://kodify.net/tradingview/orders/percentage-profit/" rel="noreferrer">https://kodify.net/tradingview/orders/percentage-profit/</a></p>
  <p>and this one for SL
  <a href="https://kodify.net/tradingview/orders/percentage-stop/" rel="noreferrer">https://kodify.net/tradingview/orders/percentage-stop/</a></p>
  <p>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.</p>
  <pre><code>//@version=3
  strategy(title=&quot;Take profit (% of instrument price)&quot;,
       overlay=true, pyramiding=1)
  
  // STEP 1:
  // Make inputs that set the take profit % (optional)
  longProfitPerc = input(title=&quot;Long Take Profit (%)&quot;,
       type=float, minval=0.0, step=0.1, defval=3) * 0.01
  
  longLossPerc = input(title=&quot;Long Stop Loss (%)&quot;,
       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 &gt; 0) ? longExitPrice : na,
       color=green, style=circles,
       linewidth=3, title=&quot;Long Take Profit&quot;)
  
  plot(series=(strategy.position_size &gt; 0) ? longStopPrice : na,
       color=red, style=cross,
       linewidth=2, title=&quot;Long Stop Loss&quot;)
  // Submit entry orders
  if (enterLong)
      strategy.entry(id=&quot;EL&quot;, long=true)
  
  
  
  // STEP 3:
  // Submit exit orders based on take profit price
  if (strategy.position_size &gt; 0)
      strategy.exit(id=&quot;TP&quot;, limit=longExitPrice)
  
  
  if (strategy.position_size &gt; 0)
      strategy.exit(id=&quot;SL&quot;, stop=longStopPrice)
  </code></pre>