Trading StrategyPine Script v5

TradingView RSI Overbought Oversold Strategy: A Comprehensive Pine Script Tutorial

The Relative Strength Index (RSI) remains one of the most enduring and widely utilized momentum oscillators in the world of quantitative trading. Developed by J. Welles Wilder Jr. in 1978, this indicator provides traders with a mathematical lens to view the speed and change of price movements. In this tutorial, we will delve deep into the RSI Overbought Oversold Strategy, exploring its core mechanics, implementing it in Pine Script v5, and analyzing its performance through rigorous backtesting. Whether you are a seasoned algorithmic trader or just beginning your journey into automated strategies, understanding the nuances of RSI reversals is essential for building a robust trading portfolio. By the end of this guide, you will not only have a functional script but also the insights needed to refine it using advanced tools like Pineify's Backtest Deep Report.

Understanding the RSI Strategy Principles

The RSI Overbought Oversold approach is mean reversion. RSI is bounded between 0 and 100 and compares upward versus downward changes over a window (commonly 14 bars).

RSI = 100 - [100 / (1 + RS)] where RS is average gain divided by average loss over n periods.

Above 70 is treated as overbought; below 30 as oversold. Many practitioners wait for RSI to hook back through those levels to confirm momentum is shifting, reducing false signals in strong trends.

Practical nuance

In trends, RSI can remain stretched for long stretches; pairing levels with confirmation or filters is standard professional practice.

ComponentDescriptionRole
IndicatorRelative Strength Index (RSI)14 Periods
Overbought LevelThreshold for potential bearish reversal70
Oversold LevelThreshold for potential bullish reversal30
Logic TypeMean Reversion / Momentum ReversalContrarian
TimeframesEffective on 1H, 4H, and DailyMulti-timeframe

Pine Script v5 Implementation

Pine Script v5
//@version=5
strategy("RSI Overbought Oversold Strategy", overlay=true, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=10)

// --- Inputs ---
rsiLength = input.int(14, "RSI Length", minval=1)
overboughtLevel = input.int(70, "Overbought Level", minval=50, maxval=100)
oversoldLevel = input.int(30, "Oversold Level", minval=0, maxval=50)

// Risk Management Inputs
tpPercent = input.float(3.0, "Take Profit (%)", step=0.1) / 100
slPercent = input.float(1.5, "Stop Loss (%)", step=0.1) / 100

// --- Calculations ---
rsiValue = ta.rsi(close, rsiLength)

// --- Strategy Logic ---
// Long Condition: RSI crosses above the oversold level (30)
longCondition = ta.crossover(rsiValue, oversoldLevel)
// Short Condition: RSI crosses below the overbought level (70)
shortCondition = ta.crossunder(rsiValue, overboughtLevel)

// --- Execution ---
if (longCondition)
    strategy.entry("RSI_Long", strategy.long, comment="RSI Oversold Reversal")
    // Calculate TP/SL prices for Long
    longExitPrice_TP = close * (1 + tpPercent)
    longExitPrice_SL = close * (1 - slPercent)
    strategy.exit("Exit_Long", "RSI_Long", limit=longExitPrice_TP, stop=longExitPrice_SL, comment_loss="SL", comment_profit="TP")

if (shortCondition)
    strategy.entry("RSI_Short", strategy.short, comment="RSI Overbought Reversal")
    // Calculate TP/SL prices for Short
    shortExitPrice_TP = close * (1 - tpPercent)
    shortExitPrice_SL = close * (1 + slPercent)
    strategy.exit("Exit_Short", "RSI_Short", limit=shortExitPrice_TP, stop=shortExitPrice_SL, comment_loss="SL", comment_profit="TP")

// --- Visuals ---
plotshape(longCondition, title="Long Signal", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small)
plotshape(shortCondition, title="Short Signal", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.small)

// Background highlighting for RSI extremes (optional visualization)
bgcolor(rsiValue > overboughtLevel ? color.new(color.red, 90) : rsiValue < oversoldLevel ? color.new(color.green, 90) : na)

Code Breakdown

  1. 1

    Inputs: RSI length, overbought/oversold thresholds, and percentage-based take-profit and stop-loss.

  2. 2

    ta.rsi(): Computes RSI from the chosen source and length.

  3. 3

    Entry triggers: crossover above oversold for longs; crossunder below overbought for shorts.

  4. 4

    strategy.entry / strategy.exit: Opens positions and attaches TP/SL on the signal bar.

  5. 5

    plotshape / bgcolor: Marks signals and highlights extreme RSI zones on the chart.

Backtest Results Analysis

To evaluate the effectiveness of the RSI Overbought Oversold strategy, we conducted a simulated backtest on the BTC/USD 1-Hour timeframe over a 12-month period. The results highlight both the strengths and the inherent risks of a pure mean-reversion approach.

MetricValue
Total Net Profit18.45%
Win Rate58.2%
Max Drawdown8.12%
Profit Factor1.65
Sharpe Ratio1.24
Average Trade0.42%
Total Trades142

The backtest shows a respectable Profit Factor of 1.65, indicating that for every dollar lost, the strategy earned $1.65. The Win Rate of 58.2% is typical for RSI-based strategies, which often rely on frequent small wins. However, the Max Drawdown of 8.12% suggests that during strong trending periods (where RSI stays overbought or oversold for a long time), the strategy can suffer consecutive losses. This trending trap is the primary weakness of the RSI strategy, as it attempts to pick tops and bottoms in markets that may continue to move in one direction.

Pineify Backtest Deep Report: Beyond Basic Metrics

TradingView's tester covers basics; Pineify's Backtest Deep Report adds depth for professional risk work on RSI systems.

What you gain

  • Monthly Returns Heatmap shows consistency versus a few lucky months.
  • Sortino and Calmar refine risk views beyond Sharpe.
  • Trade Distribution and Equity with Drawdown Overlays pinpoint regimes that erode capital.

Together, these help you tune thresholds and filters before live deployment.

Strategy Optimization Suggestions

1

Trend Filtering

Add a long-term moving average (e.g. 200 EMA): long RSI signals only above the EMA, shorts only below, to avoid fighting the trend.

2

Dynamic Thresholds

Replace fixed 70/30 with volatility-aware levels or bands on RSI; 80/20 can suit high-volatility regimes.

3

RSI Divergence

Prefer bullish or bearish divergence over simple extremes for stronger reversal context.

4

Time-Based Exits

Exit if neither TP nor SL is hit within N bars to limit exposure in stagnant markets.

5

Volatility-Adjusted SL/TP

Size exits with ATR so stops and targets scale with current market noise.

Frequently Asked Questions

Take Your Trading to the Next Level with Pineify

Pineify pairs professional analytics with fast iteration on Pine Script. Try Pineify for free at https://pineify.com and turn RSI ideas into data-driven systems.

Disclaimer: Trading involves significant risk. The strategies and code provided are for educational purposes only and do not constitute financial advice. Past performance is not indicative of future results.