Dual MACD Divergence with SMA Trend Resonance Strategy

MACD SMA 趋势共振 背离指标 风险管理 自动交易 RSR
Created on: 2025-04-27 13:24:47 Modified on: 2025-04-27 13:24:47
Copy: 3 Number of hits: 464
avatar of ianzeng123 ianzeng123
2
Follow
319
Followers

 Dual MACD Divergence with SMA Trend Resonance Strategy  Dual MACD Divergence with SMA Trend Resonance Strategy

Overview

The Dual MACD Divergence with SMA Trend Resonance Strategy is a technically-oriented quantitative trading system that combines divergence signals from both fast and slow MACD indicators with a proximity filter to the 28-period Simple Moving Average (SMA28) to capture potential trend reversal points. The strategy achieves higher reliability by requiring divergence signals to appear simultaneously on two MACD timeframes, coupled with the condition that price must be near the SMA28. Designed to automatically identify both long and short trading opportunities, the strategy manages exits through a preset risk-reward ratio and is particularly suited for 15-minute timeframe trading.

Strategy Principle

The core principle of this strategy is based on the synchronous confirmation of multiple technical indicators, specifically:

  1. Dual MACD Divergence Signal Detection:

    • Slow MACD is set with parameters (14,28,9) to capture medium-term trend shifts
    • Fast MACD is set with parameters (10,21,7) to capture short-term momentum changes
    • Bullish divergence condition: When the lowest point of the recent 5 candles is lower than the lowest point of the previous 10 candles, while the MACD histogram shows an upward trend
    • Bearish divergence condition: When the highest point of the recent 5 candles is higher than the highest point of the previous 10 candles, while the MACD histogram shows a downward trend
  2. SMA28 Proximity Filter:

    • Calculates the proximity of the current price to the 28-period Simple Moving Average
    • Requires price to be within ±1.5% of the SMA28 (proximity threshold set at 0.015)
    • This filter ensures trades occur near key support/resistance areas, increasing signal reliability
  3. Resonance Confirmation Logic:

    • Long signal: Slow MACD bullish divergence + Fast MACD bullish divergence + Price near SMA28
    • Short signal: Slow MACD bearish divergence + Fast MACD bearish divergence + Price near SMA28
  4. Risk Management Mechanism:

    • Fixed risk-to-reward ratio of 1:1.5
    • Take profit: ±1.5% from entry price (depending on long/short direction)
    • Stop loss: ±1.0% from entry price (depending on long/short direction)

Strategy Advantages

Deep analysis of the strategy code reveals the following significant advantages:

  1. Multiple Confirmation Mechanism: Requiring divergence signals to appear simultaneously on two differently parameterized MACDs greatly reduces the probability of false signals, improving trade quality.

  2. Zone Filtering Design: By requiring price to be near the SMA28, the strategy ensures trades occur at technically significant locations, avoiding trades in irrelevant areas.

  3. Automatic Bidirectional Trading: The strategy can automatically identify and execute trades in both directions, adapting to different market environments and capturing opportunities in all directions.

  4. Preset Risk Management: Built-in fixed risk-reward ratio (1:1.5) automatically sets take-profit and stop-loss levels for each trade, ensuring consistent and standardized fund management.

  5. Visualization of Trading Signals: Using plotshape and plot functions to intuitively display trading signals, take-profit, and stop-loss levels on the chart, making it easier for traders to monitor and understand strategy execution.

  6. Alert Function Integration: Built-in alert condition settings facilitate integration with trading bots, enabling fully automated trade execution and reducing human intervention and emotional influence.

  7. Parameter Optimization Capability: Various parameters of the strategy (such as MACD periods, SMA period, proximity threshold, risk-reward ratio, etc.) can be adjusted and optimized according to specific market conditions.

Strategy Risks

Despite its well-designed nature, the strategy still faces the following potential risks and challenges:

  1. Overtrading Risk: In highly volatile but directionless markets, dual MACD divergence signals may appear frequently, leading to overtrading and fee erosion. The solution is to add additional filtering conditions, such as trend strength indicators or trading frequency limits.

  2. Fixed Stop-Loss Risk: Using a fixed percentage stop-loss may not adequately protect capital during periods of high volatility. Consider using volatility-based dynamic stop-losses (such as ATR multiples) to make stop-loss levels more aligned with the current market environment.

  3. False Divergence Signals: MACD divergence sometimes produces false signals, especially in strong trending markets. It is recommended to add confirmation indicators, such as RSI or volume indicators, to further validate signal validity.

  4. Parameter Dependency: Strategy performance is highly dependent on the chosen parameter settings and may require frequent adjustments to adapt to different market environments. The solution is to conduct comprehensive parameter optimization tests to find more robust parameter combinations.

  5. SMA Proximity Limitation: In rapidly breaking or sharply falling environments, price may quickly deviate from SMA28, causing the strategy to miss important trading opportunities. Consider adding trend recognition logic to relax proximity requirements when trend changes are confirmed.

  6. Consecutive Loss Risk: Under certain market conditions, the strategy may produce a series of consecutive losing trades. Overall risk control mechanisms should be implemented, such as daily maximum loss limits or percentage-based risk control.

Strategy Optimization Directions

Based on in-depth analysis of the code, the following are feasible optimization directions:

  1. Dynamic Risk Management Improvements:

    • Replace fixed stop-loss/take-profit ratios with dynamic settings based on market volatility
    • Introduce fund management algorithms such as the Kelly Criterion or fixed proportion risk models
    • Implement maximum trade number limits within specific time periods to avoid overtrading
  2. Signal Quality Enhancement:

    • Add RSI divergence confirmation, requiring both MACD and RSI to show divergence signals simultaneously
    • Introduce volume analysis to ensure divergence signals are accompanied by meaningful volume changes
    • Add trend strength filters (such as the ADX indicator) to trade only in suitable trending environments
  3. Trade Timing Optimization:

    • Implement dynamic SMA proximity thresholds that automatically adjust based on market volatility
    • Add time filters to avoid low liquidity or high volatility periods
    • Introduce market structure analysis to identify high-probability support/resistance zones
  4. Multi-Timeframe Analysis:

    • Integrate higher timeframe trend confirmation signals to avoid trading against major trends
    • Implement cascade signal systems requiring indicators across multiple timeframes to align
    • Add macro trend filters to trade only in the direction of the main trend
  5. Machine Learning Enhancement:

    • Introduce machine learning models based on historical data to predict the success probability of divergence signals
    • Implement adaptive parameter optimization to dynamically adjust strategy parameters based on recent market performance
    • Develop signal quality scoring systems to execute only high-quality trading signals
  6. Backtesting and Validation Improvements:

    • Implement Monte Carlo simulations to test strategy performance under various market conditions
    • Add walk-forward testing to verify parameter robustness
    • Develop portfolio backtesting frameworks to evaluate correlation and combined effects with other strategies

Summary

The Dual MACD Divergence with SMA Trend Resonance Strategy is an elegantly designed quantitative trading system that provides a structured approach to finding potential trend reversal points by integrating confirmation from multiple technical indicators. The core strengths of the strategy lie in its multiple confirmation mechanism and built-in risk management system, making it particularly suitable for 15-minute timeframe trading. While there are potential risks such as overtrading and parameter dependency, these can be effectively mitigated through the proposed optimization directions.

By further optimizing signal quality, risk management, and timing selection, the strategy has the potential to become an even more robust and adaptive trading system. Particularly, introducing dynamic risk management mechanisms and multi-timeframe analysis could significantly enhance the overall performance of the strategy. For quantitative traders seeking technically-driven automated trading solutions, this provides a solid foundational framework that can be customized and extended according to individual risk preferences and market conditions.

Strategy source code
/*backtest
start: 2024-04-26 00:00:00
end: 2025-04-25 08:00:00
period: 2d
basePeriod: 2d
exchanges: [{"eid":"Futures_Binance","currency":"SOL_USDT"}]
*/

//@version=5
strategy("BTC 雙MACD 背離策略(基礎共振 / 適用15分鐘 / 多空自動)", overlay=true, default_qty_type=strategy.fixed, default_qty_value=100)

// === 均線(SMA28) ===
sma28 = ta.sma(close, 28)
sma_touch = math.abs(close - sma28) / sma28 < 0.015

// === MACD 計算(慢速) ===
[macdSlow, signalSlow, _] = ta.macd(close, 14, 28, 9)
histSlow = macdSlow - signalSlow
bullish_div_slow = ta.lowest(low, 5) < ta.lowest(low[10], 5) and histSlow > histSlow[1]
bearish_div_slow = ta.highest(high, 5) > ta.highest(high[10], 5) and histSlow < histSlow[1]

// === MACD 計算(快速) ===
[macdFast, signalFast, _] = ta.macd(close, 10, 21, 7)
histFast = macdFast - signalFast
bullish_div_fast = ta.lowest(low, 5) < ta.lowest(low[10], 5) and histFast > histFast[1]
bearish_div_fast = ta.highest(high, 5) > ta.highest(high[10], 5) and histFast < histFast[1]

// === 基礎共振條件 ===
superLong = bullish_div_slow and bullish_div_fast and sma_touch
superShort = bearish_div_slow and bearish_div_fast and sma_touch

longEntry = superLong
shortEntry = superShort

// === 可調式風報比(改為 1:1.5) ===
risk = 0.01
reward = 0.015

long_tp = close * (1 + reward)
long_sl = close * (1 - risk)
short_tp = close * (1 - reward)
short_sl = close * (1 + risk)

if longEntry
    strategy.entry("做多進場", strategy.long)
    strategy.exit("做多出場", from_entry="做多進場", limit=long_tp, stop=long_sl)

if shortEntry
    strategy.entry("做空進場", strategy.short)
    strategy.exit("做空出場", from_entry="做空進場", limit=short_tp, stop=short_sl)

plotshape(superLong, title="共振多", location=location.belowbar, color=color.green, style=shape.labelup, size=size.tiny)
plotshape(superShort, title="共振空", location=location.abovebar, color=color.red, style=shape.labeldown, size=size.tiny)

plot(longEntry ? long_tp : na, title="多TP", color=color.green, linewidth=1)
plot(longEntry ? long_sl : na, title="多SL", color=color.red, linewidth=1)
plot(shortEntry ? short_tp : na, title="空TP", color=color.green, linewidth=1)
plot(shortEntry ? short_sl : na, title="空SL", color=color.red, linewidth=1)

// === Alert 設定 ===
alertcondition(longEntry, title="多單共振進場", message="LONG_ENTRY")
alertcondition(shortEntry, title="空單共振進場", message="SHORT_ENTRY")