Pine Script v5 · Strategy
Macd Divergence + MTF EMA
A Pine Script v5 strategy built on MACD (close, 12), EMA (close, 5) and Crossunder (hist, 0). It has 4 order rules, 2 entries among them, and trades long and short with the default settings. Exits use a stop loss and a profit target. Each trade commits 20% of equity and pays 0.1 commission. 20 settings; defaults include Source close, Fast EMA 15 and Fast EMA Period 5.
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 Divergence + MTF EMA repaint?
- No
- No repainting patterns were found in the source. The live replay was not measured: the script acts only when barstate.isconfirmed is true, which Zeal Terminal's engine never reports during a live replay (it does not run a bar's closing update in live mode), so the replay cannot test this script.
- How did Macd Divergence + MTF EMA do on BTCUSDT 1D with default settings?
- Not measured
- It closed no trades there from 26 Jan 2024 to 21 Oct 2026 with the default settings, so there is no result to report. Its code limits trading to a date window, which can leave this period out. It closed no trades on the other markets either. A backtest, not investment advice.
- What alerts does Macd Divergence + MTF EMA have?
- 2
- "Long Trade: " + syminfo.ticker; "Short Trade: " + syminfo.ticker.
- Does Macd Divergence + MTF EMA run in Pine Script v6?
- No
- The v6 version does not run in Zeal Terminal's engine: Pine Script v6 Error at @L122:C19: cannot use 'float' as a condition — Pine Script v6 does not cast 'int' or 'float' to 'bool' implicitly. Wrap it in bool(). The v6 version is shown for reference and is not offered as a download.
- Does Macd Divergence + MTF EMA use a stop loss?
- Yes
- strategy.exit sets a stop on line 119, 145.
BTCUSDT · 1D · default settings
- Plot
- Plot
- Plot
- Plot
- Winning trade
- Losing trade
- Equity
- Buy and hold
Needs BINANCE:BTCUSDT 15 data, not available: a lower timeframe than the chart; the engine does not evaluate intrabar data Needs BINANCE:BTCUSDT 60 data, not available: a lower timeframe than the chart; the engine does not evaluate intrabar data Values that depend on it are empty on this chart.
- Net profit
- 0.00%
- $0.00
- Buy and hold
- +102.5%
- same period
- Closed trades
- 0
- 0 won · 0 lost
- Profitable
- 0.0%
- of closed trades
- Profit factor
- —
- gross profit ÷ gross loss
- Max drawdown
- 0.00%
- $0.00
One run with the author's default settings, $1,000 starting capital, commission as the script sets it. 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
2 settings do nothing
“Start Time”, “Finish Time” are declared but never read.
-
Note
No slippage
Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.
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 |
|---|---|---|---|
| Start Time | timestamp('01 Apr 2018 13:30 +0000') | time | unused |
| Finish Time | timestamp('30 Sep 2021 13:30 +0000') | time | unused |
| Show Long Positions | true | bool | entry Go Long line 113 |
| Show Short Positions | true | bool | entry Go Short line 139 |
| Source | close | source | macd signal hist ma_15 ma_60 ma_slo |
| EMAS Settings | |||
| Fast EMA | 15 | timeframe | ma_15 |
| Fast EMA Period | 5 | int | ma_15 |
| Slow EMA | 60 | timeframe | ma_60 |
| Slow EMA Period | 10 | int | ma_60 |
| Filter Settings | |||
| Enable a Third Ema filter? | true | bool | bullish_filter bearish_filter plot |
| Filter EMA Period | 100 | int | ma_slo |
| Filter Resolution EMA | D | timeframe | ma_slo |
| MACD Properties | |||
| MACD TimeFrame | | timeframe | macd signal hist |
| Fast Length | 12 | int | macd signal hist |
| Sign Length | 26 | int | macd signal hist |
| Sign Length | 9 | int | macd signal hist |
| Trade Management | |||
| Lookback period | 14 | int · min 1 | sl sh |
| Profit Multiplier based on Stop Loss | 6.0 | float · min 0.1 | longTakeProf profitValue shortTakeProf SprofitValue |
| Short Stop Loss Percentage | 1.0 | float · min 0.0 | shortStopLoss bstopValue |
| Long Stop Loss Percentage | 2.0 | float · min 0.0 | longStopLoss astopValue |
What it calculates
- MACDSource (close), Fast Length (12), Sign Length (26), Sign Length (9)
macd · line 47 - MACDSource (close), Fast Length (12), Sign Length (26), Sign Length (9)
signal · line 47 - MACDSource (close), Fast Length (12), Sign Length (26), Sign Length (9)
hist · line 47 - EMASource (close), Fast EMA Period (5)
ma_15 · line 48 - EMASource (close), Slow EMA Period (10)
ma_60 · line 49 - EMASource (close), Filter EMA Period (100)
ma_slo · line 50 - Crossunderhist, 0
prior_top · line 73 - Crossunderhist, 0
prior_top_close · line 77 - Crossoverhist, 0
prior_bottom · line 84 - Crossoverhist, 0
prior_bottom_close · line 88 - Lowestlow, Lookback period (14)
sl · line 99 - Highesthigh, Lookback period (14)
sh · line 125
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.
The script has 67 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open Go Long long | bottom and notInTrade and bullish_filter and long_pos and barstate.isconfirmed | On | 114 |
| Exit Exit Long stop and limit | longTrade | On | 119 |
| Open Go Short short | top and notInTrade and bearish_filter and short_pos and barstate.isconfirmed | On | 140 |
| Exit Exit Short stop and limit | shortTrade | On | 145 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Alerts
| Alert | Call | Message | Line |
|---|---|---|---|
| (no title) | alert | "Long Trade: " + syminfo.ticker | 115 |
| (no title) | alert | "Short Trade: " + syminfo.ticker | 141 |
Does it repaint?
No
No repainting patterns in the source.
- ClearHigher-timeframe data4 request.security call(s), none with lookahead on.
- 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
Not run on other markets: the script requests BINANCE:BTCUSDT 15, BINANCE:BTCUSDT 60, and that data is not available here (a lower timeframe than the chart; the engine does not evaluate intrabar data; a lower timeframe than the chart; the engine does not evaluate intrabar data). Its results would rest on empty values.
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 Divergence + MTF EMA this page | — | v5 strategy | 0.0% | 0 | 0.0% |
| [2022] MACD Cross Strategy (version 1) by spuckles12 | macd ema lowest highest | v5 strategy | does not run in Zeal Terminal | ||
| CC Trend strategy 2- Downtrend Short by CheatCode1 | ema highest lowest | v5 strategy | No trades on this market | ||
| TrianglePoint strategy by mohanee | highest lowest ema | v4 strategy | +45.4% | 11 | 101.9% |
| Lagged Donchian Channel + EMA by Mysteriown | ema highest lowest | v4 strategy | −12.3% | 4 | 12.3% |
| Backtest Custom HiLo Strategy by luyikaibr | ema highest lowest | v4 strategy | No trades on this market | ||
Upgrade and export
Written in Pine Script v5. The clean-v5 step types the settings and moves when = into if blocks, which v6 requires; it is run before and after like any upgrade.
- No v6-only features. v6 is not needed to run this script.
Clean v5
VerifiedNothing to change.
Does it run in Pine Script v6?
No
The v6 version does not run in Zeal Terminal's engine: Pine Script v6 Error at @L122:C19: cannot use 'float' as a condition — Pine Script v6 does not cast 'int' or 'float' to 'bool' implicitly. Wrap it in bool(). The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.
⋯// © maxits-//@version=5+//@version=6// MACD Divergence + Multi Time Frame EMA⋯Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 35 ms | With a workaround 1,000 bars in 96 ms | Not measured |
| PineTS | Not tested | Not tested | Not measured |
Zeal Terminal's engine currently reads an order side written as direction = strategy.long, direction = strategy.short as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 114, 140) so the engine trades the way the script says. The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market.
“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.
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/// © maxits//@version=5// MACD Divergence + Multi Time Frame EMA// This Strategy uses 3 indicators: the Macd and two emas in different time frames// The configuration of the strategy is:// Macd standar configuration (12, 26, 9) in 1H resolution// 10 periods ema, in 1H resolution// 5 periods ema, in 15 minutes resolution// We use the two emas to filter for long and short positions. // If 15 minutes ema is above 1H ema, we look for long positions// If 15 minutes ema is below 1H ema, we look for short positions // We can use an aditional filter using a 100 days ema, so when the 15' and 1H emas are above the daily ema we take long positions// Using this filter improves the strategy // We wait for Macd indicator to form a divergence between histogram and price// If we have a bullish divergence, and 15 minutes ema is above 1H ema, we wait for macd line to cross above signal line and we open a long position// If we have a bearish divergence, and 15 minutes ema is below 1H ema, we wait for macd line to cross below signal line and we open a short position// We close both position after a cross in the oposite direction of macd line and signal line// Also we can configure a Take profit parameter and a trailing stop lossstrategy('Macd Divergence + MTF EMA [Trading Solutions]', overlay=true, initial_capital=1000, default_qty_value=20, default_qty_type=strategy.percent_of_equity, commission_value=0.1, pyramiding=0)// User Inputsi_time = input.time(defval=timestamp('01 Apr 2018 13:30 +0000'), title='Start Time') // Starting time for backtestf_time = input.time(defval=timestamp('30 Sep 2021 13:30 +0000'), title='Finish Time') // Finishing time for backtestlong_pos = input.bool (title='Show Long Positions', defval=true) // Enable Long Positionsshort_pos = input.bool (title='Show Short Positions', defval=true) // Enable Short Positionssrc = input.source(title='Source', defval=close) // Price value to calculate indicatorsemas_properties = "EMAS Settings"mtf_15 = input.timeframe(title='Fast EMA', defval='15', group = emas_properties) // Resolucion para MTF EMA 15 minutesma_15_length = input.int(5, title='Fast EMA Period', group = emas_properties) // MTF EMA 15 minutes Lengthmtf_60 = input.timeframe(title='Slow EMA', defval='60', group = emas_properties) // Resolucion para MTF EMA 60 minutesma_60_length = input.int(10, title='Slow EMA Period', group = emas_properties) // MTF EMA 60 minutes LengthfilterSettings = "Filter Settings"e_new_filter = input.bool (title='Enable a Third Ema filter?', defval=true, group = filterSettings) // Enable Filterslowest_ema_len = input.int (title='Filter EMA Period', defval = 100, group = filterSettings) // Filter EMA Lengthslowest_ema_res = input.timeframe(title='Filter Resolution EMA', defval='D', group = filterSettings) // Filter Resolutionmacd_properties = 'MACD Properties'macd_res = input.timeframe(title='MACD TimeFrame', defval='', group = macd_properties) // MACD Time Framefast_len = input.int (title='Fast Length', defval=12, group = macd_properties) // Fast MA Lengthslow_len = input.int (title='Sign Length', defval=26, group = macd_properties) // Sign MA Lengthsign_len = input.int (title='Sign Length', defval=9, group = macd_properties)syst_properties = 'Trade Management' // Propertieslookback = input.int (title='Lookback period', defval=14, minval=1, group = syst_properties) // Candles to lookback for swing high or lowmultiplier = input.float(title='Profit Multiplier based on Stop Loss', defval=6.0, minval=0.1, group = syst_properties) // Profit multiplier based on stop lossshortStopPer = input.float(title='Short Stop Loss Percentage', defval=1.0, minval=0.0, group = syst_properties) / 100 // Target Percentage longStopPer = input.float(title='Long Stop Loss Percentage', defval=2.0, minval=0.0, group = syst_properties) / 100 // Sloss Percentage// Indicators[macd, signal, hist] = request.security(syminfo.tickerid, macd_res, ta.macd(src, fast_len, slow_len, sign_len))ma_15 = request.security(syminfo.tickerid, mtf_15, ta.ema(src, ma_15_length))ma_60 = request.security(syminfo.tickerid, mtf_60, ta.ema(src, ma_60_length))ma_slo = request.security(syminfo.tickerid, slowest_ema_res, ta.ema(src, slowest_ema_len))// Macd Plotcol_grow_above = #26A69Acol_grow_below = #FFCDD2col_fall_above = #B2DFDBcol_fall_below = #EF5350plot(macd, color=color.new(color.blue, 0)) plot(signal, color=color.new(color.orange, 0))plot(hist, 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)// MTF EMA Plotbullish_filter = e_new_filter ? ma_15 > ma_60 and ma_60 > ma_slo : ma_15 > ma_60bearish_filter = e_new_filter ? ma_15 < ma_60 and ma_60 < ma_slo : ma_15 < ma_60plot(ma_15, color=color.new(color.blue, 0))plot(ma_60, color=color.new(color.yellow, 0))plot(e_new_filter ? ma_slo : na, color=ma_60 > ma_slo ? color.new(color.green, 0) : color.new(color.red, 0))////////////////////////////////////////////// Logic For Macd Divergencezero_cross = falsezero_cross := ta.crossover(hist, 0) or ta.crossunder(hist, 0) //Cruce del Histograma a la linea 0// plot(zero_cross ? 1 : na)// MACD DIVERGENCE TOPS (Bearish Divergence) highest_top = 0.0prior_top = 0.0highest_top := zero_cross == true ? 0.0 : hist > 0 and hist > highest_top[1] ? hist : highest_top[1]prior_top := ta.crossunder(hist, 0) ? highest_top[1] : prior_top[1] highest_top_close = 0.0prior_top_close = 0.0highest_top_close := zero_cross == true ? 0.0 : hist > 0 and hist > highest_top[1] ? close : highest_top_close[1]prior_top_close := ta.crossunder(hist, 0) ? highest_top_close[1] : prior_top_close[1] top = falsetop := highest_top[1] < prior_top[1] and highest_top_close[1] > prior_top_close[1] and hist < hist[1] and ta.crossunder(hist, 0) // Bearish Divergence: top == true // MACD DIVERGENCE BOTTOMS (Bullish Divergence) lowest_bottom = 0.0prior_bottom = 0.0lowest_bottom := zero_cross == true ? 0.0 : hist < 0 and hist < lowest_bottom[1] ? hist : lowest_bottom[1]prior_bottom := ta.crossover(hist, 0) ? lowest_bottom[1] : prior_bottom[1]lowest_bottom_close = 0.0prior_bottom_close = 0.0lowest_bottom_close := zero_cross == true ? 0.0 : hist < 0 and hist < lowest_bottom[1] ? close : lowest_bottom_close[1]prior_bottom_close := ta.crossover(hist, 0) ? lowest_bottom_close[1] : prior_bottom_close[1]bottom = falsebottom := lowest_bottom[1] > prior_bottom[1] and lowest_bottom_close[1] < prior_bottom_close[1] and hist > hist[1] and ta.crossover(hist, 0) // Bullish Divergence: bottom == true ////////////////////////////////////////////// Logic For RSI Divergence////////////////////////////////////////////// System Conditions //////////////////////////////////////////////inTrade = strategy.position_size != 0 // In TradelongTrade = strategy.position_size > 0 // Long positionshortTrade = strategy.position_size < 0 // Short positionnotInTrade = strategy.position_size == 0 // No tradeentryPrice = strategy.position_avg_price // Position Entry Price////////////////////////////////////////////// Long Conditions //////////////////////////////////////////////sl = ta.lowest(low, lookback) // Swing Low for Long EntrylongStopLoss = 0.0 // Trailing Stop Loss calculationlongStopLoss := if longTrade astopValue = sl * (1 - longStopPer) math.max(longStopLoss[1], astopValue)else 0longTakeProf = 0.0 // Profit calculation based on stop losslongTakeProf := if longTrade profitValue = entryPrice + (entryPrice - longStopLoss) * multiplier math.max(longTakeProf[1], profitValue)else 0// Long Entry Conditionsif bottom and notInTrade and bullish_filter and long_pos and barstate.isconfirmed strategy.entry(id='Go Long', direction=strategy.long, comment='Long Position') alert("Long Trade: " + syminfo.ticker, alert.freq_once_per_bar_close) label.new(bar_index, low, text = "Long Trade", textcolor = color.white, color = color.green, style = label.style_label_up)// strategy.close(id="Go Long", when=zero_cross)if longTrade strategy.exit('Exit Long', 'Go Long', limit=longTakeProf, stop=longStopLoss) plot(longTrade and longStopLoss ? longStopLoss : na, title='Long Stop Loss', color=color.new(color.red, 0), style=plot.style_linebr)plot(longTrade and longTakeProf ? longTakeProf : na, title='Long Take Prof', color=color.new(color.green, 0), style=plot.style_linebr)////////////////////////////////////////////// Short Conditions //////////////////////////////////////////////sh = ta.highest(high, lookback) // Swing High for Short EntryshortStopLoss = 0.0shortStopLoss := if shortTrade bstopValue = sh * (1 + shortStopPer) math.min(shortStopLoss[1], bstopValue)else 999999shortTakeProf = 0.0shortTakeProf := if shortTrade SprofitValue = entryPrice - (shortStopLoss - entryPrice) * multiplier math.min(SprofitValue, shortTakeProf[1])else 999999// Short Entryif top and notInTrade and bearish_filter and short_pos and barstate.isconfirmed strategy.entry(id='Go Short', direction=strategy.short, comment='Short Position') alert("Short Trade: " + syminfo.ticker, alert.freq_once_per_bar_close) label.new(bar_index, high, text = "Short Trade", textcolor = color.white, color = color.red, style = label.style_label_down)// strategy.close(id="Go Short", when=zero_cross)if shortTrade strategy.exit('Exit Short', 'Go Short', limit=shortTakeProf, stop=shortStopLoss)plot(shortTrade and shortStopLoss ? shortStopLoss : na, title='Short Stop Loss', color=color.new(color.red, 0), style=plot.style_linebr)plot(shortTrade and shortTakeProf ? shortTakeProf : na, title='Short Take Prof', color=color.new(color.green, 0), style=plot.style_linebr)