Strategy · Pine Script v5 · On the chart

Our MACD Backtesting

by benniebendiksen· code credited to jack_forsterton10

This Pine Script strategy computes a MACD indicator with customizable fast, slow, and signal EMA lengths applied to close prices.

View on GitHub

GitHub stars7on the repository
Pine versionv5runs as is
Lines of code49
Settings3inputs
LicenceMIT
Last update1 year ago21 Apr 2025

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

49 lines of Pine Script v5 from pine_scripts/macd_backtesting_pine.txt, published under MIT. Keep the author's credit and licence lines when you reuse it.

macd_backtesting_pine.txt
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © jack_forsterton10

//@version=5
strategy("Our MACD Backtesting", overlay=true)
// macd params (3,5,3) for minute candlesticks 
fastLength = input(18)
slowlength = input(30)
macdLength = input(18)
macdLine = ta.ema(close, fastLength) - ta.ema(close, slowlength)
signalLine = ta.ema(macdLine, macdLength)
delta = macdLine - signalLine
if (ta.crossover(delta, 0))
    strategy.entry("MacdLE", strategy.long, comment="MacdLE")
if (ta.crossunder(delta, 0))
    strategy.entry("MacdSE", strategy.short, comment="MacdSE")
//plot(strategy.equity, title="equity", color=color.red, linewidth=2, style=plot.style_areabr)


close_values = [] #list to hold close values indexed at timestamp
close_values.Index = type(datetime.timestamp) #convert index from int to type timestamp
candlestick_length = 10s
lookback_period = 2hr
lookback_period_start = get_starting_timestamp_of_lookback_period
make_candlesticks_from_requests(candlestick_length, lookback_period_start, close_value)
    candle_start_timestamp = lookback_period_start
    candle_stop_timestamp = candle_start_timestamp + candlestick_length
    returned_response_array = get_agg_trade(start_time=initial_timestamp, limit=1000) # the aggTrade api call to binance

    #base case for terminating recursive stack
    if len(returned_response_array) < 1000: #i.e., the last returned response array
        for elem in returned_response_array[1:]:
            if elem['timestamp'] > candle_stop_timestamp
                close_values.append(index=candle_start_timestamp, elem['price'] )
                candle_start_timestamp = candle_stop_timestamp
                candle_stop_timestamp = candle_start_timestamp + candlestick_length
        close_values.append(index=candle_start_timestamp, returned_response_array[-1]['price'] )
        return close_values

    # recursive step
    # process response array to grab timestamp at beginning of every ten seconds and price at end of every ten seconds
    else:
        for elem in returned_response_array[1:]:
            if elem['timestamp'] > candle_stop_timestamp
                close_values.append(index=candle_start_timestamp, elem['price'] )
                candle_start_timestamp = candle_stop_timestamp
                candle_stop_timestamp = candle_start_timestamp + candlestick_length
        #once done processing the 1000 elems, make recursive call for next 1000 elems (possibly less for the final call)
        make_candlesticks_from_requests(candlestick_length, candle_start_timestamp, close_values)

Overview

Delta is calculated as the difference between the MACD line and signal line, plotted as an overlay on the price chart. Long entries trigger on delta crossover above zero, short entries on crossover below zero. No exit rules or stop loss are defined, so positions remain open until an opposite signal. Inputs adjust the three EMA periods. It draws directly on the main price chart without separate panes.

Details

Published by

benniebendiksen on GitHub

Code credit

jack_forsterton10, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Oscillators & momentum, Moving averages, Trend

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Settings

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

SettingTypeDefaultVariable
fastLengthint18fastLength
slowlengthint30slowlength
macdLengthint18macdLength
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

This strategy combines Arnaud Legoux Moving Average percentage price change calculations with an adaptive Gaussian Moving Average to generate trend-following signals. Long and short entries are triggered when the ALMA change calculation crosses above or below

Strategy v5 Moving averagesOscillators & momentum
Updated 6 weeks ago · None stated GitHub repository of ESM2024 - ALMA Smoothed Gaussian Moving Average
218 stars

This strategy generates trading signals based on a selectable momentum engine, supporting MACD, RSI, Stochastic, or Rate of Change. Entries trigger on signal crosses, zero-line crosses, or threshold crosses, with an optional moving average trend filter. Risk m

Strategy v6 Oscillators & momentumTrend
Updated 3 months ago · None stated GitHub repository of Momentum Strategy Template

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

SMA RSI Strategy

by PythonForForex
64 stars

This strategy evaluates simple moving averages and the Relative Strength Index to generate trading signals. It calculates a 10-period SMA, a 30-period SMA, and a 14-period RSI. Long positions are entered when the fast SMA crosses above the slow SMA while RSI i

Strategy v5 TrendOscillators & momentum
Updated 4 years ago · None stated GitHub repository of SMA RSI 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