Advertisement
andypartridge47

Lesson 2.6

Oct 22nd, 2024
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.14 KB | None | 0 0
  1. //@version=5
  2. strategy("Learning Scripts 2.4", overlay=true)
  3.  
  4. stopLossPercentage = input.float(3, "Stop Loss Percentage") * 0.005
  5.  
  6. takeProfitPercentage = input.float(3, "Take Profit Percentage") * 0.03
  7.  
  8.  
  9. ema12 = ta.ema(close, 12)
  10. ema21 = ta.ema(close, 21)
  11.  
  12. // 1. Create two persistent variables for the take profit and stop loss lines
  13.  
  14. // We use var so that they values stay persistent
  15. // If we didn't use var these values would be changed to na every new bar
  16. // When we use var we have to tell pinesript that this will be a line
  17. var line stopLossLine = na
  18. var line takeProfitLine = na
  19.  
  20. // 2. Add logic to manually reset the lines or extend the lines
  21.  
  22. if strategy.position_size == 0 // If we don't have a position we reset the lines to na
  23. stopLossLine := na
  24. takeProfitLine := na
  25. else
  26. stopLossLine.set_x2(bar_index) // If we do have a position we extend the lines to the next bar
  27. takeProfitLine.set_x2(bar_index)
  28.  
  29. if ta.crossover(ema12, ema21) and strategy.position_size == 0
  30. stopLoss = close * (1 - stopLossPercentage)
  31.  
  32. takeProfit = close * (1 + takeProfitPercentage)
  33.  
  34.  
  35. // 3. Draw the start of the lines when we enter a position
  36.  
  37. stopLossLine := line.new(bar_index, stopLoss, bar_index, stopLoss, color=color.red)
  38. takeProfitLine := line.new(bar_index, takeProfit, bar_index, takeProfit, color=color.green)
  39.  
  40. strategy.entry("Long", strategy.long)
  41. strategy.exit("SL / TP", "Long", stop=stopLoss, limit=takeProfit)
  42.  
  43. if ta.crossunder(ema12, ema21) and strategy.position_size == 0
  44. stopLoss = close * (1 + stopLossPercentage)
  45.  
  46. takeProfit = close * (1 - takeProfitPercentage)
  47.  
  48.  
  49. // 3. Draw the start of the lines when we enter a position
  50.  
  51. stopLossLine := line.new(bar_index, stopLoss, bar_index, stopLoss, color=color.red)
  52. takeProfitLine := line.new(bar_index, takeProfit, bar_index, takeProfit, color=color.green)
  53.  
  54. strategy.entry("Short", strategy.short)
  55. strategy.exit("SL / TP", "Short", stop=stopLoss, limit=takeProfit)
  56.  
  57.  
  58. bandColor = ema12 > ema21 ? color.green : color.red
  59. plot(ema12, color=bandColor, linewidth=1)
  60. plot(ema21, color=bandColor, linewidth=3)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement