Strategy · Pine Script v5 · On the chart

RSI Extremes - Mean Reversion

by Basant1Saini· code credited to TradingTools

This strategy looks for mean-reversion entries when RSI crosses back through the oversold or overbought levels, or recovers from more extreme RSI readings.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code78
Settings11inputs
LicenceNone statedfile: MPL-2.0
Last update7 months ago4 Mar 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

78 lines of Pine Script v5 from 3_RSI_Extremes/3_RSI_Extremes.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

3_RSI_Extremes.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0
// © TradingTools

//@version=5
strategy("RSI Extremes - Mean Reversion", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=100)

// ─── Inputs ───
rsiLength       = input.int(14, "RSI Length", group="RSI Settings")
rsiOverbought   = input.float(75, "Overbought Level", minval=50, maxval=95, group="RSI Settings")
rsiOversold     = input.float(25, "Oversold Level", minval=5, maxval=50, group="RSI Settings")
rsiExtremeOB    = input.float(85, "Extreme Overbought", minval=70, maxval=99, group="RSI Settings")
rsiExtremeOS    = input.float(15, "Extreme Oversold", minval=1, maxval=30, group="RSI Settings")
useDivergence   = input.bool(true, "Use RSI Divergence Confirmation", group="RSI Settings")
maLength        = input.int(200, "Trend Filter MA Length", group="Filters")
useTrendFilter  = input.bool(true, "Use Trend Filter (MA)", group="Filters")
atrLength       = input.int(14, "ATR Length", group="Risk Management")
atrMult         = input.float(2.0, "ATR Multiplier for SL", step=0.1, group="Risk Management")
rrRatio         = input.float(2.0, "Risk:Reward Ratio", step=0.1, group="Risk Management")

// ─── Calculations ───
rsiVal  = ta.rsi(close, rsiLength)
trendMA = ta.sma(close, maLength)
atrVal  = ta.atr(atrLength)

// ─── Divergence Detection ───
// Bullish divergence: price makes lower low but RSI makes higher low
priceLowerLow   = low < ta.lowest(low, 5)[1]
rsiHigherLow    = rsiVal > ta.valuewhen(priceLowerLow[1], rsiVal, 0)
bullDivergence  = priceLowerLow and rsiHigherLow and rsiVal < rsiOversold

// Bearish divergence: price makes higher high but RSI makes lower high
priceHigherHigh = high > ta.highest(high, 5)[1]
rsiLowerHigh    = rsiVal < ta.valuewhen(priceHigherHigh[1], rsiVal, 0)
bearDivergence  = priceHigherHigh and rsiLowerHigh and rsiVal > rsiOverbought

// ─── Entry Conditions ───
// Standard: RSI crosses back from extreme + optional trend filter + optional divergence
trendBullOK = useTrendFilter ? close > trendMA : true
trendBearOK = useTrendFilter ? close < trendMA : true

// RSI crossing back from oversold zone (mean reversion long)
rsiLongSignal  = ta.crossover(rsiVal, rsiOversold) or (rsiVal[1] <= rsiExtremeOS and rsiVal > rsiExtremeOS)
rsiShortSignal = ta.crossunder(rsiVal, rsiOverbought) or (rsiVal[1] >= rsiExtremeOB and rsiVal < rsiExtremeOB)

longCondition  = rsiLongSignal and (useDivergence ? bullDivergence or rsiVal[1] <= rsiExtremeOS : true)
shortCondition = rsiShortSignal and (useDivergence ? bearDivergence or rsiVal[1] >= rsiExtremeOB : true)

// ─── Execute Trades ───
if longCondition and strategy.position_size == 0
    sl = close - atrVal * atrMult
    tp = close + (close - sl) * rrRatio
    strategy.entry("RSI Long", strategy.long)
    strategy.exit("RSI Long Exit", "RSI Long", stop=sl, limit=tp)

if shortCondition and strategy.position_size == 0
    sl = close + atrVal * atrMult
    tp = close - (sl - close) * rrRatio
    strategy.entry("RSI Short", strategy.short)
    strategy.exit("RSI Short Exit", "RSI Short", stop=sl, limit=tp)

// ─── RSI Panel ───
var rsiPanel = "RSI Panel"
hline(rsiOverbought, "Overbought", color=color.red, linestyle=hline.style_dashed, display=display.none)
hline(rsiOversold, "Oversold", color=color.green, linestyle=hline.style_dashed, display=display.none)
hline(50, "Midline", color=color.gray, linestyle=hline.style_dotted, display=display.none)

// ─── Overlay Plotting ───
plot(useTrendFilter ? trendMA : na, "Trend MA", color=color.new(color.gray, 30), linewidth=2)

plotshape(longCondition, title="Long Signal", location=location.belowbar, style=shape.diamond, color=color.green, size=size.small, text="RSI")
plotshape(shortCondition, title="Short Signal", location=location.abovebar, style=shape.diamond, color=color.red, size=size.small, text="RSI")

// ─── Background on Extreme RSI ───
bgcolor(rsiVal >= rsiExtremeOB ? color.new(color.red, 85) : rsiVal <= rsiExtremeOS ? color.new(color.green, 85) : na, title="Extreme RSI Zone")

// ─── Alerts ───
alertcondition(longCondition, title="RSI Extreme Long", message="RSI Extremes: Oversold reversal detected — Long entry")
alertcondition(shortCondition, title="RSI Extreme Short", message="RSI Extremes: Overbought reversal detected — Short entry")

Overview

Optional divergence confirmation can require a price and RSI mismatch before entry. It opens one long or short only when flat, then sets an ATR-based stop and a take-profit scaled by the risk-to-reward ratio. The 200-period SMA trend filter is calculated but is not applied to the entry conditions. Orders and exits are drawn on the price chart.

Details

Published by

Basant1Saini on GitHub

Code credit

TradingTools, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Mean reversion, Oscillators & momentum, Divergence

Markets

Stocks

Timeframes

M1-M5, M15-H1, H4 and above

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
RSI Lengthint14rsiLength
Overbought Levelfloat75rsiOverbought
Oversold Levelfloat25rsiOversold
Extreme Overboughtfloat85rsiExtremeOB
Extreme Oversoldfloat15rsiExtremeOS
Use RSI Divergence ConfirmationbooltrueuseDivergence
Trend Filter MA Lengthint200maLength
Use Trend Filter (MA)booltrueuseTrendFilter
ATR Lengthint14atrLength
ATR Multiplier for SLfloat2.0atrMult
Risk:Reward Ratiofloat2.0rrRatio
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

The Stock and NQ Futures Convergence Strategy identifies trading opportunities by comparing the Relative Strength Index of the active chart stock against NQ futures. It enters a long position when NQ RSI rises above the upper threshold while the stock RSI stay

Strategy v5 Oscillators & momentumDivergence
Updated 2 years ago · GPL-3.0 GitHub repository of Stock and NQ Futures Convergence Strategy

VMC Strat Flex Corrected

by matlaenousse
1 stars

This strategy evaluates market conditions using a combination of WaveTrend, RSI, Stochastic RSI, and a custom Money Flow Index calculation inspired by VuManChu. It enters long positions when multiple oscillators hit oversold thresholds and generate an upward c

Strategy v6 Oscillators & momentumDivergence
Updated 10 months ago · None stated GitHub repository of VMC Strat Flex Corrected
330 stars

Alert BB + RSI [Alorse] is a multi-symbol mean-reversion strategy designed for cryptocurrency trading. It evaluates Bollinger Bands and the Relative Strength Index (RSI) across up to 20 user-defined ticker symbols simultaneously. The strategy enters long posit

Strategy v4 Oscillators & momentumVolatility & bands
Updated 2 months ago · None stated GitHub repository of Alert BB + RSI [Alorse]
285 stars

Mean Reversion Strategy is an overlay strategy that identifies pullbacks using a long-term EMA, RSI, and candlestick patterns. It generates long signals when a bullish engulfing candle forms below the EMA while RSI is oversold, and short signals when a bearish

Strategy v4 Mean reversionCandlestick patterns
Updated 3 years ago · None stated GitHub repository of Mean Reversion Strategy

This strategy draws on the price chart and combines Stochastic RSI, the Money Flow Index, and an exponential moving average to open long or short trades. Longs use the lower oscillator thresholds and shorts use the upper ones, with direction limited to longs,

Strategy v5 Oscillators & momentumMoving averages Repaints
Updated 2 years ago · GPL-3.0 GitHub repository of 3 Indicator Strategy (StochRSI, MFI & EMA) With Safety Orders

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers