⬡ INDICATOR · WITH CODE · 12 MIN READ

RSI: how to use and code the Relative Strength Index.

The world's most popular momentum oscillator — explained properly, from the formula to divergences, with ready-made code in Pine Script and Python so you can automate it.

By the RoboTraderIA Team· updated May 2026· beginner to intermediate level

The RSI is probably the first indicator every trader learns — and also one of the most misused. Most people memorize "70 sells, 30 buys" and stop there, which leads to losing money in strong trends. This guide goes further: it explains what the RSI actually measures, where it shines, where it fails, and hands you the code to plug into a bot.

01What the RSI actually measures

RSI stands for Relative Strength Index — created by J. Welles Wilder in 1978. It is a momentum oscillator: it ranges from 0 to 100 and measures the speed and magnitude of recent price moves. In plain language: it compares the size of recent gains with the size of recent losses.

  • RSI above 70: overbought — price rose fast and may be "stretched".
  • RSI below 30: oversold — price fell fast and may be "stretched" to the downside.
  • RSI at 50: balance between buying and selling strength.
70 — overbought 30 — oversold 50
The RSI oscillating between the zones. Touches above 70 (red) and below 30 (green) mark extremes.

02The formula (to understand, not to memorize)

You do not need to compute it by hand — every platform does that — but understanding the formula stops you from using it wrong:

RSI = 100 − [ 100 / (1 + RS) ]

onde RS = média dos ganhos / média das perdas (no período)

The default period is 14. The practical consequence of the formula: when there are only gains in the period, RS tends to infinity and the RSI goes to 100; when there are only losses, the RSI goes to 0. That is why it "saturates" — and that is exactly where the trap we will see next lives.

03The 3 real uses (beyond the obvious)

1. Overbought / oversold

The classic use. But careful: it works well in a ranging market; in a strong trend the RSI stays "glued" to the extreme (above 70 for days in a strong rally) and the "sell" signal has you trading against the trend — an expensive mistake.

2. Divergences (the most valuable use)

This is where the RSI's gold is. Divergence happens when price and the RSI disagree:

  • Bearish divergence: price makes a higher high, but the RSI makes a lower high → the up move is losing strength, possible reversal to the downside.
  • Bullish divergence: price makes a lower low, but the RSI makes a higher low → the fall is weakening, possible reversal to the upside.
Bearish divergence price HIGHER high ↑ RSI LOWER high ↓ Price up, RSI does not follow = buying strength weakening = possible reversal signal
In a bearish divergence, price makes a higher high but the RSI makes a lower high — a reversal warning.

3. The 50 line as a trend filter

An underrated use: an RSI consistently above 50 confirms an uptrend; below 50, a downtrend. Great as a filter for other strategies — only buy with the RSI above 50, for example.

The #1 mistake with the RSI: selling just because it went above 70. In a strong uptrend the RSI can stay above 70 for weeks while price keeps climbing. The RSI on its own is not an entry signal — it is context. Always combine it with trend and structure.

04Coding the RSI

Here is the ready-made code for the two most used platforms. Note that both Pine and Python have the RSI in their libraries — you rarely compute it by hand, but I show the manual calculation in Python so you understand what goes on inside.

Pine Script (TradingView)
//@version=5
indicator("RSI com Zonas")

periodo = input.int(14, "Período")
rsi = ta.rsi(close, periodo)

plot(rsi, "RSI", color=color.blue)
hline(70, "Sobrecompra", color=color.red)
hline(30, "Sobrevenda", color=color.green)
hline(50, "Meio", color=color.gray)

// crossover alert
if ta.crossunder(rsi, 30)
    alert("RSI entrou em sobrevenda")
Python (manual calculation, to understand it)
import pandas as pd

def calcular_rsi(precos: pd.Series, periodo=14) -> pd.Series:
    delta = precos.diff()
    ganho = delta.clip(lower=0)
    perda = -delta.clip(upper=0)
    # Wilder's exponential moving average
    media_ganho = ganho.ewm(alpha=1/periodo, adjust=False).mean()
    media_perda = perda.ewm(alpha=1/periodo, adjust=False).mean()
    rs = media_ganho / media_perda
    return 100 - (100 / (1 + rs))

# uso
df["rsi"] = calcular_rsi(df["close"])
if df["rsi"].iloc[-1] < 30:
    print("Sobrevenda — avaliar compra com confirmação")

Python shortcut: libraries like ta or pandas-ta already have RSI ready to go: ta.momentum.rsi(df["close"], window=14). Use the manual calculation above only to understand what happens under the hood.

Want to build a strategy with the RSI?

See our collection of strategies ready to automate, several of them using the RSI as a filter.

See strategies →

05Which period to use

The default of 14 is a good balance, but you can adjust it to your style:

  • Short periods (7-9): a more sensitive RSI, more signals, more noise. For scalping and fast day trading.
  • Period 14 (default): balance. It works in most cases.
  • Long periods (21+): a smoother RSI, fewer signals, more reliable. For swing trading.

Automation tip: when you optimize the period in a backtest, avoid picking the number that gave the best result on its own (overfitting). Prefer a range that performs similarly across values — robustness is worth more than a peak of past performance.

06Frequently asked questions

What is the RSI?

It is a momentum oscillator ranging from 0 to 100 that measures the speed and magnitude of price moves. Above 70 indicates overbought; below 30, oversold. Created by Wilder in 1978.

What is the best period for the RSI?

The default is 14. Shorter periods (7-9) make it more sensitive and more signal-heavy (day trading); longer ones (21+) make it smoother and more reliable (swing). There is no universal "best" — it depends on your style and the asset.

What is divergence on the RSI?

It is when price and the RSI disagree: price makes a new high but the RSI does not follow (bearish divergence), or price makes a new low but the RSI rises (bullish divergence). It signals weakening and a possible reversal. It is one of the most valuable uses.

Can I trade with the RSI alone?

It is not advisable. The RSI on its own produces a lot of false signals, especially in a trend. Use it as context/filter combined with market structure, trend and risk management. The RSI shines in combination, not in isolation.

Does the RSI work on crypto and on Brazil's B3?

Yes, it is market-agnostic — it works on any asset with price data (stocks, mini index futures, Forex, crypto). The interpretation is the same; what changes is calibrating the period to the asset's behavior.

Related reading

🎁 Get the free trading bot (with the Quotex, Deriv and IQ Option APIs)

Open source bot + ready-made API code. You edit it by chatting with ChatGPT/Claude — no programming. Free, no spam.

👉 Want the ready-made bot instead? Go to botbinaryoptions.com →