Strategy · Pine Script v5 · On the chart

RSI Strategy

by Web3Degenerate

This strategy combines RSI extreme condition filters with engulfing candlestick patterns to identify reversal entries.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code69
Settings7inputs
LicenceNone statedfile: MPL-2.0
Last update2 years ago13 Sep 2024

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

69 lines of Pine Script v5 from advanced-pine-script/9.Strategy-Scripts/5.RSI-Strategy-Example.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

5.RSI-Strategy-Example.pine
// Imported the RSI indicator code from Section 5.Indicators - Lesson #6.RSI-Chart-Signals.pine

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// @version=5
strategy("RSI Strategy", overlay=true)

// Import Zen Library
import ZenAndTheArtOfTrading/ZenLibrary/2 as zen

// Get user input
lookback     = input.int(title="Lookback", defval=7)
rsiLen       = input.int(title="RSI Length", defval=7)
rsiOB        = input.float(title="RSI Overbought", defval=80.0)
rsiOS        = input.float(title="RSI Oversold", defval=20.0)
multiplier   = input.float(title="ATR Multiplier", defval=1.0)
rr           = input.float(title="Risk:Reward", defval=1.0)
riskPerTrade = input.float(title="Risk Per Trade %", defval=1.0)

// Get RSI value
rsi = ta.rsi(close, rsiLen)
rsiSell = rsi > rsiOB
rsiBuy  = rsi < rsiOS

// Get ATR value
atr = ta.atr(14)

// Detect candle patterns
bullEC = zen.isBullishEC()
bearEC = zen.isBearishEC()

// Detect buy and sell signals
buySignal  = bullEC and (rsiBuy or rsiBuy[1]) and not na(atr) and barstate.isconfirmed and strategy.position_size == 0
sellSignal = bearEC and (rsiSell or rsiSell[1]) and not na(atr) and barstate.isconfirmed and strategy.position_size == 0

// Calculate stops & targets
longStop  = ta.lowest(low, lookback) - (atr * multiplier)
shortStop = ta.highest(high, lookback) + (atr * multiplier)
longStopDistance  = close - longStop
shortStopDistance = shortStop - close
longTarget  = close + (longStopDistance * rr)
shortTarget = close - (shortStopDistance * rr)

// Save stops & targets
var t_stop = 0.0
var t_target = 0.0

// Enter buy orders
if buySignal
    t_stop := longStop
    t_target := longTarget
    positionSize = math.floor((strategy.equity * (riskPerTrade/100)) / (close - t_stop))
    strategy.entry(id="Long", direction=strategy.long, qty=positionSize)

// Enter sell orders
if sellSignal
    t_stop := shortStop
    t_target := shortTarget
    positionSize = math.floor((strategy.equity * (riskPerTrade/100)) / (t_stop - close))
    strategy.entry(id="Short", direction=strategy.short, qty=positionSize)

// Manage exit orders (TP & SL)
strategy.exit(id="Long Exit", from_entry="Long", limit=t_target, stop=t_stop, when=strategy.position_size > 0)
strategy.exit(id="Short Exit", from_entry="Short", limit=t_target, stop=t_stop, when=strategy.position_size < 0)

// Draw data to chart
plotshape(buySignal, style=shape.triangleup, color=color.green, location=location.belowbar)
plotshape(sellSignal, style=shape.triangledown, color=color.red, location=location.abovebar)
plot(strategy.position_size != 0 ? t_stop : na, color=color.red, style=plot.style_linebr)
plot(strategy.position_size != 0 ? t_target : na, color=color.green, style=plot.style_linebr)

Overview

RSI Strategy opens positions on confirmed bars when an overbought or oversold RSI aligns with a bullish or bearish engulfing pattern. Stop losses are calculated using swing highs or lows combined with an ATR multiplier, while take-profit targets are set according to a configurable risk-to-reward ratio. Position sizing dynamically adjusts based on equity risk percentage, and trade levels are displayed directly on the price chart.

Details

Published by

Web3Degenerate on GitHub

Draws

On the price chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Lookbackint7lookback
RSI Lengthint7rsiLen
RSI Overboughtfloat80.0rsiOB
RSI Oversoldfloat20.0rsiOS
ATR Multiplierfloat1.0multiplier
Risk:Rewardfloat1.0rr
Risk Per Trade %float1.0riskPerTrade
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

This strategy calculates double-smoothed Heikin Ashi candles and plots them directly on the price chart alongside a smoothed Relative Strength Index. It evaluates market conditions against external volatility data from an inverse symbol, generating long and sh

Strategy v5 Candlestick patternsOscillators & momentum
Updated 5 months ago · None stated GitHub repository of Heikin Ashi with Session Wicks Strategy
1 stars

A strategy that scores signals from ten sources: RSI, MACD, Bollinger Bands, head and shoulders, wedges, multiple tops and bottoms, candlestick reversals, pivot support and resistance, volume spikes and an EMA ribbon filter. A trade needs a minimum pattern sco

Strategy v5 Oscillators & momentumCandlestick patterns
Updated 2 days ago · None stated GitHub repository of Fall Strategy 10-Pattern Engine
1 stars

High-Frequency Swing Reversal is a Pine Script v5 strategy that computes a reversal score from Bollinger Bands distance, RSI exhaustion, and candlestick rejection patterns such as hammers and stars. It plots VWAP, Bollinger Bands, and EMA20 on the price chart.

Strategy v5 Oscillators & momentumVolatility & bands
Updated 9 months ago · None stated GitHub repository of High-Frequency Swing Reversal

Tweezer Lyfe

by RobACurtis
1 stars

Tweezer Lyfe is a TradingView strategy that identifies Tweezer reversal patterns on the price chart. It plots Bollinger Bands with RSI and stochastic indicators for momentum confirmation. Bullish signals require a prior bearish candle closing near the lower ba

Strategy v5 TrendOscillators & momentum
Updated 2 years ago · None stated GitHub repository of Tweezer Lyfe
330 stars

Alert BB + RSI [Alorse] is a multi-symbol mean-reversion strategy designed for cryptocurrency trading. It evaluates Bollinger Bands and the Relative Strength Index (RSI) across up to 20 user-defined ticker symbols simultaneously. The strategy enters long posit

Strategy v4 Oscillators & momentumVolatility & bands
Updated 2 months ago · None stated GitHub repository of Alert BB + RSI [Alorse]
285 stars

Mean Reversion Strategy is an overlay strategy that identifies pullbacks using a long-term EMA, RSI, and candlestick patterns. It generates long signals when a bullish engulfing candle forms below the EMA while RSI is oversold, and short signals when a bearish

Strategy v4 Mean reversionCandlestick patterns
Updated 3 years ago · None stated GitHub repository of Mean Reversion Strategy

More Oscillators & momentum scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers