Zeal Terminal Open in Zeal Terminal

Pine Script v5 · Strategy

TFO + ATR Strategy with Trailing Stop Loss

A Pine Script v5 strategy built on EMA (close, length), EMA or TR (true, length) and Crossunder (trendFlexOscillator, 1.2). It has 3 order rules, 1 entry among them, and trades long only with the default settings. Exits use a stop loss. Each trade commits 10000 in cash and pays 0.5% commission. 14 settings; defaults include From Month 9, From Day 1 and From Year 2021.

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 TFO + ATR Strategy with Trailing Stop Loss repaint?
No
No repainting patterns were found in the source. The live replay was not measured: it had no trades to compare.
How did TFO + ATR Strategy with Trailing Stop Loss do on BTCUSDT 1D with default settings?
+16.78%
From 26 Jan 2024 to 21 Oct 2026, over 16 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Does TFO + ATR Strategy with Trailing Stop Loss run in Pine Script v6?
Yes
Same 16 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 TFO + ATR Strategy with Trailing Stop Loss use a stop loss?
Yes
strategy.exit sets a stop on line 150.
Does TFO + ATR Strategy with Trailing Stop Loss run in Zeal Terminal?
Yes
It compiles in 33 ms and runs 1,000 bars in 122 ms, in the browser.

BTCUSDT · 1D · default settings

  • Number of open trades
  • Profit on open longs
  • Arm Trail Stop at
  • 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 (14)
50,00075,000100,000125,000AprJulOct2025AprJulOct2026AprJulOct$165,584$303,791Equity from $150,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
+16.78%
$25,166.80
Buy and hold
+102.5%
same period
Closed trades
16
16 won · 0 lost
Profitable
100.0%
of closed trades
Profit factor
34.56
gross profit ÷ gross loss
Max drawdown
31.22%
−$54,928.50

One run with the author's default settings, $150,000 starting capital, commission as the script sets it. A long position was still open at the last bar. 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.

  • 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 129, 131, 150. The upgraded version below moves each call inside an if block.

Settings

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

SettingDefaultType and rangeFeeds
Back-Testing Start Date
From Month9int · min 1 · max 12start
From Day1int · min 1 · max 31start
From Year2021int · min 1970start
Average True Range
Min Volatility for Buy3int · min -20 · max 20 · step 1atrBuy
Min Volatility for Sell13int · min -10 · max 20 · step 1consensusSell
Average the Volatility over 3 barsfalseboolline 93
Trend Flex Ocillator
TFO Upper Level1.2float · min 0.1 · max 2.0 · step 0.1tfoSell
TFO Lower Level-0.9float · min -2.0 · max -0.1 · step 0.1tfoBuy
TrendFlex Period14int · min 2trendFlexOscillator
Selling Conditions
Allow Stategy to close positionstrueboolclose long line 130
Value (%) must exceed 0int · min -25 · max 10 · step 1acceptableROI stopLossPrice
Set Trailing Stop Loss on avg positon valuetrueboolexit exit line 149
Trailing Stop Arms At (%)15float · min 1 · max 30 · step 1longStopPrice
Trailing Stop Loss (%)2float · min 0.25 · max 9 · step 0.25exit exit

What it calculates

  • EMAclose, lengthbasicEMA · line 40
  • EMA / TRta.tr(true), lengthATR_Function · line 41
  • EMAATR_Function, PeriodEMA_ATR · line 42
  • EMA / TRta.tr(true), lengthATR · line 43
  • CrossundertrendFlexOscillator, TFO Upper Level (1.2)tfoSell · line 98

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.

closecloseprice datahigh · low · closehigh · low · closeprice dataupperLevelTFO Upper Levelsetting · 1.2fromYearFrom Yearsetting · 2021fromMonthFrom Monthsetting · 9fromDayFrom Daysetting · 1periodTrendFlexTrendFlex Periodsetting · 14armTrailing Stop Arms At (…setting · 15holdLossValue (%) must exceed setting · 0lowerLevelTFO Lower Levelsetting · -0.9buyVolatilityMin Volatility for Buysetting · 3sellVolatilityMin Volatility for Sellsetting · 13basicEMAEMA→ basicEMAATR_FunctionEMA / TR→ ATR_FunctionEMA_ATREMA→ EMA_ATRATREMA / TR→ ATRtfoSellCrossunder→ tfoSellstartstartvaluefinish, alpha, zeta, totalInvestfinish · alpha +24 valuesATR_diffATR_diffvaluevolatilityvolatilityvaluevolatilityAVGvolatilityAVGvaluebetabetavaluegammagammavaluedeltadeltavaluesuperSmoothsuperSmoothvalueEEvalueepsilonepsilonvalueEMAEMAvaluereturn_1return_1valuetrendFlexOscillatortrendFlexOscillatorvalueopenProfitPercopenProfitPercvaluelongStopPricelongStopPricevaluestopLossPricestopLossPricevalueacceptableROIacceptableROIconditiontfoBuytfoBuyconditionatrBuyatrBuyconditionconsensusBuyconsensusBuyconditionconsensusSellconsensusSellconditionentry:longOpen longstrategy.entryclose:longClose longstrategy.closeexit:exitexit exitstrategy.exitplotchar:108plotcharplotcharplotarrow:109plotarrowplotarrowplot:148Arm Trail Stop atplot

Order rules

OrderFires whenBy defaultLine
Open long longwindow() and consensusBuyOn129
Close longwindow() and consensusSellOn “Allow Stategy to close positions”131
Exit exit stopwindow()On150

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

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 1D+16.8%+102.5%16100%34.5631.2%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h+16.0%+5.5%15100%38.0013.4%8 May 2026 – 21 Oct 2026
ETHUSDT 1D+25.4%+9.8%2576%5.9834.8%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+8.1%+8.4%2568%4.6718.4%8 May 2026 – 21 Oct 2026
SOLUSDT 1D+23.2%+16.7%2882%2.7039.8%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+7.0%+21.5%2370%2.8017.1%8 May 2026 – 21 Oct 2026
BNBUSDT 1D+16.6%+148.3%3087%3.9616.5%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+1.0%+17.1%1275%1.644.7%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 barsTradesWonP&L
Rising market3100%$2,175.86
Sideways market8100%$13,190.50
Falling market5100%$10,550.40

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

How bad could the drawdown be?

0.0%

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

0%1%
All 16 trades
SideEntryExitBarsP&L
long20 Apr 2024 63,818.0021 Jul 2024 67,023.9092$399.83
long9 Jul 2024 56,714.6021 Jul 2024 67,023.9012$1,708.65
long10 Jul 2024 58,050.0021 Jul 2024 67,023.9011$1,438.16
long11 Jul 2024 57,725.8021 Jul 2024 67,023.9010$1,502.67
long8 Aug 2024 55,133.8017 Oct 2024 67,071.6070$2,054.41
long9 Aug 2024 61,686.0017 Oct 2024 67,071.6069$768.70
long10 Aug 2024 60,838.0017 Oct 2024 67,071.6068$919.50
long25 Dec 2024 98,663.6012 May 2025 103,737.00138$411.65
long1 Mar 2025 84,349.9012 May 2025 103,737.0072$2,186.93
long2 Mar 2025 86,064.5012 May 2025 103,737.0071$1,943.14
long3 Mar 2025 94,270.0012 May 2025 103,737.0070$899.23
long13 Mar 2025 83,680.1012 May 2025 103,737.0060$2,284.88
long14 Mar 2025 81,115.8012 May 2025 103,737.0059$2,674.82
long10 Apr 2025 82,615.2012 May 2025 103,737.0032$2,443.87
long11 Apr 2025 79,607.3012 May 2025 103,737.0031$2,915.95
long24 Jun 2025 105,334.0014 Jul 2025 120,836.0020$1,364.37

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
TFO + ATR Strategy with Trailing Stop Loss this page—v5 strategy+16.8%1631.2%
Scalping Trading System bot Crypto and Stocks by exlux99ema trv5 strategy+6.5%51.0%
Daily Investments Index Scalp by dailycryptoinvestmentsema trv5 strategy−6.9%4230.1%
Twin Range Filter Algo by OrcChieftainema trv4 strategy+48.4%186.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.

  • 3 strategy calls use the when = argument (line 129, 131, 150). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
  • No v6-only features. v6 is not needed to run this script.

Clean v5

VerifiedDownload the v5 script

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

  • Line 129: when = window() and consensusBuy → if block
  • Line 131: when = window() and consensusSell → if block
  • Line 150: when = window() → if block
⋯// ---------------------------------------------------------------------------------------------------------//-strategy.entry('long', strategy.long, when=window() and consensusBuy, comment='long')+if window() and consensusBuy+    strategy.entry('long', strategy.long, comment='long')if sellOnStrategy-    strategy.close('long', when=window() and consensusSell, qty_percent=100, comment='Strat')+    if window() and consensusSell+        strategy.close('long', qty_percent=100, comment='Strat')// -----------------------------------------------------------------------------------------------------------//⋯if strategy.position_size > 0 and useTrailStop-    strategy.exit('exit', 'long', when=window(), qty_percent=100, trail_price=longStopPrice, trail_offset=trail * close / syminfo.mintick, comment='Trail')+    if window()+        strategy.exit('exit', 'long', qty_percent=100, trail_price=longStopPrice, trail_offset=trail * close / syminfo.mintick, comment='Trail')//-----------------------------------------------------------------------------------------------------------//

Does it run in Pine Script v6?

Yes

Same 16 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.

Download the v6 script

⋯// Short positions are not supported in this version.  Back-testing should NEVER be considered an accurate representation of actual trading results.-//@version=5+//@version=6strategy('TFO + ATR Strategy with Trailing Stop Loss', 'TFO ATR Trailing Stop Loss', overlay=true, pyramiding=15, default_qty_type=strategy.cash, default_qty_value=10000, initial_capital=150000, currency='USD', commission_type=strategy.commission.percent, commission_value=0.5)⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 33 msYes 1,000 bars in 122 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/// © Chart0bserver //// Open Source attributions:// portions © allanster (date window code)// portions © Dr. John Ehlers (Trend Flex Oscillator)//// READ THIS CAREFULLY!!! ----------------//// This code is provided for educational purposes only.  The results of this strategy should not be considered investment advice.// The user of this script acknolwedges that it can cause serious financial loss when used as a trading tool// This strategy has a bias for HODL (Holds on to Losses) meaning that it provides NO STOP LOSS protection! // Also note that the default behavior is designed for up to 15 open long orders, and executes one order to close them all at once. // Opening a long position is predicated on The Trend Flex Oscillator (TFO) rising after being oversold, and ATR above a certain volatility threshold.// Closing a long is handled either by TFO showing overbought while above a certain ATR level, or the Trailing Stop Loss.  Pick one or both.// If the strategy is allowed to sell before a Trailing Stop Loss is triggered, you can set a "must exceed %".  Do not mistake this for a stop loss.// Short positions are not supported in this version.  Back-testing should NEVER be considered an accurate representation of actual trading results.//@version=5strategy('TFO + ATR Strategy with Trailing Stop Loss', 'TFO ATR Trailing Stop Loss', overlay=true, pyramiding=15, default_qty_type=strategy.cash, default_qty_value=10000, initial_capital=150000, currency='USD', commission_type=strategy.commission.percent, commission_value=0.5)strategy.risk.allow_entry_in(strategy.direction.long)  // There will be no short entries, only exits from long.// -----------------------------------------------------------------------------------------------------------//// Back-testing Date Range code  ----------------------------------------------------------------------------//// ---------------------------------------------------------------------------------------------------------//fromMonth = input.int(defval=9, title='From Month', minval=1, maxval=12, group='Back-Testing Start Date')fromDay = input.int(defval=1, title='From Day', minval=1, maxval=31, group='Back-Testing Start Date')fromYear = input.int(defval=2021, title='From Year', minval=1970, group='Back-Testing Start Date')thruMonth = 1       //input(defval = 1,    title = "Thru Month",      type = input.integer, minval = 1, maxval = 12, group="Back-Testing Date Range")thruDay = 1         //input(defval = 1,    title = "Thru Day",        type = input.integer, minval = 1, maxval = 31, group="Back-Testing Date Range")thruYear = 2112     //input(defval = 2112, title = "Thru Year",       type = input.integer, minval = 1970, group="Back-Testing Date Range")// === FUNCTION EXAMPLE ===start = timestamp(fromYear, fromMonth, fromDay, 00, 00)  // backtest start windowfinish = timestamp(thruYear, thruMonth, thruDay, 23, 59)  // backtest finish windowwindow() =>  // create function "within window of time    time >= start and time <= finish ? true : false// Date range code -----//// -----------------------------------------------------------------------------------------------------------//// ATR Indicator Code  --------------------------------------------------------------------------------------//// ---------------------------------------------------------------------------------------------------------//length = 18  //input(title="ATR Length", defval=18, minval=1)Period = 18  //input(18,title="ATR EMA Period")  basicEMA = ta.ema(close, length)ATR_Function = ta.ema(ta.tr(true), length)EMA_ATR = ta.ema(ATR_Function, Period)ATR = ta.ema(ta.tr(true), length)ATR_diff = ATR - EMA_ATRvolatility = 100 * ATR_diff / EMA_ATR  // measure of spread between ATR and EMAvolatilityAVG = math.round((volatility + volatility[1] + volatility[2]) / 3)buyVolatility = input.int(3, 'Min Volatility for Buy', minval=-20, maxval=20, step=1, group='Average True Range')sellVolatility = input.int(13, 'Min Volatility for Sell', minval=-10, maxval=20, step=1, group='Average True Range')useAvgVolatility = input.bool(defval=false, title='Average the Volatility over 3 bars', group='Average True Range')// End of ATR  ------------/// -----------------------------------------------------------------------------------------------------------//// TFO Indicator code  --------------------------------------------------------------------------------------//// ---------------------------------------------------------------------------------------------------------//trendflex(Series, PeriodSS, PeriodTrendFlex, PeriodEMA) =>    var SQRT2xPI = math.sqrt(8.0) * math.asin(1.0)  // 4.44288293815 Constant    alpha = SQRT2xPI / PeriodSS    beta = math.exp(-alpha)    gamma = -beta * beta    delta = 2.0 * beta * math.cos(alpha)    float superSmooth = na    superSmooth := (1.0 - delta - gamma) * (Series + nz(Series[1])) * 0.5 + delta * nz(superSmooth[1]) + gamma * nz(superSmooth[2])    E = 0.0    for i = 1 to PeriodTrendFlex by 1        E += superSmooth - nz(superSmooth[i])        E    epsilon = E / PeriodTrendFlex    zeta = 2.0 / (PeriodEMA + 1.0)    float EMA = na    EMA := zeta * epsilon * epsilon + (1.0 - zeta) * nz(EMA[1])    return_1 = EMA == 0.0 ? 0.0 : epsilon / math.sqrt(EMA)    return_1upperLevel = input.float(1.2, 'TFO Upper Level', minval=0.1, maxval=2.0, step=0.1, group='Trend Flex Ocillator')lowerLevel = input.float(-0.9, 'TFO Lower Level', minval=-2.0, maxval=-0.1, step=0.1, group='Trend Flex Ocillator')periodTrendFlex = input.int(14, 'TrendFlex Period', minval=2, group='Trend Flex Ocillator')useSuperSmootherOveride = true  //input( true, "Apply SuperSmoother Override Below*", input.bool, group="Trend Flex Ocillator")periodSuperSmoother = 8.0       //input(8.0, "SuperSmoother Period*", input.float  , minval=4.0, step=0.5, group="Trend Flex Ocillator")postSmooth = 33                 //input(33.0, "Post Smooth Period**", input.float  , minval=1.0, step=0.5, group="Trend Flex Ocillator")trendFlexOscillator = trendflex(close, periodSuperSmoother, periodTrendFlex, postSmooth)// End of TFO -------------//// -----------------------------------------------------------------------------------------------------------//// HODL Don't sell if losing n% ---------------------------------------------------------------------------- //// ---------------------------------------------------------------------------------------------------------// sellOnStrategy = input.bool(defval=true, title='Allow Stategy to close positions', group='Selling Conditions')doHoldLoss = true       // input(defval = true, title = "Strategy can sell for a loss", type = input.bool, group="Selling Conditions")holdLoss = input.int(defval=0, title='Value (%) must exceed ', minval=-25, maxval=10, step=1, group='Selling Conditions')totalInvest = strategy.position_avg_price * strategy.position_sizeopenProfitPerc = strategy.openprofit / totalInvestbool acceptableROI = openProfitPerc * 100 > holdLoss// -----------------------//// -----------------------------------------------------------------------------------------------------------//// Buying and Selling conditions  -------------------------------------------------------------------------- //// ---------------------------------------------------------------------------------------------------------//    if useAvgVolatility    volatility := volatilityAVG    volatilitytfoBuy = trendFlexOscillator < lowerLevel and trendFlexOscillator[1] < trendFlexOscillator  // Always make a purchase if TFO is in this lowest rangeatrBuy = volatility > buyVolatilitytfoSell = ta.crossunder(trendFlexOscillator, upperLevel)consensusBuy = tfoBuy and atrBuyconsensusSell = tfoSell and volatility > sellVolatilityif doHoldLoss    consensusSell := consensusSell and acceptableROI    consensusSell// --------------------//// -----------------------------------------------------------------------------------------------------------//// Tracing & Debugging --------------------------------------------------------------------------------------//// ---------------------------------------------------------------------------------------------------------//plotchar(strategy.opentrades, 'Number of open trades', ' ', location.top)plotarrow(100 * openProfitPerc, 'Profit on open longs', color.new(color.green, 75), color.new(color.red, 75))// plotchar(strategy.position_size, "Shares on hand", " ", location.top)// plotchar(totalInvest, "Total Invested", " ", location.top)// plotarrow(strategy.openprofit, "Open profit dollar amount", color.new(color.green,100), color.new(color.red, 100))// plotarrow(strategy.netprofit, "Net profit for session", color.new(color.green,100), color.new(color.red, 100))// plotchar(acceptableROI, "Acceptable ROI", " ", location.top)// plotarrow(volatility, "ATR volatility value", color.new(color.green,75), color.new(color.red, 75))// plotchar(strategy.position_avg_price, "Avgerage price of holdings", " ", location.top)// plotchar(volatilityAVG, "AVG volatility", " ", location.top)// plotchar(fiveBarsVal, "change in 5bars", " ", location.top)// plotchar(crossingUp, "crossingUp", "x",  location.belowbar, textcolor=color.white)// plotchar(crossingDown, "crossingDn", "x",  location.abovebar, textcolor=color.white)// plotchar(strategy.closedtrades, "closedtrades", " ", location.top)// plotchar(strategy.wintrades, "wintrades", " ", location.top)// plotchar(strategy.losstrades, "losstrades", " ", location.top)// plotchar(close, "close", " ", location.top)//--------------------//// -----------------------------------------------------------------------------------------------------------//// Trade Alert Execution ------------------------------------------------------------------------------------//// ---------------------------------------------------------------------------------------------------------//strategy.entry('long', strategy.long, when=window() and consensusBuy, comment='long')if sellOnStrategy    strategy.close('long', when=window() and consensusSell, qty_percent=100, comment='Strat')// -----------------------------------------------------------------------------------------------------------//// Trailing Stop Loss logic -------------------------------------------------------------------------------- //// ---------------------------------------------------------------------------------------------------------//    useTrailStop = input.bool(defval=true, title='Set Trailing Stop Loss on avg positon value', group='Selling Conditions')arm = input.float(defval=15, title='Trailing Stop Arms At (%)', minval=1, maxval=30, step=1, group='Selling Conditions') * 0.01trail = input.float(defval=2, title='Trailing Stop Loss (%)', minval=0.25, maxval=9, step=0.25, group='Selling Conditions') * 0.01longStopPrice = 0.0stopLossPrice = 0.0if strategy.position_size > 0    longStopPrice := strategy.position_avg_price * (1 + arm)    stopLossPrice := strategy.position_avg_price * ((100 - math.abs(holdLoss)) / 100)  // for use with 'stop' in strategy.exit    stopLossPriceelse    longStopPrice := close    longStopPrice// If you want to hide the Trailing Stop Loss threshold (green line), comment this outplot(longStopPrice, 'Arm Trail Stop at', color.new(color.green, 60), linewidth=2)if strategy.position_size > 0 and useTrailStop    strategy.exit('exit', 'long', when=window(), qty_percent=100, trail_price=longStopPrice, trail_offset=trail * close / syminfo.mintick, comment='Trail')//-----------------------------------------------------------------------------------------------------------//