Strategy · Pine Script v6 · On the chart

QTrade MACD

by Can3299· code credited to QTrade

QTrade MACD is a trend-following momentum strategy that enters positions on MACD histogram crossovers.

View on GitHub

GitHub stars2on the repository
Pine versionv6current
Lines of code148
Settings15inputs
LicenceAGPL-3.0
Last update4 months ago1 Jun 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

148 lines of Pine Script v6 from app/tradingview/strategy/macd/src/main.pine, published under AGPL-3.0. Keep the author's credit and licence lines when you reuse it.

main.pine
// This Pine Script® code is subject to the terms of the GNU AFFERO GENERAL PUBLIC LICENSE 3.0 at https://www.gnu.org/licenses/agpl-3.0.en.html
// © QTrade

//@version=6
strategy("QTrade MACD",
         overlay=true,
         initial_capital=10000,
         default_qty_type=strategy.cash,
         currency=currency.USD
)

// ==========================================
// 1. INPUTS
// ==========================================
// Risk Management Settings
grp_risk      = "Risk Management"
riskPercent   = input.float(1.0, "Risk Per Trade (%)", minval=0.1, group=grp_risk, tooltip="Amount of equity to risk if the Stop Loss is hit.")
rrRatio       = input.float(2.0, "Reward Per Trade (%)", step=0.1, group=grp_risk, tooltip="Take Profit distance relative to Stop Loss distance.")
atrLength     = input.int(14, "ATR Length for Backup SL", group=grp_risk)
atrMult       = input.float(2.0, "ATR Multiplier for Backup SL", step=0.1, group=grp_risk)

grp_toggles   = "Feature Toggles (On/Off)"
useSTFilter   = input.bool(true, "Trend Protection", group=grp_toggles, tooltip="It requires the trade direction to be the same as the SuperTrend direction.")
useDirFilter  = input.bool(true, "Side Protection", group=grp_toggles, tooltip="For a long position, the MACD must be below zero, and for a short position, it must be above zero.")
useDistFilter = input.bool(true, "Zero Line Tolerance Protection", group=grp_toggles, tooltip="This requires the MACD line to be a certain distance from the zero line (for the trend to mature).")

// MACD Settings
grp_macd    = "MACD Settings"
fastLength  = input.int(12, "Fast length", group=grp_macd)
slowlength  = input.int(26, "Slow length", group=grp_macd)
MACDLength  = input.int(9, "MACD length", group=grp_macd)
zeroLineTol = input.float(40.0, "Zero Line Tolerance", group=grp_macd, tooltip="The minimum distance of the MACD from the zero line.")

// SuperTrend Settings
grp_st        = "Trend Filter (SuperTrend)"
stFactor      = input.float(3.0, "SuperTrend Factor", step=0.1, group=grp_st)
stPeriod      = input.int(10, "SuperTrend ATR Period", group=grp_st)

// Fractal Settings
grp_fr        = "Fractal Settings"
leftBars      = input.int(1, "Fractal Left Bars", minval=1, group=grp_fr, tooltip="Number of bars to the left for Swing Point detection.")
rightBars     = input.int(1, "Fractal Right Bars", minval=1, group=grp_fr, tooltip="Number of bars to the right for Swing Point detection.")


// ==========================================
// 2. CALCULATIONS
// ==========================================
// MACD Calculation
[macdLine, signalLine, histLine] = ta.macd(close, fastLength, slowlength, MACDLength)

// SuperTrend Calculation
[supertrend, direction] = ta.supertrend(stFactor, stPeriod)
stUptrend   = direction < 0
stDowntrend = direction > 0

// Swing (Pivot) Points
var float lastSwingHigh = na
var float lastSwingLow  = na
ph = ta.pivothigh(high, leftBars, rightBars)
pl = ta.pivotlow(low, leftBars, rightBars)

if not na(ph)
    lastSwingHigh := ph
    if not na(pl)
        lastSwingLow  := pl

        // Backup Stop Level for ATR
        backupATR = ta.atr(atrLength) * atrMult


        // ==========================================
        // 3. FILTERS AND CONDITIONS
        // ==========================================
        // Basic MACD Crossover (Histogram crossing 0)
        macdCrossUp   = ta.crossover(histLine, 0)
        macdCrossDown = ta.crossunder(histLine, 0)

        // Filter 1: Distance Filter (Is the MACD line far enough from zero?)
        macdDistanceOk = useDistFilter ? (math.abs(macdLine) > zeroLineTol and math.abs(signalLine) > zeroLineTol) : true

        // Filter 2: Side Protection Filter
        // For long position, MACD must be below zero; for short, it must be above zero.
        canLongDir  = useDirFilter ? (macdLine < 0 and signalLine < 0) : true
        canShortDir = useDirFilter ? (macdLine > 0 and signalLine > 0) : true

        // Filter 3: SuperTrend Filter
        stLongOk  = useSTFilter ? stUptrend : true
        stShortOk = useSTFilter ? stDowntrend : true

        // Combined Entry Conditions
        longCond  = macdCrossUp and macdDistanceOk and canLongDir and stLongOk
        shortCond = macdCrossDown and macdDistanceOk and canShortDir and stShortOk


        // ==========================================
        // 4. TRADE MANAGEMENT
        // ==========================================
        // Long Entry
        if longCond
            // Use backup SL if pivot point is not found or pivot is above price
            sl = (not na(lastSwingLow) and lastSwingLow < close) ? lastSwingLow : close - backupATR
            risk_dist = close - sl
            if risk_dist > 0
                tp = close + (risk_dist * rrRatio)

                // Calculate Quantity for 1% Risk
                risk_amount = strategy.equity * (riskPercent / 100)
                pos_qty = risk_amount / risk_dist

                strategy.entry("Long", strategy.long, qty=pos_qty, comment="MACD Long")
                strategy.exit("Exit Long", from_entry="Long", stop=sl, limit=tp, comment_loss="SL", comment_profit="TP")

                // Short Entry
                if shortCond
                    // Use backup SL if pivot point is not found or pivot is below price
                    sl = (not na(lastSwingHigh) and lastSwingHigh > close) ? lastSwingHigh : close + backupATR
                    risk_dist = sl - close
                    if risk_dist > 0
                        tp = close - (risk_dist * rrRatio)

                        // Calculate Quantity for 1% Risk
                        risk_amount = strategy.equity * (riskPercent / 100)
                        pos_qty = risk_amount / risk_dist

                        strategy.entry("Short", strategy.short, qty=pos_qty, comment="MACD Short")
                        strategy.exit("Exit Short", from_entry="Short", stop=sl, limit=tp, comment_loss="SL", comment_profit="TP")


                        // ==========================================
                        // 5. VISUALIZATION
                        // ==========================================
                        // SuperTrend Line is shown on chart (if filter is active)
                        plot(useSTFilter ? supertrend : na, color=stUptrend ? color.new(color.green, 50) : color.new(color.red, 50), linewidth=2, title="SuperTrend Filter")

                        // Swing Levels (Show the last found pivots)
                        plot(lastSwingHigh, color=color.new(color.red, 70), style=plot.style_linebr, linewidth=1, title="Last Swing High Line", offset=-rightBars)
                        plot(lastSwingLow, color=color.new(color.green, 70), style=plot.style_linebr, linewidth=1, title="Last Swing Low Line", offset=-rightBars)

                        // Pivot Point Shapes
                        plotshape(ph, title="Pivot High", style=shape.diamond, location=location.abovebar, color=color.new(color.red, 0), size=size.tiny, offset=-rightBars)
                        plotshape(pl, title="Pivot Low", style=shape.diamond, location=location.belowbar, color=color.new(color.green, 0), size=size.tiny, offset=-rightBars)

                        // Signal Labels
                        plotshape(longCond, title="Long Signal", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.small, text="LONG")
                        plotshape(shortCond, title="Short Signal", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.small, text="SHORT")

                        // Histogram Coloring (Visual Aid)
                        plot(histLine, title="MACD Histogram", style=plot.style_columns, color=histLine >= 0 ? (ta.rising(histLine, 1) ? color.new(color.green, 50) : color.new(color.lime, 50)) : (ta.falling(histLine, 1) ? color.new(color.red, 50) : color.new(color.maroon, 50)))

Overview

Entry signals are filtered using SuperTrend direction alignment, zero-line position rules, and zero-line distance tolerance checks. Stop loss levels are established using recent pivot highs and lows with an ATR fallback, while take profit targets are derived from a customizable reward-to-risk ratio. Position sizing is calculated automatically based on trade risk percentage. The strategy overlays directly on the price chart.

Details

Published by

Can3299 on GitHub

Code credit

QTrade, as written in the script's header

Type

Strategy, Pine Script v6

Draws

On the price chart

Category

Trend, Oscillators & momentum, Moving averages

Markets

Crypto

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

tradingtrading-algorithmtrading-bottrading-strategies

Settings

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

SettingTypeDefaultVariable
Risk Per Trade (%)float1.0riskPercent
Reward Per Trade (%)float2.0rrRatio
ATR Length for Backup SLint14atrLength
ATR Multiplier for Backup SLfloat2.0atrMult
Trend ProtectionbooltrueuseSTFilter
Side ProtectionbooltrueuseDirFilter
Zero Line Tolerance ProtectionbooltrueuseDistFilter
Fast lengthint12fastLength
Slow lengthint26slowlength
MACD lengthint9MACDLength
Zero Line Tolerancefloat40.0zeroLineTol
SuperTrend Factorfloat3.0stFactor
Show all 15 settings
SettingTypeDefaultVariable
SuperTrend ATR Periodint10stPeriod
Fractal Left Barsint1leftBars
Fractal Right Barsint1rightBars
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