Zeal Terminal Open Zeal Terminal

Pine Script v4 · Strategy

EMA pullback strategy

A Pine Script v4 strategy built on EMA (close, 33). 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 0.075 commission. 10 settings; defaults include Take Profit Stop Loss ratio 2.06, lowest risk per trade 0.008 and highest risk per trade 0.025.

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 EMA pullback strategy repaint?
No
No repainting patterns were found in the source.
Can EMA pullback strategy be converted to Pine Script v5?
Not tested
The steps are shown below, but the original does not run in Zeal Terminal's engine, so they could not be checked.
Does EMA pullback strategy use a stop loss?
Yes
strategy.exit sets a stop on line 80, 86.
Does EMA pullback strategy run in Zeal Terminal?
No
Not yet: Pine Script v4 Error at @L102:C58: 'strategy.max_drawdown' is not available in Pine Script v4. It was added in a later version.
Does not run in Zeal Terminal yetPine Script v4 Error at @L102:C58: 'strategy.max_drawdown' is not available in Pine Script v4. It was added in a later version. 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.

  • 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 66, 74. The upgraded version below moves each call inside an if block.

  • Note

    Uses transp =, which v5 removed line 93

    transp = on line 93, 94, 108, 109. 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 ema → ta.ema, crossover → ta.crossover, crossunder → ta.crossunder, tostring → str.tostring.
  • 2 strategy calls use the when = argument (line 66, 74). It is deprecated in v5 and removed in v6, where each call moves inside an if block.

v4 → v5

Not verified

The v4 script does not run in Zeal Terminal's engine (Pine Script v4 Error at @L102:C58: 'strategy.max_drawdown' is not available in Pine Script v4. It was added in a later version.), so this step could not be checked.

  • Line 3: //@version=4 → //@version=5
  • Line 5: input(type = input.float) → input.float()
  • Line 6: input(type = input.float) → input.float()
  • Line 7: input(type = input.float) → input.float()
  • Line 9: input(type = input.integer) → input.int()
  • Line 10: input(type = input.integer) → input.int()
21 more edits
  • Line 11: input(type = input.integer) → input.int()
  • Line 12: input(type = input.integer) → input.int()
  • Line 13: input(type = input.integer) → input.int()
  • Line 14: input(type = input.integer) → input.int()
  • Line 17: ema → ta.ema
  • Line 18: ema → ta.ema
  • Line 19: ema → ta.ema
  • Line 25: crossover → ta.crossover
  • Line 35: crossunder → ta.crossunder
  • Line 46: crossover → ta.crossover
  • Line 47: crossunder → ta.crossunder
  • Line 93: transp = 90 removed: the call sets no colour to fold it into, so its default colour loses the transparency
  • Line 94: transp = 90 removed: the call sets no colour to fold it into, so its default colour loses the transparency
  • Line 99: tostring → str.tostring
  • Line 100: tostring → str.tostring
  • Line 101: tostring → str.tostring
  • Line 101: tostring → str.tostring
  • Line 101: tostring → str.tostring
  • Line 102: tostring → str.tostring
  • Line 108: transp = 90 removed: the call sets no colour to fold it into, so its default colour loses the transparency
  • Line 109: transp = 0 removed: the call sets no colour to fold it into, so its default colour loses the transparency
⋯// created by Space Jellyfish-//@version=4+//@version=5strategy("EMA pullback strategy", overlay = true, initial_capital=10000, commission_value = 0.075)-target_stop_ratio = input(title="Take Profit Stop Loss ratio", type=input.float, defval=2.06, minval=0.5, maxval=100)+target_stop_ratio = input.float(title="Take Profit Stop Loss ratio", defval=2.06, minval=0.5, maxval=100)-riskLimit_low =  input(title="lowest risk per trade", type=input.float, defval=0.008, minval=0, maxval=100)+riskLimit_low =  input.float(title="lowest risk per trade", defval=0.008, minval=0, maxval=100)-riskLimit_high =  input(title="highest risk per trade", type=input.float, defval=0.025, minval=0, maxval=100)+riskLimit_high =  input.float(title="highest risk per trade", defval=0.025, minval=0, maxval=100)//give up the trade, if the risk is smaller than limit, adjust position size if risk is bigger than limit-ema_pullbackLevel_period = input(title="EMA1 for pullback level Period", type=input.integer, defval=33, minval=1, maxval=10000)+ema_pullbackLevel_period = input.int(title="EMA1 for pullback level Period", defval=33, minval=1, maxval=10000)-ema_pullbackLimiit_period = input(title="EMA2 for pullback limit Period", type=input.integer, defval=165, minval=1, maxval=10000)+ema_pullbackLimiit_period = input.int(title="EMA2 for pullback limit Period", defval=165, minval=1, maxval=10000)-ema_trend_period = input(title="EMA3 for trend Period", type=input.integer, defval=365, minval=1, maxval=10000)+ema_trend_period = input.int(title="EMA3 for trend Period", defval=365, minval=1, maxval=10000)-startDate = input(title="Start Date", type=input.integer, defval=1, minval=1, maxval=31)+startDate = input.int(title="Start Date", defval=1, minval=1, maxval=31)-startMonth = input(title="Start Month", type=input.integer, defval=1, minval=1, maxval=12)+startMonth = input.int(title="Start Month", defval=1, minval=1, maxval=12)-startYear = input(title="Start Year", type=input.integer, defval=2018, minval=2008, maxval=2200)+startYear = input.int(title="Start Year", defval=2018, minval=2008, maxval=2200)label_forward_offset = input(25, title = "offset label")inDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0))-ema_pullbackLevel = ema(close, ema_pullbackLevel_period)+ema_pullbackLevel = ta.ema(close, ema_pullbackLevel_period)-ema_pullbackLimit = ema(close, ema_pullbackLimiit_period)+ema_pullbackLimit = ta.ema(close, ema_pullbackLimiit_period)-ema_trendDirection = ema(close, ema_trend_period)+ema_trendDirection = ta.ema(close, ema_trend_period)//ema pullback ⋯float pricePullBelowMA_minLow = na-if(crossover(close, ema_pullbackLevel))+if(ta.crossover(close, ema_pullbackLevel))    pricePullAboveEMA_maxClose := close⋯    pricePullAboveEMA_maxHigh := high-if(crossunder(close, ema_pullbackLevel))+if(ta.crossunder(close, ema_pullbackLevel))    pricePullBelowEMA_minClose := close⋯    pricePullBelowMA_minLow := low-long_strategy = crossover(close, ema_pullbackLevel) and pricePullBelowEMA_minClose < ema_pullbackLimit and ema_pullbackLevel>ema_trendDirection +long_strategy = ta.crossover(close, ema_pullbackLevel) and pricePullBelowEMA_minClose < ema_pullbackLimit and ema_pullbackLevel>ema_trendDirection -short_strategy = crossunder(close, ema_pullbackLevel) and pricePullAboveEMA_maxClose > ema_pullbackLimit and ema_pullbackLevel<ema_trendDirection+short_strategy = ta.crossunder(close, ema_pullbackLevel) and pricePullAboveEMA_maxClose > ema_pullbackLimit and ema_pullbackLevel<ema_trendDirectionfloat risk_long = na⋯p_tp = plot(takeProfit, color = color.green, linewidth = 1, style = plot.style_linebr, title="takeProfit")-fill(p_tp, p_ep, color.new(color.green, transp = 90))+fill(p_tp, p_ep, color.new(color.green))-fill(p_sl, p_ep, color.new(color.red, transp = 90))+fill(p_sl, p_ep, color.new(color.red))label_text = ""⋯else-    label_text := "Open: " + strategy.position_entry_name + " " + tostring(strategy.position_size)+    label_text := "Open: " + strategy.position_entry_name + " " + str.tostring(strategy.position_size)-label_text := label_text + "\n\nNet Profit: " + tostring(strategy.netprofit/strategy.initial_capital * 100, '#.##') + "%" +label_text := label_text + "\n\nNet Profit: " + str.tostring(strategy.netprofit/strategy.initial_capital * 100, '#.##') + "%" -label_text := label_text + "\nWin Rate: "+ tostring(strategy.wintrades/(strategy.wintrades+strategy.losstrades) * 100, '#.##') + "%" + "\n  wins: " +  tostring(strategy.wintrades) +  "\n  loses: " +  tostring(strategy.losstrades)+label_text := label_text + "\nWin Rate: "+ str.tostring(strategy.wintrades/(strategy.wintrades+strategy.losstrades) * 100, '#.##') + "%" + "\n  wins: " +  str.tostring(strategy.wintrades) +  "\n  loses: " +  str.tostring(strategy.losstrades)-label_text := label_text + "\nMax Draw Down: " + tostring(strategy.max_drawdown/strategy.initial_capital * 100, '#.##') + "%" +label_text := label_text + "\nMax Draw Down: " + str.tostring(strategy.max_drawdown/strategy.initial_capital * 100, '#.##') + "%" lbl = label.new(⋯     yloc = yloc.price, -     color = color.new(color.silver, transp = 90), +     color = color.new(color.silver), -     textcolor = color.new(color.white, transp = 0),+     textcolor = color.new(color.white),     size = size.normal,⋯

Clean v5

Not verified

The v5 script does not run in Zeal Terminal's engine (Pine Script v5 Error at @L93:C17: No value assigned to the `transp` parameter in color.new()), so this step could not be checked.

  • Line 15: input() → input.int()
  • Line 66: when = long_strategy → if block
  • Line 74: when = short_strategy → if block
⋯startYear = input.int(title="Start Year", defval=2018, minval=2008, maxval=2200)-label_forward_offset = input(25, title = "offset label")+label_forward_offset = input.int(25, title = "offset label")inDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0))⋯    if(risk_long > riskLimit_low)-        strategy.entry("long", strategy.long, qty = entryContracts, when = long_strategy)+        if long_strategy+            strategy.entry("long", strategy.long, qty = entryContracts)if (strategy.position_size == 0 and short_strategy and inDateRange)⋯    if(risk_short > riskLimit_low)-        strategy.entry("short", strategy.short, qty = entryContracts, when = short_strategy)+        if short_strategy+            strategy.entry("short", strategy.short, qty = entryContracts)//take profit / stop loss⋯

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 @L95:C17: No value assigned to the `transp` parameter in color.new()), 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.

⋯// created by Space Jellyfish-//@version=5+//@version=6strategy("EMA pullback strategy", overlay = true, initial_capital=10000, commission_value = 0.075)⋯

Settings

Every input the script declares, with its default and what it feeds. Bounds are the ones the script enforces.

SettingDefaultType and rangeFeeds
Take Profit Stop Loss ratio2.06float · min 0.5 · max 100takeProfit
lowest risk per trade0.008float · min 0 · max 100entry long entry short line 65 line 73
highest risk per trade0.025float · min 0 · max 100entryContracts line 60 line 69
EMA1 for pullback level Period33int (written input.integer) · min 1 · max 10000ema_pullbackLevel
EMA2 for pullback limit Period165int (written input.integer) · min 1 · max 10000ema_pullbackLimit
EMA3 for trend Period365int (written input.integer) · min 1 · max 10000ema_trendDirection
Start Date1int (written input.integer) · min 1 · max 31inDateRange
Start Month1int (written input.integer) · min 1 · max 12inDateRange
Start Year2018int (written input.integer) · min 2008 · max 2200inDateRange
offset label25intlbl

What it calculates

  • EMA (ema, ta.ema in v5)close, EMA1 for pullback level Period (33)ema_pullbackLevel · line 17
  • EMA (ema, ta.ema in v5)close, EMA2 for pullback limit Period (165)ema_pullbackLimit · line 18
  • EMA (ema, ta.ema in v5)close, EMA3 for trend Period (365)ema_trendDirection · line 19

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 dataema_pullbackLevel_periodEMA1 for pullback level…setting · 33ema_pullbackLimiit_periodEMA2 for pullback limit…setting · 165ema_trend_periodEMA3 for trend Periodsetting · 365highhighprice datalowlowprice datatarget_stop_ratioTake Profit Stop Loss r…setting · 2.06riskLimit_highhighest risk per tradesetting · 0.025timetimeprice datastartYearStart Yearsetting · 2018startMonthStart Monthsetting · 1startDateStart Datesetting · 1label_forward_offsetoffset labelsetting · 25ema_pullbackLevelEMA→ ema_pullbackLevelema_pullbackLimitEMA→ ema_pullbackLimitema_trendDirectionEMA→ ema_trendDirectionpricePullAboveEMA_maxClosepricePullAboveEMA_maxCl…valuepricePullAboveEMA_maxHighpricePullAboveEMA_maxHi…valuepricePullBelowEMA_minClosepricePullBelowEMA_minCl…valuepricePullBelowMA_minLowpricePullBelowMA_minLowvaluerisk_longrisk_longvaluerisk_shortrisk_shortvaluestopLossstopLossvaluetakeProfittakeProfitvalueentry_priceentry_pricevalueentryContractsentryContractsvaluelong_strategylong_strategyconditionshort_strategyshort_strategyconditioninDateRangeinDateRangeconditionlblColourlblentry:longOpen longstrategy.entryentry:shortOpen shortstrategy.entryexit:Long exitexit Long exitstrategy.exitexit:Short exitexit Short exitstrategy.exitplot:87ema pullback levelplotplot:88ema pullback limitplotplot:89ema trendplotplot:90entry_priceplotplot:91stopLossplotplot:92takeProfitplotfill:93Fillfill × 2fill:94Fillfill × 2

Order rules

OrderFires whenBy defaultLine
Open long longlong_strategycrossover(close, ema_pullbackLevel) and pricePullBelowEMA_minClose < ema_pullbackLimit and ema_pullbackLevel>ema_trendDirectionOn66
Open short shortshort_strategycrossunder(close, ema_pullbackLevel) and pricePullAboveEMA_maxClose > ema_pullbackLimit and ema_pullbackLevel<ema_trendDirectionOn74
Exit Long exit stop and limit(strategy.position_size > 0)On80
Exit Short exit stop and limit(strategy.position_size < 0)On86

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

Similar scripts

Indicators and strategies built from the same calculations.

ScriptSharesTypeNetTradesMax drawdown
EMA Slope AyE by fajardoarelysemav4 strategyNo trades on this market
ROoT by realisticDove62527emav5 strategy−4.7%2259.4%
sachin5986 by mohitesachin78emav4 strategy+32.1%3517.6%
sonu1997 by Sonu1997emav4 strategy+960.7%21,103.8%
Moving Average Crossover by Muh4mm4demav4 strategy+19,990.1%301,274.2%

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2No Pine Script v4 Error at @L102:C58: 'strategy.max_drawdown' is not available in Pine Script v4. It was added in a later version.Not measured
PineTSNo v5 and v6 only—Not measured

“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/// created by Space Jellyfish//@version=4strategy("EMA pullback strategy", overlay = true, initial_capital=10000, commission_value = 0.075)target_stop_ratio = input(title="Take Profit Stop Loss ratio", type=input.float, defval=2.06, minval=0.5, maxval=100)riskLimit_low =  input(title="lowest risk per trade", type=input.float, defval=0.008, minval=0, maxval=100)riskLimit_high =  input(title="highest risk per trade", type=input.float, defval=0.025, minval=0, maxval=100)//give up the trade, if the risk is smaller than limit, adjust position size if risk is bigger than limitema_pullbackLevel_period = input(title="EMA1 for pullback level Period", type=input.integer, defval=33, minval=1, maxval=10000)ema_pullbackLimiit_period = input(title="EMA2 for pullback limit Period", type=input.integer, defval=165, minval=1, maxval=10000)ema_trend_period = input(title="EMA3 for trend Period", type=input.integer, defval=365, minval=1, maxval=10000)startDate = input(title="Start Date", type=input.integer, defval=1, minval=1, maxval=31)startMonth = input(title="Start Month", type=input.integer, defval=1, minval=1, maxval=12)startYear = input(title="Start Year", type=input.integer, defval=2018, minval=2008, maxval=2200)label_forward_offset = input(25, title = "offset label")inDateRange = (time >= timestamp(syminfo.timezone, startYear, startMonth, startDate, 0, 0))ema_pullbackLevel = ema(close, ema_pullbackLevel_period)ema_pullbackLimit = ema(close, ema_pullbackLimiit_period)ema_trendDirection = ema(close, ema_trend_period)//ema pullback float pricePullAboveEMA_maxClose = nafloat pricePullAboveEMA_maxHigh = nafloat pricePullBelowEMA_minClose = nafloat pricePullBelowMA_minLow = naif(crossover(close, ema_pullbackLevel))    pricePullAboveEMA_maxClose := close    pricePullAboveEMA_maxHigh := highelse    pricePullAboveEMA_maxClose := pricePullAboveEMA_maxClose[1]    pricePullAboveEMA_maxHigh := pricePullAboveEMA_maxHigh[1]if(close > pricePullAboveEMA_maxClose)    pricePullAboveEMA_maxClose := closeif(high > pricePullAboveEMA_maxHigh)    pricePullAboveEMA_maxHigh := highif(crossunder(close, ema_pullbackLevel))    pricePullBelowEMA_minClose := close    pricePullBelowMA_minLow := lowelse    pricePullBelowEMA_minClose :=pricePullBelowEMA_minClose[1]    pricePullBelowMA_minLow:=pricePullBelowMA_minLow[1]    if(close < pricePullBelowEMA_minClose)    pricePullBelowEMA_minClose := closeif(low < pricePullBelowMA_minLow)    pricePullBelowMA_minLow := lowlong_strategy = crossover(close, ema_pullbackLevel) and pricePullBelowEMA_minClose < ema_pullbackLimit and ema_pullbackLevel>ema_trendDirection short_strategy = crossunder(close, ema_pullbackLevel) and pricePullAboveEMA_maxClose > ema_pullbackLimit and ema_pullbackLevel<ema_trendDirectionfloat risk_long = nafloat risk_short = nafloat stopLoss = nafloat takeProfit = nafloat entry_price = nafloat entryContracts = 0risk_long := risk_long[1]risk_short := risk_short[1]    //open a position determine the position sizeif (strategy.position_size == 0 and long_strategy and inDateRange)    risk_long := (close - pricePullBelowMA_minLow) / close    if(risk_long < riskLimit_high)        entryContracts := strategy.equity / close    else        entryContracts := (strategy.equity * riskLimit_high / risk_long)/close        if(risk_long > riskLimit_low)        strategy.entry("long", strategy.long, qty = entryContracts, when = long_strategy)if (strategy.position_size == 0 and short_strategy and inDateRange)    risk_short := (pricePullAboveEMA_maxHigh - close) / close    if(risk_short < riskLimit_high)        entryContracts := strategy.equity / close    else        entryContracts := (strategy.equity * riskLimit_high / risk_short)/close    if(risk_short > riskLimit_low)        strategy.entry("short", strategy.short, qty = entryContracts, when = short_strategy)//take profit / stop lossif(strategy.position_size > 0)    stopLoss :=   strategy.position_avg_price*(1 - risk_long)    takeProfit :=  strategy.position_avg_price*(1 + target_stop_ratio * risk_long)    entry_price := strategy.position_avg_price    strategy.exit("Long exit","long", limit = takeProfit , stop = stopLoss)    if(strategy.position_size < 0)    stopLoss :=  strategy.position_avg_price*(1 + risk_short)    takeProfit :=  strategy.position_avg_price*(1 - target_stop_ratio * risk_short)    entry_price := strategy.position_avg_price    strategy.exit("Short exit","short", limit = takeProfit, stop = stopLoss)plot(ema_pullbackLevel, color=color.aqua,  title="ema pullback level")plot(ema_pullbackLimit, color=color.purple,  title="ema pullback limit")plot(ema_trendDirection, color=color.white,  title="ema trend")p_ep = plot(entry_price, color = color.yellow, linewidth = 1, style = plot.style_linebr, title="entry_price")p_sl = plot(stopLoss, color = color.red, linewidth = 1, style = plot.style_linebr, title="stopLoss")p_tp = plot(takeProfit, color = color.green, linewidth = 1, style = plot.style_linebr, title="takeProfit")fill(p_tp, p_ep, color.new(color.green, transp = 90))fill(p_sl, p_ep, color.new(color.red, transp = 90))label_text = ""if(strategy.position_size == 0)    label_text := "No Open Position"else    label_text := "Open: " + strategy.position_entry_name + " " + tostring(strategy.position_size)label_text := label_text + "\n\nNet Profit: " + tostring(strategy.netprofit/strategy.initial_capital * 100, '#.##') + "%" label_text := label_text + "\nWin Rate: "+ tostring(strategy.wintrades/(strategy.wintrades+strategy.losstrades) * 100, '#.##') + "%" + "\n  wins: " +  tostring(strategy.wintrades) +  "\n  loses: " +  tostring(strategy.losstrades)label_text := label_text + "\nMax Draw Down: " + tostring(strategy.max_drawdown/strategy.initial_capital * 100, '#.##') + "%" lbl = label.new(     x = time + label_forward_offset *(time - time[1]),      y = close, text = label_text,      xloc = xloc.bar_time,      yloc = yloc.price,      color = color.new(color.silver, transp = 90),      textcolor = color.new(color.white, transp = 0),     size = size.normal,     textalign = text.align_left     )label.delete(lbl[1])//