Pine Script v4 · Strategy
MACD Trend Following Strategy
A Pine Script v4 strategy built on SMA or EMA (close, 12). It has 6 order rules, 4 entries among them, and trades long and short with the default settings. Exits wait for a signal; there is no stop loss. Each trade is one contract and pays no commission. 13 settings; defaults include Long/Short Long only, Fast Length 12 and Slow Length 26.
Generated from the script's code by a template: every clause is a fact read from the source. Not written by a person or a model, and not taken from the author's description.
- Does MACD Trend Following Strategy repaint?
- No
- No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 6 of 6 trades.
- How did MACD Trend Following Strategy do on BTCUSDT 1D with default settings?
- +10.45%
- From 26 Jan 2024 to 21 Oct 2026, over 17 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
- Can MACD Trend Following Strategy be converted to Pine Script v5?
- Yes
- The upgrade takes 1 step, from v4; each was run before and after on the same candles with identical results, and the v5 script can be downloaded below.
- Does MACD Trend Following Strategy use a stop loss?
- No
- Every exit waits for a signal; nothing limits a losing trade before it fires.
- Does MACD Trend Following Strategy run in Zeal Terminal?
- Yes
- It compiles in 18 ms and runs 1,000 bars in 49 ms, in the browser.
BTCUSDT · 1D · default settings
- Histogram
- MACD
- Signal
- Winning trade
- Losing trade
- Equity
- Buy and hold
- Net profit
- +10.45%
- $10,453.50
- Buy and hold
- +102.5%
- same period
- Closed trades
- 17
- 5 won · 12 lost
- Profitable
- 29.4%
- of closed trades
- Profit factor
- 1.21
- gross profit ÷ gross loss
- Max drawdown
- 20.55%
- −$28,144.40
One run with the author's default settings, $100,000 starting capital, commission as the script sets it. A long position was still open at the last bar. A single backtest says little about future results and is not a recommendation. Backtests are simulations on historical data and are not investment advice.
Review
What a careful reader of this script would point out, found by checking the source and the backtest.
-
Check
No stop loss
Every exit waits for a signal. Nothing limits a losing trade before the exit condition fires.
-
Check
No commission
The backtest assumes free trading. Results on any real exchange will be lower.
-
Note
No slippage
Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.
-
Note
Uses transp =, which v5 removed line 26
transp = on line 26, 27, 28. v5 folds the transparency into the colour with color.new(c, transp).
Upgrade and export
Written in Pine Script v4. The upgrade to v5 takes 1 step, one per version, each applied to the result of the one before. A last clean-v5 pass then types the settings and moves when = into if blocks, which v6 requires. Every step runs before and after on the same candles in Zeal Terminal's engine; a step whose results differ is shown but not offered as a download. Upgrades preserve behaviour: bugs are fixed in the Review, never silently here.
- Upgrading to v5 renames sma → ta.sma, ema → ta.ema.
v4 → v5
VerifiedSame 17 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 3: //@version=4 → //@version=5
- Line 7: input(type = input.integer) → input.int()
- Line 8: input(type = input.integer) → input.int()
- Line 9: input(type = input.source) → input.source()
- Line 10: input(type = input.integer) → input.int()
- Line 11: input(type = input.bool) → input.bool()
14 more edits
- Line 12: input(type = input.bool) → input.bool()
- Line 21: sma → ta.sma
- Line 21: ema → ta.ema
- Line 22: sma → ta.sma
- Line 22: ema → ta.ema
- Line 24: sma → ta.sma
- Line 24: ema → ta.ema
- Line 26: transp = 0 → color.new((hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below) ), 0)
- Line 27: transp = 0 → color.new(col_macd, 0)
- Line 28: transp = 0 → color.new(col_signal, 0)
- Line 54: strategy.entry(…, true) → strategy.entry(…, strategy.long)
- Line 60: strategy.entry(…, true) → strategy.entry(…, strategy.long)
- Line 63: strategy.entry(…, false) → strategy.entry(…, strategy.short)
- Line 66: strategy.entry(…, false) → strategy.entry(…, strategy.short)
⋯// © DeMindSET-//@version=4+//@version=5strategy("MACD Trend Follow Strategy", overlay=false)⋯LSB = input(title="Long/Short", defval="Long only", options=["Long only", "Short only" , "Both"]) -fast_length = input(title="Fast Length", type=input.integer, defval=12)+fast_length = input.int(title="Fast Length", defval=12)-slow_length = input(title="Slow Length", type=input.integer, defval=26)+slow_length = input.int(title="Slow Length", defval=26)-src = input(title="Source", type=input.source, defval=close)+src = input.source(title="Source", defval=close)-signal_length = input(title="Signal Smoothing", type=input.integer, minval = 1, maxval = 50, defval = 9)+signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9)-sma_source = input(title="Simple MA(Oscillator)", type=input.bool, defval=false)+sma_source = input.bool(title="Simple MA(Oscillator)", defval=false)-sma_signal = input(title="Simple MA(Signal Line)", type=input.bool, defval=false)+sma_signal = input.bool(title="Simple MA(Signal Line)", defval=false)// Plot colors⋯// Calculating-fast_ma = sma_source ? sma(src, fast_length) : ema(src, fast_length)+fast_ma = sma_source ? ta.sma(src, fast_length) : ta.ema(src, fast_length)-slow_ma = sma_source ? sma(src, slow_length) : ema(src, slow_length)+slow_ma = sma_source ? ta.sma(src, slow_length) : ta.ema(src, slow_length)macd = fast_ma - slow_ma-signal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length)+signal = sma_signal ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)hist = macd - signal-plot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below) ), transp=0 )+plot(hist, title="Histogram", style=plot.style_columns, color=color.new((hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below) ), 0) )-plot(macd, title="MACD", color=col_macd, transp=0)+plot(macd, title="MACD", color=color.new(col_macd, 0))-plot(signal, title="Signal", color=col_signal, transp=0)+plot(signal, title="Signal", color=color.new(col_signal, 0))//⋯if LSB == "Long only" and Green and window()- strategy.entry("L",true)+ strategy.entry("L",strategy.long) ⋯if LSB == "Both" and Green and window()- strategy.entry("L",true) + strategy.entry("L",strategy.long) if LSB == "Both" and Red and window()- strategy.entry("S",false)+ strategy.entry("S",strategy.short) if LSB == "Short only" and Red and window()- strategy.entry("S",false)+ strategy.entry("S",strategy.short)if LSB == "Short only" and Green and window()⋯Same 17 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 6: input() → input.string()
- Line 43: input() → input.int()
- Line 44: input() → input.int()
- Line 45: input() → input.int()
- Line 46: input() → input.int()
- Line 47: input() → input.int()
- Line 48: input() → input.int()
⋯// Getting inputs-LSB = input(title="Long/Short", defval="Long only", options=["Long only", "Short only" , "Both"]) +LSB = input.string(title="Long/Short", defval="Long only", options=["Long only", "Short only" , "Both"]) fast_length = input.int(title="Fast Length", defval=12)⋯// === INPUT BACKTEST RANGE ===-FromYear = input(defval = 2010, title = "From Year", minval = 1920)+FromYear = input.int(defval = 2010, title = "From Year", minval = 1920)-FromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)+FromMonth = input.int(defval = 1, title = "From Month", minval = 1, maxval = 12)-FromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)+FromDay = input.int(defval = 1, title = "From Day", minval = 1, maxval = 31)-ToYear = input(defval = 9999, title = "To Year", minval = 2009)+ToYear = input.int(defval = 9999, title = "To Year", minval = 2009)-ToMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12)+ToMonth = input.int(defval = 12, title = "To Month", minval = 1, maxval = 12)-ToDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31)+ToDay = input.int(defval = 31, title = "To Day", minval = 1, maxval = 31)// === FUNCTION EXAMPLE ===⋯Does it run in Pine Script v6?
No
The v6 version runs in Zeal Terminal's engine, but its results differ from the v5 version: Trades differ: 17 before, 17 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.
⋯// © DeMindSET-//@version=5+//@version=6strategy("MACD Trend Follow Strategy", overlay=false)⋯Settings
Every input the script declares, with its default and what it feeds. Bounds are the ones the script enforces.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Long/Short | Long only | string · options ["Long only", "Short only" , "Both"] | entry L close L entry L entry S entry S close S line 53 line 56 line 59 line 62 line 65 line 67 |
| Fast Length | 12 | int (written input.integer) | fast_ma |
| Slow Length | 26 | int (written input.integer) | slow_ma |
| Source | close | source | fast_ma slow_ma |
| Signal Smoothing | 9 | int (written input.integer) · min 1 · max 50 | signal |
| Simple MA(Oscillator) | false | bool | fast_ma slow_ma |
| Simple MA(Signal Line) | false | bool | signal |
| From Year | 2010 | int · min 1920 | start |
| From Month | 1 | int · min 1 · max 12 | start |
| From Day | 1 | int · min 1 · max 31 | start |
| To Year | 9999 | int · min 2009 | finish |
| To Month | 12 | int · min 1 · max 12 | finish |
| To Day | 31 | int · min 1 · max 31 | finish |
What it calculates
- SMA / EMA (
sma,ta.smain v5)Source (close), Fast Length (12)fast_ma · line 21 - SMA / EMA (
sma,ta.smain v5)Source (close), Slow Length (26)slow_ma · line 22 - SMA / EMA (
sma,ta.smain v5)macd, Signal Smoothing (9)signal · line 24
Signal flow
How price data and settings reach the orders. Each box is a name in the script, or several computed the same way; each arrow is a value one of them reads. Hover a box for its members.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open L long | LSB == "Long only" and Green and window() | On | 54 |
| Close L | LSB == "Long only" and Red and window() | On | 57 |
| Open L long | LSB == "Both" and Green and window() | On | 60 |
| Open S short | LSB == "Both" and Red and window() | On | 63 |
| Open S short | LSB == "Short only" and Red and window() | On | 66 |
| Close S | LSB == "Short only" and Green and window() | On | 68 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Does it repaint?
No
No repainting patterns in the source, and the live replay matched history.
- ClearHigher-timeframe dataThe script requests no other symbol or timeframe.
- ClearFuture-bar referencesNo negative history offsets such as close[-1].
- ClearIntrabar recalculationNo varip, calc_on_every_tick or realtime-only state. Orders are decided once per closed bar.
- ClearOrder timingOrders fill at the next bar's open, after the signal bar has closed.
The checks read the source; the replay runs it. Together they catch the common causes, not every possible one.
Other markets
The same script with default settings on 8 Binance markets. Each row is a separate backtest over the most recent 1,000 bars.
| Market | Net | Buy and hold | Trades | Won | Profit factor | Max drawdown | Period |
|---|---|---|---|---|---|---|---|
| BTCUSDT 1D | +10.5% | +102.5% | 17 | 29% | 1.21 | 20.6% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | −1.6% | +5.5% | 19 | 26% | 0.93 | 8.9% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +0.2% | +9.8% | 15 | 27% | 1.08 | 1.4% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | +0.4% | +8.4% | 15 | 33% | 1.64 | 0.3% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | −0.0% | +16.7% | 16 | 38% | 0.81 | 0.1% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | +0.0% | +21.5% | 14 | 36% | 2.53 | 0.0% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | +0.5% | +148.3% | 16 | 38% | 2.21 | 0.2% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | +0.0% | +17.1% | 17 | 29% | 1.17 | 0.1% | 8 May 2026 – 21 Oct 2026 |
Backtests are simulations on historical data and are not investment advice.
The trades
By market direction
| At entry, last 90 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 5 | 40% | −$1,221.07 |
| Sideways market | 6 | 17% | $1,406.50 |
| Falling market | 6 | 33% | $10,268.10 |
Rising and falling mean the market moved more than 15% over the 90 bars before entry.
How bad could the drawdown be?
30.9%
The 95th percentile of the worst drawdown when the same 17 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 14.9% to 30.9%; the tick is what actually happened, 19.6%. Order luck alone moves it this much.
All 17 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 29 Feb 2024 62,432.10 | 16 Apr 2024 63,420.00 | 47 | $987.88 |
| long | 18 May 2024 67,024.00 | 17 Jun 2024 66,676.90 | 30 | −$347.14 |
| long | 19 Jul 2024 63,987.90 | 5 Aug 2024 58,161.00 | 17 | −$5,826.92 |
| long | 25 Aug 2024 64,157.00 | 31 Aug 2024 59,124.00 | 6 | −$5,033.03 |
| long | 19 Sep 2024 61,760.00 | 30 Dec 2024 93,738.20 | 102 | $31,978.20 |
| long | 6 Jan 2025 98,363.60 | 10 Jan 2025 92,552.50 | 4 | −$5,811.12 |
| long | 17 Jan 2025 99,987.30 | 6 Feb 2025 96,612.40 | 20 | −$3,374.86 |
| long | 20 Apr 2025 85,077.00 | 22 Jun 2025 102,120.00 | 63 | $17,043.00 |
| long | 27 Jun 2025 106,947.00 | 21 Aug 2025 114,271.00 | 55 | $7,324.17 |
| long | 14 Sep 2025 115,918.00 | 26 Sep 2025 108,994.00 | 12 | −$6,923.80 |
| long | 2 Oct 2025 118,595.00 | 16 Oct 2025 110,763.00 | 14 | −$7,831.71 |
| long | 6 Jan 2026 93,859.70 | 25 Jan 2026 89,225.30 | 19 | −$4,634.37 |
| long | 16 Mar 2026 72,815.30 | 23 Mar 2026 67,859.00 | 7 | −$4,956.25 |
| long | 26 Mar 2026 71,336.50 | 27 Mar 2026 68,820.30 | 1 | −$2,516.22 |
| long | 10 Apr 2026 71,788.00 | 23 May 2026 75,539.50 | 43 | $3,751.52 |
| long | 16 Jul 2026 64,756.30 | 2 Aug 2026 62,823.70 | 17 | −$1,932.63 |
| long | 8 Aug 2026 64,923.20 | 13 Aug 2026 63,480.00 | 5 | −$1,443.21 |
Similar scripts
Indicators and strategies built from the same calculations, run on BTCUSDT 1D with their own defaults so they can be compared directly.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| MACD Trend Following Strategy this page | — | v4 strategy | +10.5% | 17 | 20.6% |
| MACD Long Strat by TheGrindToday | ema sma | v4 strategy | +24.0% | 79 | 20.1% |
| Stock trending strategy by exlux99 | ema sma | v4 strategy | +35.3% | 21 | 14.7% |
| 4-Hour Stochastic EMA Trend by slymnturkoglu | ema sma | v4 strategy | No trades on this market | ||
| 4X EMA and volume strategy by SoftKill21 | ema sma | v4 strategy | +1.8% | 3 | 25.8% |
| Simple Momentum Strategy Based on SMA, EMA and Volume by slip_stream | sma ema | v4 strategy | +7.4% | 18 | 27.4% |
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 18 ms | With a workaround 1,000 bars in 49 ms | Not measured |
| PineTS | No v5 and v6 only | — | Not measured |
Zeal Terminal's engine currently reads an order side written as true, false as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 54, 60, 63, 66) so the engine trades the way the script says.
“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report. PineTS runs Pine Script v5 and v6 only.
Source
Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © DeMindSET//@version=4strategy("MACD Trend Follow Strategy", overlay=false)// Getting inputsLSB = input(title="Long/Short", defval="Long only", options=["Long only", "Short only" , "Both"]) fast_length = input(title="Fast Length", type=input.integer, defval=12)slow_length = input(title="Slow Length", type=input.integer, defval=26)src = input(title="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)// Plot colorscol_grow_above = #26A69Acol_grow_below = #FFCDD2col_fall_above = #B2DFDBcol_fall_below = #EF5350col_macd = #0094ffcol_signal = #ff6a00// Calculatingfast_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_masignal = sma_signal ? sma(macd, signal_length) : ema(macd, signal_length)hist = macd - signalplot(hist, title="Histogram", style=plot.style_columns, color=(hist>=0 ? (hist[1] < hist ? col_grow_above : col_fall_above) : (hist[1] < hist ? col_grow_below : col_fall_below) ), transp=0 )plot(macd, title="MACD", color=col_macd, transp=0)plot(signal, title="Signal", color=col_signal, transp=0)//Bull= macd > signalBear= macd < signalConBull=macd>0ConBear=macd<0//Green= Bull and ConBullRed= Bear and ConBearYellow= Bull and ConBearBlue= Bear and ConBull//bcolor = Green ? color.green : Red ? color.red : Yellow ? color.yellow : Blue ? color.blue : nabarcolor(color=bcolor)// === INPUT BACKTEST RANGE ===FromYear = input(defval = 2010, title = "From Year", minval = 1920)FromMonth = input(defval = 1, title = "From Month", minval = 1, maxval = 12)FromDay = input(defval = 1, title = "From Day", minval = 1, maxval = 31)ToYear = input(defval = 9999, title = "To Year", minval = 2009)ToMonth = input(defval = 12, title = "To Month", minval = 1, maxval = 12)ToDay = input(defval = 31, title = "To Day", minval = 1, maxval = 31)// === FUNCTION EXAMPLE ===start = timestamp(FromYear, FromMonth, FromDay, 00, 00) // backtest start windowfinish = timestamp(ToYear, ToMonth, ToDay, 23, 59) // backtest finish windowwindow() => time >= start and time <= finish ? true : false // create function "within window of time"if LSB == "Long only" and Green and window() strategy.entry("L",true) if LSB == "Long only" and Red and window() strategy.close("L",qty_percent=100,comment="TP Long") if LSB == "Both" and Green and window() strategy.entry("L",true) if LSB == "Both" and Red and window() strategy.entry("S",false) if LSB == "Short only" and Red and window() strategy.entry("S",false)if LSB == "Short only" and Green and window() strategy.close("S",qty_percent=100,comment="TP Short")