Indicator TutorialPine Script v6

Master the Relative Strength Index: From the Momentum Oscillator to Custom Pine Script

Understand RSI math, ship a full Pine Script v6 example, or build visually with Pineify.

Whether you scalp 1-minute charts or hunt exhaustion on the daily, learning how to create and customize RSI in TradingView sharpens timing, risk management, and confluence with other tools.

What is RSI (Relative Strength Index)?

The Relative Strength Index (RSI) is a momentum oscillator that measures the speed and magnitude of price changes. J. Welles Wilder Jr. introduced it in New Concepts in Technical Trading Systems (1978). It is bounded between 0 and 100.

Traditionally, RSI above 70 suggests overbought conditions and below 30 suggests oversold conditions. These are guidelines, not automatic entries—context and trend matter.

Why Traders Use This Indicator

  • Clear visualization of whether average gains or losses dominate over the lookback window.
  • Divergence signals when price makes new extremes but RSI does not, hinting at fading momentum.
  • Simple thresholds and the 50 level help frame bullish versus bearish momentum regimes.
  • Works across stocks, forex, crypto, and futures when paired with sensible risk controls.
ParameterDefaultDescription
Length14Number of periods for the RSI calculation; Wilder originally recommended 14.
SourceClosePrice series used for gains and losses (usually close).
Overbought level70Upper threshold where the market is often treated as overbought.
Oversold level30Lower threshold where the market is often treated as oversold.
Smoothing typeRMAWilder's smoothing (RMA) matches classic RSI; using SMA changes the behavior.

How RSI Works: The Formula

RSI is computed in two conceptual steps: relative strength (RS), then the bounded RSI value.

Core formulas

  • RS = average gain over n periods ÷ average loss over n periods (losses as positive magnitudes).
  • RSI = 100 − (100 ÷ (1 + RS)).

Wilder's smoothing (RMA) updates averages recursively, which stabilizes RSI compared with a simple moving average of gains and losses.

Signal Interpretation

  • Overbought/oversold exits: crossing back below 70 or above 30 from extreme zones is a common reactive signal.
  • 50-level crossover: above 50 suggests average gains exceed average losses; below 50 suggests the opposite.
  • Swing rejections: RSI reaches an extreme, pulls back, then fails to retest that extreme before breaking a prior pivot—treated by some traders as a stronger reversal pattern.

Combining with Other Indicators

RSI is usually confirmed, not used alone:

  • MACD for broader momentum alignment.
  • Bollinger Bands when band touches coincide with RSI extremes.
  • Volume or VWAP to validate participation on reversal attempts.

The Hard Way: Writing Pine Script Manually

Challenges of Manual Coding

Pine executes on every bar—streaming time-series thinking is unfamiliar if you come from general-purpose languages.

Limited debugger feedback makes mismatches (e.g., SMA vs RMA) painful to trace.

Alerts, backgrounds, and divergence logic expand scope and interaction bugs quickly.

Version upgrades may require refactors when built-ins or namespaces change.

Pine Script v6
//@version=6
indicator("Advanced Custom RSI with Divergence", overlay=false, precision=2)

// --- Input Parameters ---
rsiLength = input.int(14, "RSI Length", minval=1)
rsiSource = input.source(close, "RSI Source")
obLevel   = input.int(70, "Overbought Level", minval=50, maxval=100)
osLevel   = input.int(30, "Oversold Level", minval=0, maxval=50)
showBg    = input.bool(true, "Show Background Color?")
showDiv   = input.bool(true, "Show Divergence?")

// --- RSI Calculation ---
rsiValue = ta.rsi(rsiSource, rsiLength)

// --- Plotting the RSI ---
rsiColor = rsiValue > obLevel ? color.red : rsiValue < osLevel ? color.green : color.gray
plot(rsiValue, "RSI", color=rsiColor, linewidth=2)

// --- Drawing Levels ---
h1 = hline(obLevel, "Overbought", color=color.new(color.red, 50), linestyle=hline.style_dashed)
h2 = hline(osLevel, "Oversold", color=color.new(color.green, 50), linestyle=hline.style_dashed)
hline(50, "Middle Line", color=color.new(color.gray, 50), linestyle=hline.style_dotted)

// --- Background Highlighting ---
fill(h1, h2, color=color.new(color.gray, 90), title="RSI Range Fill")
bgcolor(showBg and rsiValue > obLevel ? color.new(color.red, 90) : na)
bgcolor(showBg and rsiValue < osLevel ? color.new(color.green, 90) : na)

// --- Simple Divergence Detection Logic ---
bullDiv = low[0] < low[1] and rsiValue[0] > rsiValue[1] and rsiValue < osLevel
bearDiv = high[0] > high[1] and rsiValue[0] < rsiValue[1] and rsiValue > obLevel

plotshape(showDiv and bullDiv, "Bullish Div", shape.triangleup, location.bottom, color.green, size=size.small)
plotshape(showDiv and bearDiv, "Bearish Div", shape.triangledown, location.top, color.red, size=size.small)

// --- Alerts ---
alertcondition(ta.crossunder(rsiValue, obLevel), "RSI Exit Overbought", "RSI has crossed below the overbought level.")
alertcondition(ta.crossover(rsiValue, osLevel), "RSI Exit Oversold", "RSI has crossed above the oversold level.")
alertcondition(bullDiv, "Bullish Divergence", "A bullish divergence has been detected!")
alertcondition(bearDiv, "Bearish Divergence", "A bearish divergence has been detected!")

Maintenance Note: Each new feature—multi-timeframe RSI, dynamic bands, or stacked filters—multiplies code paths. Visual builders and generated code reduce regression risk when you iterate.

The Easy Way: Build with Pineify Visual Editor

What if you could create the same indicator without writing a single line of code? Pineify is a visual editor designed for TradingView users who want professional-grade indicators through an intuitive interface.

FeatureManual Pine ScriptPineify Visual Editor
Learning curveSteep (months to master)Minimal (minutes)
Time to buildHours or daysSeconds or minutes
Error rateHigh (syntax and logic)Low (generated code)
MaintenanceManual updatesRegenerate after visual edits
AI assistanceExternal tools onlyBuilt-in generation

Iterate faster than hand-writing every plot, alert, and input.

Compose RSI with filters and other indicators without managing merge conflicts in code.

Describe logic in plain language where AI assists layout and wiring.

Step-by-Step Tutorial

1

Open Pineify

Sign in at pineify.app and create a new indicator project.

2

Add RSI

Insert the RSI block and set length, source, and OB/OS thresholds.

3

Enhance visuals

Add background colors or shapes when RSI enters extreme zones.

4

Wire alerts

Connect alert blocks to crosses of 30/70 or custom conditions.

5

Generate Pine Script

Export the script when the workspace matches your intent.

6

Deploy to TradingView

Paste into the Pine Editor and add the indicator to your chart.

7

Tune and retest

Adjust length and levels per symbol, then forward-test responsibly.

Trading Strategies & Pro Tips

RSI divergence (reversal context)

Bullish: price lower low with RSI higher low. Bearish: price higher high with RSI lower high. Signals disagreement between price and momentum.

Pro Tip: Divergences near extremes (above 70 or below 30) are generally more credible than mid-range noise.

RSI trendline breakouts

Draw trendlines on RSI peaks or troughs; breaks can precede price breakouts when momentum confirms.

50-level crossover (trend filter)

Treat crosses above 50 as bullish momentum bias and below 50 as bearish—useful to filter counter-trend entries.

Failure swings (Wilder-style)

Bullish failure swing: RSI overshoots below 30, recovers above 30, holds, then breaks a prior reaction high. Bearish pattern mirrors above 70.

Common Mistakes to Avoid

  • Selling every touch of 70 in a strong uptrend—RSI can remain overbought for long stretches.
  • Weighing a 1-minute RSI the same as a daily signal without higher timeframe context.
  • Shortening length without accepting the extra noise and false positives.

Frequently Asked Questions

Build your RSI without writing a single line of code

  • Compose complex indicators visually in minutes.
  • Generate clean Pine Script automatically.
  • Use AI to translate trading ideas into blocks.

Disclaimer: Trading involves significant risk. The indicators, code, and strategies provided are for educational purposes only and do not constitute financial advice. Past performance is not indicative of future results.