Strategy · Pine Script v4 · On the chart

RSI + Slow Stochastic + MACD Long Strategy (Daily)

by krosenfeld7

This strategy opens long trades when RSI stays above its midline, the slow stochastic is oversold and its K line crosses above D, and MACD crosses its signal line, all within a configurable delay.

View on GitHub

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

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

RSI+Slow_Stochastic+MACD_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 + Slow Stochastic + MACD Long Strategy (Daily)", 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)
stopLossMethod = input(title="Stop Loss Method?", type=input.string, defval="Pivot", options=["Pivot", "Percent %", "ATR"])

// Algorithm / Strategy Goes here
// Set long / short variables to execute positions below
rsiOver = input(title="RSI Highline", type=input.integer, defval=70, minval=70, maxval=100)
rsiMid = input(title="RSI Midline", type=input.integer, defval=50, minval=30, maxval=70)
rsiUnder = input(title="RSI Lowline", type=input.integer, defval=30, maxval=30, minval=0)
maxDelay = input(title="Label+Indicator Delay", type=input.integer, defval=5, minval=0)
barsback = input(title="Lookback", type=input.integer, defval=3, minval=1)

// RSI Section
len1 = input(14, minval=1, title="RSI Length")
src1 = input(close, "RSI Source", type = input.source)
up = rma(max(change(src1), 0), len1)
down = rma(-min(change(src1), 0), len1)
rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))

rsiLong = rsi > rsiMid
rsiShort = rsi < rsiMid

rsiLongExitCondition = rsi > rsiOver
rsiShortExitCondition = rsi < rsiUnder

// Slow Stochastic
smoothK = input(14, minval=1), smoothD = input(3, minval=1)
k = sma(stoch(close, high, low, smoothK), 3)
d = sma(k, smoothD)

stoLong = k < rsiUnder and d < rsiUnder and crossover(k, d)
stoShort = k > rsiOver and d > rsiOver and crossunder(k, d)

stoLongExitCondition = k > rsiOver and d > rsiOver
stoShortExitCondition = k < rsiUnder and d < rsiUnder

// MACD Section
fast_length = input(title="MACD Fast Length", type=input.integer, defval=12)
slow_length = input(title="MACD Slow Length", type=input.integer, defval=26)
src = 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(src, fast_length) : ema(src, fast_length)
slow_ma = sma_source ? sma(src, slow_length) : ema(src, slow_length)
macd = fast_ma - slow_ma
signal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length)

plottableMacd = (macd / 10000) * 100 + 50
plottableSignal = (signal / 10000) * 100 + 50

macdLong = crossover(macd, signal)
macdShort = crossunder(macd, signal)

// Bullish (Long)
// RSI is above 50, trend is upwards
// Stochastic is in Oversold, cross up
// MACD crossing up
// Stop loss at last pivot low
// Exit when stochastic and rsi are overbought

longStopLoss = pivotlow(low, barsback, barsback)

tempLong = barssince(rsiLong) < maxDelay and barssince(stoLong) < maxDelay and barssince(macdLong) < maxDelay
longExitCondition = rsiLongExitCondition and stoLongExitCondition
long = tempLong ? 1 : 0

// Bearish (Short)
// RSI is below 50, trend is downwards
// Stochastic is in Overbought, cross down
// MACD crossing down
// Stop loss at last pivot high
// Exit when stochastic and rsi are oversold

shortStopLoss = pivothigh(high, barsback, barsback)

tempShort = barssince(rsiShort) < maxDelay and barssince(stoShort) < maxDelay and barssince(macdShort) < maxDelay
shortExitCondition = rsiShortExitCondition and stoShortExitCondition
short = tempShort ? 1 : 0

var float longExitPrice = na
var float longStopPrice = na

// 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

if stopLossMethod == "Pivot"
    longExitPrice := strategy.position_avg_price * (1 + longProfitPercent)
    if strategy.opentrades == 0
        longStopPrice := longStopLoss[barssince(longStopLoss)]
    
if stopLossMethod == "Percent %"
    // Calculating exact prices for stop loss and exit prices
    longExitPrice := strategy.position_avg_price * (1 + longProfitPercent)
    longStopPrice := strategy.position_avg_price * (1 - longLossPercent)

if stopLossMethod == "ATR"
    // Profit & Loss via ATR
    longExitPrice := strategy.position_avg_price + atr * atrMultiplier
    longStopPrice := strategy.position_avg_price - atr * atrMultiplier

// 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)

// Exit on RSI overbought
strategy.close(id = "Long", comment = "RSI Overbought", when = longExitCondition)

Overview

RSI + Slow Stochastic + MACD Long Strategy (Daily) draws on the price chart. A long exits when RSI and the stochastic are both overbought. The stop can follow a confirmed pivot low, a percent loss, or an ATR multiple, and a profit percent is also set. Lengths, thresholds, order expiration, and equity sizing are adjustable. It targets daily bars and does not add to an open long.

Details

Published by

krosenfeld7 on GitHub

Type

Strategy, Pine Script v4

Draws

On the price chart

Category

Oscillators & momentum

Markets

Any symbol

Timeframes

H4 and above

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
Stop Loss Method?stringPivotstopLossMethod
RSI Highlineint70rsiOver
RSI Midlineint50rsiMid
RSI Lowlineint30rsiUnder
Label+Indicator Delayint5maxDelay
Lookbackint3barsback
RSI Lengthint14len1
RSI Sourcesourceclosesrc1
smoothKint14smoothK
smoothDint3smoothD
Show all 22 settings
SettingTypeDefaultVariable
MACD Fast Lengthint12fast_length
MACD Slow Lengthint26slow_length
MACD Sourcesourceclosesrc
Signal Smoothingint9signal_length
Simple MA (Oscillator)boolfalsesma_source
Simple MA (Signal Line)boolfalsesma_signal
ATR Lengthint14length
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

2 EMA/SMA + RSI Strategy [Alorse] combines three configurable moving averages with a short-period Relative Strength Index filter. It plots fast, slow, and trend moving averages on the price chart. Long entries trigger when the fast moving average is above the

Strategy v4 TrendOscillators & momentum
Updated 2 months ago · None stated GitHub repository of 2 EMA/SMA + RSI Strategy [Alorse]

Acrypto - Weighted Strategy

by AlbertoCuadra
318 stars

This strategy plots on the price chart and opens long or short positions when a weighted score from MACD, Stochastic RSI, RSI, Supertrend and a moving-average crossover exceeds a user-set trigger. Each component has its own weight and candle delay. Entries can

Strategy v5 TrendOscillators & momentum
Updated 3 years ago · Custom licence GitHub repository of Acrypto - Weighted Strategy
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

MACD Strategy

by TradersPost
218 stars

This overlay strategy is built around MACD inputs for a fast average, a slow average, and a signal line. Comments say the script keeps MACD values available and can draw a histogram and zero line in a separate pane, with an optional overlay on price. Settings

Strategy v6 Oscillators & momentumMoving averages
Updated 3 months ago · None stated GitHub repository of MACD Strategy

255 EMA Strategy

by hasnocool
106 stars

255 EMA Strategy combines an exponential moving average with Average True Range bands and standard MACD crossovers to generate entry signals. Drawn directly on the price chart, it plots the central 255 EMA along with upper and lower volatility envelopes. Trade

Strategy v4 Moving averagesOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of 255 EMA 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