//version=5
strategy("MACD Strategy", overlay=true)

// Define input parameters
fast_length = input(12, title="Fast Length")
slow_length = input(26, title="Slow Length")
signal_length = input(9, title="Signal Length")
risk_to_reward_ratio = 0.1
stop_loss_multiplier = 2
trail_stop_multiplier = 1

// Calculate MACD values
[macd_line, signal_line, _] = ta.macd(close, fast_length, slow_length, signal_length)

// Calculate stop loss levels
fix_stop_loss = close * (1 - risk_to_reward_ratio)
atr_value = ta.atr(14)
atr_stop_loss = strategy.position_avg_price - atr_value * stop_loss_multiplier

// Calculate trail stop level
trail_stop = strategy.position_avg_price - atr_value * trail_stop_multiplier

// Entry Logic - Buy when MACD crosses above the Signal Line and Sell when MACD crosses below the Signal Line
entry_condition_long = ta.crossover(macd_line, signal_line)
entry_condition_short = ta.crossunder(macd_line, signal_line)

// Exit Logic
exit_long = strategy.position_avg_price <= fix_stop_loss or low <= atr_stop_loss
exit_short = strategy.position_avg_price >= fix_stop_loss or high >= atr_stop_loss

// Trail Stop Logic
trail_stop_long = close >= trail_stop
trail_stop_short = close <= trail_stop

// Submit entry orders
if entry_condition_long
strategy.entry("Buy", strategy.long)
if entry_condition_short
strategy.entry("Sell", strategy.short)

// Submit exit orders
strategy.exit("Exit Buy", "Buy", stop = fix_stop_loss, trail_offset = atr_value * trail_stop_multiplier, trail_price = trail_stop_long)
strategy.exit("Exit Sell", "Sell", stop = fix_stop_loss, trail_offset = atr_value * trail_stop_multiplier, trail_price = trail_stop_short)

// Plot MACD lines and Signal line for reference
plot(macd_line, title="MACD", color=color.blue)
plot(signal_line, title="Signal Line", color=color.red)

// Plot ATR value for reference
plot(atr_value, color=color.green)
Chart PatternsHarmonic PatternsTrend Analysis

إخلاء المسؤولية