Pine Script v5 · Strategy
5min MACD scalp by Joel
A Pine Script v5 strategy built on EMA (close, 50), Crossover and Crossunder. 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 is one contract and pays no commission. 45 settings; defaults include Long TP (%) 0.5, Short TP (%) 0.5 and Long SL (%) 0.4.
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 5min MACD scalp by Joel repaint?
- Yes
- At least one pattern in the source can repaint: intrabar recalculation.
- Does 5min MACD scalp by Joel run in Pine Script v6?
- Not tested
- The v5 script does not run in Zeal Terminal's engine (Pine Script v5 Error at @L5:C0: no source was supplied for the library 'ZenAndTheArtOfTrading/ZenLibrary/2'. 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 5min MACD scalp by Joel use a stop loss?
- Yes
- strategy.exit sets a stop on line 124, 136.
- Does 5min MACD scalp by Joel run in Zeal Terminal?
- No
- Not yet: it imports the library ZenAndTheArtOfTrading/ZenLibrary/2, whose source is not available here, so it does not run here
Review
What a careful reader of this script would point out, found by checking the source.
-
Check
No commission
The backtest assumes free trading. Results on any real exchange will be lower.
-
Note
2 settings have no label
In the settings dialog i_rsiRes (line 37), i_testerPosition (line 51) show an empty name. The labels on this page come from the variable names.
-
Note
No slippage
Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.
-
Note
Uses an argument v6 removed
when = on line 124, 136. The upgraded version below moves each call inside an if block.
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 |
|---|---|---|---|
| Strategy | |||
| Long | true | bool | line 61 |
| Short | true | bool | line 61 |
| Start DateDate & time to begin trading from | timestamp('01 Jan 2020 00:00 +0100') | time | c_dateFilter |
| End DateDate & time to stop trading | timestamp('1 Jan 2099 00:00 +0100') | time | c_dateFilter |
| Long TP (%) | 0.5 | float · min 0.0 · step 0.1 | c_longExitPrice |
| Short TP (%) | 0.5 | float · min 0.0 · step 0.1 | c_shortExitPrice |
| Long SL (%) | 0.4 | float · min 0.0 · step 0.1 | c_longStopPrice |
| Short SL (%) | 0.4 | float · min 0.0 · step 0.1 | c_shortStopPrice |
| Pause trades | |||
| For how many bars?Pauses trades for X bars after a closed trade\n0 = OFF | 0 | int · min 0 | c_longCondition c_shortCondition line 99 |
| Only loosing trades | true | bool | c_longCondition c_shortCondition |
| | How much?Number of loosing trades in a row | 1 | int · min 1 | c_longCondition c_shortCondition line 99 |
| EMAs trend | |||
| Trend typeEma cross - trend based on ema crosses, eg. fast above slow = long and vice versa,\nEma slow/fast - trend based on whether the close price is above/under selected ema | Ema cross | string · options ["Ema cross", "Ema slow", "Ema fast"] | c_emaCrossBull c_emaCrossBear c_emaAbove c_emaUnder |
| Ema fast lenght | 50 | int · step 5 | c_emaFast |
| Ema slow lenght | 200 | int · step 5 | c_emaSlow |
| Valid cross?How many bars back is the cross still valid?\nWhen some of the Emas is selected as an Trend type then it counts the bars since the close price crossed above the selected ema | 350 | int · step 5 | c_longCondition c_shortCondition |
| MACD settings | |||
| MACD resolution | | timeframe | c_hist _ |
| Fast Length | 12 | int · min 1 | c_hist _ |
| Slow Length | 26 | int · min 1 | c_hist _ |
| Signal Smoothing | 9 | int · min 1 · max 50 | c_hist _ |
| Histogram peak finder | |||
| Min histogram valueMinimum for a positive/negative histogram value that is taken into account.\nSet to zero if you want to turn it off. | 0.00000 | float · min 0.00000 | c_histMinLong c_histMinShort |
| Lookback period | 10 | int · min 1 | c_histHighest c_histLowest |
| Compare with histogram average?Highest/Lowest hist bar - Current histogram value must be greater than 100% + X% times the average histogram | false | bool | c_longCondition c_shortCondition |
| Avg histogram lenghtLength of the histogram average, similar to MA length | 50 | int · min 1 · step 5 | c_histBear c_histBull c_histBearAvg c_histBullAvg |
| % above avgHistogram positive/value must be above the average * % | 50 | int · min 1 · step 5 | c_aboveHistAvgLong c_aboveHistAvgShort |
| RSI filter | |||
| Use RSI Filter | false | bool | c_longCondition c_shortCondition |
| I rsi Res (no label in the script) | | timeframe | c_rsiSrc |
| Lenght | 14 | int | c_rsi |
| Min for Long | 0.0 | float · min 0.0 · max 100.0 · step 0.5 | c_longCondition |
| Max for Long | 70.0 | float · min 0.0 · max 100.0 · step 0.5 | c_longCondition |
| Min for Short | 30.0 | float · min 0.0 · max 100.0 · step 0.5 | c_shortCondition |
| Max for Short | 100.0 | float · min 0.0 · max 100.0 · step 0.5 | c_shortCondition |
| RSI direction confirmationLong only if its supported by rising RSI and Short only if its supported by falling RSI\nWorks only if Use RSI is ON | false | bool | c_longCondition c_shortCondition |
| Bars back for directionLookback period for RSI values | 1 | int · min 1 | c_rsiRising c_rsiFalling |
| Pullback filter | |||
| Use Pullback filterThis aims to chatch a possible swing low/high for a better quality position\nFor a long position it checks how many candles were in the opposite direction, so you don't enter the trade when it's been going up for a long time and vice versa | false | bool | c_longCondition c_shortCondition |
| Lookback period | 2 | int · min 1 | c_pullbackCountGreen c_pullbackCountRed |
| More thanHow many candles should be in the opposite direction?\nCan't be bigger than the lookback period | 2 | int · min 1 | c_longCondition c_shortCondition |
| Back tester table | |||
| Show back testerTurn on/off inbuilt backtester display | true | bool | line 170 |
| I tester Position (no label in the script)Position of the backtester table | Top right | string · options ["Top right", "Top left", "Bottom right", "Bottom left"] | testTable |
| R:RRisk:Reward profile | 1.0 | float | balance |
| Starting BalanceYour starting balance for the custom inbuilt tester system | 100.0 | float | balance dollarReturn line 176 line 177 |
| Risk Per TradeYour desired % risk per trade (as a whole number) | 1.0 | float | balance |
| 3Commas bot settings | |||
| Show 3Commas bot comments | false | bool | entry LONG open exit Long close entry SHORT open exit Short close |
| Long Bot ID | | string | entry LONG open exit Long close |
| Short Bot ID | | string | entry SHORT open exit Short close |
| Email Token | | string | entry LONG open exit Long close entry SHORT open exit Short close |
What it calculates
- EMAclose, Ema fast lenght (50)
c_emaFast · line 64 - EMAclose, Ema slow lenght (200)
c_emaSlow · line 65 - Crossoveri_emaOpt == "Ema cross" ? c_emaFast : close, i_emaOpt == "Ema fast" ? c_emaFast : c_emaSlow · chosen by Trend type
c_emaCrossBull · line 66 - Crossunderi_emaOpt == "Ema cross" ? c_emaFast : close, i_emaOpt == "Ema fast" ? c_emaFast : c_emaSlow · chosen by Trend type
c_emaCrossBear · line 67 - Barssincec_emaCrossBull
c_crossBarsBackBull · line 70 - Barssincec_emaCrossBear
c_crossBarsBackBear · line 71 - MACDf_rpSecurity("", i_macdRes, close), Fast Length (12), Slow Length (26), Signal Smoothing (9)
c_hist · line 75 - RSIc_rsiSrc, Lenght (14)
c_rsi · line 81 - Risingc_rsi, Bars back for direction (1)
c_rsiRising · line 91 - Fallingc_rsi, Bars back for direction (1)
c_rsiFalling · line 92
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 77 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 LONG open long | c_longCondition and strategy.opentrades == 0 | On | 120 |
| Exit Long close stop and limit | strategy.opentrades != 0 | On | 124 |
| Open SHORT open short | c_shortCondition and strategy.opentrades == 0 | On | 132 |
| Exit Short close stop and limit | strategy.opentrades != 0 | On | 136 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Does it repaint?
Yes
At least one pattern in the source can repaint; it is marked Check below.
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].
- CheckIntrabar recalculationreads realtime-only state. Live values can differ from history.
- 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.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| Strategy Myth-Busting #13 - MultiEMA+BXTrender - [SP-MYN] by myncrypto | ema rsi rising falling | v5 strategy | −0.3% | 2 | 0.3% |
| RSI of MACD Strategy [Long only] by mohanee | macd rsi ema | v4 strategy | No trades on this market | ||
| PMA Strategy Idea by QuantCT | ema rising falling | v4 strategy | +51.7% | 129 | 30.8% |
| TEMA-DEMA-HMA Strategy by Tuned_Official | ema rising falling | v4 strategy | +73.8% | 4 | 30.6% |
| Linear Cross Trading Strategy by stocktechbot | macd rising falling | v5 strategy | +9.7% | 14 | 2.7% |
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.
- 2 strategy calls use the when = argument (line 124, 136). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
- 3 settings use the untyped input() (line 57, 58, 59). It still compiles in v6; input.int, input.float or input.source state the type.
- No v6-only features. v6 is not needed to run this script.
Clean v5
Not verifiedThe v5 script does not run in Zeal Terminal's engine (Pine Script v5 Error at @L5:C0: no source was supplied for the library 'ZenAndTheArtOfTrading/ZenLibrary/2'. Libraries cannot be fetched from TradingView; supply the source in the 'libraries' option. No libraries were supplied.), so this step could not be checked.
- Line 57: input() → input.string()
- Line 58: input() → input.string()
- Line 59: input() → input.string()
- Line 124: when = strategy.opentrades != 0 → if block
- Line 136: when = strategy.opentrades != 0 → if block
⋯i_useComments = input.bool(false, "Show 3Commas bot comments", group = i_3Commas)-i_botIDLong = input(title="Long Bot ID", defval="", group = i_3Commas)+i_botIDLong = input.string(title="Long Bot ID", defval="", group = i_3Commas)-i_botIDShort = input(title="Short Bot ID", defval="", group = i_3Commas)+i_botIDShort = input.string(title="Short Bot ID", defval="", group = i_3Commas)-i_tokenID = input(title="Email Token", defval="", group = i_3Commas)+i_tokenID = input.string(title="Email Token", defval="", group = i_3Commas)// Get strategy direction and set time⋯ comment = i_useComments ? '{\n "action": "start_bot_and_start_deal",\n "message_type": "bot",\n "bot_id": ' + str.tostring(i_botIDLong) + ',\n "email_token": "' + str.tostring(i_tokenID) + '",\n "delay_seconds": 0}' : na)-strategy.exit(- id = "Long close",- from_entry = "LONG open",- limit = c_longExitPrice,- stop = c_longStopPrice,- when = strategy.opentrades != 0,- comment = i_useComments ? '{\n "action": "close_at_market_price_all_and_stop_bot",\n "message_type": "bot",\n "bot_id": ' + str.tostring(i_botIDLong) + ',\n "email_token": "' + str.tostring(i_tokenID) + '",\n "delay_seconds": 0}' : na)+if strategy.opentrades != 0+ strategy.exit(+ id = "Long close",+ from_entry = "LONG open",+ limit = c_longExitPrice,+ stop = c_longStopPrice,+ comment = i_useComments ? '{\n "action": "close_at_market_price_all_and_stop_bot",\n "message_type": "bot",\n "bot_id": ' + str.tostring(i_botIDLong) + ',\n "email_token": "' + str.tostring(i_tokenID) + '",\n "delay_seconds": 0}' : na)if c_shortCondition and strategy.opentrades == 0⋯ comment = i_useComments ? '{\n "action": "start_bot_and_start_deal",\n "message_type": "bot",\n "bot_id": ' + str.tostring(i_botIDShort) + ',\n "email_token": "' + str.tostring(i_tokenID) + '",\n "delay_seconds": 0}' : na)-strategy.exit(- id = "Short close",- from_entry = "SHORT open",- limit = c_shortExitPrice,- stop = c_shortStopPrice,- when = strategy.opentrades != 0,- comment = i_useComments ? '{\n "action": "close_at_market_price_all_and_stop_bot",\n "message_type": "bot",\n "bot_id": ' + str.tostring(i_botIDShort) + ',\n "email_token": "' + str.tostring(i_tokenID) + '",\n "delay_seconds": 0}' : na)+if strategy.opentrades != 0+ strategy.exit(+ id = "Short close",+ from_entry = "SHORT open",+ limit = c_shortExitPrice,+ stop = c_shortStopPrice,+ comment = i_useComments ? '{\n "action": "close_at_market_price_all_and_stop_bot",\n "message_type": "bot",\n "bot_id": ' + str.tostring(i_botIDShort) + ',\n "email_token": "' + str.tostring(i_tokenID) + '",\n "delay_seconds": 0}' : na)// Plotting emas⋯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 @L5:C0: no source was supplied for the library 'ZenAndTheArtOfTrading/ZenLibrary/2'. 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.
⋯// © Zippy111 and inspired by the youtuber Joel on Crypto-//@version=5+//@version=6strategy("5min MACD scalp by Joel (3commas)", shorttitle = "5m MACD scalp", overlay=true, margin_long=100, margin_short=100)⋯Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | No It imports the library ZenAndTheArtOfTrading/ZenLibrary/2, whose source is not available here, so it does not run here | 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 120, 132) 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/// © Zippy111 and inspired by the youtuber Joel on Crypto//@version=5strategy("5min MACD scalp by Joel (3commas)", shorttitle = "5m MACD scalp", overlay=true, margin_long=100, margin_short=100)import ZenAndTheArtOfTrading/ZenLibrary/2 as l_zenvar g_strategy = "Strategy"i_chkLong = input.bool(true, title = 'Long', inline ='1', group = g_strategy)i_chkShort = input.bool(true, title = 'Short', inline='1', group= g_strategy)i_startTime = input.time(title='Start Date', defval=timestamp('01 Jan 2020 00:00 +0100'), group=g_strategy, tooltip='Date & time to begin trading from')i_endTime = input.time(title='End Date', defval=timestamp('1 Jan 2099 00:00 +0100'), group=g_strategy, tooltip='Date & time to stop trading')i_longProfitPerc = input.float(title='Long TP (%)', minval=0.0, step=0.1, defval=0.5, inline='2', group= g_strategy) * 0.01i_shortProfitPerc = input.float(title='Short TP (%)', minval=0.0, step=0.1, defval=0.5, inline='3', group= g_strategy) * 0.01i_longStopPerc = input.float(title='Long SL (%)', minval=0.0, step=0.1, defval=0.4, inline='2', group= g_strategy) * 0.01i_shortStopPerc = input.float(title='Short SL (%)', minval=0.0, step=0.1, defval=0.4, inline='3', group= g_strategy) * 0.01var g_pause = "Pause trades"i_tradePause = input.int(title= "For how many bars?", defval=0, minval = 0, group= g_pause, tooltip="Pauses trades for X bars after a closed trade\n0 = OFF")i_tradePauseLoss = input.bool(title= "Only loosing trades", defval = true, inline = "4", group= g_pause)i_tradeLossNum = input.int(title= "| How much?", defval=1, minval = 1, group= g_pause, inline = "4", tooltip="Number of loosing trades in a row")var g_ema = "EMAs trend"i_emaOpt = input.string(title = "Trend type", defval = "Ema cross", options = ["Ema cross", "Ema slow", "Ema fast"], group = g_ema, tooltip = "Ema cross - trend based on ema crosses, eg. fast above slow = long and vice versa,\nEma slow/fast - trend based on whether the close price is above/under selected ema")i_emaFast = input.int(title = "Ema fast lenght", defval = 50, step = 5, group = g_ema)i_emaSlow = input.int(title = "Ema slow lenght", defval = 200, step = 5, group = g_ema)i_emaTrendBarsBack = input.int(title = "Valid cross?", defval = 350, step = 5, tooltip = "How many bars back is the cross still valid?\nWhen some of the Emas is selected as an Trend type then it counts the bars since the close price crossed above the selected ema", group = g_ema)var g_macd = "MACD settings"i_macdRes = input.timeframe(title = "MACD resolution", defval = "", group = g_macd)i_macdFastLen = input.int(title="Fast Length", minval = 1, defval=12, group = g_macd)i_macdSlowLen = input.int(title="Slow Length", minval = 1, defval=26, group = g_macd)i_macdSignalLen = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9, group = g_macd)var g_hist = "Histogram peak finder"i_histMin = input.float(title = "Min histogram value", defval = 0.00000, minval = 0.00000, group = g_hist, tooltip = "Minimum for a positive/negative histogram value that is taken into account.\nSet to zero if you want to turn it off.")i_histHighestLookback = input.int(title = "Lookback period", defval = 10, minval = 1, group = g_hist)i_useHistChk = input.bool(false, title = 'Compare with histogram average?', group = g_hist, tooltip = "Highest/Lowest hist bar - Current histogram value must be greater than 100% + X% times the average histogram")i_histAvgLookback = input.int(title = "Avg histogram lenght", defval = 50, minval = 1, step = 5, tooltip = "Length of the histogram average, similar to MA length", group = g_hist)i_aboveHist = input.int(title = "% above avg", defval = 50, minval = 1, step = 5, tooltip = "Histogram positive/value must be above the average * %", group = g_hist) * 0.01 + 1var g_rsi = "RSI filter"i_rsiChk = input.bool(false, "Use RSI Filter", group = g_rsi)i_rsiRes = input.timeframe("", "TimeFrame", group = g_rsi)i_rsiLen = input.int(14, "Lenght", group = g_rsi)i_rsiMinLong = input.float(0.0, "Min for Long", minval = 0.0, maxval = 100.0, step = 0.5, group = g_rsi, inline = "6")i_rsiMaxLong = input.float(70.0, "Max for Long", minval = 0.0, maxval = 100.0, step = 0.5, group = g_rsi, inline = "6")i_rsiMinShort = input.float(30.0, "Min for Short", minval = 0.0, maxval = 100.0, step = 0.5, group = g_rsi, inline = "7")i_rsiMaxShort = input.float(100.0, "Max for Short", minval = 0.0, maxval = 100.0, step = 0.5, group = g_rsi, inline = "7")i_rsiDirectChk = input.bool(false, "RSI direction confirmation", group = g_rsi, tooltip = "Long only if its supported by rising RSI and Short only if its supported by falling RSI\nWorks only if Use RSI is ON")i_rsiDirectLen = input.int(1, "Bars back for direction", minval = 1, group = g_rsi, tooltip = "Lookback period for RSI values")var g_additional = "Pullback filter"i_usePullbackChk = input.bool(false, title = 'Use Pullback filter', group = g_additional, tooltip = "This aims to chatch a possible swing low/high for a better quality position\nFor a long position it checks how many candles were in the opposite direction, so you don't enter the trade when it's been going up for a long time and vice versa")i_pullbackCount = input.int(title="Lookback period", defval=2, minval = 1, group = g_additional)i_pullbackBigger = input.int(title="More than", defval=2, minval = 1, group = g_additional, tooltip = "How many candles should be in the opposite direction?\nCan't be bigger than the lookback period")var g_tester = 'Back tester table'i_drawTester = input.bool(title='Show back tester', defval=true, group=g_tester, tooltip='Turn on/off inbuilt backtester display', inline = "backtester1")i_testerPosition = input.string(title='', defval="Top right", options = ["Top right", "Top left", "Bottom right", "Bottom left"], group=g_tester, tooltip='Position of the backtester table', inline = "backtester1")i_rr = input.float(title='R:R', defval=1.0, group=g_tester, tooltip='Risk:Reward profile')startBalance = input.float(title='Starting Balance', defval=100.0, group=g_tester, tooltip='Your starting balance for the custom inbuilt tester system')riskPerTrade = input.float(title='Risk Per Trade', defval=1.0, group=g_tester, tooltip='Your desired % risk per trade (as a whole number)')var i_3Commas = '3Commas bot settings'i_useComments = input.bool(false, "Show 3Commas bot comments", group = i_3Commas)i_botIDLong = input(title="Long Bot ID", defval="", group = i_3Commas)i_botIDShort = input(title="Short Bot ID", defval="", group = i_3Commas)i_tokenID = input(title="Email Token", defval="", group = i_3Commas)// Get strategy direction and set timestrategy.risk.allow_entry_in(i_chkLong and i_chkShort ? strategy.direction.all : i_chkLong ? strategy.direction.long : strategy.direction.short)c_dateFilter = time >= i_startTime and time <= i_endTime // See if this bar's time happened within date filter// Get Ema trendc_emaFast = ta.ema(close, i_emaFast)c_emaSlow = ta.ema(close, i_emaSlow)c_emaCrossBull = ta.crossover(i_emaOpt == "Ema cross" ? c_emaFast : close, i_emaOpt == "Ema fast" ? c_emaFast : c_emaSlow)c_emaCrossBear = ta.crossunder(i_emaOpt == "Ema cross" ? c_emaFast : close, i_emaOpt == "Ema fast" ? c_emaFast : c_emaSlow)c_emaAbove = (i_emaOpt == "Ema cross" ? c_emaFast >= c_emaSlow : i_emaOpt == "Ema slow" ? close > c_emaSlow : close > c_emaFast)c_emaUnder = (i_emaOpt == "Ema cross" ? c_emaFast < c_emaSlow : i_emaOpt == "Ema slow" ? close < c_emaSlow : close < c_emaFast)c_crossBarsBackBull = ta.barssince(c_emaCrossBull)c_crossBarsBackBear = ta.barssince(c_emaCrossBear)// Get MACD histogramf_rpSecurity(_symbol, _res, _src) => request.security(_symbol, _res, _src[barstate.isrealtime ? 1 : 0])[_, _, c_hist] = ta.macd(f_rpSecurity("", i_macdRes, close), i_macdFastLen, i_macdSlowLen, i_macdSignalLen)c_histBear = math.sum(c_hist > 0 ? (barstate.isrealtime ? c_hist[1] : c_hist[0]) : 0, i_histAvgLookback)c_histBull = math.sum(c_hist < 0 ? math.abs(barstate.isrealtime ? c_hist[1] : c_hist[0]) : 0, i_histAvgLookback)c_histBearAvg = (c_histBear / math.sum(c_hist > 0 ? 1 : 0, i_histAvgLookback))c_histBullAvg = (c_histBull / math.sum(c_hist < 0 ? 1 : 0, i_histAvgLookback))c_rsiSrc = f_rpSecurity("", i_rsiRes, close)c_rsi = ta.rsi(c_rsiSrc, i_rsiLen)// Sub-Condition calculationsc_histMinLong = math.abs(c_hist) > i_histMinc_histMinShort = c_hist > i_histMin c_aboveHistAvgLong = math.abs(c_hist) >= i_aboveHist * c_histBullAvgc_aboveHistAvgShort = c_hist >= (i_aboveHist * c_histBearAvg)c_histHighest = ta.highestbars(c_hist, i_histHighestLookback) == 0 or ta.highestbars(c_hist, i_histHighestLookback)[1] == 0c_histLowest = ta.highestbars(math.abs(c_hist), i_histHighestLookback) == 0 or ta.lowestbars(math.abs(c_hist), i_histHighestLookback)[1] == 0c_pullbackCountGreen = l_zen.getPullbackBarCount(i_pullbackCount, 1)c_pullbackCountRed = l_zen.getPullbackBarCount(i_pullbackCount, -1)c_rsiRising = ta.rising(c_rsi, i_rsiDirectLen)c_rsiFalling = ta.falling(c_rsi, i_rsiDirectLen)c_sinceLastTrade = ta.barssince(strategy.closedtrades > strategy.closedtrades[1]) c_sinceLastLossTrade = ta.barssince(strategy.losstrades > strategy.losstrades[1])var c_countLosstrades = 0switch strategy.losstrades > strategy.losstrades[1] => c_countLosstrades += 1 strategy.wintrades > strategy.wintrades[1] => c_countLosstrades := 0 c_countLosstrades == i_tradeLossNum and c_sinceLastLossTrade > i_tradePause => c_countLosstrades := 0 c_emaCrossBull or c_emaCrossBear => c_countLosstrades := 0// Final Long/Short conditionsc_longCondition = c_dateFilter and (i_tradePauseLoss ? (i_tradePause != 0 ? c_countLosstrades < i_tradeLossNum : true) and (strategy.losstrades != 0 ? c_sinceLastLossTrade >= i_tradePause : true) : (strategy.closedtrades != 0 ? c_sinceLastTrade >= i_tradePause : true)) and (c_emaAbove and (c_crossBarsBackBull <= i_emaTrendBarsBack)) and (i_rsiChk ? (c_rsi >= i_rsiMinLong and c_rsi <= i_rsiMaxLong and (i_rsiDirectChk ? c_rsiRising : true)) : true) and ((c_hist < 0 and c_histMinLong ? c_histLowest : false) and (i_useHistChk ? c_aboveHistAvgLong : true)) and (i_usePullbackChk ? (c_pullbackCountRed >= i_pullbackBigger) : true) c_shortCondition = c_dateFilter and (i_tradePauseLoss ? (i_tradePause != 0 ? c_countLosstrades < i_tradeLossNum : true) and (strategy.losstrades != 0 ? c_sinceLastLossTrade >= i_tradePause : true) : (strategy.closedtrades != 0 ? c_sinceLastTrade >= i_tradePause : true)) and (c_emaUnder and (c_crossBarsBackBear <= i_emaTrendBarsBack)) and (i_rsiChk ? (c_rsi >= i_rsiMinShort and c_rsi <= i_rsiMaxShort and (i_rsiDirectChk ? c_rsiFalling : true)) : true) and ((c_hist >= 0 and c_histMinShort ? c_histHighest : false) and (i_useHistChk ? c_aboveHistAvgShort : true)) and (i_usePullbackChk ? (c_pullbackCountGreen >= i_pullbackBigger) : true)c_longExitPrice = strategy.position_avg_price * (1 + i_longProfitPerc)c_shortExitPrice = strategy.position_avg_price * (1 - i_shortProfitPerc)c_longStopPrice = strategy.position_avg_price * (1 - i_longStopPerc)c_shortStopPrice = strategy.position_avg_price * (1 + i_shortStopPerc)if c_longCondition and strategy.opentrades == 0 strategy.entry( id = "LONG open", direction = strategy.long, comment = i_useComments ? '{\n "action": "start_bot_and_start_deal",\n "message_type": "bot",\n "bot_id": ' + str.tostring(i_botIDLong) + ',\n "email_token": "' + str.tostring(i_tokenID) + '",\n "delay_seconds": 0}' : na)strategy.exit( id = "Long close", from_entry = "LONG open", limit = c_longExitPrice, stop = c_longStopPrice, when = strategy.opentrades != 0, comment = i_useComments ? '{\n "action": "close_at_market_price_all_and_stop_bot",\n "message_type": "bot",\n "bot_id": ' + str.tostring(i_botIDLong) + ',\n "email_token": "' + str.tostring(i_tokenID) + '",\n "delay_seconds": 0}' : na)if c_shortCondition and strategy.opentrades == 0 strategy.entry( id = "SHORT open", direction = strategy.short, comment = i_useComments ? '{\n "action": "start_bot_and_start_deal",\n "message_type": "bot",\n "bot_id": ' + str.tostring(i_botIDShort) + ',\n "email_token": "' + str.tostring(i_tokenID) + '",\n "delay_seconds": 0}' : na)strategy.exit( id = "Short close", from_entry = "SHORT open", limit = c_shortExitPrice, stop = c_shortStopPrice, when = strategy.opentrades != 0, comment = i_useComments ? '{\n "action": "close_at_market_price_all_and_stop_bot",\n "message_type": "bot",\n "bot_id": ' + str.tostring(i_botIDShort) + ',\n "email_token": "' + str.tostring(i_tokenID) + '",\n "delay_seconds": 0}' : na)// Plotting emasplot(c_emaFast, "Ema fast", color = color.new(#4db6ac, 40), linewidth = 2, display = display.none) plot(c_emaSlow, "Ema slow", color = color.new(#f57c00, 40), linewidth = 2, display = display.none) // --- BEGIN TESTER CODE --- //// Declare performance tracking variablesvar balance = startBalancevar maxBalance = 0.0var totalWins = 0var totalLoss = 0// Detect winning tradesif strategy.wintrades != strategy.wintrades[1] balance := balance + riskPerTrade / 100 * balance * i_rr totalWins := totalWins + 1 if balance > maxBalance maxBalance := balance maxBalance// Detect losing tradesif strategy.losstrades != strategy.losstrades[1] balance := balance - riskPerTrade / 100 * balance totalLoss := totalLoss + 1// Prepare stats tablevar table testTable = table.new(i_testerPosition == "Top right" ? position.top_right : i_testerPosition == "Top left" ? position.top_left : i_testerPosition == "Bottom right" ? position.bottom_right :position.bottom_left, 5, 2, border_width=2)f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) => _cellText = _title + '\n' + _value table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor)// Draw stats tablevar bgcolor = color.new(color.black, 0)if i_drawTester if barstate.islastconfirmedhistory // Update table dollarReturn = balance - startBalance f_fillCell(testTable, 0, 0, 'Total Trades:', str.tostring(strategy.closedtrades), bgcolor, color.white) f_fillCell(testTable, 0, 1, 'Win Rate:', str.tostring(l_zen.truncate(strategy.wintrades / strategy.closedtrades * 100, 2)) + '%', (strategy.wintrades / strategy.closedtrades * 100) >= 50 ? color.green : bgcolor, color.white) f_fillCell(testTable, 1, 0, 'Starting:', '$' + str.tostring(startBalance), bgcolor, color.white) f_fillCell(testTable, 1, 1, 'Ending:', '$' + str.tostring(l_zen.truncate(balance, 2)), balance > startBalance ? color.green : bgcolor, color.white)// --- END BACKTESTER CODE --- //