Strategy · Pine Script v4 · On the chart

RSI Divergence Long Strategy (Not Good)

by krosenfeld7

This overlay strategy enters long when regular or hidden bullish RSI divergence forms between price lows and RSI pivot lows.

View on GitHub

GitHub stars5on the repository
Pine versionv4older, still runs
Lines of code91
Settings13inputs
LicenceApache-2.0
Last update3 years ago12 May 2023

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

91 lines of Pine Script v4 from RSI_Divergence/RSI_Divergence_Long_Strategy.txt, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

RSI_Divergence_Long_Strategy.txt
//@version=4
strategy(title="RSI Divergence Long Strategy (Not Good)", overlay = true, pyramiding = 0, 
         margin_long = 100, margin_short = 100, default_qty_type = strategy.percent_of_equity, 
         default_qty_value = 2, initial_capital = 2000, process_orders_on_close = true)

// Set the starting point for backtesting
start = input(title="Backtesting Start", type=input.time, defval=timestamp("1 Jan 2015"))
// Expiration time on orders
maxTimeOpen = input(title="Order Expiration", type=input.integer, defval=100, minval=1)
useAtr = input(title="Use ATR?", type=input.bool, defval=false)

len = input(title="RSI Period", minval=1, defval=9)
src = input(title="RSI Source", defval=close)
lbR = input(title="Pivot Lookback Right", defval=3)
lbL = input(title="Pivot Lookback Left", defval=1)

rangeUpper = input(title="Max of Lookback Range", defval=60)
rangeLower = input(title="Min of Lookback Range", defval=5)

osc = rsi(src, len)

plFound = na(pivotlow(osc, lbL, lbR)) ? false : true
phFound = na(pivothigh(osc, lbL, lbR)) ? false : true

_inRange(cond) =>
    bars = barssince(cond == true)
    rangeLower <= bars and bars <= rangeUpper

//------------------------------------------------------------------------------
// Regular Bullish
// Osc: Higher Low
oscHL = osc[lbR] > valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])
// Price: Lower Low
priceLL = low[lbR] < valuewhen(plFound, low[lbR], 1)
bullCond = priceLL and oscHL and plFound

//------------------------------------------------------------------------------
// Hidden Bullish
// Osc: Lower Low
oscLL = osc[lbR] < valuewhen(plFound, osc[lbR], 1) and _inRange(plFound[1])
// Price: Higher Low
priceHL = low[lbR] > valuewhen(plFound, low[lbR], 1)
hiddenBullCond = priceHL and oscLL and plFound

long = bullCond or hiddenBullCond

//------------------------------------------------------------------------------
// Regular Bearish
// Osc: Lower High
oscLH = osc[lbR] < valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])
// Price: Higher High
priceHH = high[lbR] > valuewhen(phFound, high[lbR], 1)
bearCond = priceHH and oscLH and phFound

//------------------------------------------------------------------------------
// Hidden Bearish
// Osc: Higher High
oscHH = osc[lbR] > valuewhen(phFound, osc[lbR], 1) and _inRange(phFound[1])
// Price: Lower High
priceLH = high[lbR] < valuewhen(phFound, high[lbR], 1)
hiddenBearCond = priceLH and oscHH and phFound

// Average True Range
length = input(title="ATR Length", defval=14, minval=1)
atrMultiplier = input(title="ATR Multiplier", type=input.float, defval=1, minval=0.1)
atr = atr(length)

longProfitPercent = input(title = "Profit %",
     type = input.float, minval = 0.0, step = 0.1, defval = 10) / 100
longLossPercent = input(title = "Loss %",
     type = input.float, minval = 0.0, step = 0.1, defval = 10) / 100

// Calculating exact prices for stop loss and exit prices
longExitPercentPrice = strategy.position_avg_price * (1 + longProfitPercent)
longStopPercentPrice = strategy.position_avg_price * (1 - longLossPercent)

// Profit & Loss via ATR
longExitPrice = useAtr ? strategy.position_avg_price + atr * atrMultiplier : longExitPercentPrice
longStopPrice = useAtr ? strategy.position_avg_price - atr * atrMultiplier : longStopPercentPrice

// Plotting profit / loss targets
plot(series = (strategy.position_size > 0) ? longExitPrice : na, color = color.green, style = plot.style_linebr, transp = 0, linewidth = 3, title = "Long Target")
plot(series = (strategy.position_size > 0) ? longStopPrice : na, color = color.red, style = plot.style_linebr, transp = 0, linewidth = 3, title = "Long Stop Loss")

// Submit entry orders
if time >= start
    strategy.entry(id = "Long", long = strategy.long, comment = "Long Open", when = long)

// Submit exit orders
strategy.exit(id = "Long", limit = longExitPrice, stop = longStopPrice, comment = "Long Close", when = strategy.position_size > 0)
strategy.close(id = "Long", comment = "Expired: >" + tostring(maxTimeOpen), when = (barssince(change(strategy.opentrades)) + 1) >= maxTimeOpen)

Overview

A regular signal needs a lower price low with a higher RSI low, and a hidden signal needs a higher price low with a lower RSI low, both inside a chosen bar range. It sizes each entry as a percent of equity and exits at percent profit and loss levels, or at ATR multiples when that option is enabled. It plots the long target and stop on the price chart while a position is open. Bearish divergence is calculated but is not used for entries.

Details

Published by

krosenfeld7 on GitHub

Type

Strategy, Pine Script v4

Draws

On the price chart

Category

Oscillators & momentum, Divergence

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
Backtesting Starttimetimestamp("1 Jan 2015")start
Order Expirationint100maxTimeOpen
Use ATR?boolfalseuseAtr
RSI Periodint9len
RSI Sourcesourceclosesrc
Pivot Lookback Rightint3lbR
Pivot Lookback Leftint1lbL
Max of Lookback Rangeint60rangeUpper
Min of Lookback Rangeint5rangeLower
ATR Lengthint14length
ATR Multiplierfloat1atrMultiplier
Profit %float10longProfitPercent
Show all 13 settings
SettingTypeDefaultVariable
Loss %float10longLossPercent
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

ETH_buy_3commas

by hasnocool
106 stars

This strategy overlays a Cipher B style WaveTrend study on the price chart and is titled for Ethereum buy alerts aimed at 3Commas. It calculates a WaveTrend channel and a short moving average, and can mark buy, sell, gold, and divergence dots. Settings change

Strategy v4 Oscillators & momentumDivergence
Updated 2 years ago · GPL-3.0 GitHub repository of ETH_buy_3commas
24 stars

This overlay strategy combines a Cipher B WaveTrend oscillator with two optional moving averages on the price chart. It exposes WaveTrend channel and average lengths, overbought and oversold levels, buy, sell and gold dots, and regular or hidden divergence mar

Strategy v5 Oscillators & momentumMoving averages
Updated 4 years ago · MPL-2.0 GitHub repository of Cipher B + EMAs Strategy

Divergenced A002

by ruckard
13 stars

Divergenced A002 is a momentum divergence strategy designed to identify entry opportunities using Squeeze Momentum Indicator shifts alongside price action. It enters long when momentum reaches higher lows during lower price lows and enters short on opposite di

Strategy v5 Oscillators & momentumDivergence
Updated 1 year ago · None stated GitHub repository of Divergenced A002

RSI Divergence

by muammeryldrm42
7 stars

This strategy detects bullish and bearish RSI divergences using price and RSI pivot points. A bullish divergence triggers a long entry when price forms a lower low while RSI forms a higher low below 40. A bearish divergence triggers a short entry when price fo

Strategy v5 Oscillators & momentumDivergence
Updated 3 months ago · MIT GitHub repository of RSI Divergence
330 stars

MACD + Divergences [Alorse] is a momentum strategy that calculates the MACD oscillator and identifies regular and hidden divergences using pivot high and low points. It filters trade signals with dual Exponential Moving Averages (EMA 150 and 600) to ensure tra

Strategy v4 Oscillators & momentumDivergence Repaints
Updated 2 months ago · None stated GitHub repository of MACD + Divergences [Alorse]
11 stars

The Stochastic Divergence Strategy calculates the Stochastic oscillator (%K and %D) to identify regular bullish and bearish divergence patterns against price pivots. It plots the oscillator and divergence lines in a separate indicator pane. Entries trigger on

Strategy v6 Oscillators & momentumDivergence
Updated 5 months ago · Apache-2.0 GitHub repository of Stochastic Divergence Strategy

More strategys

Trade Your Charts With a Regulated Broker

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

Compare brokers