Dual Momentum Indicator Synergy Trading System: RSI and MACD Breakout Framework

RSI MACD EMA TAKE PROFIT STOP LOSS
Created on: 2025-08-11 09:27:51 Modified on: 2025-08-11 09:27:51
Copy: 0 Number of hits: 282
avatar of ianzeng123 ianzeng123
2
Follow
319
Followers

 Dual Momentum Indicator Synergy Trading System: RSI and MACD Breakout Framework  Dual Momentum Indicator Synergy Trading System: RSI and MACD Breakout Framework

Overview

The Dual Momentum Indicator Synergy Trading System is a quantitative trading strategy based on technical analysis that ingeniously combines the strengths of the Relative Strength Index (RSI) and Moving Average Convergence Divergence (MACD) indicators, focusing on capturing strong upward trends in the market. This strategy executes long-only trades, identifying momentum breakout signals while incorporating risk management mechanisms to achieve a systematic trading decision process. The core concept is to enter positions when both RSI and MACD indicators simultaneously display bullish signals, and exit when momentum weakens or risk targets are reached, thereby capturing potential profits in trending markets.

Strategy Principles

The strategy operates based on the synergistic effect of two key technical indicators. First, it uses the RSI indicator to measure the speed and magnitude of price movements, determining whether the market is in overbought or oversold conditions. Second, it employs the MACD indicator to identify changes in market trends and momentum strength. The specific trading rules are as follows:

Entry Conditions: 1. RSI crosses above the midline (default 50) while MACD is in a bullish state (MACD line above the Signal line, with an optional requirement that MACD value > 0); or 2. MACD line crosses above the Signal line while RSI is at or above the midline position.

Additional Filters: 1. EMA trend filter: price must be higher than the specified period EMA line; 2. Oversold context filter: enter only within N bars after RSI has dipped below the oversold threshold.

Exit Conditions: 1. RSI crosses below the midline; or 2. MACD line crosses below the Signal line, and the MACD histogram is less than or equal to 0; or 3. Take Profit (default 3.0%) or Stop Loss (default 1.5%) targets are hit.

The strategy implements a state tracking mechanism to ensure entries occur only when flat and exits only when in a position, avoiding duplicate signal problems. This design ensures that each entry is followed by only one exit, maintaining clarity and consistency in the trading logic.

Strategy Advantages

  1. Indicator Synergy Effect: Combines the strengths of RSI and MACD indicators - RSI quickly responds to price changes, while MACD confirms medium to long-term trends, enhancing signal reliability when used together.

  2. Flexible Filtering Mechanisms: The strategy offers optional EMA trend filtering and oversold context filtering, allowing traders to adjust the strategy’s adaptability to different market environments.

  3. Comprehensive Risk Management: Built-in take-profit and stop-loss mechanisms allow traders to set percentage parameters according to their risk preferences, effectively controlling risk exposure per trade.

  4. Clear State Management: Tracks position status through state variables, ensuring the coherence and logic of trading signals and avoiding problems of repeated entries or exits.

  5. High Customizability: The strategy provides multiple adjustable parameters, including RSI length, MACD parameters, filtering conditions, and risk management parameters, enabling traders to optimize for different market conditions and trading instruments.

  6. Visual Assistance: The strategy includes visualization features such as entry/exit markers, bar coloring, and trigger background display, facilitating intuitive understanding and adjustment of the strategy.

Risk Analysis

  1. False Breakout Risk: In oscillating markets, RSI and MACD may generate frequent false breakout signals, leading to consecutive losing trades. To mitigate this risk, additional market environment filters such as volatility indicators or trend strength indicators can be added.

  2. Unidirectional Trading Limitation: This strategy only executes long trades, missing potential short opportunities in downtrends. In a comprehensive trading system, consider adding corresponding short strategies or pausing trading during clear downtrends.

  3. Parameter Sensitivity: Strategy performance is sensitive to parameter settings, with different markets and timeframes potentially requiring different parameter combinations. It is recommended to optimize parameters through backtesting across multiple market conditions and consider adaptive parameter methods.

  4. Stop Loss Setting Risk: Too small a stop loss may lead to frequent triggering, while too large a stop loss may cause excessive single-trade losses. Adjust the stop loss percentage based on the volatility characteristics of the target market, or consider dynamic stop loss methods such as ATR multiples.

  5. Signal Lag: As lagging indicators, RSI and MACD signals may appear after prices have already moved significantly, affecting entry prices and returns. Consider incorporating more sensitive leading indicators to optimize entry timing.

Optimization Directions

  1. Adaptive Parameter System: Develop an adaptive parameter adjustment mechanism based on market volatility or trend strength, allowing RSI and MACD parameters to automatically optimize according to current market conditions, improving the strategy’s adaptability across different market environments.

  2. Multi-Timeframe Analysis: Introduce a multi-timeframe confirmation mechanism, such as confirming trend direction on larger timeframes before executing specific trades on smaller timeframes, to reduce false signals and improve win rates.

  3. Dynamic Stop Loss Mechanism: Replace fixed percentage stops with ATR (Average True Range) based dynamic stops to better adapt to changes in market volatility, protecting capital while giving prices sufficient room to move.

  4. Money Management Optimization: Introduce position sizing algorithms based on account equity, volatility, and win rate, such as the Kelly formula or fixed-proportion risk models, to match risk exposure per trade with current account status and market conditions.

  5. Market Environment Filters: Add filters capable of identifying market environments (trending, oscillating, or transitional), such as ADX (Average Directional Index), volatility indicators, or cycle analysis tools, to execute trades only in market conditions suitable for the strategy.

  6. Add Short Trading Logic: Extend the strategy to include short trading rules, making it equally effective in downtrends, thereby building a comprehensive trading system.

Summary

The Dual Momentum Indicator Synergy Trading System creates a logically clear and risk-controlled quantitative trading framework by combining the advantages of two classic technical indicators: RSI and MACD. This strategy focuses on capturing momentum opportunities in uptrends while enhancing trade quality through multiple filtering mechanisms and risk management tools. Although inherent risks exist, such as false breakouts and parameter sensitivity, the strategy has potential for further performance improvement across various market environments through the suggested optimization directions like adaptive parameters, multi-timeframe analysis, and dynamic risk management. This strategy is particularly suitable for investors pursuing trend following and momentum trading approaches, capable of achieving stable results in the field of technical analysis-driven quantitative trading through appropriate parameter adjustments and risk control.

Strategy source code
/*backtest
start: 2025-02-28 00:00:00
end: 2025-08-10 00:00:00
period: 3h
basePeriod: 3h
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT"}]
*/

//@version=6
// Vibe coded by Andrew Grothe 2025-08-08. Adjust the TP/SL on lines 28 & 29 to fine tune the strategy
strategy("RSI + MACD Long-Only Strategy", overlay=true, pyramiding=0, initial_capital=10000, commission_type=strategy.commission.percent, commission_value=0.0)

// Inputs — RSI
rsiLen  = input.int(14, "RSI Length", minval=1, group="RSI")
rsiOB   = input.int(70, "RSI Overbought", minval=50, maxval=100, group="RSI")
rsiOS   = input.int(30, "RSI Oversold", minval=0,  maxval=50, group="RSI")
rsiMid  = input.int(50, "RSI Midline", minval=0,   maxval=100, group="RSI")

// Inputs — MACD
fastLen = input.int(12, "MACD Fast Length",   minval=1, group="MACD")
slowLen = input.int(26, "MACD Slow Length",   minval=1, group="MACD")
sigLen  = input.int(9,  "MACD Signal Length", minval=1, group="MACD")
requireAboveZero = input.bool(false, "Require MACD > 0 (trend filter)", group="MACD")

// Inputs — Filters & Visuals
useOversoldContext  = input.bool(false, "Entry must be within N bars after RSI < Oversold", group="Signals")
oversoldWindowBars  = input.int(10, "N bars after oversold", minval=1, group="Signals")
useEMATrend         = input.bool(false, "Only Long if price > EMA", group="Signals")
emaLen              = input.int(200, "EMA Length", minval=1, group="Signals")
showMarkers         = input.bool(true, "Plot Entry/Exit Markers", group="Visuals")
colorBars           = input.bool(false, "Color Bars on Signals", group="Visuals")

// Inputs — Risk
// 1 hour = 2.0/1.0, 2 hour = 10.5/2.5
useTPSL             = input.bool(true,  "Use Take Profit / Stop Loss", group="Risk")
tpPerc              = input.float(11.5,  "Take Profit %", minval=0.0, step=0.1, group="Risk")
slPerc              = input.float(2.5,  "Stop Loss %",  minval=0.0, step=0.1, group="Risk")

// Core calculations
rsi = ta.rsi(close, rsiLen)
[macd, macdSignal, macdHist] = ta.macd(close, fastLen, slowLen, sigLen)
emaTrend = ta.ema(close, emaLen)

// Conditions
macdBull = macd > macdSignal and (not requireAboveZero or macd > 0)
rsiBull  = rsi > rsiMid
recentlyOversold = ta.barssince(rsi < rsiOS) <= oversoldWindowBars
trendOk = not useEMATrend or close > emaTrend

// Precompute cross events to avoid conditional execution warnings
rsiCrossUpMid     = ta.crossover(rsi, rsiMid)
macdCrossUp       = ta.crossover(macd, macdSignal)
rsiCrossDownMid   = ta.crossunder(rsi, rsiMid)
macdCrossDown     = ta.crossunder(macd, macdSignal)

// Signals (long-only)
longTrigger = (rsiCrossUpMid and macdBull) or (macdCrossUp and rsi >= rsiMid)
longEntry   = longTrigger and (not useOversoldContext or recentlyOversold) and trendOk
exitSignal  = rsiCrossDownMid or (macdCrossDown and macdHist <= 0)

// Stateful gating so we only get one exit per entry
var bool inLong = false
inLongPrev = barstate.isfirst ? false : inLong[1]
finalLongEntry = longEntry and not inLongPrev
finalExit      = exitSignal and inLongPrev
inLong := (inLongPrev or finalLongEntry) and not finalExit

// Plots
plot(useEMATrend ? emaTrend : na, title="EMA", color=color.orange, linewidth=2)
plotshape(showMarkers and finalLongEntry,  title="Long Entry", style=shape.triangleup,   location=location.belowbar, color=color.lime, size=size.tiny, text="Long")
plotshape(showMarkers and finalExit,       title="Exit",       style=shape.triangledown, location=location.abovebar, color=color.red,  size=size.tiny, text="Exit")
barcolor(colorBars ? (finalLongEntry ? color.lime : finalExit ? color.red : na) : na)

// Debug background to visualize when raw long trigger occurs
bgcolor(longTrigger ? color.new(color.lime, 90) : na)

// Alerts
//alertcondition(finalLongEntry,  title="RSI+MACD Long Entry", message="RSI+MACD Long Entry on {{ticker}} {{interval}} at {{close}}")
//alertcondition(finalExit,       title="RSI+MACD Exit",       message="RSI+MACD Exit on {{ticker}} {{interval}} at {{close}}")

// Strategy Orders — Long only
if finalLongEntry
    strategy.entry("Long", strategy.long)

// Protective exits (TP/SL) while in position
if useTPSL and strategy.position_size > 0
    longSL = strategy.position_avg_price * (1 - slPerc / 100.0)
    longTP = strategy.position_avg_price * (1 + tpPerc / 100.0)
    strategy.exit("Long TP/SL", from_entry="Long", stop=longSL, limit=longTP)

// Signal-based exit
if finalExit and strategy.position_size > 0
    strategy.close("Long", comment="Signal Exit")