Zeal Terminal Open in Zeal Terminal

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
Prerendered with the defaults. Change anything and run it here. The script runs in your browser.
Settings (10)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$1,000,000$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.
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.

SettingDefaultType and rangeFeeds
Backtest Start Timetimestamp("01 Apr 2000 13:30 +0000")timewithin_timeframe
Take profit and different levelstrueboolline 51
Stop loss
Length of ATR for trailing stop loss14intrisk_amt stop_loss_price
ATR Multiplier for trailing stop loss2.0floatrisk_amt stop_loss_price
Signals
Main signal: Length of lookback (ATR mean reversion)20int_ATR_volat _avg_atr _std_volat
Confirmation: Lenth to lookback for trend prediction20int_drift
Order size
Allocation (%) of portfolio into this securityNo rebalancing5int · min 0 · max 100initial_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 $111floatclose 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 $122floatclose 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 $133floatclose 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_sizechanged_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.

high · low · closehigh · low · closeprice data_len_volatMain signal: Length of …setting · 20_len_driftConfirmation: Lenth to …setting · 20closecloseprice dataATR_X2_TSLATR Multiplier for trai…setting · 2.0pcnt_allocAllocation (%) of portf…setting · 5lowlowprice datatimetimeprice databacktest_timeframe_startBacktest Start Timesetting · timestamp("01 Apr 2…THIRD_LVL_PROFITThird level profitsetting · 3SECOND_LVL_PROFITSecond level profitsetting · 2FIRST_LVL_PROFITFirst level profitsetting · 1_ATR_volatATR→ _ATR_volat_avg_atrSMA→ _avg_atr_std_volatStdev→ _std_volat_driftSMA / Stdev→ _driftchanged_pos_sizeChange→ changed_pos_sizeinitial_entry_p, _prcntge_chnginitial_entry_p · _prcn…2 valuesrisk_amtrisk_amtvalueinitial_order_sizeinitial_order_sizevalueTSL_sourceTSL_sourcevaluestop_loss_pricestop_loss_pricevaluewithin_timeframewithin_timeframeconditionentry_signal_allentry_signal_allcondition_signal_diverted_ATR_signal_diverted_ATRcondition_signal_uptrend_signal_uptrendconditionTSL_line_colorColourTSL_line_colorclose:LongClose Longstrategy.closeexit:Longexit Longstrategy.exitentry:LongOpen Longstrategy.entryplot:28plotplotalert:72alertalert

Order rules

OrderFires whenBy defaultLine
Close Longclose >= initial_entry_p + THIRD_LVL_PROFIT * risk_amtOn53
Close Longclose >= initial_entry_p + SECOND_LVL_PROFIT * risk_amtOn55
Close Longclose >= initial_entry_p + FIRST_LVL_PROFIT * risk_amtOn57
Exit Long stopstrategy.position_size > 0On61
Open Long longwithin_timeframe and entry_signal_all and strategy.position_size == 0On67

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)72

Does it repaint?

No

No repainting patterns in the source.

Not measuredNo trades to compareThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, but neither the live nor the historical run produced any trades in them, so the replay says nothing either way.
  • 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 1D0.0%+102.5%00%—0.0%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h0.0%+5.5%00%—0.0%8 May 2026 – 21 Oct 2026
ETHUSDT 1D+1.0%+9.8%5143%1.083.6%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+0.1%+8.4%4838%1.021.3%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−0.9%+16.7%4342%0.946.2%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+0.2%+21.5%4943%1.051.4%8 May 2026 – 21 Oct 2026
BNBUSDT 1D+1.0%+148.3%4646%1.102.6%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+0.1%+17.1%5443%1.051.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.

ScriptSharesTypeNetTradesMax drawdown
[KL] Mean Reversion (ATR) Strategy this page—v5 strategy0.0%00.0%
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] 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%
Mean Reversion Strategy v2 [KL] by DojiEmojiatr stdev smav5 strategy+1.7%521.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.

Clean v5

VerifiedDownload the v5 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

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 36 msYes 1,000 bars in 44 msNot measured
PineTSNot testedNot testedNot 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