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
- 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.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Back-Testing Start Date | |||
| From Month | 9 | int · min 1 · max 12 | start |
| From Day | 1 | int · min 1 · max 31 | start |
| From Year | 2021 | int · min 1970 | start |
| Average True Range | |||
| Min Volatility for Buy | 3 | int · min -20 · max 20 · step 1 | atrBuy |
| Min Volatility for Sell | 13 | int · min -10 · max 20 · step 1 | consensusSell |
| Average the Volatility over 3 bars | false | bool | line 93 |
| Trend Flex Ocillator | |||
| TFO Upper Level | 1.2 | float · min 0.1 · max 2.0 · step 0.1 | tfoSell |
| TFO Lower Level | -0.9 | float · min -2.0 · max -0.1 · step 0.1 | tfoBuy |
| TrendFlex Period | 14 | int · min 2 | trendFlexOscillator |
| Selling Conditions | |||
| Allow Stategy to close positions | true | bool | close long line 130 |
| Value (%) must exceed | 0 | int · min -25 · max 10 · step 1 | acceptableROI stopLossPrice |
| Set Trailing Stop Loss on avg positon value | true | bool | exit exit line 149 |
| Trailing Stop Arms At (%) | 15 | float · min 1 · max 30 · step 1 | longStopPrice |
| Trailing Stop Loss (%) | 2 | float · min 0.25 · max 9 · step 0.25 | exit exit |
What it calculates
- EMAclose, length
basicEMA · line 40 - EMA / TRta.tr(true), length
ATR_Function · line 41 - EMAATR_Function, Period
EMA_ATR · line 42 - EMA / TRta.tr(true), length
ATR · 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.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open long long | window() and consensusBuy | On | 129 |
| Close long | window() and consensusSell | On “Allow Stategy to close positions” | 131 |
| Exit exit stop | window() | On | 150 |
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.
- ClearHigher-timeframe dataThe script requests no other symbol or timeframe.
- ClearFuture-bar referencesNo negative history offsets such as close[-1].
- ClearIntrabar recalculationNo varip, calc_on_every_tick or realtime-only state. Orders are decided once per closed bar.
- ClearOrder timingOrders fill at the next bar's open, after the signal bar has closed.
The checks read the source; the replay runs it. Together they catch the common causes, not every possible one.
Other markets
The same script with default settings on 8 Binance markets. Each row is a separate backtest over the most recent 1,000 bars.
| Market | Net | Buy and hold | Trades | Won | Profit factor | Max drawdown | Period |
|---|---|---|---|---|---|---|---|
| BTCUSDT 1D | +16.8% | +102.5% | 16 | 100% | 34.56 | 31.2% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | +16.0% | +5.5% | 15 | 100% | 38.00 | 13.4% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +25.4% | +9.8% | 25 | 76% | 5.98 | 34.8% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | +8.1% | +8.4% | 25 | 68% | 4.67 | 18.4% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | +23.2% | +16.7% | 28 | 82% | 2.70 | 39.8% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | +7.0% | +21.5% | 23 | 70% | 2.80 | 17.1% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | +16.6% | +148.3% | 30 | 87% | 3.96 | 16.5% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | +1.0% | +17.1% | 12 | 75% | 1.64 | 4.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 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 3 | 100% | $2,175.86 |
| Sideways market | 8 | 100% | $13,190.50 |
| Falling market | 5 | 100% | $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.
All 16 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 20 Apr 2024 63,818.00 | 21 Jul 2024 67,023.90 | 92 | $399.83 |
| long | 9 Jul 2024 56,714.60 | 21 Jul 2024 67,023.90 | 12 | $1,708.65 |
| long | 10 Jul 2024 58,050.00 | 21 Jul 2024 67,023.90 | 11 | $1,438.16 |
| long | 11 Jul 2024 57,725.80 | 21 Jul 2024 67,023.90 | 10 | $1,502.67 |
| long | 8 Aug 2024 55,133.80 | 17 Oct 2024 67,071.60 | 70 | $2,054.41 |
| long | 9 Aug 2024 61,686.00 | 17 Oct 2024 67,071.60 | 69 | $768.70 |
| long | 10 Aug 2024 60,838.00 | 17 Oct 2024 67,071.60 | 68 | $919.50 |
| long | 25 Dec 2024 98,663.60 | 12 May 2025 103,737.00 | 138 | $411.65 |
| long | 1 Mar 2025 84,349.90 | 12 May 2025 103,737.00 | 72 | $2,186.93 |
| long | 2 Mar 2025 86,064.50 | 12 May 2025 103,737.00 | 71 | $1,943.14 |
| long | 3 Mar 2025 94,270.00 | 12 May 2025 103,737.00 | 70 | $899.23 |
| long | 13 Mar 2025 83,680.10 | 12 May 2025 103,737.00 | 60 | $2,284.88 |
| long | 14 Mar 2025 81,115.80 | 12 May 2025 103,737.00 | 59 | $2,674.82 |
| long | 10 Apr 2025 82,615.20 | 12 May 2025 103,737.00 | 32 | $2,443.87 |
| long | 11 Apr 2025 79,607.30 | 12 May 2025 103,737.00 | 31 | $2,915.95 |
| long | 24 Jun 2025 105,334.00 | 14 Jul 2025 120,836.00 | 20 | $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.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| TFO + ATR Strategy with Trailing Stop Loss this page | — | v5 strategy | +16.8% | 16 | 31.2% |
| Scalping Trading System bot Crypto and Stocks by exlux99 | ema tr | v5 strategy | +6.5% | 5 | 1.0% |
| Daily Investments Index Scalp by dailycryptoinvestments | ema tr | v5 strategy | −6.9% | 42 | 30.1% |
| Twin Range Filter Algo by OrcChieftain | ema tr | v4 strategy | +48.4% | 18 | 6.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.
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.
⋯// 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
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 33 ms | Yes 1,000 bars in 122 ms | Not measured |
| PineTS | Not tested | Not tested | Not measured |
“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report.
Source
Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © 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')//-----------------------------------------------------------------------------------------------------------//