//@version=5
strategy("MACD & EMA Buy/Sell Strategy v2", overlay=true)
// Input parameters
emaLength = input(200, title="200 EMA Length")
rsiLength = input(14, title="RSI Length")
mfiLength = input(14, title="MFI Length")
atrLength = input(14, title="ATR Length")
longTP = [Link](0.4, title="Long Take Profit (%)") / 100
longSL = [Link](0.2, title="Long Stop Loss (%)") / 100
shortTP = [Link](0.4, title="Short Take Profit (%)") / 100
shortSL = [Link](0.2, title="Short Stop Loss (%)") / 100
trailingStop = [Link](0.2, title="Trailing Stop (%)") / 100 // Trailing stop
percentage
useTP = [Link](true, title="Use Take Profit") // Toggle take profit usage
startDate = [Link](timestamp("2024-01-01 00:00 +0000"), title="Start Date")
endDate = [Link](timestamp("2024-12-31 23:59 +0000"), title="End Date")
// Calculate indicators
ema200 = [Link](close, emaLength)
[macdLine, signalLine, _] = [Link](close, 12, 26, 9)
rsi = [Link](close, rsiLength)
mfi = [Link](close, mfiLength)
// Buy conditions
buyCondition = [Link](macdLine, signalLine) and close > ema200 and rsi > 50
and mfi > 50
// Sell conditions
sellCondition = [Link](macdLine, signalLine) and close < ema200 and rsi < 50
and mfi < 50
// Execute long order
if (buyCondition and (time >= startDate and time <= endDate))
[Link]("Long", [Link])
longTPPrice = useTP ? strategy.position_avg_price * (1 + longTP) : na // TP
based on entry price
longSLPrice = strategy.position_avg_price * (1 - longSL) // SL based on entry
price
trailingOffset = strategy.position_avg_price * trailingStop // Trailing stop
based on entry price
[Link]("TP/SL Long", from_entry="Long", limit=longTPPrice,
stop=longSLPrice, trail_offset=trailingOffset)
// Execute short order
if (sellCondition and (time >= startDate and time <= endDate))
[Link]("Short", [Link])
shortTPPrice = useTP ? strategy.position_avg_price * (1 - shortTP) : na // TP
based on entry price
shortSLPrice = strategy.position_avg_price * (1 + shortSL) // SL based on
entry price
trailingOffset = strategy.position_avg_price * trailingStop // Trailing stop
based on entry price
[Link]("TP/SL Short", from_entry="Short", limit=shortTPPrice,
stop=shortSLPrice, trail_offset=trailingOffset)
// Plot buy and sell signals
plotshape(series=buyCondition, location=[Link], color=[Link],
style=[Link], title="Buy Signal", text="BUY")
plotshape(series=sellCondition, location=[Link], color=[Link],
style=[Link], title="Sell Signal", text="SELL")
// Plot the EMA
plot(ema200, color=[Link], title="200 EMA")