Zeal Terminal Open in Zeal Terminal

Pine Script v5 · Strategy

Strategy for UT Bot Alerts indicator

A Pine Script v5 strategy built on EMA (close, 200), ATR (1) and Crossover (ema_ut, xATRTrailingStop). It has 24 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 1 in cash and pays 0.03 commission. 37 settings; defaults include Enter initial/current capital 10000, % account risk per trade 2.5 and Time session 0000-2400.

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 Strategy for UT Bot Alerts indicator repaint?
Yes
At least one pattern in the source can repaint: intrabar recalculation.
How did Strategy for UT Bot Alerts indicator do on BTCUSDT 1D with default settings?
−4.52%
From 26 Jan 2024 to 21 Oct 2026, over 42 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Does Strategy for UT Bot Alerts indicator run in Pine Script v6?
Yes
Same 42 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. Both versions were run on Zeal Terminal's engine, and the results are identical. The v6 script can be downloaded below.
Does Strategy for UT Bot Alerts indicator use a stop loss?
Yes
strategy.exit sets a stop on line 162, 163, 166, 167, 176, 177, 180, 181, 191, 192, 195, 196, 205, 206, 209, 210.
Does Strategy for UT Bot Alerts indicator run in Zeal Terminal?
Yes
It compiles in 130 ms and runs 1,000 bars in 274 ms, in the browser.

BTCUSDT · 1D · default settings

  • Buy
  • Sell
  • Close Buy
  • Close Sell
  • Plot
  • Plot
  • Plot
  • Plot
  • Plot
  • Plot
  • Plot
  • Plot
  • Plot
  • Plot
  • Plot
  • Plot
Prerendered with the defaults. Change anything and run it here. The script runs in your browser.
Settings (37)
0.0050,000100,000AprJulOct2025AprJulOct2026AprJulOct$954,778$2,025,273Equity from $1,000,000
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. The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market.
Net profit
−4.52%
−$45,234.60
Buy and hold
+102.5%
same period
Closed trades
42
4 won · 38 lost
Profitable
9.5%
of closed trades
Profit factor
0.83
gross profit ÷ gross loss
Max drawdown
15.75%
−$157,475.00

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

  • Likely bug

    ta.ema(src, 1) ignores the settings line 44

    Line 44 hard-codes 1 where line 21 uses “Ema length”. Changing those settings moves one band but not this one.

    ta.ema(src, 1)ta.ema(src, ema)
  • 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
Calculate amount position
Enter initial/current capital10000floatcontracts_amount_c long_amount_lev short_amount_lev line 255 line 257
% account risk per tradePercentage of total account to risk per trade. The USD value that should be used to risk the inserted percentage of the account. Appears green in the upper left corner2.5float · step 1long_amount_c short_amount_c long_amount_lev short_amount_lev
Use leverage ?If it is activated, there will be no monetary units or amount of assets limit for each operation (That is, each operation will not be affected by the initial / current capital since it would be using leverage). If it is deactivated, the monetary units or the amount of assets to use for each operation will be limited by the initial/current capital.trueboolline 255 line 257 plot
Time filter
Initial dateEnter the start date and time of the strategytimestamp("10 Feb 2014 13:30 +0000")timeentry L exit Tp exit Exit entry L exit Tp exit Exit entry S exit Tp exit Exit entry S exit Tp exit Exit bgcolor line 156 line 171 line 185 line 200
Final dateEnter the end date and time of the strategytimestamp("01 Jan 2030 19:30 +0000")timeentry L exit Tp exit Exit entry L exit Tp exit Exit entry S exit Tp exit Exit entry S exit Tp exit Exit bgcolor line 156 line 171 line 185 line 200
Time sessionSession time to operate. It may be different depending on your time zone, you have to find the correct hours manually.0000-2400sessionentry L exit Tp exit Exit entry L exit Tp exit Exit entry S exit Tp exit Exit entry S exit Tp exit Exit bgcolor line 156 line 171 line 185 line 200
Date backgroundAdd color to the period of time of the strategy testerfalseboolbgcolor
Session backgroundAdd color to session time backgroundfalseboolbgcolor
Trend
Ema length200int · min 1 · max 500ema200
Appearance
Show ema ?falseboolEma
Show atr from ut bot alerts ?falseboolplot
Show ema from ut bot alerts ?falseboolplot
Show signals ?trueboolBuy Sell Close Buy Close Sell
Paint candles ?falseboolbarcolor
Show stop loss ?trueboolplot
Draw position on chart ?Activate to graphically display profit, stop loss and break eventrueboolposition_price sl_long_price sl_short_price tp_long_price tp_short_price breakeven_long breakeven_short position_profit_long position_profit_short plot
Draw first take profit/breakeven price on chart ?Activate to display take profit and breakeven price. It appears as a green point in the charttrueboolplot
UT BOT ALERTS
Key VauleHigher amount, less trades. Changing this could be useful in some assets or time frames3intnLoss
ATR PeriodHigher amount, less trades. Changing this could be useful in some assets or time frames1intxATR
Signals from Heikin Ashi Candlesfalseboolsrc
Atr stop loss
SourceclosesourceshortStopLoss longStopLoss
Period14int · min 1shortStopLoss longStopLoss
Atr multiplierDefines the stop loss distance based on the Atr stop loss indicator1.5float · min 0.1 · step 0.1shortStopLoss longStopLoss
Risk management for trades
Stop loss source for atr stoplossCurrent candlestring · options ["Current candle","Past candle"]line 79 line 82 line 95
General stop loss sourceAtr stop lossstring · options ["Atr stop loss","Swing high/low"]line 92 line 95 line 98
% Account risk per trade for backtestingPercentage of total account to risk per trade2.5float · step 1long_amount short_amount
Use leverage for backtesting ?If it is activated, there will be no monetary units or amount of assets limit for each operation (That is, each operation will not be affected by the initial / current capital since it would be using leverage). If it is deactivated, the monetary units or the amount of assets to use for each operation will be limited by the initial/current capital.trueboolline 120 line 122
Risk/reward for breakeven long0.75float · step 0.1be_long be_long_plot
Risk/reward for take profit long3.0float · step 0.1tp_long
Risk/reward for break even short0.75float · step 0.1be_short be_short_plot
Risk/reward for take profit short3.0float · step 0.1tp_short
% of trade for first take profitClosing percentage of the current position when the first take profit is reached.50float · step 5exit Tp
Use take profit ?truebooltp_long_price tp_short_price entry L exit Tp exit Exit entry S exit Tp exit Exit line 156 line 185 plot
Swing highs/lows stop losses
Highest price bars: 10intstop_high
Lowest price bars: 10intstop_low
Positions management
Long positions ?trueboolentry L exit Tp exit Exit entry L exit Tp exit Exit line 156 line 171
Short positions ?trueboolentry S exit Tp exit Exit entry S exit Tp exit Exit line 185 line 200

What it calculates

  • EMAclose, Ema length (200)ema200 · line 21
  • ATRATR Period (1)xATR · line 31
  • EMAsrc, 1ema_ut · line 44
  • Crossoverema_ut, xATRTrailingStopabove · line 47
  • CrossoverxATRTrailingStop, ema_utbelow · line 48
  • ATRPeriod (14)shortStopLoss · line 80
  • ATRPeriod (14)longStopLoss · line 81
  • Highesthigh, Highest price bars: (10)stop_high · line 88
  • Lowestlow, Lowest price bars: (10)stop_low · line 89

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 102 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.

Order rules

OrderFires whenBy defaultLine
Open L longnot bought and buy and dateFilter(initial_date, final_date) and long_positions and bullish and inSession(timeSession) and use_takeprofitOn161
Exit Tp stop and limitnot bought and buy and dateFilter(initial_date, final_date) and long_positions and bullish and inSession(timeSession) and use_takeprofitOn162
Exit Exit stopnot bought and buy and dateFilter(initial_date, final_date) and long_positions and bullish and inSession(timeSession) and use_takeprofitOn163
Exit Tp stop and limitbought and high > be_longOn166
Exit Exit stopbought and high > be_longOn167
Close Lbought and sell and strategy.openprofit>0On169
Open L longnot bought and buy and dateFilter(initial_date, final_date) and long_positions and bullish and inSession(timeSession)On175
Exit Tp stopnot bought and buy and dateFilter(initial_date, final_date) and long_positions and bullish and inSession(timeSession)On176
Exit Exit stopnot bought and buy and dateFilter(initial_date, final_date) and long_positions and bullish and inSession(timeSession)On177
Exit Tp stopbought and high > be_longOn180
Exit Exit stopbought and high > be_longOn181
Close Lbought and sell and strategy.openprofit>0On183
Open S shortnot sold and sell and dateFilter(initial_date, final_date) and short_positions and bearish and inSession(timeSession) and use_takeprofitOn190
Exit Tp stop and limitnot sold and sell and dateFilter(initial_date, final_date) and short_positions and bearish and inSession(timeSession) and use_takeprofitOn191
Exit Exit stopnot sold and sell and dateFilter(initial_date, final_date) and short_positions and bearish and inSession(timeSession) and use_takeprofitOn192
Exit Tp stop and limitsold and low < be_shortOn195
Exit Exit stopsold and low < be_shortOn196
Close Ssold and buy and strategy.openprofit>0On198
Open S shortnot sold and sell and dateFilter(initial_date, final_date) and short_positions and bearish and inSession(timeSession)On204
Exit Tp stopnot sold and sell and dateFilter(initial_date, final_date) and short_positions and bearish and inSession(timeSession)On205
Exit Exit stopnot sold and sell and dateFilter(initial_date, final_date) and short_positions and bearish and inSession(timeSession)On206
Exit Tp stopsold and low < be_shortOn209
Exit Exit stopsold and low < be_shortOn210
Close Ssold and buy and strategy.openprofit>0On212

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.

9/9trades 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. On 4 of them the position changed while the bar was forming before it settled. Anyone watching live sees those changes; once the bar closes it matches history.
  • ClearHigher-timeframe data1 request.security call(s), none with lookahead on.
  • ClearFuture-bar referencesNo negative history offsets such as close[-1].
  • CheckIntrabar recalculationcalc_on_every_tick = true. Live values can differ from history.
  • 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−4.5%+102.5%4210%0.8315.7%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h−13.7%+5.5%425%0.4517.6%8 May 2026 – 21 Oct 2026
ETHUSDT 1D−3.5%+9.8%378%0.859.9%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h−18.8%+8.4%346%0.2818.8%8 May 2026 – 21 Oct 2026
SOLUSDT 1D+5.3%+16.7%3412%1.3611.2%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+48.4%+21.5%2910%2.899.4%8 May 2026 – 21 Oct 2026
BNBUSDT 1D+26.6%+148.3%316%2.6610.7%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+9.1%+17.1%368%1.2913.1%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 market119%−$64,816.80
Sideways market2010%$64,619.30
Falling market119%−$44,843.90

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

How bad could the drawdown be?

21.2%

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

0%24%
All 42 trades
SideEntryExitBarsP&L
long23 Aug 2024 64,037.2027 Aug 2024 59,593.704−$12,604.30
long23 Aug 2024 64,037.2027 Aug 2024 59,593.704−$12,604.30
short27 Aug 2024 59,415.0010 Sep 2024 57,636.0014$10,066.80
long14 Oct 2024 66,084.0023 Oct 2024 66,084.009−$153.80
long14 Oct 2024 66,084.0023 Oct 2024 66,084.009−$153.80
long8 Dec 2024 101,110.009 Dec 2024 95,182.101−$12,429.10
long8 Dec 2024 101,110.009 Dec 2024 95,182.101−$12,429.10
long6 Jan 2025 102,236.007 Jan 2025 97,023.301−$12,133.70
long6 Jan 2025 102,236.007 Jan 2025 97,023.301−$12,133.70
long2 Mar 2025 94,270.003 Mar 2025 87,820.101−$11,791.80
long2 Mar 2025 94,270.003 Mar 2025 87,820.101−$11,791.80
short9 Mar 2025 80,734.4024 Mar 2025 88,037.9015−$11,477.00
short9 Mar 2025 80,734.4024 Mar 2025 88,037.9015−$11,477.00
long24 Mar 2025 87,498.2029 Mar 2025 81,916.905−$11,212.30
long24 Mar 2025 87,498.2029 Mar 2025 81,916.905−$11,212.30
short6 Apr 2025 78,430.0011 Apr 2025 83,722.105−$10,930.30
short6 Apr 2025 78,430.0011 Apr 2025 83,722.105−$10,930.30
long21 Apr 2025 87,516.2030 May 2025 103,985.0039$73,062.70
long9 Jun 2025 110,263.0012 Jun 2025 105,785.003−$11,636.90
long9 Jun 2025 110,263.0012 Jun 2025 105,785.003−$11,636.90
long9 Jul 2025 111,234.001 Aug 2025 113,298.0023$11,870.60
long10 Aug 2025 119,294.0011 Aug 2025 118,686.001−$1,979.75
long10 Aug 2025 119,294.0011 Aug 2025 118,686.001−$1,979.75
long10 Sep 2025 113,960.0022 Sep 2025 113,960.0012−$185.88
long10 Sep 2025 113,960.0022 Sep 2025 113,960.0012−$185.88
long28 Sep 2025 112,164.0010 Oct 2025 112,164.0012−$216.02
long28 Sep 2025 112,164.0010 Oct 2025 112,164.0012−$216.02
long24 Oct 2025 111,005.0029 Oct 2025 111,005.005−$125.67
long24 Oct 2025 111,005.0029 Oct 2025 111,005.005−$125.67
short3 Nov 2025 106,583.0010 Nov 2025 106,583.007−$131.86
short3 Nov 2025 106,583.0010 Nov 2025 106,583.007−$131.86
short1 Dec 2025 86,286.002 Dec 2025 91,978.301−$11,368.10
short1 Dec 2025 86,286.002 Dec 2025 91,978.301−$11,368.10
short19 Jan 2026 92,631.004 Mar 2026 72,666.8044$127,752.00
short22 Mar 2026 67,859.007 Apr 2026 72,185.1016−$12,697.10
short22 Mar 2026 67,859.007 Apr 2026 72,185.1016−$12,697.10
short17 May 2026 77,457.7024 May 2026 77,457.707−$177.98
short17 May 2026 77,457.7024 May 2026 77,457.707−$177.98
short11 Aug 2026 63,600.0019 Aug 2026 65,688.708−$12,480.70
short11 Aug 2026 63,600.0019 Aug 2026 65,688.708−$12,480.70
long18 Sep 2026 80,883.908 Oct 2026 80,883.9020−$164.22
long18 Sep 2026 80,883.908 Oct 2026 80,883.9020−$164.22

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
Strategy for UT Bot Alerts indicator this page—v5 strategy−4.5%4215.7%
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%
Strategy Myth-Busting #1 - UT Bot+STC+Hull [MYN] by myncryptoatr ema lowest highestv5 strategy−30.7%1063.5%
Simple and Profitable Scalping Strategy (ForexSignals TV) by kevinmck100ema atr highest lowestv5 strategyNo trades on this market
ATR + STC + MA by Romediusema lowest highest atrv5 strategy−1.2%153.3%

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.

  • 4 settings use the untyped input() (line 28, 29, 30, 66). 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

VerifiedDownload the v5 script

Same 42 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.

  • Line 28: input() → input.int()
  • Line 29: input() → input.int()
  • Line 30: input() → input.bool()
  • Line 66: input() → input.source()
⋯// Inputs-a = input(3, title='Key Vaule', group = "============ UT BOT ALERTS ============", tooltip = "Higher amount, less trades. Changing this could be useful in some assets or time frames")+a = input.int(3, title='Key Vaule', group = "============ UT BOT ALERTS ============", tooltip = "Higher amount, less trades. Changing this could be useful in some assets or time frames")-c = input(1, title='ATR Period', group = "============ UT BOT ALERTS ============", tooltip = "Higher amount, less trades. Changing this could be useful in some assets or time frames")+c = input.int(1, title='ATR Period', group = "============ UT BOT ALERTS ============", tooltip = "Higher amount, less trades. Changing this could be useful in some assets or time frames")-h = input(false, title='Signals from Heikin Ashi Candles', group = "============ UT BOT ALERTS ============")+h = input.bool(false, title='Signals from Heikin Ashi Candles', group = "============ UT BOT ALERTS ============")xATR = ta.atr(c)⋯short_condition_atr = src < xATRTrailingStop and below -source_atr = input(close, title='Source', group = "============ Atr stop loss ============", inline = "A")+source_atr = input.source(close, title='Source', group = "============ Atr stop loss ============", inline = "A")length_atr = input.int(14, minval=1, title='Period', group = "============ Atr stop loss ============" , inline = "A")⋯

Does it run in Pine Script v6?

Yes

Same 42 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. Both versions were run on Zeal Terminal's engine, and the results are identical. It differs from the v5 version by 1 edit.

Download the v6 script

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/-//@version=5+//@version=6//Developed by StrategiesForEveryone⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 130 msWith a workaround 1,000 bars in 274 msNot measured
PineTSNot testedNot testedNot measured

The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market.

“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report.

Source

Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0///@version=5//Developed by StrategiesForEveryonestrategy("UT Bot alerts strategy", overlay=true, process_orders_on_close = true, initial_capital = 1000000, default_qty_type=strategy.cash, precision = 2, calc_on_every_tick = true, commission_value = 0.03)// ------ Inputs for calculating position --------initial_actual_capital = input.float(defval=10000, title = "Enter initial/current capital", group = "============ Calculate amount position ============")risk_c = input.float(2.5, '% account risk per trade', step=1, group = "============ Calculate amount position ============", tooltip = "Percentage of total account to risk per trade. The USD value that should be used to risk the inserted percentage of the account. Appears green in the upper left corner")// ------ Date filter (obtained from ZenAndTheArtOfTrading) ---------initial_date = input.time(title="Initial date", defval=timestamp("10 Feb 2014 13:30 +0000"), group="============ Time filter ============ ", tooltip="Enter the start date and time of the strategy")final_date   = input.time(title="Final date", defval=timestamp("01 Jan 2030 19:30 +0000"), group="============ Time filter ============ ", tooltip="Enter the end date and time of the strategy")dateFilter(int st, int et) => time >= st and time <= etcolorDate = input.bool(defval=false, title="Date background", tooltip = "Add color to the period of time of the strategy tester")bgcolor(colorDate and dateFilter(initial_date, final_date) ? color.new(color.blue, transp=90) : na)// ------ Session limits (obtained from ZenAndTheArtOfTrading) -------timeSession = input.session(title="Time session", defval="0000-2400", group="============ Time filter ============ ", tooltip="Session time to operate. It may be different depending on your time zone, you have to find the correct hours manually.")colorBG     = input.bool(title="Session background", defval=false, tooltip = "Add color to session time background")inSession(sess) => na(time(timeframe.period, sess + ':1234567')) == falsebgcolor(inSession(timeSession) and colorBG ? color.rgb(0, 38, 255, 84) : na)// ----------- Ema ----------------------ema = input.int(200, title='Ema length', minval=1, maxval=500, group = "============ Trend ============")ema200 = ta.ema(close, ema)bullish = close > ema200bearish = close < ema200show_ema = input.bool(defval=false, title="Show ema ?", group = "============ Appearance ============")plot(show_ema ? ema200 : na, title = "Ema", color=color.white, linewidth=2, display = display.all - display.status_line - display.price_scale)// -------------- UT BOT ALERTS INDICATOR by @QuantNomad -------------------------// Inputsa = input(3, title='Key Vaule', group = "============ UT BOT ALERTS ============", tooltip = "Higher amount, less trades. Changing this could be useful in some assets or time frames")c = input(1, title='ATR Period', group = "============ UT BOT ALERTS ============", tooltip = "Higher amount, less trades. Changing this could be useful in some assets or time frames")h = input(false, title='Signals from Heikin Ashi Candles', group = "============ UT BOT ALERTS ============")xATR = ta.atr(c)nLoss = a * xATRsrc = h ? request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close, lookahead=barmerge.lookahead_off) : closexATRTrailingStop = 0.0iff_1 = src > nz(xATRTrailingStop[1], 0) ? src - nLoss : src + nLossiff_2 = src < nz(xATRTrailingStop[1], 0) and src[1] < nz(xATRTrailingStop[1], 0) ? math.min(nz(xATRTrailingStop[1]), src + nLoss) : iff_1xATRTrailingStop := src > nz(xATRTrailingStop[1], 0) and src[1] > nz(xATRTrailingStop[1], 0) ? math.max(nz(xATRTrailingStop[1]), src - nLoss) : iff_2show_atr_ut = input.bool(defval=false, title="Show atr from ut bot alerts ?", group = "============ Appearance ============")plot(show_atr_ut ? xATRTrailingStop : na, color = color.orange, linewidth = 2, display = display.all - display.price_scale - display.status_line)pos = 0iff_3 = src[1] > nz(xATRTrailingStop[1], 0) and src < nz(xATRTrailingStop[1], 0) ? -1 : nz(pos[1], 0)pos := src[1] < nz(xATRTrailingStop[1], 0) and src > nz(xATRTrailingStop[1], 0) ? 1 : iff_3xcolor = pos == -1 ? color.red : pos == 1 ? color.green : color.blueema_ut = ta.ema(src, 1)show_ema_ut = input.bool(defval=false, title="Show ema from ut bot alerts ?", group = "============ Appearance ============")plot(show_ema_ut ? ema_ut : na, color = color.white, linewidth = 2, display = display.all - display.price_scale - display.status_line)above = ta.crossover(ema_ut, xATRTrailingStop)below = ta.crossover(xATRTrailingStop, ema_ut)buy = src > xATRTrailingStop and abovesell = src < xATRTrailingStop and belowclose_buy = src < xATRTrailingStop and belowclose_sell = src > xATRTrailingStop and abovebarbuy = src > xATRTrailingStopbarsell = src < xATRTrailingStopshow_signals = input.bool(true, title = "Show signals ?", group = "============ Appearance ============")paint_candles = input.bool(false, title = "Paint candles ?", group = "============ Appearance ============")plotshape(bullish and show_signals ? buy : na, title='Buy', text='Buy', style=shape.labelup, location=location.belowbar, color=color.new(color.green, 0), textcolor=color.new(color.white, 0), size=size.tiny , display = display.all - display.price_scale - display.status_line)plotshape(bearish and show_signals ? sell : na, title='Sell', text='Sell', style=shape.labeldown, location=location.abovebar, color=color.new(color.red, 0), textcolor=color.new(color.white, 0), size=size.tiny, display = display.all - display.price_scale - display.status_line)plotshape(bullish and show_signals ? close_buy : na, title='Close Buy', text='Cl Buy', style=shape.labelup, location=location.belowbar, color=color.new(color.green, 80), textcolor=color.new(color.white, 0), size=size.tiny, display = display.all - display.price_scale - display.status_line)plotshape(bearish and show_signals ? close_sell : na, title='Close Sell', text='Cl Sell', style=shape.labeldown, location=location.abovebar, color=color.new(color.red, 80), textcolor=color.new(color.white, 0), size=size.tiny, display = display.all - display.price_scale - display.status_line)barcolor(barbuy and paint_candles ? color.green : na)barcolor(barsell and paint_candles ? color.red : na)// -------------- Atr stop loss by garethyeo (modified) -----------------long_condition_atr = src > xATRTrailingStop and above short_condition_atr = src < xATRTrailingStop and below source_atr = input(close, title='Source', group = "============ Atr stop loss ============", inline = "A")length_atr = input.int(14, minval=1, title='Period', group = "============ Atr stop loss ============" , inline = "A")multiplier = input.float(1.5, minval=0.1, step=0.1, title='Atr multiplier', group = "============ Atr stop loss ============", inline = "A", tooltip = "Defines the stop loss distance based on the Atr stop loss indicator") show_stoploss = input.bool(defval = true, title = "Show stop loss ?", group = "============ Appearance ============")var float shortStopLoss = navar float longStopLoss = na var float atr_past_candle_long = navar float atr_past_candle_short = na//shortStopLoss = source_atr + ta.atr(length_atr) * multiplier//longStopLoss = source_atr - ta.atr(length_atr) * multiplier//atr_past_candle_short = close[1] + ta.atr(length_atr)[1] * multiplier[1]//atr_past_candle_long = close[1] - ta.atr(length_atr)[1] * multiplier[1]candle_of_stoploss = input.string(defval = "Current candle", title = "Stop loss source for atr stoploss", group = "============ Risk management for trades ============", options = ["Current candle","Past candle"])if candle_of_stoploss == "Current candle"    shortStopLoss := source_atr + ta.atr(length_atr) * multiplier    longStopLoss := source_atr - ta.atr(length_atr) * multiplierif candle_of_stoploss == "Past candle"    shortStopLoss := close[1] + ta.atr(length_atr)[1] * multiplier[1]    longStopLoss := close[1] - ta.atr(length_atr)[1] * multiplier[1]// --------- Stop loss based in last swing high/low --------high_bars = input.int(defval = 10, title = "Highest price bars: ", group = "============ Swing highs/lows stop losses ============")low_bars = input.int(defval = 10, title = "Lowest price bars: ", group = "============ Swing highs/lows stop losses ============")stop_high = ta.highest(high, high_bars)stop_low = ta.lowest(low, low_bars)// --------- Stop loss source selection ---------------stoploss_type = input.string(defval = "Atr stop loss", title = "General stop loss source", group = "============ Risk management for trades ============", options = ["Atr stop loss","Swing high/low"])if stoploss_type == "Atr stop loss"    shortStopLoss := source_atr + ta.atr(length_atr) * multiplier    longStopLoss := source_atr - ta.atr(length_atr) * multiplierif candle_of_stoploss == "Past candle" and stoploss_type == "Atr stop loss"    shortStopLoss := close[1] + ta.atr(length_atr)[1] * multiplier[1]    longStopLoss := close[1] - ta.atr(length_atr)[1] * multiplier[1]if stoploss_type == "Swing high/low"    shortStopLoss := stop_high    longStopLoss := stop_low// Ploting stop lossesplot(show_stoploss and long_condition_atr and bullish ? longStopLoss : na, color = color.white, style = plot.style_circles, linewidth = 2)plot(show_stoploss and short_condition_atr and bearish ? shortStopLoss : na, color = color.white, style = plot.style_circles, linewidth = 2)// ------------- Money management --------------strategy_contracts = strategy.equity / closedistance_sl_atr_long = -1 * (longStopLoss - close) / closedistance_sl_atr_short = (shortStopLoss - close) / closerisk = input.float(2.5, '% Account risk per trade for backtesting', step=1, group = "============ Risk management for trades ============", tooltip = "Percentage of total account to risk per trade")long_amount = strategy_contracts * (risk / 100) / distance_sl_atr_longshort_amount = strategy_contracts * (risk / 100) / distance_sl_atr_short// ---- Fixed amounts ----//fixed_amounts = input.bool(defval = false, title = "Fixed amounts ?", group = "============ Risk management for trades ============")//fixed_amount_input = input.float(defval = 1000, title = "Fixed amount in usd", group = "============ Risk management for trades ============")//if fixed_amounts //    long_amount := fixed_amount_input / close//if fixed_amounts//    short_amount := fixed_amount_input / close//leverage=input.bool(defval=true, title="Use leverage for backtesting ?", group = "============ Risk management for trades ============", tooltip = "If it is activated, there will be no monetary units or amount of assets limit for each operation (That is, each operation will not be affected by the initial / current capital since it would be using leverage). If it is deactivated, the monetary units or the amount of assets to use for each operation will be limited by the initial/current capital.")if not leverage and long_amount>strategy_contracts    long_amount:=strategy.equity/closeif not leverage and short_amount>strategy_contracts    short_amount:=strategy.equity/close// ---------- Risk management ---------------risk_reward_breakeven_long= input.float(title="Risk/reward for breakeven long", defval=0.75, step=0.1, group = "============ Risk management for trades ============")risk_reward_take_profit_long= input.float(title="Risk/reward for take profit long", defval=3.0, step=0.1, group = "============ Risk management for trades ============")risk_reward_breakeven_short= input.float(title="Risk/reward for break even short", defval=0.75, step=0.1, group = "============ Risk management for trades ============")risk_reward_take_profit_short= input.float(title="Risk/reward for take profit short", defval=3.0, step=0.1, group = "============ Risk management for trades ============")tp_percent=input.float(title="% of trade for first take profit", defval=50, step=5, group = "============ Risk management for trades ============", tooltip = "Closing percentage of the current position when the first take profit is reached.")// ------------ Trade conditions ---------------bullish := close > ema200bearish := close < ema200bought = strategy.position_size > 0sold = strategy.position_size < 0buy  := src > xATRTrailingStop and above sell := src < xATRTrailingStop and below var float sl_long = navar float sl_short = na var float be_long = navar float be_short = navar float tp_long = navar float tp_short = naif not bought    be_long:=na    sl_long:=na    tp_long:=naif not sold    be_short:=na    sl_short:=na    tp_short:=nalong_positions = input.bool(defval = true, title = "Long positions ?", group = "============ Positions management ============")short_positions = input.bool(defval = true, title = "Short positions ?", group = "============ Positions management ============")use_takeprofit = input.bool(defval = true, title = "Use take profit ?", group = "============ Risk management for trades ============")// ======================= Strategy ===================================================================================================================// Long position with take profitif not bought and buy and dateFilter(initial_date, final_date) and long_positions and bullish and inSession(timeSession) and use_takeprofit    sl_long:=longStopLoss               long_stoploss_distance = close - longStopLoss    be_long := close + long_stoploss_distance * risk_reward_breakeven_long    tp_long:=close+(long_stoploss_distance*risk_reward_take_profit_long)    strategy.entry('L', strategy.long, long_amount, alert_message = "Long")    strategy.exit("Tp", "L", stop=sl_long, limit=tp_long, qty_percent=tp_percent)    strategy.exit('Exit', 'L', stop=sl_long)if bought and high > be_long    sl_long := strategy.position_avg_price    strategy.exit("Tp", "L", stop=sl_long, limit=tp_long, qty_percent=tp_percent)    strategy.exit('Exit', 'L', stop=sl_long)if bought and sell and strategy.openprofit>0    strategy.close("L", comment="CL")// Long position without take profitif not bought and buy and dateFilter(initial_date, final_date) and long_positions and bullish and inSession(timeSession)     sl_long:=longStopLoss               long_stoploss_distance = close - longStopLoss    be_long := close + long_stoploss_distance * risk_reward_breakeven_long    strategy.entry('L', strategy.long, long_amount, alert_message = "Long")    strategy.exit("Tp", "L", stop=sl_long, qty_percent=tp_percent)    strategy.exit('Exit', 'L', stop=sl_long)if bought and high > be_long    sl_long := strategy.position_avg_price    strategy.exit("Tp", "L", stop=sl_long, qty_percent=tp_percent)    strategy.exit('Exit', 'L', stop=sl_long)if bought and sell and strategy.openprofit>0    strategy.close("L", comment="CL")// Short position with take profitif not sold and sell and dateFilter(initial_date, final_date) and short_positions and bearish and inSession(timeSession) and use_takeprofit    sl_short:=shortStopLoss    short_stoploss_distance=shortStopLoss - close      be_short:=((short_stoploss_distance*risk_reward_breakeven_short)-close)*-1    tp_short:=((short_stoploss_distance*risk_reward_take_profit_short)-close)*-1    strategy.entry("S", strategy.short, short_amount, alert_message = "Short")    strategy.exit("Tp", "S", stop=sl_short, limit=tp_short, qty_percent=tp_percent)    strategy.exit("Exit", "S", stop=sl_short)if sold and low < be_short     sl_short:=strategy.position_avg_price    strategy.exit("Tp", "S", stop=sl_short, limit=tp_short, qty_percent=tp_percent)    strategy.exit("Exit", "S", stop=sl_short)    if sold and buy and strategy.openprofit>0    strategy.close("S", comment="CS") // Short position without take profitif not sold and sell and dateFilter(initial_date, final_date) and short_positions and bearish and inSession(timeSession)     sl_short:=shortStopLoss    short_stoploss_distance=shortStopLoss - close      be_short:=((short_stoploss_distance*risk_reward_breakeven_short)-close)*-1    strategy.entry("S", strategy.short, short_amount, alert_message = "Short")    strategy.exit("Tp", "S", stop=sl_short, qty_percent=tp_percent)    strategy.exit("Exit", "S", stop=sl_short)if sold and low < be_short     sl_short:=strategy.position_avg_price    strategy.exit("Tp", "S", stop=sl_short, qty_percent=tp_percent)    strategy.exit("Exit", "S", stop=sl_short)    if sold and buy and strategy.openprofit>0    strategy.close("S", comment="CS") // ===============================================================================================================================================// ---------- Draw positions and signals on chart (strategy as an indicator) -------------if high>tp_long    tp_long:=naif low<tp_short    tp_short:=naif high>be_long    be_long:=naif low<be_short    be_short:=nashow_position_on_chart = input.bool(defval=true, title="Draw position on chart ?", group = "============ Appearance ============", tooltip = "Activate to graphically display profit, stop loss and break even")position_price = plot(show_position_on_chart? strategy.position_avg_price : na, style=plot.style_linebr, color = color.new(#ffffff, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)sl_long_price = plot(show_position_on_chart and bought ? sl_long : na, style = plot.style_linebr, color = color.new(color.red, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)sl_short_price = plot(show_position_on_chart and sold ? sl_short : na, style = plot.style_linebr, color = color.new(color.red, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)tp_long_price = plot(strategy.position_size>0 and show_position_on_chart and use_takeprofit? tp_long : na, style = plot.style_linebr, color = color.new(#4cd350, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)tp_short_price = plot(strategy.position_size<0 and show_position_on_chart and use_takeprofit? tp_short : na, style = plot.style_linebr, color = color.new(#4cd350, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)breakeven_long = plot(strategy.position_size>0 and high<be_long and show_position_on_chart ? be_long : na , style = plot.style_linebr, color = color.new(#1fc9fd, 60), linewidth = 1, display = display.all - display.status_line - display.price_scale)breakeven_short = plot(strategy.position_size<0 and low>be_short and show_position_on_chart ? be_short : na , style = plot.style_linebr, color = color.new(#1fc9fd, 60), linewidth = 1, display = display.all - display.status_line - display.price_scale)show_break_even_on_chart = input.bool(defval=true, title="Draw first take profit/breakeven price on chart ?", group = "============ Appearance ============", tooltip = "Activate to display take profit and breakeven price. It appears as a green point in the chart")long_stoploss_distance = close - longStopLossshort_stoploss_distance=shortStopLoss - closebe_long_plot = close + long_stoploss_distance * risk_reward_breakeven_longbe_short_plot =((short_stoploss_distance*risk_reward_breakeven_short)-close)*-1plot(show_break_even_on_chart and buy and bullish? be_long_plot : na, color=color.new(#1fc9fd, 10), style = plot.style_circles, linewidth = 2, display = display.all - display.price_scale)plot(show_break_even_on_chart and sell and bearish? be_short_plot : na, color=color.new(#1fc9fd, 10), style = plot.style_circles, linewidth = 2, display = display.all - display.price_scale)position_profit_long = plot(bought and show_position_on_chart and strategy.openprofit>0 ? close : na, style = plot.style_linebr, color = color.new(#4cd350, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)position_profit_short = plot(sold and show_position_on_chart and strategy.openprofit>0 ? close : na, style = plot.style_linebr, color = color.new(#4cd350, 10), linewidth = 1, display = display.all - display.status_line - display.price_scale)fill(plot1 = position_price, plot2 = position_profit_long, color = color.new(#4cd350, 90))fill(plot1 = position_price, plot2 = position_profit_short, color = color.new(#4cd350, 90))fill(plot1 = position_price, plot2 = sl_long_price, color = color.new(color.red,90))fill(plot1 = position_price, plot2 = sl_short_price, color = color.new(color.red,90))fill(plot1 = position_price, plot2 = tp_long_price, color = color.new(color.green,90))fill(plot1 = position_price, plot2 = tp_short_price, color = color.new(color.green,90))// --------------- Positions amount calculator  -------------contracts_amount_c = initial_actual_capital / closedistance_sl_long_c = -1 * (longStopLoss - close) / close distance_sl_short_c = (shortStopLoss - close) / closelong_amount_c = close * (contracts_amount_c * (risk_c / 100) / distance_sl_long_c)short_amount_c = close * (contracts_amount_c * (risk_c / 100) / distance_sl_short_c)long_amount_lev = close * (contracts_amount_c * (risk_c / 100) / distance_sl_long_c)short_amount_lev = close * (contracts_amount_c * (risk_c / 100) / distance_sl_short_c)leverage_for_calculator=input.bool(defval=true, title="Use leverage ?", group = "============ Calculate amount position ============", tooltip = "If it is activated, there will be no monetary units or amount of assets limit for each operation (That is, each operation will not be affected by the initial / current capital since it would be using leverage). If it is deactivated, the monetary units or the amount of assets to use for each operation will be limited by the initial/current capital.")if not leverage_for_calculator and long_amount_lev>initial_actual_capital    long_amount_lev:=initial_actual_capitalif not leverage_for_calculator and short_amount_lev>initial_actual_capital    short_amount_lev:=initial_actual_capitalplot(buy and leverage_for_calculator ? long_amount_c : na, color = color.rgb(136, 255, 0), display = display.all - display.pane - display.price_scale)plot(sell and leverage_for_calculator ? short_amount_c : na, color = color.rgb(136, 255, 0), display = display.all - display.pane - display.price_scale)plot(buy and not leverage_for_calculator ? long_amount_lev : na, color = color.rgb(136, 255, 0), display = display.all - display.pane - display.price_scale)plot(sell and not leverage_for_calculator ? short_amount_lev : na, color = color.rgb(136, 255, 0), display = display.all - display.pane - display.price_scale)