Pine Script RSI (Relative Strength Index)

Master this essential momentum oscillator in TradingView's Pine Script for identifying overbought/oversold conditions, trend strength, and reversals.

Last Updated on: Expertise: Intermediate

What is the Relative Strength Index (RSI)?

The Relative Strength Index (RSI), developed by J. Welles Wilder Jr., is one of the most widely used momentum oscillators in technical analysis. It measures the speed and change of price movements over a specified period, typically 14 bars. RSI oscillates between 0 and 100, providing insights into whether an asset is overbought or oversold, and helping traders identify potential trend reversals or continuations.

In Pine Script, the RSI is an indispensable tool for gauging the strength of price action and anticipating market turns, making it a cornerstone for many trading strategies.

Components and Calculation

The RSI calculation involves several steps, primarily focusing on the average gains and losses over the look-back period:

  1. Calculate Price Changes: For each bar, determine the upward price change (gain) and downward price change (loss).
    • `gain = current_close - previous_close` (if positive, else 0)
    • `loss = previous_close - current_close` (if positive, else 0)
  2. Calculate Average Gains and Average Losses: Compute the smoothed moving average (typically an Exponential Moving Average, EMA) of the gains and losses over the RSI period (e.g., 14 periods).
  3. Calculate Relative Strength (RS): `RS = Average Gain / Average Loss`.
  4. Calculate RSI: `RSI = 100 - (100 / (1 + RS))`

When there are no average losses in the period, the RS value becomes infinite, and the RSI will be 100. Conversely, if there are no average gains, the RS value will be zero, and the RSI will be 0.

Basic RSI Implementation in Pine Script

Pine Script v5 provides a straightforward built-in function `ta.rsi()` for calculating the Relative Strength Index.

//@version=5
indicator("My RSI Indicator", overlay=false) // overlay=false to plot in a separate pane

// Input for RSI length
length = input.int(14, title="RSI Length", minval=1)

// Calculate RSI value using the built-in function
rsiValue = ta.rsi(close, length)

// Plot the RSI line
plot(rsiValue, title="RSI", color=color.purple, linewidth=2)

// Plot horizontal lines for overbought and oversold levels
h_overbought = hline(70, "Overbought", color=color.red)
h_oversold = hline(30, "Oversold", color=color.green)

// Fill background between RSI and levels for visual clarity
fill(h_overbought, h_oversold, color.new(color.gray, 90))
Standard Levels: The conventional overbought level is 70 (or 80 for strong trends) and the oversold level is 30 (or 20 for strong trends).

Practical RSI Trading Strategies

1. Overbought and Oversold Conditions

This is the most common use of RSI. When RSI crosses above 70, the asset is considered overbought, suggesting a potential pullback or reversal. When RSI crosses below 30, it's considered oversold, indicating a potential bounce or reversal.

//@version=5
strategy("RSI Overbought/Oversold Strategy", overlay=true)

// Inputs for RSI
length = input.int(14, title="RSI Length", minval=1)
overboughtLevel = input.int(70, title="Overbought Level")
oversoldLevel = input.int(30, title="Oversold Level")

// Calculate RSI
rsiValue = ta.rsi(close, length)

// Define conditions for entries and exits
longCondition = ta.crossunder(rsiValue, oversoldLevel) // RSI goes oversold
longExitCondition = ta.crossover(rsiValue, oversoldLevel) // RSI exits oversold (potential buy) - corrected typo 'oversledLevel' to 'oversoldLevel'

shortCondition = ta.crossover(rsiValue, overboughtLevel) // RSI goes overbought
shortExitCondition = ta.crossunder(rsiValue, overboughtLevel) // RSI exits overbought (potential sell)

// Strategy entries/exits
if (longExitCondition) // Using exit of oversold as buy signal
    strategy.entry("Long", strategy.long)

if (shortExitCondition) // Using exit of overbought as sell signal
    strategy.entry("Short", strategy.short)

// Optional: Plot RSI in a separate pane for visualization
// plot(rsiValue, "RSI", color.purple)
// hline(overboughtLevel, "Overbought", color.red)
// hline(oversoldLevel, "Oversold", color.green)

2. RSI Centerline Crossover

The 50-level on the RSI often acts as a centerline, indicating a shift in momentum bias. Crossing above 50 suggests bullish momentum, while crossing below suggests bearish momentum.

//@version=5
strategy("RSI Centerline Crossover", overlay=true)

// Inputs for RSI
length = input.int(14, title="RSI Length", minval=1)
centerLine = input.int(50, title="Centerline")

// Calculate RSI
rsiValue = ta.rsi(close, length)

// Define conditions for entries and exits
longCondition = ta.crossover(rsiValue, centerLine)
shortCondition = ta.crossunder(rsiValue, centerLine)

// Strategy entries/exits
if (longCondition)
    strategy.entry("Long", strategy.long)

if (shortCondition)
    strategy.entry("Short", strategy.short)

// Optional: Plot RSI in a separate pane
// plot(rsiValue, "RSI", color.purple)
// hline(centerLine, "Centerline", color.gray)

3. RSI Divergence Strategy

Divergence occurs when price and RSI move in opposite directions, often signaling a potential trend reversal. It suggests that the current trend is weakening.

//@version=5
indicator("RSI Divergence Scanner", overlay=true)

// Inputs for RSI
length = input.int(14, title="RSI Length", minval=1)
overboughtLevel = input.int(70, title="Overbought Level")
oversoldLevel = input.int(30, title="Oversold Level")

// Calculate RSI
rsiValue = ta.rsi(close, length)

// Plot RSI in a separate pane
plot(rsiValue, "RSI", color.purple)
hline(overboughtLevel, "Overbought", color.red)
hline(oversoldLevel, "Oversold", color.green)
hline(50, "Centerline", color.gray)

// Simple divergence detection (conceptual, robust detection requires advanced pivot logic)
// This is a simplified example and might need refinement for actual trading.

// Bullish Divergence (Price lower low, RSI higher low)
bullishDivergence = close[2] > close[1] and close[1] > close and rsiValue[2] < rsiValue[1] and rsiValue[1] < rsiValue

// Bearish Divergence (Price higher high, RSI lower high)
bearishDivergence = close[2] < close[1] and close[1] < close and rsiValue[2] > rsiValue[1] and rsiValue[1] > rsiValue

plotshape(bullishDivergence, title="Bullish Divergence", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small)
plotshape(bearishDivergence, title="Bearish Divergence", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.small)

alertcondition(bullishDivergence, "Bullish RSI Divergence", "Potential bullish reversal based on RSI divergence.")
alertcondition(bearishDivergence, "Bearish RSI Divergence", "Potential bearish reversal based on RSI divergence.")

Optimizing RSI Performance

To get the most from the Relative Strength Index in Pine Script:

RSI in Strong Trends: In a strong uptrend, RSI can remain overbought for extended periods, and in a strong downtrend, it can remain oversold. Do not blindly fade strong trends based solely on overbought/oversold RSI readings.

Common RSI Pitfalls

Conclusion

The Relative Strength Index (RSI) is a fundamental and highly versatile momentum oscillator in Pine Script for TradingView. Its ability to quantify the speed and change of price movements makes it invaluable for identifying overbought and oversold conditions, assessing trend strength, and spotting potential reversals through divergence. By understanding its calculation, thoughtfully tuning its parameters, and integrating it strategically with other technical analysis tools, you can leverage the RSI to gain deeper insights into market dynamics and enhance your trading decisions.