Strategy · Pine Script v4 · On the chart

RSI + MACD + BB Long Strategy (Not Good)

by krosenfeld7

Calculates a combination of the Relative Strength Index, MACD histogram, and Bollinger Bands contraction to identify long trade entries.

View on GitHub

GitHub stars5on the repository
Pine versionv4older, still runs
Lines of code93
Settings18inputs
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

93 lines of Pine Script v4 from RSI+MACD+BB/RSI+MACD+BB_Long_Strategy.txt, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

RSI+MACD+BB_Long_Strategy.txt
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © krosenfeld7

//@version=4
strategy("RSI + MACD + BB Long Strategy (Not Good)", overlay = true, pyramiding = 0, 
         margin_long = 100, margin_short = 100, default_qty_type = strategy.percent_of_equity, 
         default_qty_value = 20, 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)

// Algorithm / Strategy Goes here
// Set long / short variables to execute positions below
// RSI Section
len = input(14, minval = 1, title = "RSI Length")
src = input(close, "RSI Source", type = input.source)
up = rma(max(change(src), 0), len)
down = rma(-min(change(src), 0), len)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))

// MACD Section
// Getting inputs
fast_length = input(title = "MACD Fast Length", type = input.integer, defval = 12)
slow_length = input(title = "MACD Slow Length", type = input.integer, defval = 26)
src2 = input(title = "MACD Source", type = input.source, defval = close)
signal_length = input(title = "Signal Smoothing", type = input.integer, minval = 1, maxval = 50, defval = 9)
sma_source = input(title = "Simple MA (Oscillator)", type = input.bool, defval = false)
sma_signal = input(title = "Simple MA (Signal Line)", type = input.bool, defval = false)
// Calculating
fast_ma = sma_source ? sma(src2, fast_length) : ema(src2, fast_length)
slow_ma = sma_source ? sma(src2, slow_length) : ema(src2, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length)
hist = macd - signal
value = (hist >= 0 ? (hist[1] < hist ? 1 : 3) : (hist[1] < hist ? 2 : 4))

// Bollinger Bands Section
bollinger_avg_len = 50
length = input(20, minval = 1)
src3 = input(close, title = "BB Source")
mult = input(2.0, minval = 0.001, maxval = 50, title = "BB StdDev")
basis = sma(src3, length)
dev = mult * stdev(src3, length)
upper = basis + dev
lower = basis - dev

band_width_avg = 0.0
for i = 0 to bollinger_avg_len
    band_width_avg += 2 * dev[i]

band_width_avg /= bollinger_avg_len
band_consolidating = band_width_avg > 2 * dev

cross70under = crossunder(rsi, 70)
cross50over = crossover(rsi, 50)
cross50under = crossunder(rsi, 50)

validLongRSI = barssince((cross50under and barssince(cross50over) > barssince(cross70under))) == 0
longRSI = (barssince(validLongRSI) < barssince(cross50over)) and (rsi < 50) and not cross50over
long = (close > open and value[1] == 4 and value == 2 and longRSI and band_consolidating) ? 1 : 0

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

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

The strategy signals a long position on a bullish bar when the MACD histogram turns upward while negative, RSI remains below fifty following a pullback, and Bollinger Bands indicate a consolidation phase. Position exits can be managed using configurable percentage take-profit and stop-loss targets, an optional ATR-based exit mechanism, or a maximum bar duration expiration. Plots and executes directly on the main price chart.

Details

Published by

krosenfeld7 on GitHub

Type

Strategy, Pine Script v4

Draws

On the price chart

Category

Oscillators & momentum, Volatility & bands, Mean reversion

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 Lengthint14len
RSI Sourcesourceclosesrc
MACD Fast Lengthint12fast_length
MACD Slow Lengthint26slow_length
MACD Sourcesourceclosesrc2
Signal Smoothingint9signal_length
Simple MA (Oscillator)boolfalsesma_source
Simple MA (Signal Line)boolfalsesma_signal
lengthint20length
Show all 18 settings
SettingTypeDefaultVariable
BB Sourcesourceclosesrc3
BB StdDevfloat2.0mult
ATR Lengthint14atrLength
ATR Multiplierfloat1atrMultiplier
Profit %float10longProfitPercent
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

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]
106 stars

A multi-timeframe Dollar Cost Averaging (DCA) trading strategy that combines signals from three RSI indicators, three CCI indicators, and Bollinger Bands. It places up to five weighted scale-in safety orders to lower the average entry price. The script offers

Strategy v5 Oscillators & momentumVolatility & bands
Updated 2 years ago · GPL-3.0 GitHub repository of 3RSI 3CCI BB 5orders DCA Strategy+
104 stars

This strategy combines Bollinger Bands with a short RSI to fade moves that leave the bands and then return. A long requires the prior bar below the lower band and oversold, then a close back inside the band while RSI is between 30 and 50. Shorts mirror that at

Strategy v5 Oscillators & momentumVolatility & bands
Updated 3 years ago · MIT GitHub repository of Bollinger Bands and RSI Strategy

Greeffer RSI Strategy

by SammyEnigma
18 stars

Greeffer RSI Strategy is a trading strategy that generates buy and sell entries based on Bollinger Bands and RSI levels. It places stop orders at upper and lower Bollinger Bands on band crossovers, and adds positions when RSI reaches extreme levels. Users can

Strategy v4 Oscillators & momentumVolatility & bands
Updated 6 years ago · None stated GitHub repository of Greeffer RSI Strategy
13 stars

This strategy overlays the price chart to trade DAX futures during European market hours. It calculates exponential and simple moving averages, RSI, MACD, Bollinger Bands, ATR, and realized volatility to simulate VIX levels. Trades execute when session time fi

Strategy v5 Sessions & timeOscillators & momentum
Updated 8 months ago · Custom licence GitHub repository of ClaudeHedge - DAX Session 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