Strategy · Pine Script v5 · On the chart

MACD Long Strategy [Alorse]

by Alorse· code credited to Bunghole 2021

This strategy enters long when the MACD line crosses above its signal after RSI has been oversold within the last ten bars, and enters short on a MACD cross under after a recent overbought RSI.

View on GitHub

GitHub stars330on the repository
Pine versionv5runs as is
Lines of code56
Settings12inputs
LicenceNone statedfile: MPL-2.0
Last update2 months ago25 Aug 2026

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

56 lines of Pine Script v5 from strategies/momentum/MACD Long Strategy [Bunghole].pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

MACD Long Strategy [Bunghole].pine
//@version=5
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Bunghole 2021
strategy(title='MACD Long Strategy [Alorse]', overlay=true, pyramiding=0, currency=currency.USD, default_qty_type=strategy.percent_of_equity, initial_capital=1000, default_qty_value=20, commission_type=strategy.commission.percent, commission_value=0.1)


//// Stoploss and Take Profit Parameters
// Enable Long Strategy
enable_long_strategy = input.bool(true, title='Enable Long Strategy', group='SL/TP For Long Strategy', inline='1')
long_stoploss_value = input.float(defval=50, title='Stoploss %', minval=0.1, group='SL/TP For Long Strategy', inline='2')
long_stoploss_percentage = close * (long_stoploss_value / 100) / syminfo.mintick
long_takeprofit_value = input.float(defval=50, title='Take Profit %', minval=0.1, group='SL/TP For Long Strategy', inline='2')
long_takeprofit_percentage = close * (long_takeprofit_value / 100) / syminfo.mintick

// Enable Short Strategy
enable_short_strategy = input.bool(true, title='Enable Short Strategy', group='SL/TP For Short Strategy', inline='3')
short_stoploss_value = input.float(defval=50, title='Stoploss %', minval=0.1, group='SL/TP For Short Strategy', inline='4')
short_stoploss_percentage = close * (short_stoploss_value / 100) / syminfo.mintick
short_takeprofit_value = input.float(defval=50, title='Take Profit %', minval=0.1, group='SL/TP For Short Strategy', inline='4')
short_takeprofit_percentage = close * (short_takeprofit_value / 100) / syminfo.mintick


//// Indicator Inputs
// RSI
rsi_over_sold = input.int(defval=30, minval=1, title='Over Sold Level', group='RSI')
rsi_over_bought = input.int(defval=70, minval=1, title='Over Bought Level', group='RSI')
rsi_length = input.int(defval=14, minval=1, title='RSI Length', group='RSI')
rsi = ta.rsi(close, rsi_length)

// MACD
fast_ma = input.int(defval=12, minval=1, title='FastMA Length', group='MACD')
slow_ma = input.int(defval=26, minval=1, title='SlowMA Length', group='MACD')
signal_length = input.int(defval=9, minval=1, title='Signal Length', group='MACD')
[macd_line, signal_line, hist_line] = ta.macd(close, fast_ma, slow_ma, signal_length)


//// Strategy
// Creating Long and Short Strategy
was_over_sold = ta.barssince(rsi <= rsi_over_sold) <= 10
was_over_bought = ta.barssince(rsi >= rsi_over_bought) <= 10
crossover_bull = ta.crossover(macd_line, signal_line)
crossover_bear = ta.crossunder(macd_line, signal_line)
buy_signal = was_over_sold and crossover_bull
sell_signal = was_over_bought and crossover_bear

// Long Strategy
if buy_signal and enable_long_strategy
    strategy.entry('Long', strategy.long, when=buy_signal, alert_message='Open Long Position')
    strategy.exit('Long  SL/TP', from_entry='Long', loss=long_stoploss_percentage, profit=long_takeprofit_percentage, alert_message='Your Long SL/TP Limit As Been Triggered.')
    strategy.close('Long', when=sell_signal, alert_message='Close Long Position')

// Short Strategy
if sell_signal and enable_short_strategy
    strategy.entry('Short', strategy.short, when=sell_signal, alert_message='Open Short Position')
    strategy.exit('Short SL/TP', from_entry='Short', loss=short_stoploss_percentage, profit=short_takeprofit_percentage, alert_message='Your Short SL/TP Limit As Been Triggered.')
    strategy.close('Short', when=buy_signal, alert_message='Close Short Position')

Overview

Each side can be switched off. Default stop loss and take profit are fifty percent of price, sized in ticks, and the opposite signal also closes the position. Quantity is twenty percent of equity. Signals and exits are applied on the price chart. It does not pyramid.

Details

Published by

Alorse on GitHub

Code credit

Bunghole 2021, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Oscillators & momentum

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.

Topics

pinescriptpinescript-indicatorspinescript-strategiestrading-strategiestradingviewtradingview-alerttradingview-strategy

Settings

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

SettingTypeDefaultVariable
Enable Long Strategybooltrueenable_long_strategy
Stoploss %float50long_stoploss_value
Take Profit %float50long_takeprofit_value
Enable Short Strategybooltrueenable_short_strategy
Stoploss %float50short_stoploss_value
Take Profit %float50short_takeprofit_value
Over Sold Levelint30rsi_over_sold
Over Bought Levelint70rsi_over_bought
RSI Lengthint14rsi_length
FastMA Lengthint12fast_ma
SlowMA Lengthint26slow_ma
Signal Lengthint9signal_length
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

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

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