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
- 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.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Backtest Start Time | timestamp("01 Apr 2000 13:30 +0000") | time | within_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 loss | 2.0 | float | ATR_TSL |
| Length of ATR for trailing stop lossInitial risk amount = atr(this length) x multiplier | 14 | int | stop_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. | 5 | int · min 0 · max 100 | initial_order_size |
| Take profit and different levels | true | bool | line 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 $11 | 1 | float | close 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 $12 | 2 | float | close 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 $13 | 3 | float | close Long line 82 |
| Hypothesis testing | |||
| Length of ATR (fast) for diversion test | 5 | int | atr_fast std_error |
| Length of ATR (slow) for diversion testThis needs to be larger than Fast | 50 | int | test_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 upward | 14 | int | _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.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Exit Long stop | strategy.position_size > 0 | On | 73 |
| Open Long long | within_timeframe and entry_signal_all and strategy.position_size == 0 | On | 79 |
| Close Long | close >= initial_entry_p + THIRD_LVL_PROFIT * risk_amt and TP_taken_count == 2 | On | 83 |
| Close Long | close >= initial_entry_p + SECOND_LVL_PROFIT * risk_amt and TP_taken_count == 1 | On | 86 |
| Close Long | close >= initial_entry_p + FIRST_LVL_PROFIT * risk_amt and TP_taken_count == 0 | On | 89 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Alerts
| Alert | Call | Message | Line |
|---|---|---|---|
| (no title) | alert | str.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.
- 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.
| Market | Net | Buy and hold | Trades | Won | Profit factor | Max drawdown | Period |
|---|---|---|---|---|---|---|---|
| BTCUSDT 1D | +1.7% | +102.5% | 52 | 65% | 1.38 | 1.5% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | −0.0% | +5.5% | 47 | 57% | 0.98 | 0.9% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +1.6% | +9.8% | 55 | 64% | 1.20 | 3.7% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | +0.1% | +8.4% | 40 | 55% | 1.05 | 1.4% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | −0.8% | +16.7% | 50 | 62% | 0.92 | 3.4% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | −1.2% | +21.5% | 48 | 56% | 0.66 | 1.8% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | +2.9% | +148.3% | 52 | 69% | 1.66 | 1.4% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | −1.0% | +17.1% | 53 | 58% | 0.61 | 1.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 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 13 | 62% | −$1,408,700.00 |
| Sideways market | 24 | 54% | −$5,424,110.00 |
| Falling market | 15 | 87% | $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.
All 52 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 18 Mar 2024 68,393.50 | 13 Apr 2024 63,245.30 | 26 | −$3,763,320.00 |
| long | 20 Apr 2024 63,818.00 | 1 May 2024 59,014.70 | 11 | −$3,746,570.00 |
| long | 9 May 2024 61,193.00 | 21 May 2024 71,446.60 | 12 | $2,768,470.00 |
| long | 9 May 2024 61,193.00 | 14 Jun 2024 65,931.20 | 36 | $2,558,620.00 |
| long | 21 Jun 2024 64,870.00 | 24 Jun 2024 60,639.70 | 3 | −$3,253,090.00 |
| long | 26 Jun 2024 61,806.00 | 4 Jul 2024 58,655.50 | 8 | −$2,533,030.00 |
| long | 17 Aug 2024 58,874.60 | 27 Aug 2024 58,361.60 | 10 | −$431,921.00 |
| long | 18 Sep 2024 60,314.00 | 27 Sep 2024 65,174.00 | 9 | $1,331,640.00 |
| long | 18 Sep 2024 60,314.00 | 1 Oct 2024 61,451.30 | 13 | $623,229.00 |
| long | 7 Oct 2024 62,819.90 | 16 Oct 2024 67,074.10 | 9 | $1,118,860.00 |
| long | 7 Oct 2024 62,819.90 | 30 Oct 2024 72,736.40 | 23 | $2,608,040.00 |
| long | 7 Oct 2024 62,819.90 | 4 Nov 2024 67,264.60 | 28 | $1,173,410.00 |
| long | 16 Nov 2024 91,032.10 | 23 Nov 2024 98,892.00 | 7 | $1,430,510.00 |
| long | 16 Nov 2024 91,032.10 | 17 Dec 2024 106,059.00 | 31 | $2,734,840.00 |
| long | 16 Nov 2024 91,032.10 | 19 Dec 2024 97,438.70 | 33 | $1,178,820.00 |
| long | 24 Dec 2024 94,881.50 | 13 Jan 2025 90,970.30 | 20 | −$2,065,120.00 |
| long | 22 Jan 2025 106,144.00 | 3 Feb 2025 95,479.70 | 12 | −$5,022,800.00 |
| long | 15 Feb 2025 97,500.50 | 25 Feb 2025 90,024.10 | 10 | −$3,820,440.00 |
| long | 28 Feb 2025 84,708.60 | 3 Mar 2025 94,270.00 | 3 | $1,864,480.00 |
| long | 28 Feb 2025 84,708.60 | 10 Mar 2025 78,129.20 | 10 | −$2,572,530.00 |
| long | 11 Mar 2025 78,595.90 | 6 Apr 2025 79,081.40 | 26 | $306,344.00 |
| long | 17 Apr 2025 84,030.40 | 23 Apr 2025 93,443.00 | 6 | $1,844,870.00 |
| long | 17 Apr 2025 84,030.40 | 9 May 2025 103,262.00 | 22 | $3,769,320.00 |
| long | 17 Apr 2025 84,030.40 | 21 May 2025 106,850.00 | 34 | $4,472,650.00 |
| long | 17 Apr 2025 84,030.40 | 31 May 2025 103,154.00 | 44 | $38,247.20 |
| long | 3 Jun 2025 105,858.00 | 20 Jun 2025 102,491.00 | 17 | −$1,592,480.00 |
| long | 29 Jun 2025 107,297.00 | 11 Jul 2025 116,010.00 | 12 | $1,350,550.00 |
| long | 29 Jun 2025 107,297.00 | 14 Jul 2025 119,087.00 | 15 | $1,827,430.00 |
| long | 29 Jun 2025 107,297.00 | 1 Aug 2025 113,273.00 | 33 | $932,350.00 |
| long | 7 Aug 2025 114,992.00 | 14 Aug 2025 123,306.00 | 7 | $1,205,550.00 |
| long | 7 Aug 2025 114,992.00 | 19 Aug 2025 113,284.00 | 12 | −$498,818.00 |
| long | 13 Sep 2025 116,029.00 | 24 Sep 2025 111,314.00 | 11 | −$2,041,610.00 |
| long | 27 Sep 2025 109,643.00 | 2 Oct 2025 118,595.00 | 5 | $1,360,630.00 |
| long | 27 Sep 2025 109,643.00 | 3 Oct 2025 120,529.00 | 6 | $1,654,660.00 |
| long | 27 Sep 2025 109,643.00 | 7 Oct 2025 124,659.00 | 10 | $2,282,290.00 |
| long | 27 Sep 2025 109,643.00 | 10 Oct 2025 117,696.00 | 13 | $8,052.49 |
| long | 19 Oct 2025 107,185.00 | 30 Oct 2025 106,373.00 | 11 | −$381,800.00 |
| long | 23 Nov 2025 84,739.80 | 6 Jan 2026 93,859.70 | 44 | $1,805,750.00 |
| long | 23 Nov 2025 84,739.80 | 20 Jan 2026 90,315.90 | 58 | $2,213,720.00 |
| long | 22 Jan 2026 89,454.70 | 29 Jan 2026 84,412.70 | 7 | −$2,853,770.00 |
| long | 7 Feb 2026 70,580.30 | 22 Mar 2026 67,453.30 | 43 | −$2,235,760.00 |
| long | 2 Apr 2026 68,113.90 | 14 Apr 2026 74,418.00 | 12 | $1,550,800.00 |
| long | 2 Apr 2026 68,113.90 | 5 May 2026 79,861.00 | 33 | $2,889,780.00 |
| long | 2 Apr 2026 68,113.90 | 18 May 2026 76,410.10 | 46 | $2,049,170.00 |
| long | 21 May 2026 77,552.20 | 28 May 2026 72,995.10 | 7 | −$2,975,840.00 |
| long | 30 May 2026 73,460.80 | 2 Jun 2026 69,721.30 | 3 | −$2,572,750.00 |
| long | 8 Jun 2026 63,332.00 | 24 Jun 2026 60,849.60 | 16 | −$1,976,030.00 |
| long | 13 Jul 2026 63,780.00 | 20 Aug 2026 69,334.80 | 38 | $1,460,910.00 |
| long | 13 Jul 2026 63,780.00 | 21 Aug 2026 73,027.00 | 39 | $2,431,970.00 |
| long | 13 Jul 2026 63,780.00 | 22 Aug 2026 78,338.00 | 40 | $3,828,760.00 |
| long | 27 Aug 2026 79,023.80 | 22 Sep 2026 86,620.00 | 26 | $1,618,000.00 |
| long | 27 Aug 2026 79,023.80 | 8 Oct 2026 80,857.60 | 42 | $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.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| Mean Reversion Strategy v2 [KL] this page | — | v5 strategy | +1.7% | 52 | 1.5% |
| MCL-YG Pair Trading Strategy by shark792 | sma stdev atr | v5 strategy | No trades on this market | ||
| [KL] Relative Volume + ATR Strategy by DojiEmoji | atr sma stdev | v4 strategy | −32.7% | 10 | 33.3% |
| [KL] Mean Reversion (ATR) Strategy by DojiEmoji | atr sma stdev | v5 strategy | No trades on this market | ||
| [KL] Double Bollinger Bands Strategy (for Crypto-FOREX) by DojiEmoji | sma stdev atr | v4 strategy | −42.2% | 42 | 56.8% |
| Fractal Breakout Strategy [KL] by DojiEmoji | sma atr stdev | v5 strategy | +1.9% | 36 | 0.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.
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.
⋯// © DojiEmoji-//@version=5+//@version=6strategy("Mean Reversion (ATR) Strategy v2 [KL] ", overlay=true, pyramiding=1, initial_capital=1000000000)⋯Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 45 ms | With a workaround 1,000 bars in 54 ms | Not measured |
| PineTS | Not tested | Not tested | Not 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