Advertisement
andypartridge47

MACD and EMA Strat

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