Twin Optimized Trend Tracker (TOTT) strategy in Pine Script
A smoothed moving average is traded against two bands drawn just above and below its trailing stop line (OTT).
OTT · Moving average · long and short · by KivancOzbilgic · Mozilla Public License 2.0
What its backtest shows
Best of 60 settings: +187.98% · picked in real time: −21.99%
Both over the same months (May 2022 – Oct 2026): the best setting chosen afterwards, and the walk-forward – a setting picked every few months from the months before, the way you could have picked it at the time.
Binance BTC/USDT 4h · Apr 18, 2020 – Nov 13, 2026 · commission 0.1% per order, slippage 2 ticks · includes short trades · 60 settings tested
The verdict
No clear answer: the best of 60 results was picked after the fact, and among many results the best one comes out high even without an edge – the more results, the higher (selection bias, Bailey & López de Prado 2014). The pick made on the first 70% of the period ranked in the top half on the last 30%; with no real edge, that happens about half the time.
The checks in plain words
- Check on a period the pick did not use
- On Nov 23, 2024 – Nov 13, 2026 (the last 30%, not used by this pick): +44.78%, rank 24 of 60 settings. Typical setting there: +27.13%. Buy & hold there: −29.94%. The setting picked on the first 70% ranked in the top half on the last 30%. With no real edge, that happens about half the time.
- Without its 5 best positions
- Without its 5 best positions (of 63), the same setting would have made +27.25% instead of +1,809.17%.
- Walk-forward
- Picking, every 6 months, the setting with the best return-to-drawdown ratio over the previous 24 months ended above 10% of 20,000 random picks and not above the median setting. Only 9 windows, so the test has little power. Over the same 54 months: walk-forward −21.99% (switching costs included), median setting +47.75%, buy & hold +106.17%; 4 of 9 windows were profitable.
- Monte Carlo
- In 1 of 20 resampled paths of the walk-forward, the largest drop was more than 89.9% (in half of them more than 69.7%). Monte Carlo rebuilds paths from blocks of this backtest's own days; it describes this backtest, it is not a forecast.
Once in a trade, it switches between long and short and stays in the market. The large result of its best setting rests on a few trades, and picked every few months from the months before it lost money. Read the large number as what the past allowed afterwards, not as what to expect.
A finished backtest in your account, right after the payment: nothing runs again and no credits are used. Paid once by card. Test it on your coin puts this script with its ranges into the order form, where you choose the coin. Your first backtest is free; after that you pay as you go.
Hypothetical results on past data: they describe this backtest, they are not a forecast and not a recommendation.
The rules
- Builds a moving average (the VAR average by default) and a trailing line a set percentage away from it, the OTT.
- Enters long when the average crosses above the upper twin band (OTT plus a small coefficient), short when it crosses below the lower one.
- Has no separate exit: each signal turns the position around, so the strategy is always in the market once it started.
What to watch for
- An always-in-the-market system pays fees on every flip; check how many trades it makes.
- The twin coefficient decides how often a small move flips the position – a tiny change can change the trade count a lot.
How PineTester judges a backtest, with its sources: how we judge results.
The Pine Script code
The author's code with its licence notice (Mozilla Public License 2.0), with one change marked in the code: the same test conditions for every library strategy in its strategy() line – the whole account per trade (split over the entries where it adds to a position), 0.1% commission per order and 2 ticks slippage; the trading rules are unchanged. Pine Script v5; PineTester converts it to v6 automatically, so results can differ slightly from TradingView.
//@version=5
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © KivancOzbilgic
// Modified by PineTester (2026-11-14): the same test conditions for every library strategy in strategy(): 100% of equity per entry,
// 0.1% commission per order, 2 ticks slippage, initial capital 10,000. The trading rules are unchanged.
//created by: @Anil_Ozeksi
//developer: ANIL ÖZEKŞİ
//author: @kivancozbilgic
strategy('Twin Optimized Trend Tracker', 'TOTT', overlay=true, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type=strategy.commission.percent, commission_value=0.1, slippage=2)
src = input(close, title='Source')
length = input.int(40, 'OTT Period', minval=1)
percent = input.float(1, 'Optimization Constant', step=0.1, minval=0)
coeff = input.float(0.001, 'Twin OTT Coefficient', step=0.001, minval=0)
showsupport = input(title='Show Support Line?', defval=true)
showsignalsk = input(title='Show Signals?', defval=true)
mav = input.string(title='Moving Average Type', defval='VAR', options=['SMA', 'EMA', 'WMA', 'TMA', 'VAR', 'WWMA', 'ZLEMA', 'TSF'])
highlighting = input(title='Highlighter On/Off ?', defval=true)
Var_Func(src, length) =>
valpha = 2 / (length + 1)
vud1 = src > src[1] ? src - src[1] : 0
vdd1 = src < src[1] ? src[1] - src : 0
vUD = math.sum(vud1, 9)
vDD = math.sum(vdd1, 9)
vCMO = nz((vUD - vDD) / (vUD + vDD))
VAR = 0.0
VAR := nz(valpha * math.abs(vCMO) * src) + (1 - valpha * math.abs(vCMO)) * nz(VAR[1])
VAR
VAR = Var_Func(src, length)
Wwma_Func(src, length) =>
wwalpha = 1 / length
WWMA = 0.0
WWMA := wwalpha * src + (1 - wwalpha) * nz(WWMA[1])
WWMA
WWMA = Wwma_Func(src, length)
Zlema_Func(src, length) =>
zxLag = length / 2 == math.round(length / 2) ? length / 2 : (length - 1) / 2
zxEMAData = src + src - src[zxLag]
ZLEMA = ta.ema(zxEMAData, length)
ZLEMA
ZLEMA = Zlema_Func(src, length)
Tsf_Func(src, length) =>
lrc = ta.linreg(src, length, 0)
lrc1 = ta.linreg(src, length, 1)
lrs = lrc - lrc1
TSF = ta.linreg(src, length, 0) + lrs
TSF
TSF = Tsf_Func(src, length)
getMA(src, length) =>
ma = 0.0
if mav == 'SMA'
ma := ta.sma(src, length)
ma
if mav == 'EMA'
ma := ta.ema(src, length)
ma
if mav == 'WMA'
ma := ta.wma(src, length)
ma
if mav == 'TMA'
ma := ta.sma(ta.sma(src, math.ceil(length / 2)), math.floor(length / 2) + 1)
ma
if mav == 'VAR'
ma := VAR
ma
if mav == 'WWMA'
ma := WWMA
ma
if mav == 'ZLEMA'
ma := ZLEMA
ma
if mav == 'TSF'
ma := TSF
ma
ma
MAvg = getMA(src, length)
fark = MAvg * percent * 0.01
longStop = MAvg - fark
longStopPrev = nz(longStop[1], longStop)
longStop := MAvg > longStopPrev ? math.max(longStop, longStopPrev) : longStop
shortStop = MAvg + fark
shortStopPrev = nz(shortStop[1], shortStop)
shortStop := MAvg < shortStopPrev ? math.min(shortStop, shortStopPrev) : shortStop
dir = 1
dir := nz(dir[1], dir)
dir := dir == -1 and MAvg > shortStopPrev ? 1 : dir == 1 and MAvg < longStopPrev ? -1 : dir
MT = dir == 1 ? longStop : shortStop
OTT = MAvg > MT ? MT * (200 + percent) / 200 : MT * (200 - percent) / 200
OTTup = OTT * (1 + coeff)
OTTdn = OTT * (1 - coeff)
PPLOT = plot(showsupport ? MAvg : na, color=color.new(#0585E1, 0), linewidth=2, title='Support Line')
pALLup = plot(nz(OTTup[2]), color=color.new(color.green, 0), linewidth=2, title='OTTup')
pALLdn = plot(nz(OTTdn[2]), color=color.new(color.red, 0), linewidth=2, title='OTTdown')
buySignalk = ta.crossover(MAvg, OTTup[2])
sellSignalk = ta.crossunder(MAvg, OTTdn[2])
K1 = ta.barssince(buySignalk)
K2 = ta.barssince(sellSignalk)
O1 = ta.barssince(buySignalk[1])
O2 = ta.barssince(sellSignalk[1])
plotshape(buySignalk and showsignalsk and O1 > K2 ? math.min(low, OTTdn) : na, title='Buy', text='Buy', location=location.absolute, style=shape.labelup, size=size.tiny, color=color.new(color.green, 0), textcolor=color.new(color.white, 0))
plotshape(sellSignalk and showsignalsk and O2 > K1 ? math.max(high, OTTup) : na, title='Sell', text='Sell', location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.new(color.red, 0), textcolor=color.new(color.white, 0))
mPlot = plot(ohlc4, title='', style=plot.style_circles, linewidth=0, display=display.none)
longFillColor = highlighting ? O2 > K1 ? color.green : na : na
shortFillColor = highlighting ? O1 > K2 ? color.red : na : na
fill(mPlot, PPLOT, title='UpTrend Highligter', color=longFillColor, transp=90)
fill(mPlot, PPLOT, title='DownTrend Highligter', color=shortFillColor, transp=90)
fill(pALLup, pALLdn, title='Flat Zone Highligter', color=color.new(color.blue, 90))
dummy0 = input(true, title='=Backtest Inputs=')
FromDay = input.int(defval=1, title='From Day', minval=1, maxval=31)
FromMonth = input.int(defval=1, title='From Month', minval=1, maxval=12)
FromYear = input.int(defval=2005, title='From Year', minval=2005)
ToDay = input.int(defval=1, title='To Day', minval=1, maxval=31)
ToMonth = input.int(defval=1, title='To Month', minval=1, maxval=12)
ToYear = input.int(defval=9999, title='To Year', minval=2006)
Start = timestamp(FromYear, FromMonth, FromDay, 00, 00)
Finish = timestamp(ToYear, ToMonth, ToDay, 23, 59)
Timerange() =>
time >= Start and time <= Finish ? true : false
if buySignalk
strategy.entry('Long', strategy.long, when=Timerange())
if sellSignalk
strategy.entry('Short', strategy.short, when=Timerange())
Related strategies
- Omar MMR – A MACD crossover in an uptrend of three EMAs, with a fixed take profit and stop loss.
- PresentTrend – An ATR band follows the price and switches sides with the Money Flow Index; a turn of the band opens the trade.
Open-source script by KivancOzbilgic, shown under the Mozilla Public License 2.0. Not a recommendation; neither the author nor TradingView endorses PineTester. Backtests are hypothetical results on past data, not a forecast.