Advertisement
andypartridge47

Learning Scrips 1

Nov 14th, 2024
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. //@version=5
  2. strategy("TEST MACD Strategy with Take Profit and Trailing Stop", overlay=true)
  3.  
  4. // MACD settings
  5. fastLength = input.int(12, minval=1, title="MACD Fast Length")
  6. slowLength = input.int(26, minval=1, title="MACD Slow Length")
  7. signalSmoothing = input.int(9, minval=1, title="MACD Signal Smoothing")
  8.  
  9. [macdLine, signalLine, _] = ta.macd(close, fastLength, slowLength, signalSmoothing)
  10. histogram = macdLine - signalLine
  11.  
  12. // EMA settings
  13. ema11 = ta.ema(close, 11)
  14. ema22 = ta.ema(close, 22)
  15. ema50 = ta.ema(close, 50)
  16. ema100 = ta.ema(close, 100)
  17. ema200 = ta.ema(close, 200)
  18.  
  19. // Take profit and trailing stop inputs
  20. takeProfitPercent = input.float(50, title="Take Profit (in %)", minval=0.1) / 100
  21. trailingStopPercent = input.float(10, title="Trailing Stop (in %)", minval=0.1) / 100
  22.  
  23. // Buy and sell conditions
  24. buyCondition = ta.crossover(macdLine, signalLine)
  25. sellCondition = ta.crossunder(macdLine, signalLine)
  26.  
  27. // Uptrend and downtrend conditions
  28. uptrend = na(ema200) and ema50 > ema100 and ema100 > ema200
  29. downtrend = na(ema200) and ema50 > ema100 and ema100 > ema200
  30.  
  31. // Calculate take profit and trailing stop prices
  32. takeProfitPrice = close * (1 + takeProfitPercent)
  33. trailingStopPrice = close * trailingStopPercent
  34.  
  35. // Execute buy order with trailing stop if market is trending
  36. if (buyCondition and uptrend)
  37. strategy.entry("Buy", strategy.long)
  38. strategy.exit("Take Profit/Stop Loss", from_entry="Buy", limit=takeProfitPrice, trail_offset=trailingStopPrice)
  39.  
  40. // Execute sell order with trailing stop if market is trending
  41. if (sellCondition and downtrend)
  42. strategy.entry("Sell", strategy.short)
  43. strategy.exit("Take Profit/Stop Loss", from_entry="Sell", limit=close * (1 - takeProfitPercent), trail_offset=close * trailingStopPercent)
  44.  
  45. // Plot MACD and Signal lines
  46. plot(macdLine, color=color.blue, title="MACD Line")
  47. plot(signalLine, color=color.orange, title="Signal Line")
  48. plot(histogram, color=color.red, style=plot.style_histogram, title="Histogram")
  49.  
  50. // Plot EMA 11, EMA 22, and EMA 50
  51. plot11 = plot(ema11, color=color.green, title="EMA 11")
  52. plot22 = plot(ema22, color=color.red, title="EMA 22")
  53. plot50 = plot(ema50, color=color.blue, title="EMA 50")
  54.  
  55. // Fill the area between EMA 11 and EMA 22
  56. fill(plot11, plot22, color=ema11 > ema22 ? color.new(color.green, 75) : color.new(color.red, 75))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement