Edgoro
Momentum indicator

RSI indicator: formula, settings and Pine Script v6 code

How the Relative Strength Index works, how traders read overbought, oversold and divergence, which settings to use, and a free RSI script for TradingView.

What it measures

The Relative Strength Index compares the size of recent up-moves with the size of recent down-moves and squeezes the result into a scale from 0 to 100. A high reading means gains have dominated the last few bars; a low reading means losses have.

That makes RSI a momentum gauge: it tells you how hard price has been pushing in one direction, not whether the market is cheap or expensive. An RSI of 80 says "the recent move up was strong and one-sided", nothing more. J. Welles Wilder introduced it in 1978, and it has been a default on almost every charting platform since.

The formula in words

  1. For every bar, take the change from the previous close. A positive change counts as a gain, a negative change as a loss (as a positive number). The other value is zero.
  2. Average the gains and the losses over the last N bars using Wilder's smoothing: each new average is the previous average × (N − 1) / N, plus the new value / N. It behaves like an exponential average with a slow decay.
  3. Divide the average gain by the average loss. That ratio is called RS.
  4. RSI = 100 − 100 / (1 + RS).

If there were no losses at all, RSI is 100; if there were no gains, it is 0. Because of the smoothing, the first few dozen bars of any chart are a warm-up period: values there can differ from what you see on a chart with more history loaded.

How traders read it

  • Overbought and oversold. The classic zones are above 70 and below 30. In a sideways market, RSI turning back down out of 70 or back up out of 30 is read as momentum fading. In a strong trend, RSI can sit above 70 (or below 30) for weeks, so the zones alone are not reversal signals.
  • The 50 line. Above 50, average gains outweigh average losses. Trend followers often only take longs when RSI is above 50 and shorts when it is below.
  • Divergence. Price makes a higher high while RSI makes a lower high: the move is continuing with less force. Divergence can last a long time before anything happens, which is why it needs a defined trigger. See how to code RSI divergence in Pine Script.
  • Range shift. In uptrends RSI tends to bounce from the 40–50 area rather than reaching 30, and in downtrends it often stalls around 50–60. Watching where pullbacks stop says something about the trend's health.

Common settings

SettingTypical valueWhat changing it does
Length14Wilder's original. Shorter lengths react faster and reach the extremes more often; longer lengths are smoother.
Levels70 / 3080 / 20 gives fewer, more extreme readings. Short-length variants often use 90 / 10.
SourceCloseSome traders use hlc3 or ohlc4 for a slightly smoother line.
Short-term variantLength 2 to 5Used in pullback studies with extreme levels; very noisy on its own.

Whatever you pick, change the levels together with the length: a 70 on a 5-period RSI is a much weaker reading than a 70 on a 21-period RSI.

Pine Script v6 code

The complete, self-contained script is below. Copy it into a new indicator in TradingView's Pine Editor, or download the .pine file.

Pine Script v6
//@version=6
indicator("RSI with signal zones", shorttitle = "RSI", format = format.price, precision = 2)

len     = input.int(14, "RSI length", minval = 2)
src     = input.source(close, "Source")
obLevel = input.int(70, "Overbought level", minval = 50, maxval = 100)
osLevel = input.int(30, "Oversold level", minval = 0, maxval = 50)
showSig = input.bool(true, "Show signal line")
sigLen  = input.int(9, "Signal line length", minval = 1)

r   = ta.rsi(src, len)
sig = ta.sma(r, sigLen)

// RSI leaving a zone: crossing back above oversold, or back below overbought.
leavesOversold   = ta.crossover(r, osLevel)
leavesOverbought = ta.crossunder(r, obLevel)

plot(r, "RSI", color = color.new(color.purple, 0), linewidth = 2)
plot(showSig ? sig : na, "Signal", color = color.new(color.orange, 0))
obLine = hline(obLevel, "Overbought", color = color.gray, linestyle = hline.style_dashed)
hline(50, "Midline", color = color.new(color.gray, 60), linestyle = hline.style_dotted)
osLine = hline(osLevel, "Oversold", color = color.gray, linestyle = hline.style_dashed)
fill(obLine, osLine, color = color.new(color.purple, 92), title = "Range")

plotshape(leavesOversold, "Leaves oversold", shape.triangleup, location.bottom, color.new(color.teal, 0), size = size.tiny)
plotshape(leavesOverbought, "Leaves overbought", shape.triangledown, location.top, color.new(color.red, 0), size = size.tiny)

alertcondition(leavesOversold, "RSI leaves oversold", "RSI crossed back above the oversold level on {{ticker}} ({{interval}})")
alertcondition(leavesOverbought, "RSI leaves overbought", "RSI crossed back below the overbought level on {{ticker}} ({{interval}})")

The script draws RSI in its own pane with the two zones shaded, an optional moving-average signal line, and small triangles when RSI crosses back out of a zone (a more specific event than simply being in it). Every number is an input, so you can change the length and levels from the indicator's settings without editing code.

Two alert conditions are included. When you create the alert, choose Once per bar close: on the live bar RSI moves with every tick, so a cross can appear and disappear before the bar closes.

Add it to your chart

  1. Open any chart on TradingView and open the Pine Editor.
  2. Create a new indicator, delete the template code and paste the script.
  3. Click Save, then Add to chart. Change lengths and levels from the indicator's settings.

Stuck on an error? See how to add a Pine Script indicator to TradingView.

Pitfalls

  • Selling every 70. In trends, overbought can stay overbought. Combine the zones with a trend filter or use them only in ranges you have defined.
  • Changing the length but not the levels. Shorter RSI lengths hit the extremes far more often, so the same levels mean less.
  • Acting on the live bar. A cross on an unfinished bar is provisional. Alerts set to once per bar close avoid most surprises.
  • Divergence as a timing tool. Divergence describes slowing momentum, not a turning point. It can repeat several times before price reverses, or never.
  • Comparing values across platforms. The warm-up period and small data differences between feeds mean two charts can show slightly different readings on the same bar.

The script is an educational example: test it on your own markets before relying on it. Indicators describe the past; they don't predict the future. Trading involves substantial risk of loss and is not suitable for every investor. Edgoro is a software tool, not a broker or financial adviser: nothing it produces is investment advice, and past or backtested performance does not guarantee future results.

Make it yours with Edgoro

Describe the change in plain English and Edgoro writes the Pine Script v6 for you, ready to paste. For example:

“Plot RSI(14) with 70/30 levels, mark when it crosses back above 30 while the close is above the 200 EMA, and alert once per bar close.”

Build your RSI indicator