Pine Script v5 · Strategy
FTB Strategy (Automated)
A Pine Script v5 strategy built on RSI (close, 3). It has 2 order rules, 1 entry among them, and trades short only with the default settings. Exits use a stop loss and a profit target. Each trade is one contract and pays no commission. 24 settings; defaults include Stop Pips 2.0, Risk:Reward 1.0 and Timezone 0200-0700.
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 FTB Strategy (Automated) repaint?
- No
- No repainting patterns were found in the source.
- What alerts does FTB Strategy (Automated) have?
- 2
- alertString; pc_id + ",cancelshort," + symbol.
- Does FTB Strategy (Automated) run in Pine Script v6?
- Not tested
- The v5 script does not run in Zeal Terminal's engine (Pine Script v5 Error at @L103:C0: no source was supplied for the library 'ZenAndTheArtOfTrading/ZenLibrary/5'. Libraries cannot be fetched from TradingView; supply the source in the 'libraries' option. No libraries were supplied.), so this step could not be checked. The v6 version is shown for reference and is not offered as a download.
- Does FTB Strategy (Automated) use a stop loss?
- Yes
- strategy.exit sets a stop on line 96.
- Does FTB Strategy (Automated) run in Zeal Terminal?
- No
- Not yet: it imports the library ZenAndTheArtOfTrading/ZenLibrary/5, whose source is not available here, so it does not run here
Review
What a careful reader of this script would point out, found by checking the source.
-
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 79, 96. 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 |
|---|---|---|---|
| Risk Settings | |||
| Stop PipsHow many pips above high to put stop loss | 2.0 | float | shortStopPrice |
| Risk:RewardThis determines the risk:reward profile of the setup | 1.0 | float | shortTargetPrice balance |
| Filter Settings | |||
| TimezoneWhich timezone to search for FTB signals in | 0200-0700 | session | filters line 86 Session |
| RSI OB/OS?If true then the RSI must be considered overbought before a signal is valid | true | bool | rsiFilter |
| Previous Bar Must Be Bullish?If true then the previous bar must have closed bullish | false | bool | closeFilter |
| High FilterIf true then the signal bar must be the highest bar over X bars | false | bool | highFilter |
| High LookbackThis is for setting the High Filter lookback distance | 10 | int | highFilter |
| Candle Close %For identifying shooting star candles (0.5 = must close <= 50% mark of candle size) | 0.5 | float | bearFib |
| RSI LengthRSI length | 3 | int | rsiValue |
| RSI OBRSI overbought threshold | 70.0 | float | rsiFilter |
| Day Filter | |||
| MondayTake trades on this day? | true | bool | days |
| TuesdayTake trades on this day? | true | bool | days |
| WednesdayTake trades on this day? | true | bool | days |
| ThursdayTake trades on this day? | true | bool | days |
| FridayTake trades on this day? | true | bool | days |
| Backtester Settings | |||
| Starting BalanceYour starting balance for the inbuilt tester system | 10000.0 | float | balance dollarReturn line 145 line 149 |
| Risk Per TradeYour desired % risk per trade (as a whole number) | 1.0 | float | positionSize balance |
| Draw BacktesterTurn on/off inbuilt backtester display | true | bool | line 141 |
| PineConnector Settings | |||
| License IDThis is your PineConnector license ID | ID | string | line 43 alert |
| Risk Per TradeThis is how much to risk per trade (% of balance or lots) | 1 | float · step 0.5 | line 43 |
| MetaTrader PrefixThis is your broker's MetaTrader symbol prefix | | string | symbol |
| MetaTrader SuffixThis is your broker's MetaTrader symbol suffix | | string | symbol |
| SpreadEnter your average spread for this pair (used for offsetting limit order) | 0.5 | float | price |
| Use Limit Order?If true a limit order will be used, if false a market order will be used | true | bool | limit price line 83 |
What it calculates
- RSIclose, RSI Length (3)
rsiValue · line 45
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 Short short | strategy.position_size == 0 | On | 79 |
| Exit Short Exit stop and limit | strategy.position_size != 0 | On | 96 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Alerts
| Alert | Call | Message | Line |
|---|---|---|---|
| (no title) | alert | alertString | 81 |
| (no title) | alert | pc_id + ",cancelshort," + symbol | 84 |
Does it repaint?
No
No repainting patterns in the source.
The live replay needs a run, and this script does not run in Zeal Terminal yet; the answer comes from the checks on the source alone.
- 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.
Similar scripts
Indicators and strategies built from the same calculations.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| IFR2 by EduardoMattje | rsi highest | v4 strategy | +12.1% | 118 | 0.8% |
| PlanB Quant Investing 101 v2 by fillippone | rsi highest | v4 strategy | No trades on this market | ||
| Bull Trend Filtered StochRSI (BTFS) by SnarkyPuppy | highest rsi | v5 strategy | +36.9% | 21 | 21.5% |
| Gap Reversion Strategy by TradeAutomation | rsi highest | v5 strategy | No trades on this market | ||
| Jigga - Heatmap Comparision by jigneshjc | rsi highest | v5 strategy | No trades on this market | ||
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.
- 2 strategy calls use the when = argument (line 79, 96). 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
Not verifiedThe v5 script does not run in Zeal Terminal's engine (Pine Script v5 Error at @L101:C0: no source was supplied for the library 'ZenAndTheArtOfTrading/ZenLibrary/5'. Libraries cannot be fetched from TradingView; supply the source in the 'libraries' option. No libraries were supplied.), so this step could not be checked.
- Line 79: when = strategy.position_size == 0 → if block
- Line 96: when = strategy.position_size != 0 → if block
⋯ positionSize = math.floor((strategy.equity * (riskPerTrade/100)) / (t_stop - close))- strategy.entry(id="Short", direction=strategy.short, qty=positionSize, when=strategy.position_size == 0)+ if strategy.position_size == 0+ strategy.entry(id="Short", direction=strategy.short, qty=positionSize) alertString = pc_entry_alert("sell", t_stop, t_target) ⋯// Exit trade whenever our stop or target is hit-strategy.exit(id="Short Exit", from_entry="Short", limit=t_target, stop=t_stop, when=strategy.position_size != 0)+if strategy.position_size != 0+ strategy.exit(id="Short Exit", from_entry="Short", limit=t_target, stop=t_stop)// =============================================================================⋯Does it run in Pine Script v6?
Not tested
The v5 script does not run in Zeal Terminal's engine (Pine Script v5 Error at @L103:C0: no source was supplied for the library 'ZenAndTheArtOfTrading/ZenLibrary/5'. Libraries cannot be fetched from TradingView; supply the source in the 'libraries' option. No libraries were supplied.), so this step could not be checked. The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.
⋯// Last Updated: 10th March 2022-// @version=5+// @version=6strategy("FTB Strategy", shorttitle="FTB", overlay=true, calc_on_order_fills=true, initial_capital=10000)⋯Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | No It imports the library ZenAndTheArtOfTrading/ZenLibrary/5, whose source is not available here, so it does not run here | Not measured | |
| PineTS | Not tested | Not tested | Not measured |
Zeal Terminal's engine currently reads an order side written as direction = strategy.short as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (line 79) so the engine trades the way the script says.
“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/// © ZenAndTheArtOfTrading// Last Updated: 10th March 2022// @version=5strategy("FTB Strategy", shorttitle="FTB", overlay=true, calc_on_order_fills=true, initial_capital=10000)// Risk Settingsvar g_risk = "Risk Settings"pips = input.float(title="Stop Pips", defval=2.0, group=g_risk, tooltip="How many pips above high to put stop loss")rr = input.float(title="Risk:Reward", defval=1.0, group=g_risk, tooltip="This determines the risk:reward profile of the setup")// Filtersvar g_filter = "Filter Settings"timezone = input.session(title="Timezone", defval="0200-0700", group=g_filter, tooltip="Which timezone to search for FTB signals in")useRsiFilter = input.bool(title="RSI OB/OS?", defval=true, group=g_filter, tooltip="If true then the RSI must be considered overbought before a signal is valid")useCloseFilter = input.bool(title="Previous Bar Must Be Bullish?", defval=false, group=g_filter, tooltip="If true then the previous bar must have closed bullish")useHighFilter = input.bool(title="High Filter", defval=false, group=g_filter, tooltip="If true then the signal bar must be the highest bar over X bars")highLookback = input.int(title="High Lookback", defval=10, group=g_filter, tooltip="This is for setting the High Filter lookback distance")fib = input.float(title="Candle Close %", defval=0.5, group=g_filter, tooltip="For identifying shooting star candles (0.5 = must close <= 50% mark of candle size)")rsiLen = input.int(title="RSI Length", defval=3, group=g_filter, tooltip="RSI length")rsiOB = input.float(title="RSI OB", defval=70.0, group=g_filter, tooltip="RSI overbought threshold")var g_days = "Day Filter"d_monday = input.bool(title="Monday", defval=true, group=g_days, tooltip="Take trades on this day?", inline="days")d_tuesday = input.bool(title="Tuesday", defval=true, group=g_days, tooltip="Take trades on this day?", inline="days")d_wednesday = input.bool(title="Wednesday", defval=true, group=g_days, tooltip="Take trades on this day?", inline="days")d_thursday = input.bool(title="Thursday", defval=true, group=g_days, tooltip="Take trades on this day?", inline="days")d_friday = input.bool(title="Friday", defval=true, group=g_days, tooltip="Take trades on this day?", inline="days")var g_tester = "Backtester Settings"startBalance = input.float(title="Starting Balance", defval=10000.0, group=g_tester, tooltip="Your starting balance for the inbuilt tester system")riskPerTrade = input.float(title="Risk Per Trade", defval=1.0, group=g_tester, tooltip="Your desired % risk per trade (as a whole number)")drawTester = input.bool(title="Draw Backtester", defval=true, group=g_tester, tooltip="Turn on/off inbuilt backtester display")// PineConnector Settingsvar g_pc = "PineConnector Settings"pc_id = input.string(title="License ID", defval="ID", group=g_pc, tooltip="This is your PineConnector license ID")pc_risk = input.float(title="Risk Per Trade", defval=1, step=0.5, group=g_pc, tooltip="This is how much to risk per trade (% of balance or lots)")pc_prefix = input.string(title="MetaTrader Prefix", defval="", group=g_pc, tooltip="This is your broker's MetaTrader symbol prefix")pc_suffix = input.string(title="MetaTrader Suffix", defval="", group=g_pc, tooltip="This is your broker's MetaTrader symbol suffix")pc_spread = input.float(title="Spread", defval=0.5, group=g_pc, tooltip="Enter your average spread for this pair (used for offsetting limit order)")pc_limit = input.bool(title="Use Limit Order?", defval=true, group=g_pc, tooltip="If true a limit order will be used, if false a market order will be used")// Generate PineConnector alert stringvar symbol = pc_prefix + syminfo.ticker + pc_suffixvar limit = pc_limit ? "limit" : ""pc_entry_alert(direction, sl, tp) => price = pc_limit ? "price=" + str.tostring(pc_spread) + "," : "" pc_id + "," + direction + limit + "," + symbol + "," + price + "sl=" + str.tostring(sl) + ",tp=" + str.tostring(tp) + ",risk=" + str.tostring(pc_risk)// Get RSI filterrsiValue = ta.rsi(close, rsiLen)rsiFilter = not useRsiFilter or rsiValue >= rsiOB// Check high & close filterhighFilter = not useHighFilter or high == ta.highest(high, highLookback)closeFilter = not useCloseFilter or close[1] > open[1]// InSession() determines if a price bar falls inside the specified session (and day)days = d_monday ? "2" : ""days := days + (d_tuesday ? "3" : "")days := days + (d_wednesday ? "4" : "")days := days + (d_thursday ? "5" : "")days := days + (d_friday ? "6" : "")inSession(sess) => na(time(timeframe.period, sess + ":" + days)) == false// Calculate 50% mark of candle sizebearFib = (high - low) * fib + low// Check filtersfilters = inSession(timezone) and closeFilter and high > high[1] and rsiFilter and highFilter and open != close// Detect valid shooting star pinbar patternvar takenTradeAlready = falsestar = filters and close < bearFib and open < bearFib and not takenTradeAlready and strategy.position_size == 0// Calculate stops & targetsshortStopPrice = high + (syminfo.mintick * pips * 10)shortStopDistance = shortStopPrice - closeshortTargetPrice = close - (shortStopDistance * rr)// Save stops & targets for the current tradevar t_stop = 0.0var t_target = 0.0var t_entry = 0.0// If we detect a valid shooting star, save our stops & targets, enter short and generate alertif star and barstate.isconfirmed t_stop := shortStopPrice t_target := shortTargetPrice t_entry := close takenTradeAlready := true positionSize = math.floor((strategy.equity * (riskPerTrade/100)) / (t_stop - close)) strategy.entry(id="Short", direction=strategy.short, qty=positionSize, when=strategy.position_size == 0) alertString = pc_entry_alert("sell", t_stop, t_target) alert(alertString, alert.freq_once_per_bar_close)// If price has exceeded target then cancel limit order if it's still active if pc_limit and low <= t_target and strategy.position_size == 0 and takenTradeAlready alert(pc_id + ",cancelshort," + symbol, alert.freq_once_per_bar_close)// If we have exited the FTB session then reset our takenTradeAlready flag for the next sessionif not inSession(timezone) and inSession(timezone)[1] takenTradeAlready := false// Draw stops & targetsplot(star or strategy.position_size != 0 ? t_stop : na, color=color.red, style=plot.style_linebr, title="SL")plot(star or strategy.position_size != 0 ? t_target : na, color=color.green, style=plot.style_linebr, title="TP")// Draw short signalsplotshape(star ? 1 : na, style=shape.triangledown, color=color.red)// Change background color to highlight detection zonebgcolor(color=inSession(timezone) ? color.new(color.red,80) : na, title="Session")// Exit trade whenever our stop or target is hitstrategy.exit(id="Short Exit", from_entry="Short", limit=t_target, stop=t_stop, when=strategy.position_size != 0)// =============================================================================// START BACKTEST CODE// =============================================================================// Import Zen libraryimport ZenAndTheArtOfTrading/ZenLibrary/5 as zen// Declare balance tracking variables (for backtester simulation)var balance = startBalancevar drawdown = 0.0var maxDrawdown = 0.0var maxBalance = 0.0var totalPips = 0.0// Increase profit for winswonTrade = strategy.wintrades != strategy.wintrades[1]if wonTrade balance += riskPerTrade / 100 * balance * rr totalPips += zen.toWhole(math.abs(t_entry - t_target)) if balance > maxBalance maxBalance := balance// Decrease profit for losseslostTrade = strategy.losstrades != strategy.losstrades[1]if lostTrade balance -= riskPerTrade / 100 * balance totalPips -= zen.toWhole(math.abs(t_stop - t_entry)) // Update drawdown drawdown := balance / maxBalance - 1 if drawdown < maxDrawdown maxDrawdown := drawdown// Declare error tracking variables (for identifying how many "questionable" trades were detected)var questionableTrades = 0flagQuestionableTrade = false// If price has hit both TP & SL on the same bar, flag it for further investigationif ((wonTrade or lostTrade) and high >= t_stop and low <= t_target) questionableTrades += 1 flagQuestionableTrade := true// Highlight questionable tradesbgcolor(flagQuestionableTrade ? color.new(color.purple,50) : na)// Prepare stats tablevar table testTable = table.new(position.top_right, 5, 2, border_width=1)f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) => _cellText = _title + "\n" + _value table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor)// Draw stats tablevar bgcolor = color.blackif barstate.islastconfirmedhistory if drawTester dollarReturn = balance - startBalance f_fillCell(testTable, 0, 0, "Total Trades:", str.tostring(strategy.closedtrades) + " [*" + str.tostring(questionableTrades) + "]", bgcolor, color.white) f_fillCell(testTable, 0, 1, "Win Rate:", str.tostring(zen.truncate(strategy.wintrades / strategy.closedtrades * 100)) + "%", bgcolor, color.white) f_fillCell(testTable, 1, 0, "Starting:", "$" + str.tostring(startBalance), bgcolor, color.white) f_fillCell(testTable, 1, 1, "Ending:", "$" + str.tostring(zen.truncate(balance)), bgcolor, color.white) f_fillCell(testTable, 2, 0, "Return:", "$" + str.tostring(zen.truncate(dollarReturn)), bgcolor, dollarReturn > 0 ? color.green : color.red) f_fillCell(testTable, 2, 1, "Pips:", (totalPips > 0 ? "+" : "") + str.tostring(zen.truncate(totalPips)), bgcolor, color.white) f_fillCell(testTable, 3, 0, "Return:", (dollarReturn > 0 ? "+" : "") + str.tostring(zen.truncate(dollarReturn / startBalance * 100)) + "%", dollarReturn > 0 ? color.green : color.red, color.white) f_fillCell(testTable, 3, 1, "Max DD:", str.tostring(zen.truncate(maxDrawdown * 100)) + "%", color.red, color.white)// =============================================================================// END BACKTEST CODE// =============================================================================