Relative Strength Index (RSI) in Pine Script
A bounded momentum oscillator that compares average gains with average losses over 14 bars, scaled from 0 to 100, with 70 and 30 as the overbought and oversold lines.
Definition
The Relative Strength Index (RSI) is a bounded momentum oscillator. It compares the average size of up closes with the average size of down closes over a lookback, usually 14 bars, and maps the ratio onto a scale from 0 to 100. A reading of 50 means gains and losses have balanced. The higher the reading, the more the recent bars have closed up rather than down. Because the scale is fixed, the same numbers mean the same thing on any instrument and any timeframe. That is why RSI sits in the bounded family with the stochastic and Williams %R rather than with MACD or rate of change.
RSI measures the persistence of one-sided closes, not the size of the move. A market that closes up 10 days in a row reads above 70 even if each gain is small, because the average loss in the window is near zero. That is the point: the indicator reads how lopsided recent price change has been, and lopsided change tends to pause. It does not say the pause will be a reversal. In a strong trend the pause can be a sideways drift that resets the average loss while price barely retreats. The oscillator then leaves the zone from the same side it entered.
J. Welles Wilder published RSI in 1978 in New Concepts in Technical Trading Systems, alongside ATR, ADX and the Parabolic SAR. He used 14 periods on daily bars, 70 as the overbought line and 30 as the oversold line. He smoothed the averages with his own recursive method, which is slower than a simple average of the same length. Those settings are still the defaults on almost every platform. Shorter lengths such as 2 to 7 make the line swing to the extremes on most pullbacks. Longer lengths such as 21 keep it near the middle and reserve the zones for real washouts.
On the chart the line spends most of its time between 30 and 70 and touches the zones a few times a month on daily bars. It reaches a zone quickly, because Wilder's smoothing responds fast to a run of closes in one direction, and it leaves slowly. The 50 line divides the bull side from the bear side. In an uptrend the pullbacks tend to bottom between 40 and 50 and the rallies run to 80; in a downtrend the bounces stall between 50 and 60 while the declines reach 20. A shift in that range often shows before the price trend itself changes.
Reading the chart
Read RSI as a position on a fixed scale, then as a shape, and only then as a signal.
- Open a 14-period RSI in its own pane under the price chart with lines at 70, 30 and 50. Check the timeframe: a 14-period RSI on 5-minute bars covers about an hour, and on daily bars it covers three weeks.
- Locate the current reading. Above 70 the recent closes have been mostly up, below 30 mostly down, and between the lines the pane is neutral. Note whether the line has just entered a zone or has been in it for many bars.
- Watch for the exit from the zone rather than the entry. A cross back above 30 after a dip below it is the classic long trigger, and a cross back below 70 is the short trigger. The library's script marks exactly those crosses.
- Compare the last two swings of the oscillator with the last two swings of price. A new price low with a higher RSI low is a bullish divergence; the mirror at highs is bearish. Divergence warns that momentum is thinning before the trend turns.
- Note the range the oscillator has been using. If pullbacks keep bottoming near 40 and rallies keep topping near 80, the trend is up and readings near 70 are normal. A first dip below 30 after months above 40 is a regime change.
- Check the trend on the chart or on a higher timeframe before acting on a zone exit. In a strong trend the exit from overbought is usually a pause. Only the exit from oversold in the trend's direction is a with-trend trigger.
The maths
RSI turns the ratio of smoothed average gains to smoothed average losses into a number between 0 and 100.
The first average is a simple mean of the first n gains and losses. Every later value uses the recursive form, which is Wilder's smoothing and equals an EMA of length 2n − 1.
When the average loss is zero the ratio is undefined and RSI is set to 100; when the average gain is zero it is 0. Both happen on short lengths after a run of one-way closes.
Because the smoothing is recursive, the value on any bar depends on every earlier bar. Two platforms with different history lengths can show slightly different RSI on the same chart until the difference decays.
Inputs that matter
| Input | Typical | What changing it does |
|---|---|---|
| Length | 14 | Shorter lengths reach 70 and 30 on almost every swing and give many signals; longer lengths hold the line near 50 and reserve the zones for large moves. |
| Overbought | 70 | Raising it to 80 cuts the short marks in an uptrend and keeps only the strongest overshoots; lowering it gives earlier but more frequent shorts. |
| Oversold | 30 | Lowering it to 20 waits for deeper washouts before a long mark; raising it to 40 turns the zone into a trend pullback trigger. |
| Source | close | Using hl2 or a smoothed series removes one-bar spikes from the reading at the cost of a little lag. |
In practice
- As a mean-reversion trigger in ranges: the rule goes long when RSI crosses back above 30 and short when it crosses back below 70. That is what the library's indicator marks as Long and Short, and what its strategy trades with an exit at the 50 line.
- As a trend pullback tool: in an uptrend, the rule treats dips to 40 or 50 as the long zone and ignores overbought readings, since a trending market spends weeks above 70 without reversing.
- As a regime gauge: the range RSI has occupied for the last few months tells you the trend. Readings that cannot break below 40 say the bull regime holds; a first close below 30 says it may be ending.
- As a divergence detector: compare consecutive RSI pivots with price pivots. A lower price low with a higher RSI low often precedes a bottom, and the library's divergence script makes that comparison at confirmed pivots.
- As a filter on other triggers: the filter requires RSI above 50 before it passes a long breakout or a moving-average cross, so that the momentum of closes agrees with the direction of the entry.
Where it goes wrong
- Shorting because RSI is above 70. In a trend the oscillator stays there for weeks; the cross back below the line comes first, and even then the trend decides.
- Reading a 14-period RSI on the wrong timeframe. On 1-minute bars it covers 14 minutes of noise; match the length and the timeframe to the swing you want to trade.
- Going long on every oversold reading in a downtrend. Oversold in a falling market often becomes more oversold; rules that hold up require a divergence, a higher-timeframe support or a trend filter first.
- Treating a divergence as a signal on its own. Divergence says momentum is thinning; the trade needs a confirming price event such as a break of the swing that formed it.
Compared with
Stochastic Oscillator. The stochastic locates the close inside the recent high-low range, so it reaches its extremes faster and oscillates more. RSI averages gains against losses, so it is smoother and holds a level longer. Traders use the stochastic for timing inside a range and RSI for the regime read.
Williams %R. Williams %R is the raw stochastic turned upside down on a 0 to −100 scale, with no smoothing, so it flickers in and out of its zones. RSI is heavily smoothed. Both are bounded, but %R answers where the close is in the range and RSI answers how one-sided the closes have been.
MACD. MACD is unbounded: it measures the distance between two moving averages in price units and can grow without limit in a trend. RSI is capped at 100, which is why it looks overbought in a trend while MACD keeps rising. Use MACD for trend momentum and RSI for range extremes.
Money Flow Index. MFI is RSI computed on money flow instead of price change, so volume weights each bar's contribution. It reaches its zones on high-volume moves that RSI treats like any other. The two diverging from each other is itself a read: a rising RSI with a flat MFI is a rally on thin volume.
Build it in Quant
Type one of these in the Quant desk, or click it. A request that fits a checked template is assembled on the spot without a credit; anything beyond the blanks goes to the copilot, which edits on top of the checked script.
Questions
What is the best RSI setting?
There is no best setting, only a match between the length and the swing you trade. 14 on daily bars is the default and reads the three-week swing. 2 to 5 catches one to three day exhaustions on indices and is used with 10 and 90 as the lines. 21 or more suits position traders who want the zones to mean something rare. Change the levels with the length: shorter lengths need wider zones.
Does RSI above 70 mean a short?
No. It means the last 14 closes have been mostly up, which is what a healthy uptrend looks like. Markets regularly spend weeks above 70 during a strong advance. The short trigger is the cross back below 70, and even that reads as a pause until the price chart confirms with a lower high or a break of support. In a trend, overbought is normal; in a range it is the stretch reversion rules use.
Why does RSI stay oversold during a crash?
Because every new down close keeps the average gain near zero, so the ratio cannot recover until the market prints a run of up closes. Wilder's smoothing also carries the losses forward for many bars. That is why a long on the first dip below 30 in a falling market fails so often: the oscillator can hold under 30 for weeks while price keeps sliding. Reversion rules wait for the cross back above 30 or for a divergence.
How is RSI different from the stochastic?
RSI compares average gains with average losses, so it reads how lopsided the closes have been. The stochastic reads where the last close sits within the recent high-low range. A market that grinds up in small steps reads high on both; a market that spikes and closes at the top of a wide range reads higher on the stochastic. RSI is smoother and slower; the stochastic is faster and noisier.
What does the library's RSI script actually mark?
The indicator plots RSI with lines at the overbought, oversold and 50 levels, and colours the line red above 70 and green below 30. It prints a Long mark when RSI crosses back above 30 and a Short mark when it crosses back below 70, on confirmed bars only. The strategy takes those same crosses as entries, closes when RSI returns to 50, and puts a stop 2 ATR from the entry.
Can I use RSI on a 1-minute chart?
Yes, but the 14-period reading then describes the last 14 minutes, and the zones will be visited many times an hour. Most intraday traders either lengthen the period, use a higher timeframe for the regime and the 1-minute RSI only for timing, or treat the marks as scalps with a tight stop. The maths does not change; the swing it describes does.