Back to all posts

RSI Trading Strategy: Complete Guide with Code Examples

Learn how to build profitable RSI trading strategies with ready-to-use code for TradingView, MetaTrader, and Python. Covers basic to advanced RSI techniques.

SpendDock Team··5 min read
RSITechnical IndicatorsPineScriptMQL5Trading Strategy

The Relative Strength Index (RSI) is one of the most popular momentum indicators used by traders worldwide. In this comprehensive guide, we'll cover everything you need to know about building profitable RSI trading strategies, including ready-to-use code for TradingView, MetaTrader, and Python.

What is RSI?

The RSI measures the speed and magnitude of recent price changes to evaluate overbought or oversold conditions. Developed by J. Welles Wilder Jr. in 1978, it oscillates between 0 and 100.

Key Levels:

  • RSI above 70 = Overbought (potential sell signal)
  • RSI below 30 = Oversold (potential buy signal)
  • RSI at 50 = Neutral momentum

Basic RSI Strategy

The simplest RSI strategy:

  1. Buy when RSI drops below 30 (oversold)
  2. Sell when RSI rises above 70 (overbought)

PineScript Code (TradingView)

pinescript
//@version=5
strategy("RSI Strategy", overlay=true)

// RSI Settings
rsiLength = input(14, "RSI Length")
oversold = input(30, "Oversold Level")
overbought = input(70, "Overbought Level")

// Calculate RSI
rsiValue = ta.rsi(close, rsiLength)

// Entry Conditions
longCondition = ta.crossover(rsiValue, oversold)
shortCondition = ta.crossunder(rsiValue, overbought)

// Execute Trades
if (longCondition)
    strategy.entry("Long", strategy.long)
if (shortCondition)
    strategy.close("Long")

// Plot RSI
plot(rsiValue, "RSI", color=color.purple)
hline(oversold, "Oversold", color=color.green)
hline(overbought, "Overbought", color=color.red)

MQL5 Code (MetaTrader 5)

mql5
//+------------------------------------------------------------------+
//| RSI Strategy Expert Advisor                                       |
//+------------------------------------------------------------------+
#include <Trade\Trade.mqh>

input int RSI_Period = 14;
input int Oversold = 30;
input int Overbought = 70;
input double LotSize = 0.1;

CTrade trade;
int rsiHandle;

int OnInit()
{
    rsiHandle = iRSI(_Symbol, PERIOD_CURRENT, RSI_Period, PRICE_CLOSE);
    if(rsiHandle == INVALID_HANDLE)
        return(INIT_FAILED);
    return(INIT_SUCCEEDED);
}

void OnTick()
{
    double rsi[];
    ArraySetAsSeries(rsi, true);
    CopyBuffer(rsiHandle, 0, 0, 2, rsi);

    // Buy when RSI crosses above oversold
    if(rsi[1] < Oversold && rsi[0] >= Oversold)
    {
        if(PositionsTotal() == 0)
            trade.Buy(LotSize, _Symbol);
    }

    // Sell when RSI crosses below overbought
    if(rsi[1] > Overbought && rsi[0] <= Overbought)
    {
        trade.PositionClose(_Symbol);
    }
}

void OnDeinit(const int reason)
{
    IndicatorRelease(rsiHandle);
}

Python Code

python
import pandas as pd
import numpy as np

def calculate_rsi(prices, period=14):
    """Calculate RSI indicator"""
    delta = prices.diff()
    gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
    loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
    rs = gain / loss
    rsi = 100 - (100 / (1 + rs))
    return rsi

def rsi_strategy(df, rsi_period=14, oversold=30, overbought=70):
    """
    RSI Trading Strategy
    Buy when RSI crosses above oversold
    Sell when RSI crosses below overbought
    """
    df = df.copy()
    df['rsi'] = calculate_rsi(df['close'], rsi_period)

    # Generate signals
    df['signal'] = 0
    df.loc[df['rsi'] < oversold, 'signal'] = 1  # Buy signal
    df.loc[df['rsi'] > overbought, 'signal'] = -1  # Sell signal

    # Generate positions
    df['position'] = df['signal'].replace(0, np.nan).ffill().fillna(0)

    return df

# Example usage
# df = pd.read_csv('your_data.csv')
# result = rsi_strategy(df)

Advanced RSI Strategies

1. RSI + Moving Average Confirmation

Combine RSI signals with trend confirmation for higher probability trades:

  • Only take RSI buy signals when price is above 200 EMA
  • Only take RSI sell signals when price is below 200 EMA
pinescript
//@version=5
strategy("RSI + EMA Strategy", overlay=true)

// Settings
rsiLength = input(14, "RSI Length")
emaLength = input(200, "EMA Length")
oversold = input(30, "Oversold Level")

// Calculate indicators
rsiValue = ta.rsi(close, rsiLength)
ema200 = ta.ema(close, emaLength)

// Entry: RSI oversold AND price above EMA (uptrend)
longCondition = ta.crossover(rsiValue, oversold) and close > ema200

if (longCondition)
    strategy.entry("Long", strategy.long)

// Exit when RSI reaches 70
if (rsiValue > 70)
    strategy.close("Long")

plot(ema200, "EMA 200", color=color.yellow)

2. RSI Divergence Strategy

Look for divergences between price and RSI:

  • Bullish divergence: Price makes lower low, RSI makes higher low
  • Bearish divergence: Price makes higher high, RSI makes lower high

Divergences often signal potential trend reversals.

3. RSI with Stop Loss

Add risk management with a percentage-based stop loss:

pinescript
//@version=5
strategy("RSI with Stop Loss", overlay=true)

// Settings
rsiLength = input(14, "RSI Length")
oversold = input(30, "Oversold Level")
stopLossPercent = input.float(2.0, "Stop Loss %") / 100

// Calculate RSI
rsiValue = ta.rsi(close, rsiLength)

// Entry
longCondition = ta.crossover(rsiValue, oversold)

if (longCondition)
    strategy.entry("Long", strategy.long)
    strategy.exit("SL", "Long", stop=close * (1 - stopLossPercent))

// Take profit at RSI 70
if (rsiValue > 70)
    strategy.close("Long")

Best RSI Settings

TimeframeRSI LengthOversoldOverbought
Scalping (1-5min)7-92080
Day Trading (15-60min)143070
Swing Trading (Daily)14-213070
Position Trading (Weekly)21-282575

Common RSI Mistakes to Avoid

  1. Trading RSI alone — Always confirm with other indicators or price action
  2. Using default settings for all timeframes — Adjust RSI length for your timeframe
  3. Ignoring the trend — RSI works best with trend confirmation
  4. No stop loss — Always use risk management
  5. Trading every signal — Wait for high-probability setups

RSI Backtest Results

Here's what typical RSI strategy performance looks like on major markets:

MarketAnnual ReturnMax DrawdownWin Rate
S&P 5008-12%15-20%55-60%
Forex (EUR/USD)6-10%12-18%50-55%
Crypto (BTC)15-25%25-35%45-55%

Results vary based on market conditions and settings.

Generate Your RSI Strategy Instantly

Instead of writing code manually, describe your RSI strategy in plain English:

"Buy when RSI drops below 30 and price is above 200 EMA. Set stop loss at 2% and take profit when RSI reaches 70."

SpendDock generates production-ready code for TradingView, MetaTrader, NinjaTrader, or Python in seconds — no coding required.

Conclusion

The RSI is a powerful indicator when used correctly. Key takeaways:

  1. Use RSI with trend confirmation (moving averages)
  2. Adjust settings based on your timeframe
  3. Always use stop losses
  4. Look for RSI divergences for high-probability trades
  5. Backtest before trading live

Ready to build your own RSI strategy? Try SpendDock and generate production-ready code in seconds.

Skip the Coding — Generate Your Strategy

Describe your trading strategy in plain English and get production-ready code for TradingView, MetaTrader, NinjaTrader, or Python.

Try SpendDock Free