Zeal Terminal Open Zeal Terminal

Pine Script v5 · Strategy

[2022] MACD Cross Strategy (version 1)

A Pine Script v5 strategy built on MACD (close, 12), EMA (close, 200) and ATR (14). It has 8 order rules, 4 entries among them, and trades long and short with the default settings. Exits use a stop loss and a profit target. Each trade commits 100% of equity and pays no commission. 14 settings; defaults include EMA Filter Length 200, EMA Max Bars Above/Below 1 and Stop Loss Multiplier 0.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 [2022] MACD Cross Strategy (version 1) repaint?
No
No repainting patterns were found in the source.
Does [2022] MACD Cross Strategy (version 1) run in Pine Script v6?
Not tested
The v5 script does not run in Zeal Terminal's engine (Pine Script v5 Error at @L24:C0: no source was supplied for the library 'ZenAndTheArtOfTrading/ZenLibrary/5'. Libraries cannot be fetched from TradingView; supply the source in the 'libraries' option. No libraries were supplied.), so this step could not be checked. The v6 version is shown for reference and is not offered as a download.
Does [2022] MACD Cross Strategy (version 1) use a stop loss?
Yes
strategy.exit sets a stop on line 144, 145, 146, 147.
Does [2022] MACD Cross Strategy (version 1) run in Zeal Terminal?
No
Not yet: it imports the library ZenAndTheArtOfTrading/ZenLibrary/5, whose source is not available here, so it does not run here
Does not run in Zeal Terminal yetIt imports the library ZenAndTheArtOfTrading/ZenLibrary/5, whose source is not available here, so it does not run here. The settings, logic and review below are read from the source, which does not need a run.

Review

What a careful reader of this script would point out, found by checking the source.

  • Check

    2 settings do nothing

    “Oscillator MA Type”, “Signal Line MA Type” are declared but never read.

  • Check

    No commission

    The backtest assumes free trading. Results on any real exchange will be lower.

  • Check

    Every trade uses all the equity

    default_qty_value is 100% of equity.

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

SettingDefaultType and rangeFeeds
System Entry Settings
EMA Filter Length200intema
EMA Max Bars Above/Below1intlongTrade shortTrade
Stop Loss Multiplier0.5float · step 0.5longStop shortStop
Stop Loss Lookback7intlongStop shortStop
System Risk Settings
Risk:Reward Target 11.0floattradeTarget1
Risk:Reward Target 22.0floattradeTarget2
Profit % Target 125floatexit Long Exit #1 exit Short Exit #1
Forex Risk Per Trade %1.0floatpositionSize
MACD Settings
Price SourceclosesourcemacdLine signalLine histLine
Fast Length12intmacdLine signalLine histLine
Slow Length26intmacdLine signalLine histLine
Signal Smoothing9int · min 1 · max 50macdLine signalLine histLine
Oscillator MA TypeEMAstring · options ["SMA", "EMA"]unused
Signal Line MA TypeEMAstring · options ["SMA", "EMA"]unused

What it calculates

  • MACDPrice Source (close), Fast Length (12), Slow Length (26), Signal Smoothing (9)macdLine · line 58
  • MACDPrice Source (close), Fast Length (12), Slow Length (26), Signal Smoothing (9)signalLine · line 58
  • MACDPrice Source (close), Fast Length (12), Slow Length (26), Signal Smoothing (9)histLine · line 58
  • EMAclose, EMA Filter Length (200)ema · line 60
  • ATR14atr · line 61
  • CrossoversignalLine, macdLinecrossUp · line 63
  • CrossundersignalLine, macdLinecrossDown · line 64
  • Lowestlow, Stop Loss Lookback (7)longStop · line 77
  • Highesthigh, Stop Loss Lookback (7)shortStop · line 78

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.

closecloseprice datai_fast_lengthFast Lengthsetting · 12i_slow_lengthSlow Lengthsetting · 26i_signal_lengthSignal Smoothingsetting · 9i_ema_filterEMA Filter Lengthsetting · 200high · low · closehigh · low · closeprice datalowlowprice datai_stop_lookbackStop Loss Lookbacksetting · 7i_stop_multiStop Loss Multipliersetting · 0.5highhighprice datai_rr1Risk:Reward Target 1setting · 1.0i_rr2Risk:Reward Target 2setting · 2.0i_riskPerTradeForex Risk Per Trade %setting · 1.0i_ema_filter2EMA Max Bars Above/Belowsetting · 1macdLineMACD→ macdLinesignalLineMACD→ signalLinehistLineMACD→ histLineemaEMA→ emaatrATR→ atrcrossUpCrossover→ crossUpcrossDownCrossunder→ crossDownlongStopLowest→ longStopshortStopHighest→ shortStopconversionCurrencyPairconversionCurrencyPairvalueconversionCurrencyRateconversionCurrencyRatevaluetradeStoptradeStopvaluetradeTarget1tradeTarget1valuetradeTarget2tradeTarget2valuetradeSizetradeSizevaluestopDistancestopDistancevaluepositionSizepositionSizevalueaccountSameAsCounterCurrency, accountSameAsBaseCurrency, accountNeitherCurrencyaccountSameAsCounterCur…3 conditionstradeFilterstradeFiltersconditionupTrend, downTrendupTrend · downTrend2 conditionslongConditions, shortConditionslongConditions · shortC…2 conditionslongSignallongSignalconditionshortSignalshortSignalconditionlongTradelongTradeconditionshortTradeshortTradeconditiontColourtentry:LongOpen Longstrategy.entryentry:ShortOpen Shortstrategy.entryexit:Long Exit #1exit Long Exit #1strategy.exitexit:Long Exit #2exit Long Exit #2strategy.exitexit:Short Exit #1exit Short Exit #1strategy.exitexit:Short Exit #2exit Short Exit #2strategy.exitplot:153EMAplotplotshape:154Long Setupplotshapeplotshape:155Short Setupplotshapeplot:157Stop Lossplotplot:158Profit Target 1plotplot:159Profit Target 2plot

Order rules

OrderFires whenBy defaultLine
Open Long longsyminfo.type == "forex"On104
Open Long longsyminfo.type == "forex"On106
Open Short shortsyminfo.type == "forex"On119
Open Short shortsyminfo.type == "forex"On121
Exit Long Exit #1 stop and limitevery barOn144
Exit Long Exit #2 stop and limitevery barOn145
Exit Short Exit #1 stop and limitevery barOn146
Exit Short Exit #2 stop and limitevery barOn147

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.

The live replay needs a run, and this script does not run in Zeal Terminal yet; the answer comes from the checks on the source alone.

  • ClearHigher-timeframe data1 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.

Similar scripts

Indicators and strategies built from the same calculations.

ScriptSharesTypeNetTradesMax drawdown
255 EMA Strategy by tweakerIDema macd atr lowest highestv4 strategy−218.4%11186.1%
Richard's Strategy by Deepak8369highest lowest atr emav4 strategy+34.6%7026.3%
Classic Long Term Trend Following System by Robrecht99ema highest lowest atrv5 strategy+2.9%51.1%
Macd Divergence + MTF EMA by Trading_Solutions_macd ema lowest highestv5 strategyNo trades on this market
Strategy Myth-Busting #1 - UT Bot+STC+Hull [MYN] by myncryptoatr ema lowest highestv5 strategy−30.7%1063.5%

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

Verified

Nothing to change.

Does it run in Pine Script v6?

Not tested

The v5 script does not run in Zeal Terminal's engine (Pine Script v5 Error at @L24:C0: no source was supplied for the library 'ZenAndTheArtOfTrading/ZenLibrary/5'. Libraries cannot be fetched from TradingView; supply the source in the 'libraries' option. No libraries were supplied.), so this step could not be checked. The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯//-// @version=5+// @version=6strategy("[2022] MACD Cross Strategy", overlay=true,⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2No It imports the library ZenAndTheArtOfTrading/ZenLibrary/5, whose source is not available here, so it does not run hereNot measured
PineTSNot testedNot testedNot 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 104, 106, 119, 121) 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.

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///// System Rules:// Indicators: MACD indicator (default values), ATR (14), EMA (200)// 1. Price must be trading above/below the 200 EMA// 2. Only 1 bar can close above/below the 200 EMA over the past 5 bars// 3. We take the FIRST MACD cross and ignore subsequent signals until TP/SL is hit// 4. Stop Loss = 0.5 ATR above/below the recent swing high/low (7 bars lookback)// 5. First take profit = 1:1 (25%)// 6. Second take profit = 2:1 (100%)// 7. Move stop loss to break-even after 1st target is hit//// @version=5strategy("[2022] MACD Cross Strategy", overlay=true,     currency="USD",     calc_on_order_fills=true,     use_bar_magnifier=false,     initial_capital=10000,     default_qty_type=strategy.percent_of_equity,     default_qty_value=100, // 100% of balance invested on each trade     commission_type=strategy.commission.cash_per_contract)     //commission_value=0.005) // Interactive Brokers rate// Import ZenLibraryimport ZenAndTheArtOfTrading/ZenLibrary/5 as zen// Get user inputvar g_system    = "System Entry Settings"i_ema_filter    = input.int(title="EMA Filter Length", defval=200, group=g_system)i_ema_filter2   = input.int(title="EMA Max Bars Above/Below", defval=1, group=g_system)i_stop_multi    = input.float(title="Stop Loss Multiplier", defval=0.5, step=0.5, group=g_system)i_stop_lookback = input.int(title="Stop Loss Lookback", defval=7, group=g_system)var g_risk      = "System Risk Settings"i_rr1           = input.float(title="Risk:Reward Target 1", defval=1.0, group=g_risk)i_rr2           = input.float(title="Risk:Reward Target 2", defval=2.0, group=g_risk)i_target1       = input.float(title="Profit % Target 1", defval=25, group=g_risk)i_riskPerTrade  = input.float(title="Forex Risk Per Trade %", defval=1.0)var g_macd      = "MACD Settings"i_price_src     = input.source(title="Price Source", defval=close, group=g_macd)i_fast_length   = input.int(title="Fast Length", defval=12, group=g_macd)i_slow_length   = input.int(title="Slow Length", defval=26, group=g_macd)i_signal_length = input.int(title="Signal Smoothing", minval=1, maxval=50, defval=9, group=g_macd)i_sma_source    = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"], group=g_macd)i_sma_signal    = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"], group=g_macd)//------------- DETERMINE CURRENCY CONVERSION RATE -------------//// Check if our account currency is the same as the base or quote currency or neither (for risk $ conversion purposes)accountSameAsCounterCurrency = strategy.account_currency == syminfo.currencyaccountSameAsBaseCurrency = strategy.account_currency == syminfo.basecurrencyaccountNeitherCurrency = not accountSameAsCounterCurrency and not accountSameAsBaseCurrency// Get currency conversion rates if applicableconversionCurrencyPair = accountSameAsCounterCurrency ? syminfo.tickerid : strategy.account_currency + syminfo.currencyconversionCurrencyRate = accountSameAsBaseCurrency or accountNeitherCurrency ? request.security(conversionCurrencyPair, "D", close, ignore_invalid_symbol=true) : 1.0// Display the current conversion currency ticker (for debug purposes)if barstate.islastconfirmedhistory    table t = table.new(position.top_right, 1, 2, color.black)    table.cell(t, 0, 0, "Conversion: " + conversionCurrencyPair + " (" + str.tostring(conversionCurrencyRate) + ")", text_color=color.white, text_size=size.small)    table.cell(t, 0, 1, "Account: $" + str.tostring(zen.truncate(strategy.equity)), text_color=color.white, text_size=size.small)//------------- END CURRENCY CONVERSION RATE CODE -------------//// Calculate MACD[macdLine, signalLine, histLine] = ta.macd(i_price_src, i_fast_length, i_slow_length, i_signal_length)// Get indicator valuesema = ta.ema(close, i_ema_filter)atr = ta.atr(14)// Check for zero-point crossescrossUp     = ta.crossover(signalLine, macdLine)crossDown   = ta.crossunder(signalLine, macdLine)// Check general system filterstradeFilters = not na(ema) and not na(atr)// Check trend conditionsupTrend     = close > emadownTrend   = close < ema// Check trade conditionslongConditions  = tradeFilters and macdLine[1] < 0 and signalLine[1] < 0shortConditions = tradeFilters and macdLine[1] > 0 and signalLine[1] > 0// Confirm long & short setupslongSignal   = longConditions and upTrend and crossDownshortSignal  = shortConditions and downTrend and crossUp// Calculate stop losslongStop    = ta.lowest(low, i_stop_lookback) - (atr * i_stop_multi)shortStop   = ta.highest(high, i_stop_lookback) + (atr * i_stop_multi)// Save stops & targetsvar float tradeStop = navar float tradeTarget1 = navar float tradeTarget2 = navar float tradeSize = na// Count bars above/below MAint barsAboveMA = 0int barsBelowMA = 0for i = 1 to 5    if close[i] < ema[i]        barsBelowMA += 1    if close[i] > ema[i]        barsAboveMA += 1// Combine signal filterslongTrade   = longSignal  and barsBelowMA <= i_ema_filter2 and strategy.position_size == 0shortTrade  = shortSignal and barsAboveMA <= i_ema_filter2 and strategy.position_size == 0// Handle long trade entry (enter position, reset stops & targets)if longTrade    if syminfo.type == "forex"        tradeStop := longStop        stopDistance = close - tradeStop        tradeTarget1 := close + (stopDistance * i_rr1)        tradeTarget2 := close + (stopDistance * i_rr2)        tradeSize := na        positionSize = zen.av_getPositionSize(strategy.equity, i_riskPerTrade, zen.toWhole(stopDistance) * 10, conversionCurrencyRate)        strategy.entry(id="Long", direction=strategy.long, qty=positionSize)    else        strategy.entry(id="Long", direction=strategy.long)        tradeStop := na        tradeTarget1 := na        tradeTarget2 := na// Handle short trade entry (enter position, reset stops & targets)if shortTrade    if syminfo.type == "forex"        tradeStop := shortStop        stopDistance = tradeStop - close        tradeTarget1 := close - (stopDistance * i_rr1)        tradeTarget2 := close - (stopDistance * i_rr2)        tradeSize := na        positionSize = zen.av_getPositionSize(strategy.equity, i_riskPerTrade, zen.toWhole(shortStop - close) * 10, conversionCurrencyRate)        strategy.entry(id="Short", direction=strategy.short, qty=positionSize)    else        strategy.entry(id="Short", direction=strategy.short)        tradeStop := na        tradeTarget1 := na        tradeTarget2 := na    // Handle forex trade size tracking variableif syminfo.type == "forex" and strategy.position_size != 0 and na(tradeSize)    tradeSize := strategy.position_size// Handle long stops & target calculationif strategy.position_size > 0 and na(tradeStop) and syminfo.type != "forex"    tradeStop := longStop    stopDistance = strategy.position_avg_price - tradeStop    tradeTarget1 := strategy.position_avg_price + (stopDistance * i_rr1)    tradeTarget2 := strategy.position_avg_price + (stopDistance * i_rr2)    tradeSize := strategy.position_size// Handle short stops & target calculationif strategy.position_size < 0 and na(tradeStop) and syminfo.type != "forex"    tradeStop := shortStop    stopDistance = tradeStop - strategy.position_avg_price    tradeTarget1 := strategy.position_avg_price - (stopDistance * i_rr1)    tradeTarget2 := strategy.position_avg_price - (stopDistance * i_rr2)    tradeSize := strategy.position_size// Handle trade exitsstrategy.exit(id="Long Exit #1",  from_entry="Long",  limit=tradeTarget1, stop=tradeStop, qty_percent=i_target1)strategy.exit(id="Long Exit #2",  from_entry="Long",  limit=tradeTarget2, stop=tradeStop, qty_percent=100)strategy.exit(id="Short Exit #1", from_entry="Short", limit=tradeTarget1, stop=tradeStop, qty_percent=i_target1)strategy.exit(id="Short Exit #2", from_entry="Short", limit=tradeTarget2, stop=tradeStop, qty_percent=100)// Handle both long & short trade break-even stops (do this AFTER first position has exited above ^)if strategy.position_size != tradeSize    tradeStop := strategy.position_avg_price    tradeTarget1 := na// Draw conditional dataplot(ema, color=close > ema ? color.green : color.red, linewidth=2, title="EMA")plotshape(longTrade,  style=shape.triangleup,   color=color.green, location=location.belowbar, title="Long Setup")plotshape(shortTrade, style=shape.triangledown, color=color.red,   location=location.abovebar, title="Short Setup")// Draw stops & targetsplot(strategy.position_size != 0 ? tradeStop : na,   color=color.red,   style=plot.style_linebr, title="Stop Loss")plot(strategy.position_size != 0 ? tradeTarget1 : na, color=color.green, style=plot.style_linebr, title="Profit Target 1")plot(strategy.position_size != 0 ? tradeTarget2 : na, color=color.green, style=plot.style_linebr, title="Profit Target 2")