Zeal Terminal Open in Zeal Terminal

Pine Script v4 · Strategy

Twin Range Filter Algo

A Pine Script v4 strategy built on EMA (x - x[1], t), TR (true) and ATR or Lowest or SMA (length). It has 6 order rules, 2 entries among them, and trades long and short with the default settings. Exits use a stop loss and a profit target. Each trade is one contract and pays no commission. 27 settings; defaults include Source close, Fast period 27 and Fast range 1.6.

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 Twin Range Filter Algo repaint?
Yes
At least one pattern in the source can repaint: intrabar recalculation.
How did Twin Range Filter Algo do on BTCUSDT 1D with default settings?
+48.40%
From 26 Jan 2024 to 21 Oct 2026, over 18 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Can Twin Range Filter Algo be converted to Pine Script v5?
No
The automatic step from v4 to v5 changes the results, so no v5 download is offered; the edits are shown below.
What alerts does Twin Range Filter Algo have?
2
i_message_long; i_message_short.
Does Twin Range Filter Algo use a stop loss?
Yes
strategy.exit sets a stop on line 133, 136.

BTCUSDT · 1D · default settings

  • Plot
  • Plot
  • Plot
  • Plot
  • 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 (27)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$148,403$202,527Equity from $100,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
+48.40%
$48,404.80
Buy and hold
+102.5%
same period
Closed trades
18
9 won · 9 lost
Profitable
50.0%
of closed trades
Profit factor
2.85
gross profit ÷ gross loss
Max drawdown
6.82%
−$9,758.73

One run with the author's default settings, $100,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

    sma(low, length) ignores the settings line 89

    Line 89 hard-codes low where line 51 uses “Source”. Changing those settings moves one band but not this one.

    sma(low, length)sma(source, length)
  • Likely bug

    sma(high, length) ignores the settings line 95

    Line 95 hard-codes high where line 51 uses “Source”. Changing those settings moves one band but not this one.

    sma(high, length)sma(source, length)
  • Likely bug

    sma(high, length) ignores the settings line 109

    Line 109 hard-codes high where line 51 uses “Source”. Changing those settings moves one band but not this one.

    sma(high, length)sma(source, length)
  • Likely bug

    sma(low, length) ignores the settings line 116

    Line 116 hard-codes low where line 51 uses “Source”. Changing those settings moves one band but not this one.

    sma(low, length)sma(source, length)
  • Check

    1 setting does nothing

    “Following conditions and backtest algorithm are added by @greenmask9 🎯, original script is written by @colinmck 👍. Read both of their's release notes for more info on how this script works.” is declared but never read.

  • 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.

  • Note

    Uses an argument v6 removed

    when = on line 147, 148. The upgraded version below moves each call inside an if block.

Upgrade and export

Written in Pine Script v4. The upgrade to v5 takes 1 step, one per version, each applied to the result of the one before. A last clean-v5 pass then types the settings and moves when = into if blocks, which v6 requires. Every step runs before and after on the same candles in Zeal Terminal's engine; a step whose results differ is shown but not offered as a download. Upgrades preserve behaviour: bugs are fixed in the Review, never silently here.

  • Upgrading to v5 renames ema → ta.ema, abs → math.abs, sma → ta.sma, rma → ta.rma, wma → ta.wma, tr → ta.tr, floor → math.floor, atr → ta.atr, lowest → ta.lowest, highest → ta.highest, barssince → ta.barssince.
  • 2 strategy calls use the when = argument (line 147, 148). It is deprecated in v5 and removed in v6, where each call moves inside an if block.

v4 → v5

Differs

Trades differ: 18 before, 27 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.

  • Line 3: //@version=4 → //@version=5
  • Line 13: ema → ta.ema
  • Line 13: abs → math.abs
  • Line 14: ema → ta.ema
  • Line 44: input(type = input.bool) → input.bool()
  • Line 45: input(type = input.bool) → input.bool()
38 more edits
  • Line 51: sma → ta.sma
  • Line 54: rma → ta.rma
  • Line 57: ema → ta.ema
  • Line 59: wma → ta.wma
  • Line 65: rma → ta.rma
  • Line 68: sma → ta.sma
  • Line 71: ema → ta.ema
  • Line 73: wma → ta.wma
  • Line 74: tr → ta.tr
  • Line 75: tr → ta.tr
  • Line 76: floor → math.floor
  • Line 77: input(type = input.integer) → input.int()
  • Line 83: input(type = input.float) → input.float()
  • Line 87: atr → ta.atr
  • Line 88: lowest → ta.lowest
  • Line 89: sma → ta.sma
  • Line 90: atr → ta.atr
  • Line 93: atr → ta.atr
  • Line 94: abs → math.abs
  • Line 94: lowest → ta.lowest
  • Line 95: abs → math.abs
  • Line 95: sma → ta.sma
  • Line 96: atr → ta.atr
  • Line 102: input(type = input.float) → input.float()
  • Line 106: atr → ta.atr
  • Line 107: atr → ta.atr
  • Line 108: abs → math.abs
  • Line 108: highest → ta.highest
  • Line 109: abs → math.abs
  • Line 109: sma → ta.sma
  • Line 113: atr → ta.atr
  • Line 114: atr → ta.atr
  • Line 115: abs → math.abs
  • Line 115: lowest → ta.lowest
  • Line 116: abs → math.abs
  • Line 116: sma → ta.sma
  • Line 129: barssince → ta.barssince
  • Line 130: barssince → ta.barssince
⋯// © colinmck, greenmask9-//@version=4+//@version=5strategy(title="Twin Range Filter Algo v.3", shorttitle = "Twin Range Strategy", overlay=true)⋯    wper = t * 2 - 1-    avrng = ema(abs(x - x[1]), t)+    avrng = ta.ema(math.abs(x - x[1]), t)-    smoothrng = ema(avrng, wper) * m+    smoothrng = ta.ema(avrng, wper) * m    smoothrng⋯//-Separator = input(title="Following conditions and backtest algorithm are added by @greenmask9 🎯, original script is written by @colinmck 👍. Read both of their's release notes for more info on how this script works.", type=input.bool, defval=false, group = "Greenmask's testing resources & ATR condition")+Separator = input.bool(title="Following conditions and backtest algorithm are added by @greenmask9 🎯, original script is written by @colinmck 👍. Read both of their's release notes for more info on how this script works.", defval=false, group = "Greenmask's testing resources & ATR condition")-disabler = input(title="Disable @greenmask9's ATR conditions", type=input.bool, defval=false, group = "Greenmask's testing resources & ATR condition")+disabler = input.bool(title="Disable @greenmask9's ATR conditions", defval=false, group = "Greenmask's testing resources & ATR condition")//second⋯    if s2 == "SMA"-        sma(source, l2)+        ta.sma(source, l2)    else        if s2 == "RMA"-            rma(source, l2)+            ta.rma(source, l2)        else            if s2 == "EMA"-                ema(source, l2)+                ta.ema(source, l2)            else-                wma(source, l2)+                ta.wma(source, l2)//third⋯    if s3 == "RMA"-        rma(source, l3)+        ta.rma(source, l3)    else        if s3 == "SMA"-            sma(source, l3)+            ta.sma(source, l3)        else            if s3 == "EMA"-                ema(source, l3)+                ta.ema(source, l3)            else-                wma(source, l3)+                ta.wma(source, l3)-atr20=atr2(tr(true), l2)+atr20=atr2(ta.tr(true), l2)-atr30=atr3(tr(true), l3)+atr30=atr3(ta.tr(true), l3)-ordersize=floor(strategy.initial_capital/close)+ordersize=math.floor(strategy.initial_capital/close)-maxcandles_till_close = input(title="Time-based Close", type=input.integer, defval=17, group = "Alternative Exit")+maxcandles_till_close = input.int(title="Time-based Close", defval=17, group = "Alternative Exit")i_time = input(true, "Enable Time Base Close", group = "Alternative Exit" )⋯i_sl_atr = input(10, "Calculation Length", group = "Stop-loss")-i_sl_perc = input(80, "Percentage", group = "Stop-loss", type = input.float) / 100+i_sl_perc = input.float(80, "Percentage", group = "Stop-loss") / 100i_sl_ticks = input(defval = 10, minval = 1, title = "Number of ticks", group = "Stop-loss") * syminfo.mintick⋯f_stop_long (calculation, length, mult, ticks) =>-    stop_0 = calculation == "Low - (ATR[len] * %)" ? low - (atr(length) * mult) - ticks   :+    stop_0 = calculation == "Low - (ATR[len] * %)" ? low - (ta.atr(length) * mult) - ticks   :-     calculation == "Low - (close - lowest low[len]) * %" ? low - (close - (lowest(low, length))) * mult - ticks :+     calculation == "Low - (close - lowest low[len]) * %" ? low - (close - (ta.lowest(low, length))) * mult - ticks :-     calculation == "Low - (close - average low[len]) * %" ? low - (close - sma(low, length)) * mult - ticks :+     calculation == "Low - (close - average low[len]) * %" ? low - (close - ta.sma(low, length)) * mult - ticks :-     calculation ==  "Close - (ATR[len] * %)" ? close - (atr(length) * mult) - ticks  :+     calculation ==  "Close - (ATR[len] * %)" ? close - (ta.atr(length) * mult) - ticks  :     low - ticksf_stop_short (calculation, length, mult, ticks) =>-    stop_0 = calculation == "Low - (ATR[len] * %)" ? high + (atr(length) * mult) + ticks  :+    stop_0 = calculation == "Low - (ATR[len] * %)" ? high + (ta.atr(length) * mult) + ticks  :-     calculation == "Low - (close - lowest low[len]) * %" ? high + abs(close - lowest(high, length)) * mult + ticks :+     calculation == "Low - (close - lowest low[len]) * %" ? high + math.abs(close - ta.lowest(high, length)) * mult + ticks :-     calculation == "Low - (close - average low[len]) * %" ? high + abs(close - sma(high, length)) * mult + ticks :+     calculation == "Low - (close - average low[len]) * %" ? high + math.abs(close - ta.sma(high, length)) * mult + ticks :-     calculation ==  "Close - (ATR[len] * %)" ? close + (atr(length) * mult) + ticks  :+     calculation ==  "Close - (ATR[len] * %)" ? close + (ta.atr(length) * mult) + ticks  :     high + ticks⋯i_tr_atr = input(10, "Calculation Length", group = "Target")-i_tr_perc = input(500, "Percentage", group = "Target", type = input.float) / 100+i_tr_perc = input.float(500, "Percentage", group = "Target") / 100i_tr_ticks = input(defval = 10, minval = 1, title = "Number of ticks", group = "Target") * syminfo.mintick⋯f_target_long (calculation, length, mult, ticks) =>-    stop_0 = calculation == "High + (ATR[len] * %)" ? high + (atr(length) * mult) + ticks :+    stop_0 = calculation == "High + (ATR[len] * %)" ? high + (ta.atr(length) * mult) + ticks :-     calculation == "Close + (ATR[len] * %)" ? close + (atr(length) * mult) + ticks :+     calculation == "Close + (ATR[len] * %)" ? close + (ta.atr(length) * mult) + ticks :-     calculation == "Close + abs(close - highest high[len]) * %" ? close + abs(close - (highest(high, length))) * mult + ticks :+     calculation == "Close + abs(close - highest high[len]) * %" ? close + math.abs(close - (ta.highest(high, length))) * mult + ticks :-     calculation == "Close + abs(close - average high[len]) * %" ? close + abs(close - sma(high, length)) * mult + ticks :+     calculation == "Close + abs(close - average high[len]) * %" ? close + math.abs(close - ta.sma(high, length)) * mult + ticks :     calculation ==  "High + TicksNumber" ? high + ticks  :⋯f_target_short (calculation, length, mult, ticks) =>-    stop_0 = calculation == "High + (ATR[len] * %)" ? low - (atr(length) * mult) - ticks :+    stop_0 = calculation == "High + (ATR[len] * %)" ? low - (ta.atr(length) * mult) - ticks :-     calculation == "Close + (ATR[len] * %)" ? close - (atr(length) * mult) - ticks :+     calculation == "Close + (ATR[len] * %)" ? close - (ta.atr(length) * mult) - ticks :-     calculation == "Close + abs(close - highest high[len]) * %" ? close - abs(close - (lowest(low, length))) * mult - ticks :+     calculation == "Close + abs(close - highest high[len]) * %" ? close - math.abs(close - (ta.lowest(low, length))) * mult - ticks :-     calculation == "Close + abs(close - average high[len]) * %" ? close - abs(close - sma(low, length)) * mult - ticks :+     calculation == "Close + abs(close - average high[len]) * %" ? close - math.abs(close - ta.sma(low, length)) * mult - ticks :     calculation ==  "High + TicksNumber" ? low - ticks  :⋯bear = short and (atr20<atr30 or disabler)-bullclock = barssince(bull)+bullclock = ta.barssince(bull)-bearclock = barssince(bear)+bearclock = ta.barssince(bear)if (bull)⋯

Clean v5

Verified

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

  • Line 5: input() → input.source()
  • Line 7: input() → input.int()
  • Line 8: input() → input.float()
  • Line 9: input() → input.int()
  • Line 10: input() → input.int()
  • Line 47: input() → input.int()
18 more edits
  • Line 48: input() → input.string()
  • Line 61: input() → input.int()
  • Line 62: input() → input.string()
  • Line 78: input() → input.bool()
  • Line 81: input() → input.string()
  • Line 82: input() → input.int()
  • Line 84: input() → input.int()
  • Line 85: input() → input.bool()
  • Line 100: input() → input.string()
  • Line 101: input() → input.int()
  • Line 103: input() → input.int()
  • Line 104: input() → input.bool()
  • Line 137: input() → input.string()
  • Line 138: input() → input.bool()
  • Line 139: input() → input.string()
  • Line 140: input() → input.bool()
  • Line 147: when = bullclock == maxcandles_till_close → if block
  • Line 148: when = bearclock == maxcandles_till_close → if block
⋯strategy(title="Twin Range Filter Algo v.3", shorttitle = "Twin Range Strategy", overlay=true)-source = input(defval=close, title="Source")+source = input.source(defval=close, title="Source")// Smooth Average Range-per1 = input(defval=27, minval=1, title="Fast period", group ="Twin Range Filter @colinmck")+per1 = input.int(defval=27, minval=1, title="Fast period", group ="Twin Range Filter @colinmck")-mult1 = input(defval=1.6, minval=0.1, title="Fast range", group ="Twin Range Filter @colinmck")+mult1 = input.float(defval=1.6, minval=0.1, title="Fast range", group ="Twin Range Filter @colinmck")-per2 = input(defval=55, minval=1, title="Slow period", group ="Twin Range Filter @colinmck")+per2 = input.int(defval=55, minval=1, title="Slow period", group ="Twin Range Filter @colinmck")-mult2 = input(defval=2, minval=0.1, title="Slow range", group ="Twin Range Filter @colinmck")+mult2 = input.int(defval=2, minval=0.1, title="Slow range", group ="Twin Range Filter @colinmck")smoothrng(x, t, m) =>⋯//second-l2 = input(title="ATR1", defval=32, minval=1, group = "ATR condition", tooltip = "C: Short-range volatility must be low than long-term volatility measurement for the entry.")+l2 = input.int(title="ATR1", defval=32, minval=1, group = "ATR condition", tooltip = "C: Short-range volatility must be low than long-term volatility measurement for the entry.")-s2 = input(title="Smoothing", defval="SMA", options=["RMA", "SMA", "EMA", "WMA"], tooltip = "C: Short-range volatility must be low than long-term volatility measurement for the entry.", group = "ATR condition")+s2 = input.string(title="Smoothing", defval="SMA", options=["RMA", "SMA", "EMA", "WMA"], tooltip = "C: Short-range volatility must be low than long-term volatility measurement for the entry.", group = "ATR condition")atr2(source, l2) => ⋯//third-l3 = input(title="ATR2", defval=64, minval=1, group = "ATR condition", tooltip = "C: Short-range volatility must be low than long-term volatility measurement for the entry.")+l3 = input.int(title="ATR2", defval=64, minval=1, group = "ATR condition", tooltip = "C: Short-range volatility must be low than long-term volatility measurement for the entry.")-s3 = input(title="Smoothing", defval="RMA", options=["RMA", "SMA", "EMA", "WMA"], tooltip = "C: Short-range volatility must be low than long-term volatility measurement for the entry.", group = "ATR condition")+s3 = input.string(title="Smoothing", defval="RMA", options=["RMA", "SMA", "EMA", "WMA"], tooltip = "C: Short-range volatility must be low than long-term volatility measurement for the entry.", group = "ATR condition")atr3(source, l3) => ⋯maxcandles_till_close = input.int(title="Time-based Close", defval=17, group = "Alternative Exit")-i_time = input(true, "Enable Time Base Close", group = "Alternative Exit" )+i_time = input.bool(true, "Enable Time Base Close", group = "Alternative Exit" )//stopvarip stop_long = 0.0, varip entry = 0.0, varip stop_short = 0.0-i_sl_type = input("Low - (close - lowest low[len]) * %", options = ["Low - (ATR[len] * %)", "Low - (close - lowest low[len]) * %", "Low - (close - average low[len]) * %", "Close - (ATR[len] * %)", "Low - TicksNumber"], title="Calculation (Long)", group = "Stop-loss", tooltip = "This is a stop-loss calculation for long positions. Reversed logic is used for short stop-loss. *Calculation Low - TicksNumber doesn't use Percentage-based multiplier. **Number of ticks is always substracted (added) after the initial calculation. ")+i_sl_type = input.string("Low - (close - lowest low[len]) * %", options = ["Low - (ATR[len] * %)", "Low - (close - lowest low[len]) * %", "Low - (close - average low[len]) * %", "Close - (ATR[len] * %)", "Low - TicksNumber"], title="Calculation (Long)", group = "Stop-loss", tooltip = "This is a stop-loss calculation for long positions. Reversed logic is used for short stop-loss. *Calculation Low - TicksNumber doesn't use Percentage-based multiplier. **Number of ticks is always substracted (added) after the initial calculation. ")-i_sl_atr = input(10, "Calculation Length", group = "Stop-loss")+i_sl_atr = input.int(10, "Calculation Length", group = "Stop-loss")i_sl_perc = input.float(80, "Percentage", group = "Stop-loss") / 100-i_sl_ticks = input(defval = 10, minval = 1, title = "Number of ticks", group = "Stop-loss") * syminfo.mintick+i_sl_ticks = input.int(defval = 10, minval = 1, title = "Number of ticks", group = "Stop-loss") * syminfo.mintick-i_stoploss = input(true, "Enable Stop-loss", group = "Stop-loss")+i_stoploss = input.bool(true, "Enable Stop-loss", group = "Stop-loss")f_stop_long (calculation, length, mult, ticks) =>⋯varip target_long = 0.0, varip target_short = 0.0-i_tr_type = input("Close + (ATR[len] * %)", options = ["High + (ATR[len] * %)", "Close + (ATR[len] * %)", "Close + abs(close - highest high[len]) * %",  "Close + abs(close - average high[len]) * %",  "High + TicksNumber", "Close + TicksNumber"], title="Calculation (Long)", group = "Target", tooltip = "Raw number of ticks is always added to the target.")+i_tr_type = input.string("Close + (ATR[len] * %)", options = ["High + (ATR[len] * %)", "Close + (ATR[len] * %)", "Close + abs(close - highest high[len]) * %",  "Close + abs(close - average high[len]) * %",  "High + TicksNumber", "Close + TicksNumber"], title="Calculation (Long)", group = "Target", tooltip = "Raw number of ticks is always added to the target.")-i_tr_atr = input(10, "Calculation Length", group = "Target")+i_tr_atr = input.int(10, "Calculation Length", group = "Target")i_tr_perc = input.float(500, "Percentage", group = "Target") / 100-i_tr_ticks = input(defval = 10, minval = 1, title = "Number of ticks", group = "Target") * syminfo.mintick+i_tr_ticks = input.int(defval = 10, minval = 1, title = "Number of ticks", group = "Target") * syminfo.mintick-i_target = input(true, "Enable Target", group = "Target")+i_target = input.bool(true, "Enable Target", group = "Target")f_target_long (calculation, length, mult, ticks) =>⋯strategy.exit("Exit", from_entry = "Twin Short", limit = target_short, stop = stop_short)-i_message_long = input("Long entry default message: x", "Long Entry Alert Message", group = "Alert")+i_message_long = input.string("Long entry default message: x", "Long Entry Alert Message", group = "Alert")-i_long_alert = input(true,"Enable Long Alert", group = "Alert")+i_long_alert = input.bool(true,"Enable Long Alert", group = "Alert")-i_message_short = input("Long entry default message: x", "Short Entry Alert Message", group = "Alert")+i_message_short = input.string("Long entry default message: x", "Short Entry Alert Message", group = "Alert")-i_short_alert = input(true,"Enable Short Alert", group = "Alert")+i_short_alert = input.bool(true,"Enable Short Alert", group = "Alert")if (bull and strategy.position_size[1] == 0 and i_long_alert)⋯if (i_time)-    strategy.close("Twin Long", when = bullclock == maxcandles_till_close, comment = "Time")+    if bullclock == maxcandles_till_close+        strategy.close("Twin Long", comment = "Time")-    strategy.close("Twin Short", when = bearclock == maxcandles_till_close, comment = "Time")+    if bearclock == maxcandles_till_close+        strategy.close("Twin Short", comment = "Time")c_fill_stop = color.new(color.red, 90)⋯

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: 27 before, 18 after on BTCUSDT 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.

⋯// © colinmck, greenmask9-//@version=5+//@version=6strategy(title="Twin Range Filter Algo v.3", shorttitle = "Twin Range Strategy", overlay=true)⋯

Settings

Every input the script declares, with its default and what it feeds. Bounds are the ones the script enforces.

SettingDefaultType and rangeFeeds
Sourceclosesourcesmrng1 smrng2 filt longCond shortCond line 51 line 54 line 57 line 59 line 65 line 68 line 71 line 73
Twin Range Filter @colinmck
Fast period27int · min 1smrng1
Fast range1.6float · min 0.1smrng1
Slow period55int · min 1smrng2
Slow range2int · min 0.1smrng2
Greenmask's testing resources & ATR condition
Following conditions and backtest algorithm are added by @greenmask9 🎯, original script is written by @colinmck 👍. Read both of their's release notes for more info on how this script works.falseboolunused
Disable @greenmask9's ATR conditionsfalseboolbull bear
ATR condition
ATR1C: Short-range volatility must be low than long-term volatility measurement for the entry.32int · min 1atr20 line 51 line 54 line 57 line 59
SmoothingC: Short-range volatility must be low than long-term volatility measurement for the entry.SMAstring · options ["RMA", "SMA", "EMA", "WMA"]line 50 line 53 line 56
ATR2C: Short-range volatility must be low than long-term volatility measurement for the entry.64int · min 1atr30 line 65 line 68 line 71 line 73
SmoothingC: Short-range volatility must be low than long-term volatility measurement for the entry.RMAstring · options ["RMA", "SMA", "EMA", "WMA"]line 64 line 67 line 70
Alternative Exit
Time-based Close17int (written input.integer)close Twin Long close Twin Short
Enable Time Base Closetrueboolclose Twin Long close Twin Short line 146
Stop-loss
Calculation (Long)This is a stop-loss calculation for long positions. Reversed logic is used for short stop-loss. *Calculation Low - TicksNumber doesn't use Percentage-based multiplier. **Number of ticks is always substracted (added) after the initial calculation. Low - (close - lowest low[len]) * %string · options ["Low - (ATR[len] * %)", "Low - (close - lowest low[len]) * %", "Low - (close - average low[len]) * %", "Close - (ATR[len] * %)", "Low - TicksNumber"]stop_long stop_short
Calculation Length10intstop_long stop_short
Percentage80floatstop_long stop_short
Number of ticks10int · min 1stop_long stop_short
Enable Stop-losstrueboolstop_long stop_short p_longstop p_shortstop plot
Target
Calculation (Long)Raw number of ticks is always added to the target.Close + (ATR[len] * %)string · options ["High + (ATR[len] * %)", "Close + (ATR[len] * %)", "Close + abs(close - highest high[len]) * %", "Close + abs(close - average high[len]) * %", "High + TicksNumber", "Close + TicksNumber"]target_long target_short
Calculation Length10inttarget_long target_short
Percentage500floattarget_long target_short
Number of ticks10int · min 1target_long target_short
Enable Targettruebooltarget_long target_short p_longtarget p_shorttarget plot
Alert
Long Entry Alert MessageLong entry default message: xstringalert
Enable Long Alerttrueboolline 141
Short Entry Alert MessageLong entry default message: xstringalert
Enable Short Alerttrueboolline 143

What it calculates

  • EMA (ema, ta.ema in v5)abs(x - x[1]), tavrng · line 13
  • EMA (ema, ta.ema in v5)avrng, wpersmoothrng · line 14
  • TR (tr, ta.tr in v5)trueatr20 · line 74
  • TR (tr, ta.tr in v5)trueatr30 · line 75
  • ATR / Lowest / SMA (atr, ta.atr in v5)lengthstop_0 · line 113
  • Barssince (barssince, ta.barssince in v5)bullbullclock · line 129
  • Barssince (barssince, ta.barssince in v5)bearbearclock · line 130

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

Order rules

OrderFires whenBy defaultLine
Open Twin Long long(bull)On132
Exit Exit stop and limitevery barOn133
Open Twin Short short(bear)On135
Exit Exit stop and limitevery barOn136
Close Twin Longbullclock == maxcandles_till_closeOn147
Close Twin Shortbearclock == maxcandles_till_closeOn148

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

Alerts

AlertCallMessageLine
(no title)alerti_message_long142
(no title)alerti_message_short144

Does it repaint?

Yes

At least one pattern in the source can repaint; it is marked Check below.

11/11trades 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 5 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 dataThe script requests no other symbol or timeframe.
  • ClearFuture-bar referencesNo negative history offsets such as close[-1].
  • CheckIntrabar recalculationuses varip. Live values can differ from history.
  • 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+48.4%+102.5%1850%2.856.8%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h−1.2%+5.5%2945%0.934.3%8 May 2026 – 21 Oct 2026
ETHUSDT 1D+47.5%+9.8%2133%1.5937.1%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h−12.0%+8.4%3832%0.7318.6%8 May 2026 – 21 Oct 2026
SOLUSDT 1D+66.6%+16.7%2348%1.7920.8%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+5.1%+21.5%3040%1.1615.0%8 May 2026 – 21 Oct 2026
BNBUSDT 1D−34.4%+148.3%2520%0.5447.9%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+13.5%+17.1%3238%1.5812.2%8 May 2026 – 21 Oct 2026

Backtests are simulations on historical data and are not investment advice.

Settings heatmap

Two settings that feed the entry signal, moved around their defaults. The best in-sample pair (ATR1 38, ATR2 54) made +25.7% before 26 Dec 2025 and +15.3% after it, worse than the defaults' +24.2% after. Tuning on the past did not carry forward. 80% of the 64 combinations made money in-sample and 100% out-of-sample.

Before 26 Dec 2025 · in-sample
ATR2 ↓ · ATR1 →1619222732384554
32−23%−8%+10%+10%+12%+11%+6%+0%
38−23%−8%+10%+10%+12%+10%+16%+5%
45−23%−8%+10%+10%+9%+13%+16%+11%
54−3%−9%+7%+12%+24%+26%+16%+14%
64−3%−20%+7%+12%+24%+26%+16%+16%
77−3%+9%+7%+9%+24%+16%+16%+16%
90−0%+9%+22%+24%+24%+19%+16%+16%
109−0%+9%+24%+24%+24%+19%+16%+16%
From 26 Dec 2025 · out-of-sample
ATR2 ↓ · ATR1 →1619222732384554
32+16%+23%+21%+23%+17%+15%+17%+25%
38+16%+23%+21%+23%+14%+18%+17%+28%
45+16%+23%+16%+22%+20%+18%+21%+28%
54+16%+23%+13%+22%+24%+15%+21%+28%
64+16%+17%+13%+20%+24%+15%+21%+28%
77+27%+17%+13%+20%+24%+15%+26%+28%
90+21%+17%+13%+18%+22%+15%+26%+28%
109+18%+20%+13%+18%+22%+13%+24%+28%

Net P&L of trades opened in each period, as a share of starting capital. marks the defaults and the best in-sample cell. Hover a cell for its trade count. Backtests are simulations on historical data and are not investment advice.

The trades

By market direction

At entry, last 90 barsTradesWonP&L
Rising market250%$13,017.20
Sideways market1060%$28,590.00
Falling market633%$6,797.63

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

How bad could the drawdown be?

13.1%

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

0%15%
All 18 trades
SideEntryExitBarsP&L
long14 Sep 2024 60,498.001 Oct 2024 63,327.6017$2,829.61
short2 Oct 2024 60,804.907 Oct 2024 63,783.205−$2,978.32
long15 Oct 2024 66,084.001 Nov 2024 70,292.0017$4,208.01
short4 Nov 2024 68,776.005 Nov 2024 69,816.501−$1,040.48
long7 Nov 2024 75,572.0012 Nov 2024 89,629.705$14,057.70
short7 Apr 2025 78,430.009 Apr 2025 82,908.002−$4,477.96
long12 Apr 2025 83,423.8029 Apr 2025 95,011.2017$11,587.30
long5 Jan 2026 91,529.7021 Jan 2026 88,427.7016−$3,102.08
short21 Jan 2026 88,427.7031 Jan 2026 76,787.8010$11,639.90
long16 Mar 2026 72,815.3022 Mar 2026 68,918.106−$3,897.13
short22 Mar 2026 68,918.1023 Mar 2026 70,972.701−$2,054.61
long8 Apr 2026 71,924.2025 Apr 2026 77,437.1017$5,512.91
short18 May 2026 77,457.702 Jun 2026 66,604.8015$10,852.90
long15 Jun 2026 65,746.4024 Jun 2026 59,890.909−$5,855.55
short25 Jun 2026 61,078.005 Jul 2026 63,144.0010−$2,066.01
long5 Jul 2026 63,144.0022 Jul 2026 66,556.1017$3,412.14
short17 Aug 2026 62,900.0017 Aug 2026 63,620.500−$720.49
long20 Aug 2026 69,334.806 Sep 2026 79,831.8017$10,497.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
Twin Range Filter Algo this page—v4 strategy+48.4%186.8%
Dazzling Bolts by OrcChieftainsma ema atr barssincev4 strategy+8.5%1413.0%
[fpemehd] SSL Baseline Strategy by DuDu95ema sma lowest tr atrv5 strategy+2.3%713.7%
SSL + Wave Trend Strategy by kevinmck100ema sma lowest tr atrv5 strategy−1.0%11.0%
Lorentzian Classification Strategy by StrategiesForEveryoneema sma barssince atr lowestv5 strategydoes not run in Zeal Terminal
ATR + STC + MA by Romediusema lowest atr smav5 strategy−1.2%153.3%

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 42 msWith a workaround 1,000 bars in 134 msNot measured
PineTSNo v5 and v6 only—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. PineTS runs Pine Script v5 and v6 only.

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/// © colinmck, greenmask9//@version=4strategy(title="Twin Range Filter Algo v.3", shorttitle = "Twin Range Strategy", overlay=true)source = input(defval=close, title="Source")// Smooth Average Rangeper1 = input(defval=27, minval=1, title="Fast period", group ="Twin Range Filter @colinmck")mult1 = input(defval=1.6, minval=0.1, title="Fast range", group ="Twin Range Filter @colinmck")per2 = input(defval=55, minval=1, title="Slow period", group ="Twin Range Filter @colinmck")mult2 = input(defval=2, minval=0.1, title="Slow range", group ="Twin Range Filter @colinmck")smoothrng(x, t, m) =>    wper = t * 2 - 1    avrng = ema(abs(x - x[1]), t)    smoothrng = ema(avrng, wper) * m    smoothrngsmrng1 = smoothrng(source, per1, mult1)smrng2 = smoothrng(source, per2, mult2)smrng = (smrng1 + smrng2) / 2// Range Filterrngfilt(x, r) =>    rngfilt = x    rngfilt := x > nz(rngfilt[1]) ? x - r < nz(rngfilt[1]) ? nz(rngfilt[1]) : x - r :        x + r > nz(rngfilt[1]) ? nz(rngfilt[1]) : x + r    rngfiltfilt = rngfilt(source, smrng)upward = 0.0upward := filt > filt[1] ? nz(upward[1]) + 1 : filt < filt[1] ? 0 : nz(upward[1])downward = 0.0downward := filt < filt[1] ? nz(downward[1]) + 1 : filt > filt[1] ? 0 : nz(downward[1])hband = filt + smrnglband = filt - smrnglongCond = bool(na)shortCond = bool(na)longCond := source > filt and source > source[1] and upward > 0 or source > filt and source < source[1] and upward > 0shortCond := source < filt and source < source[1] and downward > 0 or source < filt and source > source[1] and downward > 0CondIni = 0CondIni := longCond ? 1 : shortCond ? -1 : CondIni[1]long = longCond and CondIni[1] == -1short = shortCond and CondIni[1] == 1// Plotting// Strategy// From this part on, programmer is greenmaks9//Separator = input(title="Following conditions and backtest algorithm are added by @greenmask9 🎯, original script is written by @colinmck 👍. Read both of their's release notes for more info on how this script works.", type=input.bool, defval=false, group = "Greenmask's testing resources & ATR condition")disabler = input(title="Disable @greenmask9's ATR conditions", type=input.bool, defval=false, group = "Greenmask's testing resources & ATR condition")//secondl2 = input(title="ATR1", defval=32, minval=1, group = "ATR condition", tooltip = "C: Short-range volatility must be low than long-term volatility measurement for the entry.")s2 = input(title="Smoothing", defval="SMA", options=["RMA", "SMA", "EMA", "WMA"], tooltip = "C: Short-range volatility must be low than long-term volatility measurement for the entry.", group = "ATR condition")atr2(source, l2) =>     if s2 == "SMA"        sma(source, l2)    else        if s2 == "RMA"            rma(source, l2)        else            if s2 == "EMA"                ema(source, l2)            else                wma(source, l2)//thirdl3 = input(title="ATR2", defval=64, minval=1, group = "ATR condition", tooltip = "C: Short-range volatility must be low than long-term volatility measurement for the entry.")s3 = input(title="Smoothing", defval="RMA", options=["RMA", "SMA", "EMA", "WMA"], tooltip = "C: Short-range volatility must be low than long-term volatility measurement for the entry.", group = "ATR condition")atr3(source, l3) =>     if s3 == "RMA"        rma(source, l3)    else        if s3 == "SMA"            sma(source, l3)        else            if s3 == "EMA"                ema(source, l3)            else                wma(source, l3)atr20=atr2(tr(true), l2)atr30=atr3(tr(true), l3)ordersize=floor(strategy.initial_capital/close)maxcandles_till_close = input(title="Time-based Close", type=input.integer, defval=17, group = "Alternative Exit")i_time = input(true, "Enable Time Base Close", group = "Alternative Exit" )//stopvarip stop_long = 0.0, varip entry = 0.0, varip stop_short = 0.0i_sl_type = input("Low - (close - lowest low[len]) * %", options = ["Low - (ATR[len] * %)", "Low - (close - lowest low[len]) * %", "Low - (close - average low[len]) * %", "Close - (ATR[len] * %)", "Low - TicksNumber"], title="Calculation (Long)", group = "Stop-loss", tooltip = "This is a stop-loss calculation for long positions. Reversed logic is used for short stop-loss. *Calculation Low - TicksNumber doesn't use Percentage-based multiplier. **Number of ticks is always substracted (added) after the initial calculation. ")i_sl_atr = input(10, "Calculation Length", group = "Stop-loss")i_sl_perc = input(80, "Percentage", group = "Stop-loss", type = input.float) / 100i_sl_ticks = input(defval = 10, minval = 1, title = "Number of ticks", group = "Stop-loss") * syminfo.minticki_stoploss = input(true, "Enable Stop-loss", group = "Stop-loss")f_stop_long (calculation, length, mult, ticks) =>    stop_0 = calculation == "Low - (ATR[len] * %)" ? low - (atr(length) * mult) - ticks   :     calculation == "Low - (close - lowest low[len]) * %" ? low - (close - (lowest(low, length))) * mult - ticks :     calculation == "Low - (close - average low[len]) * %" ? low - (close - sma(low, length)) * mult - ticks :     calculation ==  "Close - (ATR[len] * %)" ? close - (atr(length) * mult) - ticks  :     low - ticksf_stop_short (calculation, length, mult, ticks) =>    stop_0 = calculation == "Low - (ATR[len] * %)" ? high + (atr(length) * mult) + ticks  :     calculation == "Low - (close - lowest low[len]) * %" ? high + abs(close - lowest(high, length)) * mult + ticks :     calculation == "Low - (close - average low[len]) * %" ? high + abs(close - sma(high, length)) * mult + ticks :     calculation ==  "Close - (ATR[len] * %)" ? close + (atr(length) * mult) + ticks  :     high + ticks//targetvarip target_long = 0.0, varip target_short = 0.0i_tr_type = input("Close + (ATR[len] * %)", options = ["High + (ATR[len] * %)", "Close + (ATR[len] * %)", "Close + abs(close - highest high[len]) * %",  "Close + abs(close - average high[len]) * %",  "High + TicksNumber", "Close + TicksNumber"], title="Calculation (Long)", group = "Target", tooltip = "Raw number of ticks is always added to the target.")i_tr_atr = input(10, "Calculation Length", group = "Target")i_tr_perc = input(500, "Percentage", group = "Target", type = input.float) / 100i_tr_ticks = input(defval = 10, minval = 1, title = "Number of ticks", group = "Target") * syminfo.minticki_target = input(true, "Enable Target", group = "Target")f_target_long (calculation, length, mult, ticks) =>    stop_0 = calculation == "High + (ATR[len] * %)" ? high + (atr(length) * mult) + ticks :     calculation == "Close + (ATR[len] * %)" ? close + (atr(length) * mult) + ticks :     calculation == "Close + abs(close - highest high[len]) * %" ? close + abs(close - (highest(high, length))) * mult + ticks :     calculation == "Close + abs(close - average high[len]) * %" ? close + abs(close - sma(high, length)) * mult + ticks :     calculation ==  "High + TicksNumber" ? high + ticks  :     close + ticksf_target_short (calculation, length, mult, ticks) =>    stop_0 = calculation == "High + (ATR[len] * %)" ? low - (atr(length) * mult) - ticks :     calculation == "Close + (ATR[len] * %)" ? close - (atr(length) * mult) - ticks :     calculation == "Close + abs(close - highest high[len]) * %" ? close - abs(close - (lowest(low, length))) * mult - ticks :     calculation == "Close + abs(close - average high[len]) * %" ? close - abs(close - sma(low, length)) * mult - ticks :     calculation ==  "High + TicksNumber" ? low - ticks  :     close - ticksif (strategy.position_size >= 0 or strategy.position_size[1] != strategy.position_size)    stop_short := i_stoploss ? f_stop_short(i_sl_type, i_sl_atr, i_sl_perc, i_sl_ticks) : na    target_short := i_target ? f_target_short(i_tr_type, i_tr_atr, i_tr_perc, i_tr_ticks) : naif (strategy.position_size <= 0 or strategy.position_size[1] != strategy.position_size)    stop_long := i_stoploss ? f_stop_long(i_sl_type, i_sl_atr, i_sl_perc, i_sl_ticks) : na    target_long := i_target ? f_target_long(i_tr_type, i_tr_atr, i_tr_perc, i_tr_ticks) : naif (strategy.position_size == 0 or strategy.position_size[1] != strategy.position_size)    entry := openbull = long and (atr20<atr30 or disabler)bear = short and (atr20<atr30 or disabler)bullclock = barssince(bull)bearclock = barssince(bear)if (bull)    strategy.entry("Twin Long", strategy.long, ordersize)strategy.exit("Exit", from_entry =  "Twin Long", limit = target_long, stop = stop_long)if (bear)    strategy.entry("Twin Short", strategy.short, ordersize)strategy.exit("Exit", from_entry = "Twin Short", limit = target_short, stop = stop_short)i_message_long = input("Long entry default message: x", "Long Entry Alert Message", group = "Alert")i_long_alert = input(true,"Enable Long Alert", group = "Alert")i_message_short = input("Long entry default message: x", "Short Entry Alert Message", group = "Alert")i_short_alert = input(true,"Enable Short Alert", group = "Alert")if (bull and strategy.position_size[1] == 0 and i_long_alert)    alert(i_message_long, alert.freq_once_per_bar_close)if (bear and strategy.position_size[1] == 0 and i_short_alert)    alert(i_message_short, alert.freq_once_per_bar_close)//time stoplossif (i_time)    strategy.close("Twin Long", when = bullclock == maxcandles_till_close, comment = "Time")    strategy.close("Twin Short", when = bearclock == maxcandles_till_close, comment = "Time")c_fill_stop = color.new(color.red, 90)c_fill_target = color.new(color.green, 90)p_longstop = plot(strategy.position_size > 0 and i_stoploss  ? stop_long : na, linewidth = 2, color = color.red, style = plot.style_linebr)p_shortstop = plot(strategy.position_size < 0 and i_stoploss ? stop_short : na, linewidth = 2, color = color.red, style = plot.style_linebr)p_entry = plot(strategy.position_size != 0 ? entry : na, linewidth = 2, color = color.blue, style = plot.style_linebr)p_longtarget = plot(strategy.position_size > 0 and i_target ? target_long : na, linewidth = 2, color = color.green, style = plot.style_linebr)p_shorttarget = plot(strategy.position_size < 0 and i_target ? target_short : na, linewidth = 2, color = color.green, style = plot.style_linebr)fill(p_entry, p_longstop, c_fill_stop)fill(p_entry, p_shortstop, c_fill_stop)fill(p_entry, p_longtarget, c_fill_target)fill(p_entry, p_shorttarget, c_fill_target)