Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //@version=5
- strategy("MACD Strategy with Take Profit and Trailing Stop", overlay=true)
- // MACD settings
- fastLength = input.int(12, minval=1, title="MACD Fast Length")
- slowLength = input.int(26, minval=1, title="MACD Slow Length")
- signalSmoothing = input.int(9, minval=1, title="MACD Signal Smoothing")
- [macdLine, signalLine, _] = ta.macd(close, fastLength, slowLength, signalSmoothing)
- histogram = macdLine - signalLine
- // EMA settings
- ema11 = ta.ema(close, 11)
- ema22 = ta.ema(close, 22)
- // Take profit and trailing stop inputs
- takeProfitPercent = input.float(50, title="Take Profit (in %)", minval=0.1) / 100
- trailingStopPercent = input.float(10, title="Trailing Stop (in %)", minval=0.1) / 100
- // Buy and sell conditions
- buyCondition = ta.crossover(macdLine, signalLine)
- sellCondition = ta.crossunder(macdLine, signalLine)
- // Calculate take profit and trailing stop prices
- takeProfitPrice = close * (1 + takeProfitPercent)
- trailingStopPrice = close * trailingStopPercent
- // Execute buy order with trailing stop
- if (buyCondition)
- strategy.entry("Buy", strategy.long)
- strategy.exit("Take Profit/Stop Loss", from_entry="Buy", limit=takeProfitPrice, trail_offset=trailingStopPrice)
- if (sellCondition)
- strategy.entry("Sell", strategy.short)
- strategy.exit("Take Profit/Stop Loss", from_entry="Sell", limit=close * (1 - takeProfitPercent), trail_offset=close * trailingStopPercent)
- // Plot MACD and Signal lines
- plot(macdLine, color=color.blue, title="MACD Line")
- plot(signalLine, color=color.orange, title="Signal Line")
- plot(histogram, color=color.red, style=plot.style_histogram, title="Histogram")
- // Plot EMA 11 and EMA 22
- plot11 = plot(ema11, color=color.green, title="EMA 11")
- plot22 = plot(ema22, color=color.red, title="EMA 22")
- // Fill the area between EMA 11 and EMA 22
- 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