Advertisement
andypartridge47

MACD with EMA 11, 22, 50

Nov 13th, 2024
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. //@version=5
  2. strategy("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.  
  17. // Take profit and trailing stop inputs
  18. takeProfitPercent = input.float(50, title="Take Profit (in %)", minval=0.1) / 100
  19. trailingStopPercent = input.float(10, title="Trailing Stop (in %)", minval=0.1) / 100
  20.  
  21. // Buy and sell conditions
  22. buyCondition = ta.crossover(macdLine, signalLine)
  23. sellCondition = ta.crossunder(macdLine, signalLine)
  24.  
  25. // Market trending condition
  26. ema50_slope = (ema50 - ema50[10]) / 10
  27. isTrending = math.abs(close - ema50) > ta.atr(14) and ema50_slope > 0
  28.  
  29. // Calculate take profit and trailing stop prices
  30. takeProfitPrice = close * (1 + takeProfitPercent)
  31. trailingStopPrice = close * trailingStopPercent
  32.  
  33. // Execute buy order with trailing stop if market is trending
  34. if (buyCondition and isTrending)
  35. strategy.entry("Buy", strategy.long)
  36. strategy.exit("Take Profit/Stop Loss", from_entry="Buy", limit=takeProfitPrice, trail_offset=trailingStopPrice)
  37.  
  38. // Execute sell order with trailing stop if market is trending
  39. if (sellCondition and isTrending)
  40. strategy.entry("Sell", strategy.short)
  41. strategy.exit("Take Profit/Stop Loss", from_entry="Sell", limit=close * (1 - takeProfitPercent), trail_offset=close * trailingStopPercent)
  42.  
  43. // Plot MACD and Signal lines
  44. plot(macdLine, color=color.blue, title="MACD Line")
  45. plot(signalLine, color=color.orange, title="Signal Line")
  46. plot(histogram, color=color.red, style=plot.style_histogram, title="Histogram")
  47.  
  48. // Plot EMA 11, EMA 22, and EMA 50
  49. plot11 = plot(ema11, color=color.green, title="EMA 11")
  50. plot22 = plot(ema22, color=color.red, title="EMA 22")
  51. plot50 = plot(ema50, color=color.blue, title="EMA 50")
  52.  
  53. // Fill the area between EMA 11 and EMA 22
  54. 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