MACD-SuperTrend Fusion Trend Following Trading System

MACD supertrend EMA SMA ATR 趋势跟踪 交叉信号 动量指标
Created on: 2025-07-25 11:42:12 Modified on: 2025-07-25 11:42:12
Copy: 0 Number of hits: 355
avatar of ianzeng123 ianzeng123
2
Follow
319
Followers

 MACD-SuperTrend Fusion Trend Following Trading System  MACD-SuperTrend Fusion Trend Following Trading System

Overview

The MACD-SuperTrend Fusion Trend Following Trading System is a quantitative trading strategy that combines two powerful technical indicators designed to identify and follow market trends. This strategy merges the momentum characteristics of Moving Average Convergence Divergence (MACD) with the trend-following capabilities of the SuperTrend indicator to create a comprehensive trading system. By considering both price momentum and trend direction simultaneously, the strategy aims to capture strong trend changes while filtering out potential false signals. The system supports multi-directional trading (long, short, or both) and offers flexible parameter adjustment options, allowing traders to optimize according to different market environments and personal risk preferences.

Strategy Principles

The core logic of this strategy is based on the synergistic action of two main technical indicators:

  1. SuperTrend Indicator: This is an ATR (Average True Range) based trend-following indicator that can be plotted on price charts to show the current trend. When the SuperTrend line is below the price, it indicates an uptrend; when the SuperTrend line is above the price, it indicates a downtrend. The SuperTrend calculation in the code uses a user-defined ATR period (default 10) and multiplier factor (default 3.0).

  2. MACD Indicator: The Moving Average Convergence Divergence indicator measures price momentum by calculating the difference between two moving averages. The strategy allows users to choose the type of moving average (SMA or EMA) for calculating MACD as well as parameters (fast line, slow line, and signal line).

The key decision logic of the strategy is as follows:

  • Long Entry Condition: When the SuperTrend indicator shows an uptrend (direction1 < 0) and simultaneously the MACD histogram is positive (hist > 0). This indicates that the price is in an uptrend with sufficient upward momentum.
  • Long Exit Condition: When the SuperTrend indicator turns to a downtrend (direction1 > 0), or the price falls below the slow EMA.
  • Short Entry Condition: When the SuperTrend indicator shows a downtrend (direction1 > 0) and simultaneously the MACD histogram is negative (hist < 0). This indicates that the price is in a downtrend with sufficient downward momentum.
  • Short Exit Condition: When the SuperTrend indicator turns to an uptrend (direction1 < 0), or the price breaks above the slow EMA.

The strategy also offers a “Use ST Only” option (onlyST parameter), which when enabled will rely solely on SuperTrend signals for trading, ignoring the influence of the MACD indicator.

Strategy Advantages

  1. Dual Confirmation Mechanism: By combining SuperTrend trend confirmation and MACD momentum confirmation, the strategy reduces the risk of false signals and improves trade quality. This dual filtering approach can effectively reduce losing trades in ranging markets.

  2. Strong Adaptability: The strategy parameters are highly customizable, including trading direction, indicator type, and period settings, making it adaptable to various market environments and trading styles. For example, traders can choose to execute only long trades or short trades, or adjust the sensitivity of SuperTrend based on market characteristics.

  3. Clear Trend Visualization: The SuperTrend indicator is plotted directly on the price chart, allowing traders to visually identify trend direction and potential support/resistance areas. The strategy uses color filling to enhance visual effects, with green areas indicating uptrends and red areas indicating downtrends.

  4. Built-in Risk Management: The strategy uses the slow EMA as a potential stop-loss reference point, providing a clear exit strategy for each trade. This approach helps control risk exposure for each trade and protects capital.

  5. Flexible Implementation Options: The strategy can run in “full mode” (combining MACD and SuperTrend) or “simplified mode” (using only SuperTrend), allowing traders to adjust strategy complexity according to market conditions.

Strategy Risks

  1. Trend Reversal Lag: As a trend-following system, the strategy may react slowly to sharp market reversals, leading to increased drawdowns. Especially in high-volatility environments, both SuperTrend and MACD indicators may fail to capture trend changes in a timely manner, missing optimal exit points.

  2. Poor Performance in Ranging Markets: In sideways or trendless markets, the strategy may generate frequent false signals, resulting in a series of small losing trades. While the dual confirmation mechanism can mitigate this issue, it cannot eliminate it completely.

  3. Parameter Dependency: Strategy performance is highly dependent on the chosen parameters. Improper parameter settings may lead to over-optimization or overfitting to specific market conditions, reducing the strategy’s applicability across different market environments.

  4. Signal Conflict Risk: Under certain market conditions, SuperTrend and MACD may provide contradictory signals, which could lead to difficult or delayed trading decisions. For example, SuperTrend might indicate an uptrend while MACD might show weakening momentum.

  5. Fixed Parameter Limitations: The strategy uses fixed indicator parameters rather than dynamically adjusting them based on market conditions, which may limit its adaptability in markets with varying volatility.

Strategy Optimization Directions

  1. Dynamic Parameter Adjustment: Implement parameter adaptive mechanisms based on market volatility or other market characteristics. For example, increase the SuperTrend ATR multiplier in high-volatility environments and decrease it in low-volatility environments to better adapt to different market conditions.

  2. Add Filters: Introduce additional filters to reduce false signals, such as trading time filters, volume confirmation, or volatility filters. For example, adding ADX (Average Directional Index) to ensure trading only in strong trend markets.

  3. Optimize Exit Strategy: Develop more sophisticated exit mechanisms, such as trailing stops, partial profit locking, or volatility-based dynamic stop-losses. This can help better manage risk while preserving most of the trend profits.

  4. Timeframe Analysis: Implement multi-timeframe analysis to ensure trade direction aligns with the trend in higher timeframes. This can be done by adding trend confirmation from higher timeframes to reduce counter-trend trading.

  5. Machine Learning Integration: Explore using machine learning algorithms to optimize strategy parameters or identify market conditions best suited for the strategy. This can be done by analyzing historical data to identify relationships between parameters and market conditions, thereby improving strategy adaptability.

  6. Risk Management Enhancement: Implement more refined position sizing based on market volatility, account size, and personal risk preferences. This can be done by dynamically adjusting position size based on ATR or other volatility measures to maintain consistent risk levels.

Summary

The MACD-SuperTrend Fusion Trend Following Trading System represents a balanced and comprehensive quantitative trading approach that combines trend identification and momentum confirmation. By merging the trend-following capabilities of SuperTrend with the momentum analysis of MACD, the strategy provides a powerful framework for capturing sustained trend movements.

The main advantages of the strategy lie in its dual confirmation mechanism and high customizability, making it suitable for various market environments and trading styles. However, as a trend-following system, it may perform poorly in ranging markets and react slowly to trend reversals.

To optimize the strategy, traders can consider implementing dynamic parameter adjustment, additional filtering mechanisms, improved exit strategies, and multi-timeframe analysis. These optimizations can improve the strategy’s robustness and adaptability, making it more effective across different market conditions.

Overall, the MACD-SuperTrend Fusion Trend Following Trading System provides a solid foundation for trend identification and trading, suitable for traders who focus on following the trend and seeking profits in major market movements. With proper risk management and continuous optimization, this strategy can be a valuable asset in a trader’s toolkit.

Strategy source code
/*backtest
start: 2024-07-25 00:00:00
end: 2025-07-23 08:00:00
period: 4d
basePeriod: 4d
exchanges: [{"eid":"Futures_Binance","currency":"BTC_USDT"}]
*/

//@version=5
strategy("TTFT - Strategy", overlay=true)

// Trading Direction Dropdown
tradeDirection = input.string("both", "Trading Direction", options=["long", "short", "both"])
onlyST = input.string("No", "Use ST Only?", options=["Yes", "No"])
period = input.string("LOW", "TF Period", options=["HIGH", "LOW"])
algo = input.string("ttft", "Algo Name")
instrument = input.string("", "Instrument")

// MACD Inputs
fast_length = input(12, "Fast Length")
slow_length = input(26, "Slow Length")
signal_length = input(9, "Signal Smoothing")
sma_source = input.string("EMA", "Oscillator MA Type", options=["SMA", "EMA"])
sma_signal = input.string("EMA", "Signal Line MA Type", options=["SMA", "EMA"])


// MACD Calculation
fast_ma = sma_source == "SMA" ? ta.sma(close, fast_length) : ta.ema(close, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(close, slow_length) : ta.ema(close, slow_length)
slow_ema = ta.ema(close, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
hist = macd - signal

// Input Parameters for Supertrend 1
atrPeriod1 = input(10, "ATR Length for Supertrend 1")
factor1 = input.float(3.0, "Factor for Supertrend 1", step=0.01)

// Supertrend Calculation for 1
[supertrend1, direction1] = ta.supertrend(factor1, atrPeriod1)

bool isBullish = false
bool exitLong= false
bool isBearish = false
bool exitShort= false

if(onlyST == 'No')
    // Combined Conditions
    isBullish := direction1 < 0 and hist > 0
    isBearish := direction1 > 0 and hist < 0
    exitLong := direction1 > 0 or ta.crossunder(close, slow_ema)
    exitShort := direction1 < 0 or ta.crossover(close, slow_ema)

else
    isBullish := direction1 < 0
    isBearish := direction1 > 0
    exitLong := direction1 > 0
    exitShort := direction1 < 0

if(instrument == "")
    instrument := syminfo.ticker

// Strategy Entry and Exit based on Trading Direction
if (tradeDirection == "both" or tradeDirection == "long") and isBullish
    strategy.entry("Buy", strategy.long, comment="L", alert_message="{\"source\": \"TV\", \"stopLoss\": \""+str.tostring(slow_ema)+"\",\"Period\": \""+period+"\",\"Algo\": \""+algo+"\",\"Open\": \""+str.tostring(open)+"\",\"High\": \""+str.tostring(high)+"\",\"Low\": \""+str.tostring(low)+"\",\"Close\": \""+str.tostring(close)+"\",\"Status\": \"L\",\"Signal\": \"buy\",\"Indicator\": \"TTFT\",\"Instrument\": \""+instrument+"\"}")

if (tradeDirection == "both" or tradeDirection == "long") and exitLong
    strategy.close("Buy", comment="LE", alert_message = "{\"source\": \"TV\", \"Period\": \""+period+"\",\"Algo\": \""+algo+"\",\"Open\": \""+str.tostring(open)+"\",\"High\": \""+str.tostring(high)+"\",\"Low\": \""+str.tostring(low)+"\",\"Close\": \""+str.tostring(close)+"\",\"Status\": \"LE\",\"Signal\": \"sell\",\"Indicator\": \"TTFT\",\"Instrument\": \""+instrument+"\"}")

if (tradeDirection == "both" or tradeDirection == "short") and isBearish
    strategy.entry("Sell", strategy.short, comment="S", alert_message = "{\"source\": \"TV\", \"stopLoss\": \""+str.tostring(slow_ema)+"\",\"Period\": \""+period+"\",\"Algo\": \""+algo+"\",\"Open\": \""+str.tostring(open)+"\",\"High\": \""+str.tostring(high)+"\",\"Low\": \""+str.tostring(low)+"\",\"Close\": \""+str.tostring(close)+"\",\"Status\": \"S\",\"Signal\": \"sell\",\"Indicator\": \"TTFT\",\"Instrument\": \""+instrument+"\"}")
 
if (tradeDirection == "both" or tradeDirection == "short") and exitShort
    strategy.close("Sell", comment="SE", alert_message = "{\"source\": \"TV\", \"Period\": \""+period+"\",\"Algo\": \""+algo+"\",\"Open\": \""+str.tostring(open)+"\",\"High\": \""+str.tostring(high)+"\",\"Low\": \""+str.tostring(low)+"\",\"Close\": \""+str.tostring(close)+"\",\"Status\": \"SE\",\"Signal\": \"buy\",\"Indicator\": \"TTFT\",\"Instrument\": \""+instrument+"\"}")
   
bodyMiddle1 = plot((open + close) / 2, display=display.none)
upTrend1 = plot(direction1 < 0 ? supertrend1 : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend1 = plot(direction1 < 0? na : supertrend1, "Down Trend", color = color.red, style=plot.style_linebr)

fill(bodyMiddle1, upTrend1, color.new(color.green, 90), fillgaps=false)
fill(bodyMiddle1, downTrend1, color.new(color.red, 90), fillgaps=false)