×

Pine Script Guide

RSI Trading Strategy

The Relative Strength Index (RSI) is one of the most popular momentum oscillators used in technical analysis. Developed by J. Welles Wilder Jr. in 1978, the RSI measures the speed and change of price movements, helping traders identify overbought and oversold conditions in the market.

Strategy Overview: This strategy generates buy signals when the RSI moves from oversold territory back above a threshold level, and sell signals when the RSI moves from overbought territory back below a threshold level.

Understanding the RSI Indicator

The RSI is a momentum oscillator that measures the speed and change of price movements. It oscillates between 0 and 100 and is typically used to identify overbought or oversold conditions in a market.

  • RSI above 70: Generally considered overbought (potential sell signal)
  • RSI below 30: Generally considered oversold (potential buy signal)
  • RSI = 50: Neutral, neither overbought nor oversold

The RSI is calculated using the following formula:

RSI = 100 - (100 / (1 + RS))

Where RS (Relative Strength) is the average of x periods' up closes divided by the average of x periods' down closes.

The Strategy Logic

Our RSI trading strategy is based on these rules:

  1. Buy Signal: When the RSI crosses above 30 from below (exiting oversold territory)
  2. Sell Signal: When the RSI crosses below 70 from above (exiting overbought territory)

The theory behind this strategy is that when the RSI moves out of oversold territory, it indicates a potential reversal to the upside. Conversely, when the RSI moves out of overbought territory, it suggests a potential reversal to the downside.

Implementing the Strategy in Pine Script

In TradingView, we need to create two separate scripts:

  1. An indicator script to visualize the RSI and signal points
  2. A strategy script to execute trades based on the RSI signals

RSI Indicator

First, let's create the indicator that will visualize the RSI and signal points:

Pine Script - RSI Indicator
//@version=5
indicator("RSI Strategy Indicator", overlay=false)

// Input parameters
rsi_length = input.int(14, "RSI Length", minval=1)
overbought = input.int(70, "Overbought Level", minval=50, maxval=100)
oversold = input.int(30, "Oversold Level", minval=0, maxval=50)

// Calculate RSI
rsi_value = ta.rsi(close, rsi_length)

// Detect crossovers
buy_signal = ta.crossover(rsi_value, oversold)
sell_signal = ta.crossunder(rsi_value, overbought)

// Plot RSI
plot(rsi_value, "RSI", color=color.purple, linewidth=2)

// Plot overbought/oversold levels
hline(overbought, "Overbought", color=color.red, linestyle=hline.style_dashed)
hline(oversold, "Oversold", color=color.green, linestyle=hline.style_dashed)
hline(50, "Midline", color=color.gray, linestyle=hline.style_dotted)

// Plot signals
plotshape(buy_signal, "Buy Signal", location=location.bottom, color=color.green, style=shape.triangleup, size=size.small)
plotshape(sell_signal, "Sell Signal", location=location.top, color=color.red, style=shape.triangledown, size=size.small)

// Color the background based on RSI zones
bgcolor(rsi_value > overbought ? color.new(color.red, 90) : 
       rsi_value < oversold ? color.new(color.green, 90) : 
       na)

This indicator script does the following:

  1. Allows users to set the RSI length and overbought/oversold levels
  2. Calculates the RSI value using the ta.rsi() function
  3. Detects when the RSI crosses above the oversold level (buy signal)
  4. Detects when the RSI crosses below the overbought level (sell signal)
  5. Plots the RSI line and reference levels
  6. Marks buy and sell signals with triangular shapes
  7. Colors the background to highlight overbought and oversold zones

RSI Trading Strategy

Now, let's create the strategy script that will execute trades based on the RSI signals:

Pine Script - RSI Strategy
//@version=5
strategy("RSI Trading Strategy", overlay=true)

// Input parameters
rsi_length = input.int(14, "RSI Length", minval=1)
overbought = input.int(70, "Overbought Level", minval=50, maxval=100)
oversold = input.int(30, "Oversold Level", minval=0, maxval=50)

// Risk management parameters
use_stop_loss = input.bool(true, "Use Stop Loss")
stop_loss_percent = input.float(2.0, "Stop Loss (%)", minval=0.1, step=0.1)
use_take_profit = input.bool(true, "Use Take Profit")
take_profit_percent = input.float(4.0, "Take Profit (%)", minval=0.1, step=0.1)

// Position sizing
risk_per_trade = input.float(1.0, "Risk Per Trade (%)", minval=0.1, maxval=100, step=0.1)

// Calculate RSI
rsi_value = ta.rsi(close, rsi_length)

// Detect crossovers
buy_signal = ta.crossover(rsi_value, oversold)
sell_signal = ta.crossunder(rsi_value, overbought)

// Calculate stop loss and take profit levels
long_stop_loss = use_stop_loss ? close * (1 - stop_loss_percent / 100) : na
long_take_profit = use_take_profit ? close * (1 + take_profit_percent / 100) : na

short_stop_loss = use_stop_loss ? close * (1 + stop_loss_percent / 100) : na
short_take_profit = use_take_profit ? close * (1 - take_profit_percent / 100) : na

// Entry conditions
if (buy_signal)
    strategy.entry("Buy", strategy.long)
    if (use_stop_loss or use_take_profit)
        strategy.exit("Long Exit", "Buy", stop=long_stop_loss, limit=long_take_profit)

if (sell_signal)
    strategy.entry("Sell", strategy.short)
    if (use_stop_loss or use_take_profit)
        strategy.exit("Short Exit", "Sell", stop=short_stop_loss, limit=short_take_profit)

// Plot RSI value on a separate pane for reference
plot(rsi_value, "RSI", display=display.none)

This strategy script includes:

  1. The same RSI calculation and signal detection as the indicator
  2. Additional risk management parameters (stop loss and take profit)
  3. Position sizing based on risk percentage
  4. Trade entry and exit logic based on RSI signals

Optimizing the RSI Strategy

The basic RSI strategy can be optimized in several ways:

1. Adjusting RSI Parameters

Different markets and timeframes may require different RSI settings:

  • RSI Length: Shorter periods (e.g., 7-10) make the RSI more sensitive, while longer periods (e.g., 20-25) make it smoother
  • Overbought/Oversold Levels: In strong trends, consider using more extreme levels (e.g., 80/20) to reduce false signals

2. Adding Trend Filters

To reduce false signals, consider adding trend filters such as:

  • Only take long trades when price is above a moving average
  • Only take short trades when price is below a moving average

Here's an example of adding a trend filter using a 200-period moving average:

Pine Script - RSI with Trend Filter
// Add a trend filter
trend_ma_length = input.int(200, "Trend MA Length", minval=1)
trend_ma = ta.sma(close, trend_ma_length)

// Only take long trades when price is above the trend MA
long_condition = buy_signal and close > trend_ma
// Only take short trades when price is below the trend MA
short_condition = sell_signal and close < trend_ma

// Entry conditions with filter
if (long_condition)
    strategy.entry("Buy", strategy.long)
    
if (short_condition)
    strategy.entry("Sell", strategy.short)

3. RSI Divergence

A powerful enhancement to the basic RSI strategy is to look for divergences between price and RSI:

  • Bullish Divergence: Price makes a lower low, but RSI makes a higher low (potential buy signal)
  • Bearish Divergence: Price makes a higher high, but RSI makes a lower high (potential sell signal)

Implementing divergence detection in Pine Script is more complex but can significantly improve the strategy's performance.

Backtesting Results

When backtesting the RSI strategy, consider these key performance metrics:

  • Win Rate: The percentage of winning trades
  • Profit Factor: Gross profits divided by gross losses
  • Maximum Drawdown: The largest peak-to-trough decline in account value
  • Sharpe Ratio: Risk-adjusted return (higher is better)

Important Note: The RSI strategy tends to perform best in ranging markets and may generate false signals in strongly trending markets. Always test your strategies thoroughly across different market conditions before trading with real money.

Strengths and Weaknesses

Strengths

  • Effective at identifying potential reversal points
  • Works well in ranging or cyclical markets
  • Clear and objective entry and exit signals
  • Can be combined with other indicators for confirmation

Weaknesses

  • Can generate false signals in strongly trending markets
  • RSI can remain in overbought/oversold territory for extended periods
  • May not account for fundamental factors affecting price
  • Performance varies significantly across different market conditions

Real-World Application

The Predik Scientists Association from Zug, Switzerland has found that RSI-based strategies are particularly effective when:

  1. Applied to markets that tend to move in cycles or ranges
  2. Combined with trend filters to avoid trading against the dominant trend
  3. Used with proper risk management rules
  4. Enhanced with divergence detection for stronger signals

Their research suggests that this strategy performs best in forex pairs, commodities, and certain stocks that exhibit mean-reverting behavior.

Conclusion

The RSI trading strategy is a powerful tool for identifying potential reversal points in the market. By understanding its strengths and weaknesses and applying proper optimization and risk management techniques, you can adapt this strategy to suit your trading style and market conditions.