Pine Script v5 · Strategy
[KL] Mean Reversion (ATR) Strategy
A Pine Script v5 strategy built on ATR (20), SMA (_ATR_volat, 20) and Stdev (_ATR_volat, 20). 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. 10 settings; defaults include Length of ATR for trailing stop loss 14, ATR Multiplier for trailing stop loss 2.0 and Main signal: Length of lookback (ATR mean reversion) 20.
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 [KL] Mean Reversion (ATR) Strategy repaint?
- No
- No repainting patterns were found in the source. The live replay was not measured: it had no trades to compare.
- How did [KL] Mean Reversion (ATR) Strategy do on BTCUSDT 1D with default settings?
- Not measured
- It closed no trades there from 26 Jan 2024 to 21 Oct 2026 with the default settings, so there is no result to report. Its code limits trading to a date window, which can leave this period out. On ETHUSDT 1D it did trade; that row of the markets table below has its figures. A backtest, not investment advice.
- What alerts does [KL] Mean Reversion (ATR) Strategy have?
- 1
- str.tostring(prefix) + str.tostring(msg) + str.tostring(suffix).
- Does [KL] Mean Reversion (ATR) Strategy run in Pine Script v6?
- No
- The v6 version runs in Zeal Terminal's engine, but its results differ from the v5 version: Trades differ: 51 before, 47 after on ETHUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download.
- Does [KL] Mean Reversion (ATR) Strategy use a stop loss?
- Yes
- strategy.exit sets a stop on line 61.
BTCUSDT · 1D · default settings
- Winning trade
- Losing trade
- Equity
- Buy and hold
- Net profit
- 0.00%
- $0.00
- Buy and hold
- +102.5%
- same period
- Closed trades
- 0
- 0 won · 0 lost
- Profitable
- 0.0%
- of closed trades
- Profit factor
- —
- gross profit ÷ gross loss
- Max drawdown
- 0.00%
- $0.00
One run with the author's default settings, $1,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.
-
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 |
| Take profit and different levels | true | bool | line 51 |
| Stop loss | |||
| Length of ATR for trailing stop loss | 14 | int | risk_amt stop_loss_price |
| ATR Multiplier for trailing stop loss | 2.0 | float | risk_amt stop_loss_price |
| Signals | |||
| Main signal: Length of lookback (ATR mean reversion) | 20 | int | _ATR_volat _avg_atr _std_volat |
| Confirmation: Lenth to lookback for trend prediction | 20 | int | _drift |
| Order size | |||
| Allocation (%) of portfolio into this securityNo rebalancing | 5 | int · min 0 · max 100 | initial_order_size |
| Profit taking | |||
| 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 56 |
| 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 54 |
| 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 52 |
What it calculates
- ATRMain signal: Length of lookback (ATR mean reversion) (20)
_ATR_volat · line 32 - SMA_ATR_volat, Main signal: Length of lookback (ATR mean reversion) (20)
_avg_atr · line 33 - Stdev_ATR_volat, Main signal: Length of lookback (ATR mean reversion) (20)
_std_volat · line 34 - SMA / Stdev_prcntge_chng, Confirmation: Lenth to lookback for trend prediction (20)
_drift · line 41 - Changestrategy.position_size
changed_pos_size · line 79
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 |
|---|---|---|---|
| Close Long | close >= initial_entry_p + THIRD_LVL_PROFIT * risk_amt | On | 53 |
| Close Long | close >= initial_entry_p + SECOND_LVL_PROFIT * risk_amt | On | 55 |
| Close Long | close >= initial_entry_p + FIRST_LVL_PROFIT * risk_amt | On | 57 |
| Exit Long stop | strategy.position_size > 0 | On | 61 |
| Open Long long | within_timeframe and entry_signal_all and strategy.position_size == 0 | On | 67 |
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) | 72 |
Does it repaint?
No
No repainting patterns in the source.
- 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 | 0.0% | +102.5% | 0 | 0% | — | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | 0.0% | +5.5% | 0 | 0% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +1.0% | +9.8% | 51 | 43% | 1.08 | 3.6% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | +0.1% | +8.4% | 48 | 38% | 1.02 | 1.3% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | −0.9% | +16.7% | 43 | 42% | 0.94 | 6.2% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | +0.2% | +21.5% | 49 | 43% | 1.05 | 1.4% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | +1.0% | +148.3% | 46 | 46% | 1.10 | 2.6% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | +0.1% | +17.1% | 54 | 43% | 1.05 | 1.1% | 8 May 2026 – 21 Oct 2026 |
Backtests are simulations on historical data and are not investment advice.
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 |
|---|---|---|---|---|---|
| [KL] Mean Reversion (ATR) Strategy this page | — | v5 strategy | 0.0% | 0 | 0.0% |
| 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] 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% |
| Mean Reversion Strategy v2 [KL] by DojiEmoji | atr stdev sma | v5 strategy | +1.7% | 52 | 1.5% |
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.
- 3 settings use the untyped input() (line 31, 39, 47). 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 51 trades and the same P&L on ETHUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 31: input() → input.int()
- Line 39: input() → input.int()
- Line 47: input() → input.bool()
⋯// ATR diversion test-_len_volat = input(20, title="Main signal: Length of lookback (ATR mean reversion)", group=GROUP_SIGNALS)+_len_volat = input.int(20, title="Main signal: Length of lookback (ATR mean reversion)", group=GROUP_SIGNALS)_ATR_volat = ta.atr(_len_volat)⋯// lognormal returns for trend prediction-_len_drift = input(20, title="Confirmation: Lenth to lookback for trend prediction", group=GROUP_SIGNALS)+_len_drift = input.int(20, title="Confirmation: Lenth to lookback for trend prediction", group=GROUP_SIGNALS)_prcntge_chng = math.log(close / close[1])⋯// 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")+var bool tp_mode = input.bool(true, title="Take profit and different levels")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_TP)⋯Does it run in Pine Script v6?
No
The v6 version runs in Zeal Terminal's engine, but its results differ from the v5 version: Trades differ: 51 before, 47 after on ETHUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.
⋯// © DojiEmoji-//@version=5+//@version=6strategy("Mean Reversion (ATR) Strategy [KL]", overlay=true, pyramiding=1)⋯Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 36 ms | Yes 1,000 bars in 44 ms | Not measured |
| PineTS | Not tested | Not tested | Not measured |
“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report.
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 [KL]", overlay=true, pyramiding=1)var string GROUP_TP = "Profit taking"var string GROUP_SL = "Stop loss"var string GROUP_ORDER = "Order size"var string GROUP_SIGNALS = "Signals"var string ENUM_LONG = "Long"backtest_timeframe_start = input.time(defval=timestamp("01 Apr 2000 13:30 +0000"), title="Backtest Start Time")within_timeframe = time >= backtest_timeframe_start// Variables stored upon initial entry, var initial_entry_p = float(0) // initial entry pricevar risk_amt = float(0) // initial entry price minus initial stop loss pricevar initial_order_size = 0// TSL: calculate the stop loss price. {ATR_X2_TSL = ta.atr(input.int(14, title="Length of ATR for trailing stop loss", group=GROUP_SL)) * input.float(2.0, title="ATR Multiplier for trailing stop loss", group=GROUP_SL)TSL_source = lowvar stop_loss_price = float(0)TSL_line_color = color.greenTSL_transp = 100if strategy.position_size == 0 or not within_timeframe TSL_line_color := color.black stop_loss_price := TSL_source - ATR_X2_TSLelse if strategy.position_size > 0 stop_loss_price := math.max(stop_loss_price, TSL_source - ATR_X2_TSL) TSL_transp := 0plot(stop_loss_price, color=color.new(TSL_line_color, TSL_transp))// } end of "TSL" block// ATR diversion test_len_volat = input(20, title="Main signal: Length of lookback (ATR mean reversion)", group=GROUP_SIGNALS)_ATR_volat = ta.atr(_len_volat)_avg_atr = ta.sma(_ATR_volat, _len_volat)_std_volat = ta.stdev(_ATR_volat, _len_volat)var _signal_diverted_ATR = falseMULTIPLE_ATR_STD = 1_signal_diverted_ATR := not _signal_diverted_ATR and _ATR_volat > (_avg_atr + _std_volat*MULTIPLE_ATR_STD) or _ATR_volat < (_avg_atr - _std_volat*MULTIPLE_ATR_STD)// lognormal returns for trend prediction_len_drift = input(20, title="Confirmation: Lenth to lookback for trend prediction", group=GROUP_SIGNALS)_prcntge_chng = math.log(close / close[1])_drift = ta.sma(_prcntge_chng, _len_drift) - math.pow(ta.stdev(_prcntge_chng, _len_drift), 2) * 0.5_signal_uptrend = _drift > _drift[1] and _drift > _drift[2] or _drift > 0entry_signal_all = _signal_diverted_ATR and _signal_uptrend //main signal + confirmation // Order size and profit takingpcnt_alloc = input.int(5, title="Allocation (%) of portfolio into this security", tooltip="No rebalancing", 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")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_TP)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_TP)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_TP)if tp_mode if close >= initial_entry_p + THIRD_LVL_PROFIT * risk_amt strategy.close(ENUM_LONG, comment="TP", qty=math.floor(initial_order_size / 3)) else if close >= initial_entry_p + SECOND_LVL_PROFIT * risk_amt strategy.close(ENUM_LONG, comment="TP", qty=math.floor(initial_order_size / 3)) else if close >= initial_entry_p + FIRST_LVL_PROFIT * risk_amt strategy.close(ENUM_LONG, comment="TP")// MAIN {// Update the stop limit if strategy holds a positionif 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_X2_TSL initial_order_size := math.floor(pcnt_alloc * strategy.equity / close) strategy.entry(ENUM_LONG, strategy.long, comment=strategy.position_size > 0 ? "adding" : "initial", qty=initial_order_size)// Alertsalert_per_bar(msg) => prefix = "[" + syminfo.root + "] " suffix = "(P=" + str.tostring(close, "#.##") + "; atr=" + str.tostring(_ATR_volat, "#.##") + ")" 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_per_bar("BUY") else if strategy.position_size < strategy.position_size[1] alert_per_bar("SELL")// Clean upchanged_pos_size = ta.change(strategy.position_size)if changed_pos_size and strategy.position_size == 0 initial_order_size := 0 initial_entry_p := float(0) risk_amt := float(0) stop_loss_price := float(0)else if changed_pos_size _signal_diverted_ATR := false// } end of MAIN block