Logo
OFFLINEPIXEL
/ pinescript-strategies / pine-script-rsi

$ 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.

500+ Clients Helped
100% Satisfaction
Live Trading Ready
⚠️
Trading financial markets carries risk. All content (PineScript code, indicators, strategies) on this website is for educational purposes only. Past performance is not indicative of future results. By using any code or information from this site, you agree that you are solely responsible for your trading decisions. The author disclaims all liability for any losses incurred. To gain from experts experiences, You can always try our Invite Only Scripts
01

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.

02

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))
03

Basic RSI Implementation in Pine Script

pine-script@terminal
//@version=5
indicator("My RSI Indicator", overlay=false)

// 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))
$ ✓ Compiled successfully
04

Standard Levels

Standard Levels

The conventional overbought level is 70 (or 80 for strong trends) and the oversold level is 30 (or 20 for strong trends).

05

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.

  • Buy Signal: RSI crosses below 30 and then crosses back above it.
  • Sell Signal: RSI crosses above 70 and then crosses back below it.
//@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)
longExitCondition = ta.crossover(rsiValue, oversoldLevel)

shortCondition = ta.crossover(rsiValue, overboughtLevel)
shortExitCondition = ta.crossunder(rsiValue, overboughtLevel)

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

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

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
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)

3. RSI Divergence Strategy

Divergence occurs when price and RSI move in opposite directions, often signaling a potential trend reversal.

  • Bullish Divergence: Price makes a lower low, but RSI makes a higher low.
  • Bearish Divergence: Price makes a higher high, but RSI makes a lower high.
//@version=5
indicator("RSI Divergence Scanner", overlay=true)

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

rsiValue = ta.rsi(close, length)

plot(rsiValue, "RSI", color.purple)
hline(overboughtLevel, "Overbought", color.red)
hline(oversoldLevel, "Oversold", color.green)
hline(50, "Centerline", color.gray)

bullishDivergence = close[2] > close[1] and close[1] > close and rsiValue[2] < rsiValue[1] and rsiValue[1] < rsiValue
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)
06

Optimizing RSI Performance

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

  • Parameter Tuning: The `length` parameter is crucial. While 14 is standard, shorter lengths make RSI more sensitive, while longer lengths smooth it more.
  • Adjust Levels: In highly volatile markets, consider adjusting overbought/oversold levels to 80/20 instead of 70/30.
  • Combine with Trend Filters: Use a trend filter (like a moving average or ADX) to confirm a clear trend before relying on RSI signals.
  • Multi-Timeframe Analysis: Confirm RSI signals on a higher timeframe before acting on signals from a lower timeframe.
  • Confluence with Price Action: Always look for RSI signals to be confirmed by price action.
07

RSI in Strong Trends

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.

08

Common RSI Pitfalls

  • False Overbought/Oversold Signals: RSI can stay at extreme levels in strong trends.
  • Whipsaws in Ranging Markets: RSI can oscillate frequently between 30 and 70 in choppy markets.
  • Divergence Can Be Early: Divergence can appear early and a trend might continue after the signal.
  • Not a Standalone Indicator: RSI should be used as part of a broader trading system.
09

Conclusion

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.

Enhance Your Trading

Get a high-performance Pine Script analysis tool for actionable market insights, designed for traders on the move.

This strategy runs in live mode on TradingView, helping you identify potential opportunities.

Get Pine Script Strategy