Zeal Terminal Open in Zeal Terminal

Pine Script v5 · Strategy

Mean Reversion Strategy v2 [KL]

A Pine Script v5 strategy built on ATR (5), Stdev (ta.tr, 5) and SMA or Stdev (_prcntge_chng, 14). It has 5 order rules, 1 entry among them, and trades long only with the default settings. Exits use a stop loss. Each trade is one contract and pays no commission. 12 settings; defaults include ATR Multiplier for trailing stop loss 2.0, Length of ATR for trailing stop loss 14 and Allocation (%) of portfolio into this security 5.

Generated from the script's code by a template: every clause is a fact read from the source. Not written by a person or a model, and not taken from the author's description.

Does Mean Reversion Strategy v2 [KL] repaint?
No
No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 13 of 13 trades.
How did Mean Reversion Strategy v2 [KL] do on BTCUSDT 1D with default settings?
+1.67%
From 26 Jan 2024 to 21 Oct 2026, over 52 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
What alerts does Mean Reversion Strategy v2 [KL] have?
1
str.tostring(prefix) + str.tostring(msg) + str.tostring(suffix).
Does Mean Reversion Strategy v2 [KL] run in Pine Script v6?
Yes
Same 52 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 Mean Reversion Strategy v2 [KL] use a stop loss?
Yes
strategy.exit sets a stop on line 73.

BTCUSDT · 1D · default settings

  • Plot
  • 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 (12)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$1,016,740,000$2,025,272,873Equity from $1,000,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
+1.67%
$16,740,000.00
Buy and hold
+102.5%
same period
Closed trades
52
34 won · 18 lost
Profitable
65.4%
of closed trades
Profit factor
1.38
gross profit ÷ gross loss
Max drawdown
1.46%
−$14,688,100.00

One run with the author's default settings, $1,000,000,000 starting capital, commission as the script sets it. 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.atr(14) ignores the settings line 93

    Line 93 hard-codes 14 where line 45 uses “Length of ATR (fast) for diversion test”. Changing those settings moves one band but not this one.

    ta.atr(14)ta.atr(len_fast)
  • Check

    No commission

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

  • 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
Backtest Start Timetimestamp("01 Apr 2000 13:30 +0000")timewithin_timeframe
Confidence IntervalCritical values of 1.645, 1.96, 2.58, for CI=90%/95%/99%, respectively; Under 2-tailed test to compare atr_fast vs atr_slow. Null hypothesis (H0) is that both should equal. Based on the computed test statistic value, if absolute value of it is +/- critical value, then H0 will be rejected.95%string · options ["90%","95%","99%"]critical_value
Stop loss
ATR Multiplier for trailing stop loss2.0floatATR_TSL
Length of ATR for trailing stop lossInitial risk amount = atr(this length) x multiplier14intstop_loss_price risk_amt
Order size and Profit taking
Allocation (%) of portfolio into this securitySize of positions is based on this % of undrawn capital. This is fixed throughout the backtest period.5int · min 0 · max 100initial_order_size
Take profit and different levelstrueboolline 81
First level profitRelative to risk. Example: entry at $10 and inital stop loss at $9. Taking first level profit at 1R means taking profits at $111floatclose Long line 88
Second level profitRelative to risk. Example: entry at $10 and inital stop loss at $9. Taking second level profit at 2R means taking profits at $122floatclose Long line 85
Third level profitRelative to risk. Example: entry at $10 and inital stop loss at $9. Taking third level profit at 3R means taking profits at $133floatclose Long line 82
Hypothesis testing
Length of ATR (fast) for diversion test5intatr_fast std_error
Length of ATR (slow) for diversion testThis needs to be larger than Fast50inttest_stat
Trend prediction
Length of driftFor calculation of Drift, where Drift = moving average of Log(close/prev_close) + 0.5 * its variance; If this curve is upward sloping, strategy predicts price to trend upward14int_drift

What it calculates

  • ATRLength of ATR (fast) for diversion test (5)atr_fast · line 45
  • Stdevta.tr, Length of ATR (fast) for diversion test (5)std_error · line 48
  • SMA / Stdev_prcntge_chng, Length of drift (14)_drift · line 64
  • ATR14_atr · line 93

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.

high · low · closehigh · low · closeprice datalen_fastLength of ATR (fast) fo…setting · 5len_driftLength of driftsetting · 14lowlowprice dataATR_TSLLength of ATR for trail…setting · 14closecloseprice datapcnt_allocAllocation (%) of portf…setting · 5atr_slowLength of ATR (slow) fo…setting · 50conf_intervalConfidence Intervalsetting · 95%timetimeprice databacktest_timeframe_startBacktest Start Timesetting · timestamp("01 Apr 2…THIRD_LVL_PROFITThird level profitsetting · 3SECOND_LVL_PROFITSecond level profitsetting · 2FIRST_LVL_PROFITFirst level profitsetting · 1atr_fastATR→ atr_faststd_errorStdev→ std_error_driftSMA / Stdev→ _drift_atrATR→ _atrTSL_sourceTSL_sourcevaluestop_loss_pricestop_loss_pricevalueinitial_entry_p, _prcntge_chnginitial_entry_p · _prcn…2 valuesrisk_amtrisk_amtvalueinitial_order_sizeinitial_order_sizevaluetest_stattest_statvaluecritical_valuecritical_valuevalue_entry_signal_triggered_entry_signal_triggeredvalueTP_taken_countTP_taken_countvaluewithin_timeframewithin_timeframeconditionentry_signal_allentry_signal_allconditionreject_H0reject_H0condition_confirmation_confirmationconditionTSL_line_colorColourTSL_line_colorexit:Longexit Longstrategy.exitentry:LongOpen Longstrategy.entryclose:LongClose Longstrategy.closeplot:28plotplotalert:97alertalert

Order rules

OrderFires whenBy defaultLine
Exit Long stopstrategy.position_size > 0On73
Open Long longwithin_timeframe and entry_signal_all and strategy.position_size == 0On79
Close Longclose >= initial_entry_p + THIRD_LVL_PROFIT * risk_amt and TP_taken_count == 2On83
Close Longclose >= initial_entry_p + SECOND_LVL_PROFIT * risk_amt and TP_taken_count == 1On86
Close Longclose >= initial_entry_p + FIRST_LVL_PROFIT * risk_amt and TP_taken_count == 0On89

Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.

Alerts

AlertCallMessageLine
(no title)alertstr.tostring(prefix) + str.tostring(msg) + str.tostring(suffix)97

Does it repaint?

No

No repainting patterns in the source, and the live replay matched history.

13/13trades 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 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.

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+1.7%+102.5%5265%1.381.5%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h−0.0%+5.5%4757%0.980.9%8 May 2026 – 21 Oct 2026
ETHUSDT 1D+1.6%+9.8%5564%1.203.7%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+0.1%+8.4%4055%1.051.4%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−0.8%+16.7%5062%0.923.4%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h−1.2%+21.5%4856%0.661.8%8 May 2026 – 21 Oct 2026
BNBUSDT 1D+2.9%+148.3%5269%1.661.4%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h−1.0%+17.1%5358%0.611.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 market1362%−$1,408,700.00
Sideways market2454%−$5,424,110.00
Falling market1587%$23,572,800.00

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

How bad could the drawdown be?

1.9%

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

0%2%
All 52 trades
SideEntryExitBarsP&L
long18 Mar 2024 68,393.5013 Apr 2024 63,245.3026−$3,763,320.00
long20 Apr 2024 63,818.001 May 2024 59,014.7011−$3,746,570.00
long9 May 2024 61,193.0021 May 2024 71,446.6012$2,768,470.00
long9 May 2024 61,193.0014 Jun 2024 65,931.2036$2,558,620.00
long21 Jun 2024 64,870.0024 Jun 2024 60,639.703−$3,253,090.00
long26 Jun 2024 61,806.004 Jul 2024 58,655.508−$2,533,030.00
long17 Aug 2024 58,874.6027 Aug 2024 58,361.6010−$431,921.00
long18 Sep 2024 60,314.0027 Sep 2024 65,174.009$1,331,640.00
long18 Sep 2024 60,314.001 Oct 2024 61,451.3013$623,229.00
long7 Oct 2024 62,819.9016 Oct 2024 67,074.109$1,118,860.00
long7 Oct 2024 62,819.9030 Oct 2024 72,736.4023$2,608,040.00
long7 Oct 2024 62,819.904 Nov 2024 67,264.6028$1,173,410.00
long16 Nov 2024 91,032.1023 Nov 2024 98,892.007$1,430,510.00
long16 Nov 2024 91,032.1017 Dec 2024 106,059.0031$2,734,840.00
long16 Nov 2024 91,032.1019 Dec 2024 97,438.7033$1,178,820.00
long24 Dec 2024 94,881.5013 Jan 2025 90,970.3020−$2,065,120.00
long22 Jan 2025 106,144.003 Feb 2025 95,479.7012−$5,022,800.00
long15 Feb 2025 97,500.5025 Feb 2025 90,024.1010−$3,820,440.00
long28 Feb 2025 84,708.603 Mar 2025 94,270.003$1,864,480.00
long28 Feb 2025 84,708.6010 Mar 2025 78,129.2010−$2,572,530.00
long11 Mar 2025 78,595.906 Apr 2025 79,081.4026$306,344.00
long17 Apr 2025 84,030.4023 Apr 2025 93,443.006$1,844,870.00
long17 Apr 2025 84,030.409 May 2025 103,262.0022$3,769,320.00
long17 Apr 2025 84,030.4021 May 2025 106,850.0034$4,472,650.00
long17 Apr 2025 84,030.4031 May 2025 103,154.0044$38,247.20
long3 Jun 2025 105,858.0020 Jun 2025 102,491.0017−$1,592,480.00
long29 Jun 2025 107,297.0011 Jul 2025 116,010.0012$1,350,550.00
long29 Jun 2025 107,297.0014 Jul 2025 119,087.0015$1,827,430.00
long29 Jun 2025 107,297.001 Aug 2025 113,273.0033$932,350.00
long7 Aug 2025 114,992.0014 Aug 2025 123,306.007$1,205,550.00
long7 Aug 2025 114,992.0019 Aug 2025 113,284.0012−$498,818.00
long13 Sep 2025 116,029.0024 Sep 2025 111,314.0011−$2,041,610.00
long27 Sep 2025 109,643.002 Oct 2025 118,595.005$1,360,630.00
long27 Sep 2025 109,643.003 Oct 2025 120,529.006$1,654,660.00
long27 Sep 2025 109,643.007 Oct 2025 124,659.0010$2,282,290.00
long27 Sep 2025 109,643.0010 Oct 2025 117,696.0013$8,052.49
long19 Oct 2025 107,185.0030 Oct 2025 106,373.0011−$381,800.00
long23 Nov 2025 84,739.806 Jan 2026 93,859.7044$1,805,750.00
long23 Nov 2025 84,739.8020 Jan 2026 90,315.9058$2,213,720.00
long22 Jan 2026 89,454.7029 Jan 2026 84,412.707−$2,853,770.00
long7 Feb 2026 70,580.3022 Mar 2026 67,453.3043−$2,235,760.00
long2 Apr 2026 68,113.9014 Apr 2026 74,418.0012$1,550,800.00
long2 Apr 2026 68,113.905 May 2026 79,861.0033$2,889,780.00
long2 Apr 2026 68,113.9018 May 2026 76,410.1046$2,049,170.00
long21 May 2026 77,552.2028 May 2026 72,995.107−$2,975,840.00
long30 May 2026 73,460.802 Jun 2026 69,721.303−$2,572,750.00
long8 Jun 2026 63,332.0024 Jun 2026 60,849.6016−$1,976,030.00
long13 Jul 2026 63,780.0020 Aug 2026 69,334.8038$1,460,910.00
long13 Jul 2026 63,780.0021 Aug 2026 73,027.0039$2,431,970.00
long13 Jul 2026 63,780.0022 Aug 2026 78,338.0040$3,828,760.00
long27 Aug 2026 79,023.8022 Sep 2026 86,620.0026$1,618,000.00
long27 Aug 2026 79,023.808 Oct 2026 80,857.6042$784,892.00

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
Mean Reversion Strategy v2 [KL] this page—v5 strategy+1.7%521.5%
MCL-YG Pair Trading Strategy by shark792sma stdev atrv5 strategyNo trades on this market
[KL] Relative Volume + ATR Strategy by DojiEmojiatr sma stdevv4 strategy−32.7%1033.3%
[KL] Mean Reversion (ATR) Strategy by DojiEmojiatr sma stdevv5 strategyNo trades on this market
[KL] Double Bollinger Bands Strategy (for Crypto-FOREX) by DojiEmojisma stdev atrv4 strategy−42.2%4256.8%
Fractal Breakout Strategy [KL] by DojiEmojisma atr stdevv5 strategy+1.9%360.8%

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.

  • 6 settings use the untyped input() (line 13, 14, 33, 44, 46, 63). 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 52 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.

  • Line 13: input() → input.float()
  • Line 14: input() → input.int()
  • Line 33: input() → input.bool()
  • Line 44: input() → input.int()
  • Line 46: input() → input.int()
  • Line 63: input() → input.int()
⋯// TSL: calculate the stop loss price. {-_multiple       = input(2.0, title="ATR Multiplier for trailing stop loss", group=GROUP_TSL)+_multiple       = input.float(2.0, title="ATR Multiplier for trailing stop loss", group=GROUP_TSL)-ATR_TSL         = ta.atr(input(14, title="Length of ATR for trailing stop loss", group=GROUP_TSL, tooltip="Initial risk amount = atr(this length) x multiplier")) * _multiple+ATR_TSL         = ta.atr(input.int(14, title="Length of ATR for trailing stop loss", group=GROUP_TSL, tooltip="Initial risk amount = atr(this length) x multiplier")) * _multipleTSL_source      = low⋯// Taking profits at user defined target levels relative to risked amount (i.e 1R, 2R, 3R)-var bool  tp_mode = input(true, title="Take profit and different levels", group=GROUP_ORDER)+var bool  tp_mode = input.bool(true, title="Take profit and different levels", group=GROUP_ORDER)var float FIRST_LVL_PROFIT = input.float(1, title="First level profit", tooltip="Relative to risk. Example: entry at $10 and inital stop loss at $9. Taking first level profit at 1R means taking profits at $11", group=GROUP_ORDER)⋯//     Ha : atr_fast not equals to atr_slow; implies atr_fast is either too low or too high-len_fast    = input(5,title="Length of ATR (fast) for diversion test", group=GROUP_TEST)+len_fast    = input.int(5,title="Length of ATR (fast) for diversion test", group=GROUP_TEST)atr_fast    = ta.atr(len_fast)-atr_slow    = ta.atr(input(50,title="Length of ATR (slow) for diversion test", group=GROUP_TEST, tooltip="This needs to be larger than Fast"))+atr_slow    = ta.atr(input.int(50,title="Length of ATR (slow) for diversion test", group=GROUP_TEST, tooltip="This needs to be larger than Fast"))// Calculate test statistic (test_stat)⋯_prcntge_chng = math.log(close / close[1]) -len_drift = input(14, title="Length of drift", group=GROUP_TREND, tooltip="For calculation of Drift, where Drift = moving average of Log(close/prev_close) + 0.5 * its variance; If this curve is upward sloping, strategy predicts price to trend upward")+len_drift = input.int(14, title="Length of drift", group=GROUP_TREND, tooltip="For calculation of Drift, where Drift = moving average of Log(close/prev_close) + 0.5 * its variance; If this curve is upward sloping, strategy predicts price to trend upward")_drift = ta.sma(_prcntge_chng, len_drift) - math.pow(ta.stdev(_prcntge_chng, len_drift), 2) * 0.5 // Expected return (drift) = average percentage change + half variance over the lookback period⋯

Does it run in Pine Script v6?

Yes

Same 52 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

⋯// © DojiEmoji-//@version=5+//@version=6strategy("Mean Reversion (ATR) Strategy v2 [KL] ", overlay=true, pyramiding=1, initial_capital=1000000000)⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 45 msWith a workaround 1,000 bars in 54 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/// © DojiEmoji//@version=5strategy("Mean Reversion (ATR) Strategy v2 [KL] ", overlay=true, pyramiding=1, initial_capital=1000000000)var string ENUM_LONG = "Long"var string GROUP_TEST = "Hypothesis testing"var string GROUP_TSL = "Stop loss"var string GROUP_TREND = "Trend prediction"var string GROUP_ORDER = "Order size and Profit taking"backtest_timeframe_start = input.time(defval=timestamp("01 Apr 2000 13:30 +0000"), title="Backtest Start Time")within_timeframe = time >= backtest_timeframe_start// TSL: calculate the stop loss price. {_multiple       = input(2.0, title="ATR Multiplier for trailing stop loss", group=GROUP_TSL)ATR_TSL         = ta.atr(input(14, title="Length of ATR for trailing stop loss", group=GROUP_TSL, tooltip="Initial risk amount = atr(this length) x multiplier")) * _multipleTSL_source      = lowTSL_line_color  = color.greenTSL_transp      = 100var stop_loss_price = float(0)var float initial_entry_p    = float(0)var float risk_amt           = float(0)var float initial_order_size = float(0)if strategy.position_size == 0 or not within_timeframe    TSL_line_color := color.black    stop_loss_price := TSL_source - ATR_TSLelse if strategy.position_size > 0    stop_loss_price := math.max(stop_loss_price, TSL_source - ATR_TSL)    TSL_transp := 0plot(stop_loss_price, color=color.new(TSL_line_color, TSL_transp))// } end of "TSL" block// Order size and profit taking {pcnt_alloc = input.int(5, title="Allocation (%) of portfolio into this security", tooltip="Size of positions is based on this % of undrawn capital. This is fixed throughout the backtest period.", minval=0, maxval=100, group=GROUP_ORDER) / 100// Taking profits at user defined target levels relative to risked amount (i.e 1R, 2R, 3R)var bool  tp_mode = input(true, title="Take profit and different levels", group=GROUP_ORDER)var float FIRST_LVL_PROFIT = input.float(1, title="First level profit", tooltip="Relative to risk. Example: entry at $10 and inital stop loss at $9. Taking first level profit at 1R means taking profits at $11", group=GROUP_ORDER)var float SECOND_LVL_PROFIT = input.float(2, title="Second level profit", tooltip="Relative to risk. Example: entry at $10 and inital stop loss at $9. Taking second level profit at 2R means taking profits at $12", group=GROUP_ORDER)var float THIRD_LVL_PROFIT = input.float(3, title="Third level profit", tooltip="Relative to risk. Example: entry at $10 and inital stop loss at $9. Taking third level profit at 3R means taking profits at $13", group=GROUP_ORDER)// }// ATR diversion test {// Hypothesis testing (2-tailed)://// Null hypothesis (H0) and Alternative hypothesis (Ha)://     H0 : atr_fast equals atr_slow//     Ha : atr_fast not equals to atr_slow; implies atr_fast is either too low or too highlen_fast    = input(5,title="Length of ATR (fast) for diversion test", group=GROUP_TEST)atr_fast    = ta.atr(len_fast)atr_slow    = ta.atr(input(50,title="Length of ATR (slow) for diversion test", group=GROUP_TEST, tooltip="This needs to be larger than Fast"))// Calculate test statistic (test_stat)std_error   = ta.stdev(ta.tr, len_fast) / math.pow(len_fast, 0.5)test_stat = (atr_fast - atr_slow) / std_error// Compare test_stat against critical value defined by user in settings//critical_value = input.float(1.645,title="Critical value", tooltip="Strategy uses 2-tailed test to compare atr_fast vs atr_slow. Null hypothesis (H0) is that both should equal. Based on the computed test statistic value, if absolute value of it is +/- this critical value, then H0 will be rejected.", group=GROUP_TEST)conf_interval = input.string(title="Confidence Interval", defval="95%", options=["90%","95%","99%"], tooltip="Critical values of 1.645, 1.96, 2.58, for CI=90%/95%/99%, respectively; Under 2-tailed test to compare atr_fast vs atr_slow. Null hypothesis (H0) is that both should equal. Based on the computed test statistic value, if absolute value of it is +/- critical value, then H0 will be rejected.")critical_value = conf_interval == "90%" ? 1.645 : conf_interval == "95%" ? 1.96 : 2.58reject_H0 = math.abs(test_stat) > critical_value// } end of "ATR diversion test" block// Entry signals {// main entry signal (if reject_H0 == true); gets passed onto the next bar because strategy needs to check for confirmationvar _entry_signal_triggered = falseif not _entry_signal_triggered    _entry_signal_triggered := reject_H0// Confirmation signal: Trend prediction based on expected log returns_prcntge_chng = math.log(close / close[1]) len_drift = input(14, title="Length of drift", group=GROUP_TREND, tooltip="For calculation of Drift, where Drift = moving average of Log(close/prev_close) + 0.5 * its variance; If this curve is upward sloping, strategy predicts price to trend upward")_drift = ta.sma(_prcntge_chng, len_drift) - math.pow(ta.stdev(_prcntge_chng, len_drift), 2) * 0.5 // Expected return (drift) = average percentage change + half variance over the lookback period_confirmation = _drift > _drift[1]entry_signal_all = _entry_signal_triggered and _confirmation // Putting it together, Entry signal = main signal + confirmation signalif entry_signal_all    _entry_signal_triggered := false //reset// } end of "Entry signals" block// MAIN {// Update the stop limit if strategy holds a position.if strategy.position_size > 0    strategy.exit(ENUM_LONG, comment="SL", stop=stop_loss_price)// Entryif within_timeframe and entry_signal_all and strategy.position_size == 0    initial_entry_p := close    risk_amt := ATR_TSL    initial_order_size := math.floor(pcnt_alloc * strategy.equity / close)    strategy.entry(ENUM_LONG, strategy.long, qty=initial_order_size)var int TP_taken_count = 0if tp_mode and close > strategy.position_avg_price    if close >= initial_entry_p + THIRD_LVL_PROFIT * risk_amt and TP_taken_count == 2        strategy.close(ENUM_LONG, comment="TP Lvl3", qty=math.floor(initial_order_size / 3))        TP_taken_count := TP_taken_count + 1    else if close >= initial_entry_p + SECOND_LVL_PROFIT * risk_amt and TP_taken_count == 1        strategy.close(ENUM_LONG, comment="TP Lvl2", qty=math.floor(initial_order_size / 3))        TP_taken_count := TP_taken_count + 1    else if close >= initial_entry_p + FIRST_LVL_PROFIT * risk_amt and TP_taken_count == 0        strategy.close(ENUM_LONG, comment="TP Lvl1", qty=math.floor(initial_order_size / 3))        TP_taken_count := TP_taken_count + 1    // Alerts_atr = ta.atr(14)alert_helper(msg) =>    prefix = "[" + syminfo.root + "] "    suffix = "(P=" + str.tostring(close, "#.##") + "; atr=" + str.tostring(_atr, "#.##") + ")"    alert(str.tostring(prefix) + str.tostring(msg) + str.tostring(suffix), alert.freq_once_per_bar)if strategy.position_size > 0 and ta.change(strategy.position_size)    if strategy.position_size > strategy.position_size[1]        alert_helper("BUY")    else if strategy.position_size < strategy.position_size[1]        alert_helper("SELL")// Clean up - set the variables back to default values once no longer in useif ta.change(strategy.position_size) and strategy.position_size == 0    TP_taken_count := 0    initial_entry_p := float(0)    risk_amt := float(0)    initial_order_size := float(0)    stop_loss_price := float(0)// } end of MAIN block