Zeal Terminal Open in Zeal Terminal

Pine Script v4 · Strategy

ZEGUELA DEMABOT

A Pine Script v4 strategy built on EMA (series, length). It has 7 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 90% of equity and pays 0.070% commission. 15 settings; defaults include Source Data close, Length DEMA #1 8 and Length DEMA #2 21.

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 ZEGUELA DEMABOT repaint?
No
No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 18 of 18 trades.
How did ZEGUELA DEMABOT do on BTCUSDT 1D with default settings?
+29.26%
From 26 Jan 2024 to 21 Oct 2026, over 78 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Can ZEGUELA DEMABOT be converted to Pine Script v5?
No
The automatic step from v4 to v5 changes the results, so no v5 download is offered; the edits are shown below.
Does ZEGUELA DEMABOT use a stop loss?
Yes
strategy.exit sets a stop on line 148, 151, 154, 156.
Does ZEGUELA DEMABOT run in Zeal Terminal?
Yes
It compiles in 55 ms and runs 1,000 bars in 140 ms, in the browser.

BTCUSDT · 1D · default settings

  • DEMA #1
  • DEMA #2
  • Entry Price
  • Long Stop
  • Long TP
  • Short Stop
  • Short TP
  • Winning trade
  • Losing trade
  • Equity
  • Buy and hold
Prerendered with the defaults. Change anything and run it here. The script runs in your browser.
Settings (15)
Stop Loss = 73060.2Take Profit = 113649.2Entry Price = 81178Stop Loss = 87846.843Take Profit = 75297.294Entry Price = 83663.66Pos: short50,000100,000150,000AprJulOct2025AprJulOct2026AprJulOct$128$203Equity from $100
Binance BTCUSDT 1D candles, 26 Jan 2024 to 21 Oct 2026, 1,000 bars, default settings. Triangles mark entries; circles mark exits. Lines are what the script plots. Lines, boxes and labels are the script's own drawings, the most recent ones its limits keep.
Net profit
+29.26%
$29.26
Buy and hold
+102.5%
same period
Closed trades
78
29 won · 49 lost
Profitable
37.2%
of closed trades
Profit factor
1.13
gross profit ÷ gross loss
Max drawdown
42.99%
−$78.00

One run with the author's default settings, $100 starting capital, commission as the script sets it. A short 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.

  • Note

    No slippage

    Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.

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, max → math.max, min → math.min, tostring → str.tostring, highest → ta.highest.

v4 → v5

Differs

Trades differ: 78 before, 78 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.

  • Line 4: //@version=4 → //@version=5
  • Line 8: input(type = input.source) → input.source()
  • Line 10: input(type = input.integer) → input.int()
  • Line 11: input(type = input.integer) → input.int()
  • Line 12: input(type = input.integer) → input.int()
  • Line 17: ema → ta.ema
32 more edits
  • Line 18: ema → ta.ema
  • Line 28: crossover → ta.crossover
  • Line 31: crossover → ta.crossover
  • Line 34: crossover → ta.crossover
  • Line 36: crossover → ta.crossover
  • Line 39: crossunder → ta.crossunder
  • Line 42: crossunder → ta.crossunder
  • Line 45: crossunder → ta.crossunder
  • Line 47: crossunder → ta.crossunder
  • Line 55: input(type = input.bool) → input.bool()
  • Line 56: input(type = input.float) → input.float()
  • Line 57: input(type = input.float) → input.float()
  • Line 58: input(type = input.float) → input.float()
  • Line 59: input(type = input.float) → input.float()
  • Line 69: max → math.max
  • Line 76: min → math.min
  • Line 116: input(type = input.integer) → input.int()
  • Line 118: input(type = input.integer) → input.int()
  • Line 120: input(type = input.integer) → input.int()
  • Line 122: input(type = input.integer) → input.int()
  • Line 124: input(type = input.integer) → input.int()
  • Line 126: input(type = input.integer) → input.int()
  • Line 169: tostring → str.tostring
  • Line 170: tostring → str.tostring
  • Line 171: tostring → str.tostring
  • Line 172: tostring → str.tostring
  • Line 173: tostring → str.tostring
  • Line 218: max → math.max
  • Line 218: highest → ta.highest
  • Line 221: tostring → str.tostring
  • Line 222: tostring → str.tostring
  • Line 223: tostring → str.tostring
⋯// ©zeguela-//@version=4+//@version=5strategy(title="ZEGUELA DEMABOT", commission_value=0.070, commission_type=strategy.commission.percent, initial_capital=100, default_qty_value=90, default_qty_type=strategy.percent_of_equity, overlay=true, process_orders_on_close=true)⋯// Input options-srcData = input(title="Source Data", type=input.source, defval=close)+srcData = input.source(title="Source Data", defval=close)// Length settings-len1 = input(title="Length DEMA #1", type=input.integer, defval=8, minval=1)+len1 = input.int(title="Length DEMA #1", defval=8, minval=1)-len2 = input(title="Length DEMA #2", type=input.integer, defval=21, minval=0)+len2 = input.int(title="Length DEMA #2", defval=21, minval=0)-len3 = input(title="Length DEMA #3", type=input.integer, defval=0, minval=0)+len3 = input.int(title="Length DEMA #3", defval=0, minval=0)// Step 2. Calculate indicator values⋯    if (length > 0)-        emaValue = ema(series, length)+        emaValue = ta.ema(series, length)-        2 * emaValue - ema(emaValue, length)+        2 * emaValue - ta.ema(emaValue, length)    else⋯demaCrossover = if (len2 > 0) and (len3 > 0)-    crossover(demaVal1, demaVal2) and (demaVal3 > demaVal3[1])+    ta.crossover(demaVal1, demaVal2) and (demaVal3 > demaVal3[1])else    if (len2 > 0) and (len3 == 0)-        crossover(demaVal1, demaVal2)+        ta.crossover(demaVal1, demaVal2)    else        if (len3 > 0) and (len2 == 0)-            crossover(demaVal1, demaVal3)+            ta.crossover(demaVal1, demaVal3)        else-            crossover(close, demaVal1)+            ta.crossover(close, demaVal1)// Check if there's a DEMA crossunderdemaCrossunder = if (len2 > 0) and (len3 > 0)-    crossunder(demaVal1, demaVal2) and (demaVal3 < demaVal3[1])+    ta.crossunder(demaVal1, demaVal2) and (demaVal3 < demaVal3[1])else    if (len2 > 0) and (len3 == 0)-        crossunder(demaVal1, demaVal2)+        ta.crossunder(demaVal1, demaVal2)    else        if (len3 > 0) and (len2 == 0)-            crossunder(demaVal1, demaVal3)+            ta.crossunder(demaVal1, demaVal3)        else-            crossunder(close, demaVal1)+            ta.crossunder(close, demaVal1)// Step 4. Output indicator data⋯//TRAILING STOP CODE-a = input(title="Usar Trailing Stop?", type=input.bool, defval=false)+a = input.bool(title="Usar Trailing Stop?", defval=false)-stopPerlong = input(10.0, title='Stop Loss Long %', type=input.float, group="Stop Loss & Take Profit Settings") / 100+stopPerlong = input.float(10.0, title='Stop Loss Long %', group="Stop Loss & Take Profit Settings") / 100-stopPershort = input(5.0, title='Stop Loss Short %', type=input.float, group="Stop Loss & Take Profit Settings") / 100+stopPershort = input.float(5.0, title='Stop Loss Short %', group="Stop Loss & Take Profit Settings") / 100-take1Perlong = input(40.0, title='Take Profit Long % 1', type=input.float, group="Stop Loss & Take Profit Settings") / 100+take1Perlong = input.float(40.0, title='Take Profit Long % 1', group="Stop Loss & Take Profit Settings") / 100-take1Pershort = input(10.0, title='Take Profit Short % 1', type=input.float, group="Stop Loss & Take Profit Settings") / 100+take1Pershort = input.float(10.0, title='Take Profit Short % 1', group="Stop Loss & Take Profit Settings") / 100// Determine stop loss price⋯    stopValue = close * (1 - stopPerlong)-    max(stopValue, longStopPriceTrail[1])+    math.max(stopValue, longStopPriceTrail[1])else⋯    stopValue = close * (1 + stopPershort)-    min(stopValue, shortStopPriceTrail[1])+    math.min(stopValue, shortStopPriceTrail[1])else⋯// Make input options that configure backtest date range-_startDate = input(title="Start Date", type=input.integer,+_startDate = input.int(title="Start Date",     defval=1, minval=1, maxval=31, group="BackTest Period")-_startMonth = input(title="Start Month", type=input.integer,+_startMonth = input.int(title="Start Month",     defval=4, minval=1, maxval=12, group="BackTest Period")-_startYear = input(title="Start Year", type=input.integer,+_startYear = input.int(title="Start Year",     defval=2021, minval=1800, maxval=2100, group="BackTest Period")-_endDate = input(title="End Date", type=input.integer,+_endDate = input.int(title="End Date",     defval=31, minval=1, maxval=31, group="BackTest Period")-_endMonth = input(title="End Month", type=input.integer,+_endMonth = input.int(title="End Month",     defval=12, minval=1, maxval=12, group="BackTest Period")-_endYear = input(title="End Year", type=input.integer,+_endYear = input.int(title="End Year",     defval=2031, minval=1800, maxval=2100, group="BackTest Period")⋯// Insert label with value-stopLossOnLong = "Stop Loss = " + tostring(longStop)+stopLossOnLong = "Stop Loss = " + str.tostring(longStop)-stopLossOnShort = "Stop Loss = " + tostring(shortStop)+stopLossOnShort = "Stop Loss = " + str.tostring(shortStop)-takeprofitOnLong = "Take Profit = " + tostring(longTake1Price)+takeprofitOnLong = "Take Profit = " + str.tostring(longTake1Price)-takeprofitOnShort = "Take Profit = " + tostring(shortTake1Price)+takeprofitOnShort = "Take Profit = " + str.tostring(shortTake1Price)-precoentrada = "Entry Price = " + tostring(strategy.position_avg_price)+precoentrada = "Entry Price = " + str.tostring(strategy.position_avg_price)var label FinalLabelpriceL = na⋯label.delete(lb)-lb := label.new(bar_index, max(high, highest(4)[1]), textcolor=color.white,+lb := label.new(bar_index, math.max(high, ta.highest(4)[1]), textcolor=color.white,   color=posCol,   text="Pos: "+ posDir +-      "\nPnL: "+tostring(posProfit, "#.##")+"%" ++      "\nPnL: "+str.tostring(posProfit, "#.##")+"%" +-      "\nAvg Price: "+tostring(strategy.position_avg_price, "#.####") ++      "\nAvg Price: "+str.tostring(strategy.position_avg_price, "#.####") +-      "\nClose: "+tostring(close, "#.####"))+      "\nClose: "+str.tostring(close, "#.####"))

Clean v5

Verified

Nothing 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 @L189:C32: cannot use the history-referencing operator '[]' on the literal '0' in Pine Script v6. The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯// ©zeguela-//@version=5+//@version=6strategy(title="ZEGUELA DEMABOT", commission_value=0.070, commission_type=strategy.commission.percent, initial_capital=100, default_qty_value=90, default_qty_type=strategy.percent_of_equity, overlay=true, process_orders_on_close=true)⋯

Settings

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

SettingDefaultType and rangeFeeds
Source DataclosesourcedemaVal1 demaVal2 demaVal3
Length DEMA #18int (written input.integer) · min 1demaVal1
Length DEMA #221int (written input.integer) · min 0demaVal2 demaCrossover demaCrossunder
Length DEMA #30int (written input.integer) · min 0demaVal3 demaCrossover demaCrossunder
Usar Trailing Stop?falseboollongStop shortStop
Stop Loss & Take Profit Settings
Stop Loss Long %10.0floatlongStopPrice longStopPriceTrail longStopEntrada stopL stopValue
Stop Loss Short %5.0floatshortStopPrice stopValue shortStopPriceTrail shortStopEntrada stopS
Take Profit Long % 140.0floatlongTake1Price longTPEntrada takeL
Take Profit Short % 110.0floatshortTake1Price shortTPEntrada takeS
BackTest Period
Start Date1int (written input.integer) · min 1 · max 31_inDateRange
Start Month4int (written input.integer) · min 1 · max 12_inDateRange
Start Year2021int (written input.integer) · min 1800 · max 2100_inDateRange
End Date31int (written input.integer) · min 1 · max 31_inDateRange
End Month12int (written input.integer) · min 1 · max 12_inDateRange
End Year2031int (written input.integer) · min 1800 · max 2100_inDateRange

What it calculates

  • EMA (ema, ta.ema in v5)series, lengthemaValue · line 17

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

OrderFires whenBy defaultLine
Open LONG long(demaCrossover)On147
Exit Close Long TP1 stop and limit(demaCrossover)On148
Open SHORT short(demaCrossunder)On150
Exit Close Short TP1 stop and limit(demaCrossunder)On151
Exit TP/SL stop and limitstrategy.position_size > 0On154
Exit TP/SL stop and limitstrategy.position_size < 0On156
Close (not _inDateRange)On208

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.

18/18trades identical when replayed liveThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, four per bar, and compared with the historical run. Orders are decided once per closed bar, so nothing can change mid-bar.
  • 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 timingprocess_orders_on_close = true: orders fill at the signal bar's close.

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.

MarketNetBuy and holdTradesWonProfit factorMax drawdownPeriod
BTCUSDT 1D+29.3%+102.5%7837%1.1343.0%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h+5.6%+5.5%7337%1.0817.2%8 May 2026 – 21 Oct 2026
ETHUSDT 1D+1.5%+9.8%7535%1.0143.9%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h−6.7%+8.4%7729%0.9329.7%8 May 2026 – 21 Oct 2026
SOLUSDT 1D+300.4%+16.7%5949%1.9823.1%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+1.0%+21.5%7334%1.0130.0%8 May 2026 – 21 Oct 2026
BNBUSDT 1D−30.4%+148.3%7536%0.8242.4%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+1.0%+17.1%8132%1.0117.5%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 barsTradesWonP&L
Rising market2339%$12.23
Sideways market3746%$20.06
Falling market1817%−$2.95

Rising and falling mean the market moved more than 15% over the 90 bars before entry.

How bad could the drawdown be?

48.2%

The 95th percentile of the worst drawdown when the same 78 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 24.0% to 48.2%; the tick is what actually happened, 41.7%. Order luck alone moves it this much.

0%55%
All 78 trades
SideEntryExitBarsP&L
short15 Mar 2024 69,499.9019 Mar 2024 62,549.904$8.87
long23 Apr 2024 66,414.0024 Apr 2024 64,289.601−$3.27
short24 Apr 2024 64,289.601 May 2024 57,860.607$9.38
long5 May 2024 64,012.0011 May 2024 60,826.006−$5.29
short11 May 2024 60,826.0012 May 2024 61,484.001−$1.21
long12 May 2024 61,484.0030 May 2024 68,352.2018$10.76
short30 May 2024 68,352.204 Jun 2024 70,537.805−$3.58
long4 Jun 2024 70,537.808 Jun 2024 69,310.504−$1.96
short8 Jun 2024 69,310.5024 Jun 2024 62,379.4016$10.10
long2 Jul 2024 62,135.503 Jul 2024 60,208.601−$3.61
short3 Jul 2024 60,208.605 Jul 2024 54,187.702$10.67
long12 Jul 2024 57,889.1031 Jul 2024 64,628.0019$13.53
short31 Jul 2024 64,628.004 Aug 2024 58,165.204$12.82
long17 Aug 2024 59,492.0018 Aug 2024 58,427.301−$2.73
short18 Aug 2024 58,427.3019 Aug 2024 59,438.501−$2.60
long19 Aug 2024 59,438.5029 Aug 2024 59,359.0010−$0.37
short29 Aug 2024 59,359.006 Sep 2024 53,423.108$13.45
long11 Sep 2024 57,338.001 Oct 2024 60,805.8020$8.76
short1 Oct 2024 60,805.807 Oct 2024 63,846.106−$8.04
long14 Oct 2024 66,084.0025 Oct 2024 66,698.3011$1.18
short25 Oct 2024 66,698.3028 Oct 2024 70,033.303−$7.72
long28 Oct 2024 69,962.202 Nov 2024 69,374.705−$1.40
short2 Nov 2024 69,374.706 Nov 2024 72,843.504−$7.30
long6 Nov 2024 75,572.0025 Nov 2024 93,010.0019$31.01
short25 Nov 2024 93,010.0029 Nov 2024 97,660.504−$8.40
long16 Dec 2024 106,059.0018 Dec 2024 100,204.002−$8.80
short18 Dec 2024 100,204.004 Jan 2025 98,220.5017$2.72
long4 Jan 2025 98,220.509 Jan 2025 92,552.505−$8.88
short9 Jan 2025 92,552.5014 Jan 2025 97,180.105−$7.32
long15 Jan 2025 100,497.0028 Jan 2025 101,336.0013$0.94
short28 Jan 2025 101,336.0030 Jan 2025 106,402.002−$7.02
long20 Feb 2025 98,305.0024 Feb 2025 91,552.904−$9.11
short24 Feb 2025 91,552.9026 Feb 2025 82,397.602$12.04
long5 Mar 2025 90,606.009 Mar 2025 81,545.404−$13.45
short9 Mar 2025 80,734.4014 Mar 2025 84,771.105−$6.21
long15 Mar 2025 84,338.4031 Mar 2025 82,550.0016−$2.60
short31 Mar 2025 82,550.001 Apr 2025 85,158.301−$3.73
long1 Apr 2025 85,158.306 Apr 2025 78,430.005−$8.80
short6 Apr 2025 78,430.009 Apr 2025 82,351.503−$5.22
long11 Apr 2025 83,423.805 May 2025 94,733.7024$12.98
short5 May 2025 94,733.706 May 2025 96,834.001−$2.56
long6 May 2025 96,834.0017 May 2025 103,127.0011$6.75
short17 May 2025 103,127.0020 May 2025 106,850.003−$4.21
long20 May 2025 106,850.0024 May 2025 107,762.004$0.77
short24 May 2025 107,762.0010 Jun 2025 110,274.0017−$2.70
long10 Jun 2025 110,274.0012 Jun 2025 105,672.002−$4.60
short12 Jun 2025 105,672.0025 Jun 2025 107,341.0013−$1.77
long25 Jun 2025 107,341.0021 Jul 2025 117,380.0026$9.30
short21 Jul 2025 117,380.0010 Aug 2025 119,294.0020−$1.94
long10 Aug 2025 119,294.0016 Aug 2025 117,381.006−$1.88
short16 Aug 2025 117,381.005 Sep 2025 110,660.0020$5.92
long5 Sep 2025 110,660.0022 Sep 2025 112,651.0017$1.85
short22 Sep 2025 112,651.001 Oct 2025 118,284.009−$5.81
long1 Oct 2025 118,595.0010 Oct 2025 106,735.009−$10.91
short10 Oct 2025 112,775.0025 Oct 2025 111,646.0015$0.84
long25 Oct 2025 111,646.003 Nov 2025 106,583.009−$4.61
short3 Nov 2025 106,583.0014 Nov 2025 95,924.7011$9.33
long26 Nov 2025 90,484.0017 Dec 2025 86,243.2021−$4.96
short17 Dec 2025 86,243.2020 Dec 2025 88,360.903−$2.56
long20 Dec 2025 88,360.9020 Jan 2026 88,427.7031−$0.06
short20 Jan 2026 88,427.7031 Jan 2026 79,584.9011$9.48
long15 Feb 2026 68,832.6022 Mar 2026 67,859.0035−$1.62
short22 Mar 2026 67,859.0024 Mar 2026 71,251.902−$5.31
long25 Mar 2026 71,336.5026 Mar 2026 68,820.301−$3.60
short26 Mar 2026 68,820.305 Apr 2026 69,034.2010−$0.43
long5 Apr 2026 69,034.2028 Apr 2026 76,342.8023$9.89
short28 Apr 2026 76,342.804 May 2026 80,159.906−$5.33
long4 May 2026 79,861.0012 May 2026 80,504.508$0.66
short12 May 2026 80,504.501 Jun 2026 72,454.0020$9.81
long13 Jun 2026 64,458.0026 Jun 2026 60,097.3013−$7.47
short26 Jun 2026 60,097.301 Jul 2026 60,024.005−$0.02
long1 Jul 2026 60,024.0027 Jul 2026 63,755.9026$6.17
short27 Jul 2026 63,755.907 Aug 2026 64,923.2011−$2.11
long7 Aug 2026 64,923.2011 Aug 2026 63,600.004−$2.29
short11 Aug 2026 63,600.0018 Aug 2026 64,725.407−$1.97
long18 Aug 2026 64,725.402 Sep 2026 77,340.0015$19.60
short2 Sep 2026 77,340.004 Sep 2026 81,270.402−$6.22
long20 Sep 2026 81,178.0029 Sep 2026 83,663.709$3.31

Similar scripts

Indicators and strategies built from the same calculations, run on BTCUSDT 1D with their own defaults so they can be compared directly.

ScriptSharesTypeNetTradesMax drawdown
ZEGUELA DEMABOT this page—v4 strategy+29.3%7843.0%
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 v2Yes 55 msYes 1,000 bars in 140 msNot 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/// This code is based on the study you can find here: https://kodify.net/tradingview/indicators/dema/// ©zeguela//@version=4strategy(title="ZEGUELA DEMABOT", commission_value=0.070, commission_type=strategy.commission.percent, initial_capital=100, default_qty_value=90, default_qty_type=strategy.percent_of_equity, overlay=true, process_orders_on_close=true)// Step 1. Script settings// Input optionssrcData = input(title="Source Data", type=input.source, defval=close)// Length settingslen1 = input(title="Length DEMA #1", type=input.integer, defval=8, minval=1)len2 = input(title="Length DEMA #2", type=input.integer, defval=21, minval=0)len3 = input(title="Length DEMA #3", type=input.integer, defval=0, minval=0)// Step 2. Calculate indicator values// Function that calculates the DEMADEMA(series, length) =>    if (length > 0)        emaValue = ema(series, length)        2 * emaValue - ema(emaValue, length)    else        na// Calculate the DEMA valuesdemaVal1 = DEMA(srcData, len1)demaVal2 = DEMA(srcData, len2)demaVal3 = DEMA(srcData, len3)// Step 3. Determine indicator signals// See if there's a DEMA crossoverdemaCrossover = if (len2 > 0) and (len3 > 0)    crossover(demaVal1, demaVal2) and (demaVal3 > demaVal3[1])else    if (len2 > 0) and (len3 == 0)        crossover(demaVal1, demaVal2)    else        if (len3 > 0) and (len2 == 0)            crossover(demaVal1, demaVal3)        else            crossover(close, demaVal1)// Check if there's a DEMA crossunderdemaCrossunder = if (len2 > 0) and (len3 > 0)    crossunder(demaVal1, demaVal2) and (demaVal3 < demaVal3[1])else    if (len2 > 0) and (len3 == 0)        crossunder(demaVal1, demaVal2)    else        if (len3 > 0) and (len2 == 0)            crossunder(demaVal1, demaVal3)        else            crossunder(close, demaVal1)// Step 4. Output indicator data// Plot DEMAs on the chartplot(series=demaVal1, color=color.green, linewidth=2, title="DEMA #1")plot(series=demaVal2, color=color.red, linewidth=2, title="DEMA #2")plot(series=demaVal3, color=color.fuchsia, linewidth=2, title="DEMA #3")// Step 5. Trailing Stop, Stop Loss and Take Profit calculation//TRAILING STOP CODEa = input(title="Usar Trailing Stop?", type=input.bool, defval=false)stopPerlong = input(10.0, title='Stop Loss Long %', type=input.float, group="Stop Loss & Take Profit Settings") / 100stopPershort = input(5.0, title='Stop Loss Short %', type=input.float, group="Stop Loss & Take Profit Settings") / 100take1Perlong = input(40.0, title='Take Profit Long % 1', type=input.float, group="Stop Loss & Take Profit Settings") / 100take1Pershort = input(10.0, title='Take Profit Short % 1', type=input.float, group="Stop Loss & Take Profit Settings") / 100// Determine stop loss pricelongStopPrice  = strategy.position_avg_price * (1 - stopPerlong)shortStopPrice = strategy.position_avg_price * (1 + stopPershort)longTake1Price = strategy.position_avg_price * (1 + take1Perlong)shortTake1Price = strategy.position_avg_price * (1 - take1Pershort)// Determine trail stop loss priceslongStopPriceTrail = 0.0longStopPriceTrail := if (strategy.position_size > 0)    stopValue = close * (1 - stopPerlong)    max(stopValue, longStopPriceTrail[1])else    0// Determine trailing short priceshortStopPriceTrail = 0.0shortStopPriceTrail := if (strategy.position_size < 0)    stopValue = close * (1 + stopPershort)    min(stopValue, shortStopPriceTrail[1])else    999999//Calculate wich stop to uselongStop = a ? longStopPriceTrail : longStopPriceshortStop = a ? shortStopPriceTrail : shortStopPrice//Calculate SL and TP value to throw through alertlongStopEntrada = close  * (1 - stopPerlong)shortStopEntrada = close  * (1 + stopPershort) longTPEntrada = close * (1 + take1Perlong)shortTPEntrada = close * (1 - take1Pershort)//Save the SL and TP price for furter results calculationprice_entryL = 0.0price_entryL := na(price_entryL) ? na : price_entryL[1]price_entryS = 0.0price_entryS := na(price_entryS) ? na : price_entryS[1]stopL = 0.0stopL := na(stopL) ? na : stopL[1]stopS = 0.0stopS := na(stopS) ? na : stopS[1]takeL = 0.0takeL := na(takeL) ? na : takeL[1]takeS = 0.0takeS := na(takeS) ? na : takeS[1]if (demaCrossover)    price_entryL := close    stopL := close  * (1 - stopPerlong)    takeL := close * (1 + take1Perlong)    if (demaCrossunder)    price_entryS := close    stopS := close  * (1 + stopPershort)    takeS := close * (1 - take1Pershort)//Calculate P&L resultsresultadoL = ((close - price_entryL)/price_entryL) * 100resultadoLexit = "(SL = 1% e TP = 0,5%)"resultadoS = ((price_entryS - close)/price_entryS) * 100resultadoSexit = "(SL = 1% e TP = 0,5)%"// Step 6. Strategy setup// Make input options that configure backtest date range_startDate = input(title="Start Date", type=input.integer,     defval=1, minval=1, maxval=31, group="BackTest Period")_startMonth = input(title="Start Month", type=input.integer,     defval=4, minval=1, maxval=12, group="BackTest Period")_startYear = input(title="Start Year", type=input.integer,     defval=2021, minval=1800, maxval=2100, group="BackTest Period")_endDate = input(title="End Date", type=input.integer,     defval=31, minval=1, maxval=31, group="BackTest Period")_endMonth = input(title="End Month", type=input.integer,     defval=12, minval=1, maxval=12, group="BackTest Period")_endYear = input(title="End Year", type=input.integer,     defval=2031, minval=1800, maxval=2100, group="BackTest Period")// Look if the close time of the current bar// falls inside the date range_inDateRange = (time >= timestamp(syminfo.timezone, _startYear,         _startMonth, _startDate, 0, 0)) and     (time < timestamp(syminfo.timezone, _endYear, _endMonth, _endDate, 0, 0))  //Alert configuration     _alertMessageOpenLong="OpenLong"_alertMessageCloseLong="CloseLong"_alertmessageExitLong="ExitLong"_alertmessageTPLong="TakeProfitLong"_alertMessageOpenShort="OpenShort"_alertMessageCloseShort="CloseShort"_alertMessageTPShort="TakeProfitShort"_alertMessageExitShort="ExitShort"// Step 7. Strategy Executionif (_inDateRange)    //ENTER SOME SETUP TRADES FOR TSL EXAMPLE    if (demaCrossover)        strategy.entry("LONG", strategy.long, comment = "OPEN LONG", alert_message=_alertMessageOpenLong)        strategy.exit(id="Close Long TP1", stop=stopL, limit=takeL, comment="CLOSE LONG", alert_message=_alertmessageExitLong)    if (demaCrossunder)        strategy.entry("SHORT", strategy.short, comment = "OPEN SHORT", alert_message=_alertMessageOpenShort)        strategy.exit(id="Close Short TP1", stop=stopS, limit=takeS, comment="CLOSE SHORT", alert_message=_alertMessageExitShort)    //EXIT TRADE @ TSL    if strategy.position_size > 0        strategy.exit("TP/SL", "LONG", stop=longStop, limit=longTake1Price, comment="EXIT LONG", alert_message=_alertmessageExitLong)    if strategy.position_size < 0        strategy.exit("TP/SL", "SHORT", stop=shortStop, limit=shortTake1Price, comment ="EXIT SHORT", alert_message=_alertMessageExitShort)// Step 8. Chart look and feel//Look & Feel - Plot stop loss and take profit areasp1=plot(strategy.position_avg_price, color=color.blue, style=plot.style_linebr, linewidth=1, title="Entry Price")p2=plot(series=strategy.position_size > 0 ? longStop : na, color=color.red, style=plot.style_linebr, linewidth=1, title="Long Stop")p3=plot(series=strategy.position_size > 0 ? longTake1Price : na, color=color.green, style=plot.style_linebr, linewidth=1, title="Long TP")p4=plot(series=strategy.position_size < 0 ? shortStop : na, color=color.red, style=plot.style_linebr, linewidth=1, title="Short Stop")p5=plot(series=strategy.position_size < 0 ? shortTake1Price : na, color=color.green, style=plot.style_linebr, linewidth=1, title="Short TP")fill(p1, p2, color=color.red)fill(p1, p3, color=color.green)fill(p1, p4, color=color.red)fill(p1, p5, color=color.green)// Insert label with valuestopLossOnLong = "Stop Loss = " + tostring(longStop)stopLossOnShort = "Stop Loss = " + tostring(shortStop)takeprofitOnLong = "Take Profit = " + tostring(longTake1Price)takeprofitOnShort = "Take Profit = " + tostring(shortTake1Price)precoentrada = "Entry Price = " + tostring(strategy.position_avg_price)var label FinalLabelpriceL = navar label FinalLabelpriceS = navar label slFinalLabelL = navar label slFinalLabelS = navar label slFinalLabelTPL = navar label slFinalLabelTPS = na//Draw entry and stop loss lines and labelsif strategy.position_size > 0           //write the price above the end of the stoploss line    slFinalLabelL := label.new(bar_index, longStop, stopLossOnLong, style=label.style_none, size=size.normal, textcolor=color.red)    slFinalLabelTPL := label.new(bar_index, longTake1Price, takeprofitOnLong, style=label.style_none, size=size.normal, textcolor=color.green)    FinalLabelpriceL := label.new(bar_index, strategy.position_avg_price, precoentrada, style=label.style_none, size=size.normal, textcolor=color.blue)        // Delete previous label when there is a consecutive new high, as there's no line plot in that case.    if strategy.position_size > 0[1]        label.delete(slFinalLabelL[1])        label.delete(slFinalLabelTPL[1])        label.delete(FinalLabelpriceL[1])if strategy.position_size < 0           //write the price above the end of the stoploss line    slFinalLabelS := label.new(bar_index, shortStop, stopLossOnShort, style=label.style_none, size=size.normal, textcolor=color.red)    slFinalLabelTPS := label.new(bar_index, shortTake1Price, takeprofitOnShort, style=label.style_none, size=size.normal, textcolor=color.green)    FinalLabelpriceS := label.new(bar_index, strategy.position_avg_price, precoentrada, style=label.style_none, size=size.normal, textcolor=color.blue)        // Delete previous label when there is a consecutive new high, as there's no line plot in that case.    if strategy.position_size < 0[1]        label.delete(slFinalLabelS[1])        label.delete(slFinalLabelTPS[1])         label.delete(FinalLabelpriceS[1])    // Exit open market position when date range endsif (not _inDateRange)    strategy.close_all()//Plot the box with position and P&LposColor = color.new(color.green, 75)negColor = color.new(color.red, 75)dftColor = color.new(color.blue, 75)posProfit= (strategy.position_size > 0) ? (close * 100 / strategy.position_avg_price - 100) : strategy.position_size < 0 ? (strategy.position_avg_price * 100 / close - 100) : 0.0posDir   = (strategy.position_size  > 0) ? "long" : strategy.position_size < 0 ? "short" : "flat"posCol   = (posProfit > 0) ? posColor : (posProfit < 0) ? negColor : dftColorvar label lb = nalabel.delete(lb)lb := label.new(bar_index, max(high, highest(4)[1]), textcolor=color.white,   color=posCol,   text="Pos: "+ posDir +      "\nPnL: "+tostring(posProfit, "#.##")+"%" +      "\nAvg Price: "+tostring(strategy.position_avg_price, "#.####") +      "\nClose: "+tostring(close, "#.####"))