DEV Community

FMZQuant
FMZQuant

Posted on

RSI and Stochastic RSI Divergence Trading Strategy

Overview
The RSI and Stochastic RSI Divergence Trading Strategy is an advanced technical analysis approach designed to identify key reversal points in markets. This strategy combines the power of the Relative Strength Index (RSI) and Stochastic Relative Strength Index (SRSI) by monitoring divergences between price and these momentum indicators to predict potential trend changes. Additionally, the strategy incorporates an Exponential Moving Average (EMA) as a trend filter and applies precise swing distance filters to ensure it captures meaningful market structure changes rather than market noise.

Strategy Principles
The core principle of this strategy is based on the concept of divergence in technical analysis. Divergence occurs when price movement is inconsistent with technical indicator movement, typically suggesting that the current trend may be about to reverse. The strategy focuses on four types of divergences:

  1. Regular Bullish Divergence: When price makes a lower low, but RSI or SRSI fails to make a lower low. This indicates weakening downward momentum, potentially signaling the start of an uptrend.
  2. Regular Bearish Divergence: When price makes a higher high, but RSI or SRSI fails to make a higher high. This indicates weakening upward momentum, potentially signaling the start of a downtrend.
  3. Hidden Bullish Divergence: When price makes a higher low, but RSI or SRSI makes a lower low. This typically indicates a pullback in an uptrend, suggesting the main uptrend will continue.
  4. Hidden Bearish Divergence: When price makes a lower high, but RSI or SRSI makes a higher high. This typically indicates a rebound in a downtrend, suggesting the main downtrend will continue.

The strategy employs strict filtering conditions to ensure the quality of divergence signals:

  • Uses a lookback period (default 40 periods) to find significant swing points
  • Requires a minimum swing distance percentage (default 1.5%) to filter out minor fluctuations
  • Requires a minimum price move percentage from the last swing (default 0.5%)

When a divergence is detected, the strategy plots labels and connecting lines on the chart, allowing traders to visually identify these key signals. And the strategy automatically generates long and short entry signals based on the divergence signals.

Strategy Advantages

  1. Multi-layered Confirmation: Combining RSI and Stochastic RSI provides dual confirmation, reducing the likelihood of false signals. When both indicators show divergence, the signal is more reliable.
  2. Comprehensive Divergence Detection: The strategy detects both regular divergences (suggesting trend reversals) and hidden divergences (suggesting trend continuations), providing traders with a complete market perspective.
  3. Visual Representation: By visually marking divergences on the chart with labels and connecting lines, the strategy makes it easier for traders to identify and understand signals.
  4. High Adaptability: The strategy parameters such as lookback period, minimum swing distance, and minimum price move are all adjustable, allowing traders to optimize the strategy for different market conditions and timeframes.
  5. Noise Reduction through Filters: By implementing minimum swing distance and price movement thresholds, the strategy effectively filters out market noise to focus on meaningful price structure changes.
  6. Trend Context: The incorporation of the 200-period EMA provides broader trend context, helping traders understand the divergence signals within the overall market trend.

Strategy Risks

  1. False Divergences: Even with filters, the market can still produce false divergence signals, especially in highly volatile or ranging markets. This can lead to incorrect trading decisions and potential losses.
  2. Time Lag: Divergence signals typically form after the price has already begun to reverse, which can lead to suboptimal entry points, especially in rapidly moving markets.
  3. Parameter Sensitivity: The strategy's performance is highly dependent on parameter settings such as lookback period and minimum swing distance. Inappropriate parameters can lead to too many or too few signals.
  4. Indicator Limitations: RSI and SRSI, as momentum indicators, may not be reliable in certain market conditions, particularly in prolonged trending markets or extremely volatile environments.
  5. Lack of Stop-Loss Mechanism: The current strategy implementation doesn't include explicit stop-loss strategies, which increases potential downside risk.

To mitigate these risks, it is recommended to:

  • Combine divergence signals with other technical indicators or analysis methods, such as support/resistance levels, candlestick patterns, or volume analysis
  • Test and optimize parameter settings in different market conditions
  • Implement appropriate money management and stop-loss strategies
  • Consider the significance of divergence signals in the context of the overall market trend

Strategy Optimization Directions

  1. Incorporate Stop-Loss and Take-Profit Mechanisms: The current strategy lacks risk management features. Adding dynamic stop-losses based on ATR (Average True Range) or fixed stop-losses based on key support/resistance levels can significantly improve the strategy's risk-reward ratio. Similarly, implementing take-profit rules based on price targets or time can help lock in profits.
  2. Add Trend Filters: While the strategy includes an EMA as a reference, it doesn't use it to filter trades. Adding conditions like only considering bullish divergences when price is above the 200-day EMA, or only considering bearish divergences when price is below the 200-day EMA, can help stay aligned with the major trend.
  3. Signal Confirmation Mechanisms: Introducing additional confirmation indicators, such as volume increase, candlestick confirmation patterns, or crosses of other momentum indicators, can improve signal reliability.
  4. Dynamic Parameter Adjustment: Implementing a mechanism to automatically adjust the lookback period and swing distance thresholds based on market volatility. For example, using larger thresholds in high-volatility markets and smaller thresholds in low-volatility markets.
  5. Divergence Strength Scoring: Developing a scoring system to evaluate the "strength" of a divergence based on the size of the deviation between price and indicator, the length of time over which the divergence formed, and other relevant factors. This can help traders prioritize stronger signals.
  6. Multi-Timeframe Analysis: Incorporating multi-timeframe confirmation, for example, only considering a signal when a higher timeframe also shows a divergence in the same direction, can reduce false signals.
  7. Improved Price Swing Detection: The current strategy uses simple high/low detection. Implementing more sophisticated price structure analysis (such as considering sequences of multiple swing points) can improve the accuracy of divergence detection.
  8. Market Environment Adaptation: Adding market environment classification functionality (such as trending, ranging, or high volatility) and adjusting strategy behavior based on the detected environment.

Summary
The RSI and Stochastic RSI Divergence Trading Strategy is a sophisticated and powerful technical analysis tool capable of capturing potential market reversals and trend continuation signals by identifying discrepancies between price and momentum indicators. By integrating both regular and hidden divergence detection and applying carefully designed filters, the strategy provides a comprehensive approach to identifying high-probability trading opportunities.

However, like all technical analysis methods, this strategy has limitations and risks. By implementing the suggested optimizations, such as adding risk management mechanisms, improving signal confirmation, and incorporating dynamic parameter adjustments, the strategy's robustness and performance can be significantly enhanced.

Ultimately, this strategy is best suited as part of a broader trading system, combined with other analytical tools and proper money management principles. For traders who understand technical analysis and market structure, this divergence strategy can be a valuable tool for discovering high-quality trade setups.

Strategy source code

/*backtest
start: 2024-06-26 00:00:00
end: 2025-06-24 08:00:00
period: 2d
basePeriod: 2d
exchanges: [{"eid":"Futures_Binance","currency":"ETH_USDT"}]
*/

//@version=6
strategy("RSI Divergence Strategy", overlay=true)
//strategy("RSI & SRSI Divergence Strategy with EMA & Min Swing Filter + Price Chart Lines", overlay=true)
rsiLength = input.int(14, title="RSI Length")
srsiLength = input.int(14, title="Stochastic RSI Length")
kLength = input.int(3, title="%K Length")
dLength = input.int(3, title="%D Length")
emaLength = input.int(200, title="EMA Length")
lookback = input.int(40, title="Lookback Period for Divergence")
minSwingDistPercent = input.float(1.5, title="Minimum Swing Distance (%)")
minPriceMovePercent = input.float(0.5, title="Minimum Price Move from Last Swing (%)")

rsi = ta.rsi(close, rsiLength)
srsi = ta.stoch(rsi, rsi, rsi, srsiLength)
k = ta.sma(srsi, kLength)
d = ta.sma(k, dLength)
ema200 = ta.ema(close, emaLength)

// === Bullish Regular Divergence ===
var float lastLowPrice = na
var float lastLowRsi = na
var float lastLowSrsi = na
var int lastLowIndex = na
bullishDiv = false
if ta.lowestbars(low, lookback) == 0
    if not na(lastLowPrice) and not na(lastLowRsi) and not na(lastLowSrsi)
        swingDistLow = math.abs(low - lastLowPrice) / lastLowPrice * 100
        priceMoveLow = math.abs(low - lastLowPrice) / lastLowPrice * 100
        if swingDistLow >= minSwingDistPercent and priceMoveLow >= minPriceMovePercent
            if (low < lastLowPrice and rsi > lastLowRsi) or (low < lastLowPrice and k > lastLowSrsi)
                bullishDiv := true

            lastLowPrice := low
            lastLowRsi := rsi
            lastLowSrsi := k
            lastLowIndex := bar_index
    else
        lastLowPrice := low
        lastLowRsi := rsi
        lastLowSrsi := k
        lastLowIndex := bar_index

// === Bearish Regular Divergence ===
var float lastHighPrice = na
var float lastHighRsi = na
var float lastHighSrsi = na
var int lastHighIndex = na
bearishDiv = false
if ta.highestbars(high, lookback) == 0
    if not na(lastHighPrice) and not na(lastHighRsi) and not na(lastHighSrsi)
        swingDistHigh = math.abs(high - lastHighPrice) / lastHighPrice * 100
        priceMoveHigh = math.abs(high - lastHighPrice) / lastHighPrice * 100
        if swingDistHigh >= minSwingDistPercent and priceMoveHigh >= minPriceMovePercent
            if (high > lastHighPrice and rsi < lastHighRsi) or (high > lastHighPrice and k < lastHighSrsi)
                bearishDiv := true

            lastHighPrice := high
            lastHighRsi := rsi
            lastHighSrsi := k
            lastHighIndex := bar_index
    else
        lastHighPrice := high
        lastHighRsi := rsi
        lastHighSrsi := k
        lastHighIndex := bar_index

// === Bullish Hidden Divergence ===
bullishHiddenDiv = false
if ta.lowestbars(low, lookback) == 0
    if not na(lastLowPrice) and not na(lastLowRsi) and not na(lastLowSrsi)
        swingDistLowHidden = math.abs(low - lastLowPrice) / lastLowPrice * 100
        priceMoveLowHidden = math.abs(low - lastLowPrice) / lastLowPrice * 100
        if swingDistLowHidden >= minSwingDistPercent and priceMoveLowHidden >= minPriceMovePercent
            if (low > lastLowPrice and rsi < lastLowRsi) or (low > lastLowPrice and k < lastLowSrsi)
                bullishHiddenDiv := true


// === Bearish Hidden Divergence ===
bearishHiddenDiv = false
if ta.highestbars(high, lookback) == 0
    if not na(lastHighPrice) and not na(lastHighRsi) and not na(lastHighSrsi)
        swingDistHighHidden = math.abs(high - lastHighPrice) / lastHighPrice * 100
        priceMoveHighHidden = math.abs(high - lastHighPrice) / lastHighPrice * 100
        if swingDistHighHidden >= minSwingDistPercent and priceMoveHighHidden >= minPriceMovePercent
            if (high < lastHighPrice and rsi > lastHighRsi) or (high < lastHighPrice and k > lastHighSrsi)
                bearishHiddenDiv := true


// === PLOTS ===
plot(ema200, title="EMA 200", color=color.purple, linewidth=2)

// === STRATEGY ENTRIES ===
if bullishDiv or bullishHiddenDiv
    strategy.entry("Long", strategy.long)
if bearishDiv or bearishHiddenDiv
    strategy.entry("Short", strategy.short)
Enter fullscreen mode Exit fullscreen mode

Strategy parameters

The original address: RSI and Stochastic RSI Divergence Trading Strategy

Top comments (1)

Collapse
 
gavin_g_ebd1d919ab190af19 profile image
Grace

RSI + Stochastic RSI divergence? That's like bringing two lie detectors to catch price fibs! My last 'divergence play' diverged straight into margin call territory 😂. But if this combo can actually spot real reversals (and not just my wishful thinking), I might finally stop fading rallies like it's my job!