Strategy · Pine Script v4 · On the chart

RSI + MACD + BB Short Strategy

by krosenfeld7

This strategy executes short trades based on a confluence of three indicators: Relative Strength Index (RSI), Moving Average Convergence Divergence (MACD), and Bollinger Bands standard deviation metrics.

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_Short_Strategy.txt, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

RSI+MACD+BB_Short_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 Short 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 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

cross50over = crossover(rsi, 50)
cross50under = crossunder(rsi, 50)
cross30over = crossover(rsi, 30)

validShortRSI = barssince((cross50over and barssince(cross50under) > barssince(cross30over))) == 0
shortRSI = (barssince(validShortRSI) < barssince(cross50under)) and (rsi > 50) and not cross50under
short = (close < open and value[1] == 1 and value == 3 and shortRSI 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)

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

// Calculating exact prices for stop loss and exit prices
shortExitPercentPrice = strategy.position_avg_price * (1 - shortProfitPercent)
shortStopPercentPrice = strategy.position_avg_price * (1 + shortLossPercent)

// Profit & Loss via ATR
shortExitPrice = useAtr ? strategy.position_avg_price - atr * atrMultiplier : shortExitPercentPrice
shortStopPrice = useAtr ? strategy.position_avg_price + atr * atrMultiplier : shortStopPercentPrice

// Plotting profit / loss targets
plot(series = (strategy.position_size < 0) ? shortExitPrice : na, color = #33b802, style = plot.style_linebr, transp = 0, linewidth = 3, title = "Short Target")
plot(series = (strategy.position_size < 0) ? shortStopPrice : na, color = #ff0900, style = plot.style_linebr, transp = 0, linewidth = 3, title = "Short Stop Loss")

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

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

Overview

RSI + MACD + BB Short Strategy enters short positions when a bearish bar coincides with decreasing momentum on the MACD histogram, favorable RSI levels, and Bollinger Band price consolidation. Positions exit upon reaching configurable percentage profit targets, stop loss boundaries, or after a maximum number of open bars. Standard inputs adjust indicator lengths, smoothing parameters, percentage exit triggers, and ATR options. It plots 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

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 %float10shortProfitPercent
Loss %float10shortLossPercent
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

This strategy identifies trend-following entries using a triple exponential moving average alignment and ATR-based exits on the main price chart. Long signals trigger when the fast EMA is above the medium EMA and medium is above slow, accompanied by a close ab

Strategy v4 Moving averagesVolatility & bands Repaints
Updated 2 years ago · GPL-3.0 GitHub repository of 3 EMA + Stochastic RSI + ATR
105 stars

This overlay strategy looks for gold scalps from break of structure and change of character. It enters long when a bullish break, a bullish character change, and an optional volume filter align, and short on the opposite set. Optional RSI levels can block trad

Strategy v6 SMC / ICT / price actionOscillators & momentum Repaints
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

Take Profits & Stop Losses

by PythonForForex
64 stars

This educational strategy demonstrates moving average crossovers filtered by RSI momentum, incorporating ATR-based risk management. It calculates a 10-period SMA, a 30-period SMA, a 14-period RSI, and a 14-period ATR. Long entries trigger when the fast SMA cro

Strategy v5 Moving averagesOscillators & momentum
Updated 4 years ago · None stated GitHub repository of Take Profits & Stop Losses

Momentum Rider DAILY FINAL

by greenpeas007
58 stars

This strategy combines exponential moving averages (EMA 9, 21, 50), RSI, MACD, and Supertrend indicators to enter long positions. It triggers trades using six dynamic setups based on momentum breakouts, EMA crossovers, and pullbacks. Position sizing is compute

Strategy v6 TrendOscillators & momentum Repaints
Updated 4 months ago · Custom licence GitHub repository of Momentum Rider DAILY FINAL

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