Pine Script v4 · Strategy
Ultimate Strategy Template
A Pine Script v4 strategy built on ATR (14). It has 10 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 commits InitPosition% of equity and pays no commission. 34 settings; defaults include Data source close, Trading Session 0000-2345 and Open Trading Direction ALL.
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 Ultimate Strategy Template repaint?
- No
- No repainting patterns were found in the source. The live replay was not measured: it had no trades to compare.
- How did Ultimate Strategy Template do on BTCUSDT 1D with default settings?
- Not measured
- It closed no trades there from 26 Jan 2024 to 21 Oct 2026 with the default settings, so there is no result to report. Its code limits trading to a date window, which can leave this period out. It closed no trades on the other markets either. A backtest, not investment advice.
- Can Ultimate Strategy Template be converted to Pine Script v5?
- Not tested
- The steps are shown below, but neither version placed a trade on any market tested, so there was nothing to compare and no download is offered.
- What alerts does Ultimate Strategy Template have?
- 6
- syminfo.tickerid + " Long Signal - Entry Price: " + tostring(close) + " Timeframe: " + timeframe.period; syminfo.tickerid + " Short Signal - Entry Price: " + tostring(close) + " Timeframe: " + timeframe.period; syminfo.tickerid + " Custom Close Long Signal - Entry Price: " + tostring(close) + " Timeframe: " + timeframe.period; syminfo.tickerid + " Custom Close Short Signal - Entry Price: " + tostring(close) + " Timeframe: " + timeframe.period; and more.
- Does Ultimate Strategy Template use a stop loss?
- Yes
- strategy.exit sets a stop on line 273, 276.
BTCUSDT · 1D · default settings
- ATR
- ATR
- Winning trade
- Losing trade
- Equity
- Buy and hold
- Net profit
- 0.00%
- $0.00
- Buy and hold
- +102.5%
- same period
- Closed trades
- 0
- 0 won · 0 lost
- Profitable
- 0.0%
- of closed trades
- Profit factor
- —
- gross profit ÷ gross loss
- Max drawdown
- 0.00%
- $0.00
One run with the author's default settings, $1,000,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.
-
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 transp =, which v5 removed line 202
transp = on line 202, 222, 231. v5 folds the transparency into the colour with color.new(c, transp).
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 valuewhen → ta.valuewhen, max → math.max, min → math.min, atr → ta.atr, tostring → str.tostring.
v4 → v5
Not verifiedNeither version placed a trade on any of the 8 markets, so there was nothing to compare.
- Line 3: //@version=4 → //@version=5
- Line 19: input(type = input.source) → input.source()
- Line 25: input(type = input.session) → input.session()
- Line 32: input(type = input.time) → input.time()
- Line 33: input(type = input.time) → input.time()
- Line 36: input(type = input.bool) → input.bool()
36 more edits
- Line 37: input(type = input.integer) → input.int()
- Line 38: input(type = input.bool) → input.bool()
- Line 39: input(type = input.integer) → input.int()
- Line 41: input(type = input.bool) → input.bool()
- Line 42: input(type = input.integer) → input.int()
- Line 43: input(type = input.bool) → input.bool()
- Line 45: input(type = input.integer) → input.int()
- Line 46: input(type = input.bool) → input.bool()
- Line 48: input(type = input.integer) → input.int()
- Line 49: input(type = input.bool) → input.bool()
- Line 50: input(type = input.integer) → input.int()
- Line 51: input(type = input.bool) → input.bool()
- Line 52: input(type = input.integer) → input.int()
- Line 56: input(type = input.float) → input.float()
- Line 57: input(type = input.float) → input.float()
- Line 59: input(type = input.integer) → input.int()
- Line 60: input(type = input.float) → input.float()
- Line 64: input(type = input.float) → input.float()
- Line 66: input(type = input.integer) → input.int()
- Line 67: input(type = input.float) → input.float()
- Line 90: valuewhen → ta.valuewhen
- Line 156: max → math.max
- Line 161: min → math.min
- Line 173: atr → ta.atr
- Line 174: atr → ta.atr
- Line 202: transp = 100 → color.new(color.red, 100)
- Line 222: transp = 100 → color.new(color.green, 100)
- Line 231: transp = 85 → color.new((CloseSession and BarInSession(Session)[1]) ? color.green : na, 85)
- Line 249: tostring → str.tostring
- Line 250: tostring → str.tostring
- Line 255: tostring → str.tostring
- Line 256: tostring → str.tostring
- Line 265: tostring → str.tostring
- Line 268: tostring → str.tostring
- Line 274: tostring → str.tostring
- Line 277: tostring → str.tostring
⋯// © Daveatt-// @version=4+// @version=5// https://www.tradingview.com/blog/en/use-an-input-from-another-indicator-with-your-strategy-19584/⋯// ————— You capture the Source of your indicator here-ext_source_ = input(close, type=input.source, title="Data source")+ext_source_ = input.source(close, title="Data source")// Custom close signal⋯CloseSession = input(false, title="Close positions at market at the end of each session ?")-Session = input(title="Trading Session", type=input.session, defval="0000-2345")+Session = input.session(title="Trading Session", defval="0000-2345")OpenDirection = input(defval="ALL", title="Open Trading Direction", options=["ALL", "LONG", "SHORT"])⋯// ————— Syntax coming from https://www.tradingview.com/blog/en/new-parameter-for-date-input-added-to-pine-21812/-i_startTime = input(defval = timestamp("01 Jan 2019 13:30 +0000"), title = "Start Time", type = input.time)+i_startTime = input.time(defval = timestamp("01 Jan 2019 13:30 +0000"), title = "Start Time")-i_endTime = input(defval = timestamp("30 Dec 2021 23:30 +0000"), title = "End Time", type = input.time)+i_endTime = input.time(defval = timestamp("30 Dec 2021 23:30 +0000"), title = "End Time")TradeDateIsAllowed() => DateFilter ? time >= i_startTime and time <= i_endTime : true// ————— Set the max losing streak length with an input-setmaxLosingStreak = input(title="═════════════ Set Max number of consecutive loss trades", type=input.bool, defval=false)+setmaxLosingStreak = input.bool(title="═════════════ Set Max number of consecutive loss trades", defval=false)-maxLosingStreak = input(title="Max of consecutive loss trades", type=input.integer, defval=15, minval=1)+maxLosingStreak = input.int(title="Max of consecutive loss trades", defval=15, minval=1)-setmaxWinStreak = input(title="═════════════ Set Max number of consecutive won trades", type=input.bool, defval=false)+setmaxWinStreak = input.bool(title="═════════════ Set Max number of consecutive won trades", defval=false)-maxWinStreak = input(title="Max Winning Streak Length", type=input.integer, defval=15, minval=1)+maxWinStreak = input.int(title="Max Winning Streak Length", defval=15, minval=1)// ————— Set the max consecutive days with a loss-setmaxLosingDaysStreak = input(title="═════════════ Set MAX consecutive days with a loss in a row", type=input.bool, defval=false)+setmaxLosingDaysStreak = input.bool(title="═════════════ Set MAX consecutive days with a loss in a row", defval=false)-maxLosingDaysStreak = input(title="Max of consecutive days with a loss in a row", type=input.integer, defval=3, minval=1)+maxLosingDaysStreak = input.int(title="Max of consecutive days with a loss in a row", defval=3, minval=1)-setMaxDrawdown = input(title="═════════════ Set Max Total DrawDown", type=input.bool, defval=false)+setMaxDrawdown = input.bool(title="═════════════ Set Max Total DrawDown", defval=false)// ————— Input for the strategy's maximum drawdown (in % of strategy equity)-maxPercDd = input(title="Max Drawdown (%)", type=input.integer, defval=10, minval=1, maxval=100)+maxPercDd = input.int(title="Max Drawdown (%)", defval=10, minval=1, maxval=100)-setMaxIntradayLoss = input(title="═════════════ Set Max Intraday Loss", type=input.bool, defval=false)+setMaxIntradayLoss = input.bool(title="═════════════ Set Max Intraday Loss", defval=false)// ————— Input for the strategy's maximum intraday loss (in % of strategy equity)-maxIntradayLoss = input(title="Max Intraday Loss (%)", type=input.integer, defval=3, minval=1, maxval=100)+maxIntradayLoss = input.int(title="Max Intraday Loss (%)", defval=3, minval=1, maxval=100)-setNumberDailyTrades = input(title="═════════════ Limit the number of trades per day", type=input.bool, defval=false)+setNumberDailyTrades = input.bool(title="═════════════ Limit the number of trades per day", defval=false)-maxDailyTrades = input(title="Number MAX of daily trades", type=input.integer, defval=10, minval=1, maxval=100)+maxDailyTrades = input.int(title="Number MAX of daily trades", defval=10, minval=1, maxval=100)-setNumberWeeklyTrades = input(title="═════════════ Limit the number of trades per week", type=input.bool, defval=false)+setNumberWeeklyTrades = input.bool(title="═════════════ Limit the number of trades per week", defval=false)-maxWeeklyTrades = input(title="Number MAX of weekly trades", type=input.integer, defval=50, minval=1, maxval=100)+maxWeeklyTrades = input.int(title="Number MAX of weekly trades", defval=50, minval=1, maxval=100)// ————— Stop loss management⋯// ————— Percent-LossPerc = input(title="Stop Loss (%)", type=input.float, minval=0.0, step=0.5, defval=1) * 0.01+LossPerc = input.float(title="Stop Loss (%)", minval=0.0, step=0.5, defval=1) * 0.01-TrailPerc = input(title="Trail Stop Loss (%)", type=input.float, minval=0.0, step=0.5, defval=3) * 0.01+TrailPerc = input.float(title="Trail Stop Loss (%)", minval=0.0, step=0.5, defval=3) * 0.01// ————— ATR-atrStopLength = input(title="═════════════ ATR Stop Length", type=input.integer, defval=14)+atrStopLength = input.int(title="═════════════ ATR Stop Length", defval=14)-riskRatioATR = input(defval=1, title="[ATR ONLY] Risk Ratio", type=input.float,step=0.10)+riskRatioATR = input.float(defval=1, title="[ATR ONLY] Risk Ratio",step=0.10)// ————— Take Profit⋯// ————— Percent-ProfitPerc = input(title="Take Profit (%)", type=input.float, minval=0.0, step=0.5, defval=3) * 0.01+ProfitPerc = input.float(title="Take Profit (%)", minval=0.0, step=0.5, defval=3) * 0.01// ————— ATR-atrTakeProfitLength = input(title="══════ ATR Take Profit Length", type=input.integer, defval=14)+atrTakeProfitLength = input.int(title="══════ ATR Take Profit Length", defval=14)-rewardRatioATR = input(defval=2, title="[ATR ONLY] Reward Ratio", type=input.float,step=0.10)+rewardRatioATR = input.float(defval=2, title="[ATR ONLY] Reward Ratio",step=0.10)// global variables from PineCoders⋯// Entry Price-entry_price = valuewhen(condition=bear or bull, source=close, occurrence=0)+entry_price = ta.valuewhen(condition=bear or bull, source=close, occurrence=0)// ————— RISK MANAGEMENT⋯ stopValue = close * (1 - TrailPerc)- max(stopValue, longTrailStopPrice[1])+ math.max(stopValue, longTrailStopPrice[1])else⋯ stopValue = close * (1 + TrailPerc)- min(stopValue, shortTrailStopPrice[1])+ math.min(stopValue, shortTrailStopPrice[1])else⋯// True range is max(high - low, abs(high - close[1]), abs(low - close[1]))-atr_stop = atr(atrStopLength)+atr_stop = ta.atr(atrStopLength)-atr_tp = atr(atrTakeProfitLength)+atr_tp = ta.atr(atrTakeProfitLength)// ATR used for Risk:Reward⋯plot(use_SL_ATR and strategy.position_size != 0 ? RR_STOP_ATR * riskRatioATR : na,- color=color.red, transp=100, title="ATR Stop Value")+ color=color.new(color.red, 100), title="ATR Stop Value")// Take Profit Manangement⋯plot(use_TP_ATR and strategy.position_size != 0 ? RR_TP_ATR * rewardRatioATR : na,- color=color.green, transp=100, title="ATR TP Value")+ color=color.new(color.green, 100), title="ATR TP Value")// Session calculations⋯new_session = in_session and not in_session[1]-bgcolor(color=(CloseSession and BarInSession(Session)[1]) ? color.green : na,+bgcolor(color=color.new((CloseSession and BarInSession(Session)[1]) ? color.green : na, 85),- title="Trading Session", transp=85)+ title="Trading Session")// consolidation of the conditions⋯if (longCondition and okToTrade and okToTradeInSession and open_all_longs)- strategy.entry("Long", strategy.long, alert_message="{{ticker}} Long Signal - Entry Price: " + tostring(close) + " Timeframe: {{interval}}")+ strategy.entry("Long", strategy.long, alert_message="{{ticker}} Long Signal - Entry Price: " + str.tostring(close) + " Timeframe: {{interval}}")- alert(syminfo.tickerid + " Long Signal - Entry Price: " + tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close)+ alert(syminfo.tickerid + " Long Signal - Entry Price: " + str.tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close) ⋯if (shortCondition and okToTrade and okToTradeInSession and open_all_shorts)- strategy.entry("Short", strategy.short, alert_message="{{ticker}} Short Signal - Entry Price: " + tostring(close) + " Timeframe: {{interval}}")+ strategy.entry("Short", strategy.short, alert_message="{{ticker}} Short Signal - Entry Price: " + str.tostring(close) + " Timeframe: {{interval}}")- alert(syminfo.tickerid + " Short Signal - Entry Price: " + tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close)+ alert(syminfo.tickerid + " Short Signal - Entry Price: " + str.tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close)// Execute Exits⋯ strategy.close(id="Long", alert_message="{{ticker}} Custom Close Long Signal - Timeframe: {{interval}}", comment="Custom Close Signal\nClose Long")- alert(syminfo.tickerid + " Custom Close Long Signal - Entry Price: " + tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close)+ alert(syminfo.tickerid + " Custom Close Long Signal - Entry Price: " + str.tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close)if (strategy.position_size < 0 and exit_bear) strategy.close(id="Short", alert_message="{{ticker}} Custom Close Short Signal - Timeframe: {{interval}}", comment="Custom Close Signal\nClose Short")- alert(syminfo.tickerid + " Custom Close Short Signal - Entry Price: " + tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close)+ alert(syminfo.tickerid + " Custom Close Short Signal - Entry Price: " + str.tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close)close_all = CloseDirection == "ALL"⋯ strategy.exit(id="Exit Long", from_entry="Long", stop=(useSL) ? final_SL_Long : na, limit=(useTakeProfit) ? TPlongPrice : na, alert_message="{{ticker}} Close Long Signal - Timeframe: {{interval}}")- alert(syminfo.tickerid + " Exit Long Signal - Exit Price: " + tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close)+ alert(syminfo.tickerid + " Exit Long Signal - Exit Price: " + str.tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close)if (strategy.position_size < 0 and close_all_shorts) strategy.exit(id="Exit Short", from_entry="Short", stop=(useSL) ? final_SL_Short : na, limit=(useTakeProfit) ? TPshortPrice : na, alert_message="{{ticker}} Close Short Signal - Timeframe: {{interval}}")- alert(syminfo.tickerid + " Exit Short Signal - Exit Price: " + tostring(close) + "Timeframe: " + timeframe.period, alert.freq_once_per_bar_close)+ alert(syminfo.tickerid + " Exit Short Signal - Exit Price: " + str.tostring(close) + "Timeframe: " + timeframe.period, alert.freq_once_per_bar_close)// // Close all Longs only⋯Clean v5
Not verifiedNeither version placed a trade on any of the 8 markets, so there was nothing to compare.
- Line 21: input() → input.bool()
- Line 23: input() → input.bool()
- Line 24: input() → input.bool()
- Line 26: input() → input.string()
- Line 27: input() → input.string()
- Line 28: input() → input.bool()
3 more edits
- Line 30: input() → input.bool()
- Line 54: input() → input.string()
- Line 62: input() → input.string()
⋯// Custom close signal-custom_close = input(false, title="Use Custom Close?")+custom_close = input.bool(false, title="Use Custom Close?")// ————— Bar Coloring-clrBars = input(true,title="Colour Candles to Trade Order state")+clrBars = input.bool(true,title="Colour Candles to Trade Order state")-CloseSession = input(false, title="Close positions at market at the end of each session ?")+CloseSession = input.bool(false, title="Close positions at market at the end of each session ?")Session = input.session(title="Trading Session", defval="0000-2345")-OpenDirection = input(defval="ALL", title="Open Trading Direction", options=["ALL", "LONG", "SHORT"])+OpenDirection = input.string(defval="ALL", title="Open Trading Direction", options=["ALL", "LONG", "SHORT"])-CloseDirection = input(defval="ALL", title="Close Trading Direction", options=["ALL", "LONG", "SHORT"])+CloseDirection = input.string(defval="ALL", title="Close Trading Direction", options=["ALL", "LONG", "SHORT"])-closeOnOpposite = input(true, title="Close on Opposite Signal")+closeOnOpposite = input.bool(true, title="Close on Opposite Signal")// ————— Date range filtering-DateFilter = input(false, "═════════════ Date Range Filtering")+DateFilter = input.bool(false, "═════════════ Date Range Filtering")// ————— Syntax coming from https://www.tradingview.com/blog/en/new-parameter-for-date-input-added-to-pine-21812/⋯// ————— Stop loss management-StopType = input(title="═════════════ Stop Type Selection", defval="None", options=["None", "Percent", "Trailing", "ATR"])+StopType = input.string(title="═════════════ Stop Type Selection", defval="None", options=["None", "Percent", "Trailing", "ATR"])// ————— Percent⋯// ————— Take Profit-TakeProfitType = input(title="════ Take Profit Type Selection", defval="None", options=["None", "Percent", "ATR"])+TakeProfitType = input.string(title="════ Take Profit Type Selection", defval="None", options=["None", "Percent", "ATR"])// ————— Percent⋯Does it run in Pine Script v6?
Not tested
Neither version placed a trade on any of the 8 markets, so there was nothing to compare. The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.
⋯// © Daveatt-// @version=5+// @version=6// https://www.tradingview.com/blog/en/use-an-input-from-another-indicator-with-your-strategy-19584/⋯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 |
|---|---|---|---|
| Data source | close | source | ext_source |
| Use Custom Close? | false | bool | exit_bull exit_bear |
| Colour Candles to Trade Order state | true | bool | bclr |
| Close positions at market at the end of each session ? | false | bool | okToTradeInSession longs_opened_in_session shorts_opened_in_session Trading Session |
| Trading Session | 0000-2345 | session | in_session Trading Session |
| Open Trading Direction | ALL | string · options ["ALL", "LONG", "SHORT"] | open_all open_all_longs open_all_shorts |
| Close Trading Direction | ALL | string · options ["ALL", "LONG", "SHORT"] | close_all close_all_longs close_all_shorts |
| Close on Opposite Signal | true | bool | close Long close Short line 258 line 260 |
| ═════════════ Date Range Filtering | false | bool | line 34 |
| Start Time | timestamp("01 Jan 2019 13:30 +0000") | time | line 34 |
| End Time | timestamp("30 Dec 2021 23:30 +0000") | time | line 34 |
| ═════════════ Set Max number of consecutive loss trades | false | bool | okToTradeLossStreak |
| Max of consecutive loss trades | 15 | int (written input.integer) · min 1 | okToTradeLossStreak |
| ═════════════ Set Max number of consecutive won trades | false | bool | okToTradeWinStreak |
| Max Winning Streak Length | 15 | int (written input.integer) · min 1 | okToTradeWinStreak |
| ═════════════ Set MAX consecutive days with a loss in a row | false | bool | countConsLossDays |
| Max of consecutive days with a loss in a row | 3 | int (written input.integer) · min 1 | countConsLossDays |
| ═════════════ Set Max Total DrawDown | false | bool | condmaxdrawdown |
| Max Drawdown (%) | 10 | int (written input.integer) · min 1 · max 100 | condmaxdrawdown |
| ═════════════ Set Max Intraday Loss | false | bool | condintradayloss |
| Max Intraday Loss (%) | 3 | int (written input.integer) · min 1 · max 100 | condintradayloss |
| ═════════════ Limit the number of trades per day | false | bool | tradesIntradayCount |
| Number MAX of daily trades | 10 | int (written input.integer) · min 1 · max 100 | tradesIntradayCount |
| ═════════════ Limit the number of trades per week | false | bool | okToTradeWeekly |
| Number MAX of weekly trades | 50 | int (written input.integer) · min 1 · max 100 | okToTradeWeekly |
| ═════════════ Stop Type Selection | None | string · options ["None", "Percent", "Trailing", "ATR"] | useSL use_SL_Percent use_SL_Trail use_SL_ATR |
| Stop Loss (%) | 1 | float · min 0.0 · step 0.5 | longPercStopPrice shortPercStopPrice |
| Trail Stop Loss (%) | 3 | float · min 0.0 · step 0.5 | longTrailStopPrice shortTrailStopPrice stopValue |
| ═════════════ ATR Stop Length | 14 | int (written input.integer) | atr_stop |
| [ATR ONLY] Risk Ratio | 1 | float · step 0.10 | final_SL_Long final_SL_Short ATR Stop Value |
| ════ Take Profit Type Selection | None | string · options ["None", "Percent", "ATR"] | useTakeProfit use_TP_Percent use_TP_ATR |
| Take Profit (%) | 3 | float · min 0.0 · step 0.5 | TPlongPrice TPshortPrice |
| ══════ ATR Take Profit Length | 14 | int (written input.integer) | atr_tp |
| [ATR ONLY] Reward Ratio | 2 | float · step 0.10 | TPlongPrice TPshortPrice ATR TP Value |
What it calculates
- ATR (
atr,ta.atrin v5)═════════════ ATR Stop Length (14)atr_stop · line 173 - ATR (
atr,ta.atrin v5)══════ ATR Take Profit Length (14)atr_tp · line 174
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 89 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open Long long | (longCondition and okToTrade and okToTradeInSession and open_all_longs) | On | 249 |
| Open Short short | (shortCondition and okToTrade and okToTradeInSession and open_all_shorts) | On | 255 |
| Close Long | closeOnOpposite and strategy.position_size > 0 and shortCondition | On | 259 |
| Close Short | closeOnOpposite and strategy.position_size < 0 and longCondition | On | 261 |
| Close Long | (strategy.position_size > 0 and exit_bull) | On | 264 |
| Close Short | (strategy.position_size < 0 and exit_bear) | On | 267 |
| Exit Exit Long stop and limit | (strategy.position_size > 0 and close_all_longs) | On | 273 |
| Exit Exit Short stop and limit | (strategy.position_size < 0 and close_all_shorts) | On | 276 |
| Close | not okToTradeInSession and close_all and trades_opened | On | 286 |
| Close | (close_strat) | On | 291 |
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 | syminfo.tickerid + " Long Signal - Entry Price: " + tostring(close) + " Timeframe: " + timeframe.period | 250 |
| (no title) | alert | syminfo.tickerid + " Short Signal - Entry Price: " + tostring(close) + " Timeframe: " + timeframe.period | 256 |
| (no title) | alert | syminfo.tickerid + " Custom Close Long Signal - Entry Price: " + tostring(close) + " Timeframe: " + timeframe.period | 265 |
| (no title) | alert | syminfo.tickerid + " Custom Close Short Signal - Entry Price: " + tostring(close) + " Timeframe: " + timeframe.period | 268 |
| (no title) | alert | syminfo.tickerid + " Exit Long Signal - Exit Price: " + tostring(close) + " Timeframe: " + timeframe.period | 274 |
| (no title) | alert | syminfo.tickerid + " Exit Short Signal - Exit Price: " + tostring(close) + "Timeframe: " + timeframe.period | 277 |
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 | 0.0% | +102.5% | 0 | 0% | — | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | 0.0% | +5.5% | 0 | 0% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | 0.0% | +9.8% | 0 | 0% | — | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | 0.0% | +8.4% | 0 | 0% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | 0.0% | +16.7% | 0 | 0% | — | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | 0.0% | +21.5% | 0 | 0% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | 0.0% | +148.3% | 0 | 0% | — | 0.0% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | 0.0% | +17.1% | 0 | 0% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
Backtests are simulations on historical data and are not investment advice.
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 |
|---|---|---|---|---|---|
| Ultimate Strategy Template this page | — | v4 strategy | 0.0% | 0 | 0.0% |
| SOJA PIVOT by ParaBellum68 | atr | v4 strategy | +3.3% | 9 | 18.2% |
| Volatility System by EduardoMattje | atr | v5 strategy | +150.2% | 2 | 21.5% |
| ATR Stop Buy Strategy by phobo3s | atr | v4 strategy | No trades on this market | ||
| VBand Strategy by Saravanan_Ragavan | atr | v4 strategy | No trades on this market | ||
| Volatility Breakout Strategy [Angel Algo] by AngelAlgo | atr | v5 strategy | +3.1% | 18 | 3.6% |
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 52 ms | With a workaround 1,000 bars in 174 ms | Not measured |
| PineTS | No 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/// © Daveatt// @version=4// https://www.tradingview.com/blog/en/use-an-input-from-another-indicator-with-your-strategy-19584/SystemName = "BEST Strategy Template"TradeId = "DAVE"// These values are used both in the strategy() header and in the script's relevant inputs as default values so they match.// Unless these values match in the script's Inputs and the TV backtesting Properties, results between them cannot be compared.InitCapital = 1000000InitPosition = 10.0InitCommission = 0.075InitPyramidMax = 3CalcOnorderFills = truestrategy(title=SystemName, shorttitle=SystemName, overlay=true, pyramiding=InitPyramidMax, initial_capital=InitCapital, default_qty_type=strategy.percent_of_equity, default_qty_value=InitPosition, commission_type=strategy.commission.percent, commission_value=InitCommission, calc_on_order_fills=CalcOnorderFills, precision=6, max_lines_count=500, max_labels_count=500)// ————— You capture the Source of your indicator hereext_source_ = input(close, type=input.source, title="Data source")// Custom close signalcustom_close = input(false, title="Use Custom Close?")// ————— Bar ColoringclrBars = input(true,title="Colour Candles to Trade Order state")CloseSession = input(false, title="Close positions at market at the end of each session ?")Session = input(title="Trading Session", type=input.session, defval="0000-2345")OpenDirection = input(defval="ALL", title="Open Trading Direction", options=["ALL", "LONG", "SHORT"])CloseDirection = input(defval="ALL", title="Close Trading Direction", options=["ALL", "LONG", "SHORT"])closeOnOpposite = input(true, title="Close on Opposite Signal")// ————— Date range filteringDateFilter = input(false, "═════════════ Date Range Filtering")// ————— Syntax coming from https://www.tradingview.com/blog/en/new-parameter-for-date-input-added-to-pine-21812/i_startTime = input(defval = timestamp("01 Jan 2019 13:30 +0000"), title = "Start Time", type = input.time)i_endTime = input(defval = timestamp("30 Dec 2021 23:30 +0000"), title = "End Time", type = input.time)TradeDateIsAllowed() => DateFilter ? time >= i_startTime and time <= i_endTime : true// ————— Set the max losing streak length with an inputsetmaxLosingStreak = input(title="═════════════ Set Max number of consecutive loss trades", type=input.bool, defval=false)maxLosingStreak = input(title="Max of consecutive loss trades", type=input.integer, defval=15, minval=1)setmaxWinStreak = input(title="═════════════ Set Max number of consecutive won trades", type=input.bool, defval=false)maxWinStreak = input(title="Max Winning Streak Length", type=input.integer, defval=15, minval=1)// ————— Set the max consecutive days with a losssetmaxLosingDaysStreak = input(title="═════════════ Set MAX consecutive days with a loss in a row", type=input.bool, defval=false)maxLosingDaysStreak = input(title="Max of consecutive days with a loss in a row", type=input.integer, defval=3, minval=1)setMaxDrawdown = input(title="═════════════ Set Max Total DrawDown", type=input.bool, defval=false)// ————— Input for the strategy's maximum drawdown (in % of strategy equity)maxPercDd = input(title="Max Drawdown (%)", type=input.integer, defval=10, minval=1, maxval=100)setMaxIntradayLoss = input(title="═════════════ Set Max Intraday Loss", type=input.bool, defval=false)// ————— Input for the strategy's maximum intraday loss (in % of strategy equity)maxIntradayLoss = input(title="Max Intraday Loss (%)", type=input.integer, defval=3, minval=1, maxval=100)setNumberDailyTrades = input(title="═════════════ Limit the number of trades per day", type=input.bool, defval=false)maxDailyTrades = input(title="Number MAX of daily trades", type=input.integer, defval=10, minval=1, maxval=100)setNumberWeeklyTrades = input(title="═════════════ Limit the number of trades per week", type=input.bool, defval=false)maxWeeklyTrades = input(title="Number MAX of weekly trades", type=input.integer, defval=50, minval=1, maxval=100)// ————— Stop loss managementStopType = input(title="═════════════ Stop Type Selection", defval="None", options=["None", "Percent", "Trailing", "ATR"])// ————— PercentLossPerc = input(title="Stop Loss (%)", type=input.float, minval=0.0, step=0.5, defval=1) * 0.01TrailPerc = input(title="Trail Stop Loss (%)", type=input.float, minval=0.0, step=0.5, defval=3) * 0.01// ————— ATRatrStopLength = input(title="═════════════ ATR Stop Length", type=input.integer, defval=14)riskRatioATR = input(defval=1, title="[ATR ONLY] Risk Ratio", type=input.float,step=0.10)// ————— Take ProfitTakeProfitType = input(title="════ Take Profit Type Selection", defval="None", options=["None", "Percent", "ATR"])// ————— PercentProfitPerc = input(title="Take Profit (%)", type=input.float, minval=0.0, step=0.5, defval=3) * 0.01// ————— ATRatrTakeProfitLength = input(title="══════ ATR Take Profit Length", type=input.integer, defval=14)rewardRatioATR = input(defval=2, title="[ATR ONLY] Reward Ratio", type=input.float,step=0.10)// global variables from PineCoders// ————— ColorsMyGreenRaw = color.new(color.lime,0), MyGreenMedium = color.new(#00b300,0), MyGreenSemiDark = color.new(#009900,0), MyGreenDark = color.new(#006600,0), MyGreenDarkDark = color.new(#003300,0)MyRedRaw = color.new(color.red,0), MyRedMedium = color.new(#cc0000,0), MyRedSemiDark = color.new(#990000,0), MyRedDark = color.new(#330000,0), MyRedDarkDark = color.new(#330000,0)MyFuchsiaRaw = color.new(color.fuchsia,0), MyFuchsiaMedium = color.new(#c000c0,0), MyFuchsiaDark = color.new(#800080,0), MyFuchsiaDarkDark = color.new(#400040,0)MyYellowRaw = color.new(color.yellow,0), MyYellowMedium = color.new(#c0c000,0), MyYellowDark = color.new(#808000,0), MyYellowDarkDark = color.new(#404000,0)MyOrangeRaw = color.new(#ffa500,0), MyOrangeMedium = color.new(#cc8400,0), MyOrangeDark = color.new(#996300,0)MyBlueRaw = color.new(#4985E7,0), MyBlueMedium = color.new(#4985E7,0)MyGreenBackGround = color.new(#00FF00,93), MyRedBackGround = color.new(#FF0000,90)BIG_NUMBER_COUNT = 1000 // variables initialisationext_source = nz(ext_source_)// 1 is bull signalbull = (ext_source == 1)// -1 is bear signalbear = (ext_source == -1)// 2 exit custom close longexit_bull = custom_close and (ext_source == 2)// -2 exit custom close shortexit_bear = custom_close and (ext_source == -2)// Entry Priceentry_price = valuewhen(condition=bear or bull, source=close, occurrence=0)// ————— RISK MANAGEMENTcondintradayloss = (setMaxIntradayLoss) ? maxIntradayLoss : 100strategy.risk.max_intraday_loss(value=condintradayloss, type=strategy.percent_of_equity)condmaxdrawdown = (setMaxDrawdown) ? maxPercDd : 100strategy.risk.max_drawdown(value=condmaxdrawdown, type=strategy.percent_of_equity)// daily trades calculationoktoTradeDaily = truetradesIntradayCount = (setNumberDailyTrades) ? maxDailyTrades : BIG_NUMBER_COUNTstrategy.risk.max_intraday_filled_orders(count=tradesIntradayCount)// weekly trades calculationtradesLastWeek = 0tradesLastWeek := if (dayofweek == dayofweek.monday) and (dayofweek != dayofweek[1]) strategy.closedtrades[1] + strategy.opentrades[1]else tradesLastWeek[1]// Calculate number of trades this weekweeklyTrades = (strategy.closedtrades + strategy.opentrades) - tradesLastWeekokToTradeWeekly = (setNumberWeeklyTrades) ? (weeklyTrades < maxWeeklyTrades) : true// consecutive loss days in a rowcountConsLossDays = (setmaxLosingDaysStreak) ? maxLosingDaysStreak : BIG_NUMBER_COUNTstrategy.risk.max_cons_loss_days(countConsLossDays)// Calculate the total losing streaks// Check if there's a new losing trade that increased the streaknewLoss = (strategy.losstrades > strategy.losstrades[1]) and (strategy.wintrades == strategy.wintrades[1]) and (strategy.eventrades == strategy.eventrades[1]) // Determine current losing streak lengthstreakLossLen = 0streakLossLen := if (newLoss) nz(streakLossLen[1]) + 1else if (strategy.wintrades > strategy.wintrades[1]) or (strategy.eventrades > strategy.eventrades[1]) 0 else nz(streakLossLen[1])// Check if losing streak is under max allowedokToTradeLossStreak = (setmaxLosingStreak) ? streakLossLen < maxLosingStreak : true// Calculate the total winning streaks// See if there's a new winner that increased the streaknewWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1])// Figure out current winning streak lengthstreakWinLen = 0streakWinLen := if (newWin) nz(streakWinLen[1]) + 1else if (strategy.losstrades > strategy.losstrades[1]) or (strategy.eventrades > strategy.eventrades[1]) 0 else nz(streakWinLen[1])// Check if winning streak is under max allowedokToTradeWinStreak = (setmaxWinStreak) ? streakWinLen < maxWinStreak : true// Stop loss managementlongPercStopPrice = strategy.position_avg_price * (1 - LossPerc)shortPercStopPrice = strategy.position_avg_price * (1 + LossPerc)// trailing// Determine trail stop loss priceslongTrailStopPrice = 0.0, shortTrailStopPrice = 0.0final_SL_Long = 0.0, final_SL_Short = 0.0longTrailStopPrice := if (strategy.position_size > 0) stopValue = close * (1 - TrailPerc) max(stopValue, longTrailStopPrice[1])else 0shortTrailStopPrice := if (strategy.position_size < 0) stopValue = close * (1 + TrailPerc) min(stopValue, shortTrailStopPrice[1])else 999999useSL = StopType != "None"use_SL_Percent = StopType == "Percent"use_SL_Trail = StopType == "Trailing"use_SL_ATR = StopType == "ATR"// Use this function to return the correct pip value for pips on Forex symbolspip() => syminfo.mintick * (syminfo.type == "forex" ? 10 : 1)// ATR// Function atr (average true range) returns the RMA of true range. // True range is max(high - low, abs(high - close[1]), abs(low - close[1]))atr_stop = atr(atrStopLength)atr_tp = atr(atrTakeProfitLength)// ATR used for Risk:RewardRR_STOP_ATR = 0.0, RR_STOP_ATR := nz(RR_STOP_ATR[1])RR_TP_ATR = 0.0, RR_TP_ATR := nz(RR_TP_ATR[1])// Capturig the atr value at signal time onlyif bull or bear RR_STOP_ATR := atr_stop RR_TP_ATR := atr_tpfinal_SL_Long := if use_SL_Percent longPercStopPriceelse if use_SL_Trail longTrailStopPriceelse if use_SL_ATR entry_price - (RR_STOP_ATR * riskRatioATR)final_SL_Short := if use_SL_Percent shortPercStopPriceelse if use_SL_Trail shortTrailStopPriceelse if use_SL_ATR entry_price + (RR_STOP_ATR * riskRatioATR)// Plot stop loss values for confirmationplot(series=(strategy.position_size > 0 and useSL) ? final_SL_Long : na, color=color.red, style=plot.style_cross, linewidth=2, title="Long Stop Loss")plot(series=(strategy.position_size < 0 and useSL) ? final_SL_Short : na, color=color.red, style=plot.style_cross, linewidth=2, title="Short Stop Loss")// Used for debug and check the ATR SL valueplot(use_SL_ATR and strategy.position_size != 0 ? RR_STOP_ATR * riskRatioATR : na, color=color.red, transp=100, title="ATR Stop Value")// Take Profit ManangementuseTakeProfit = TakeProfitType != "None"use_TP_Percent = TakeProfitType == "Percent"use_TP_ATR = TakeProfitType == "ATR"TPlongPrice = use_TP_Percent ? strategy.position_avg_price * (1 + ProfitPerc) : strategy.position_avg_price + (RR_TP_ATR * rewardRatioATR)TPshortPrice = use_TP_Percent ? strategy.position_avg_price * (1 - ProfitPerc) : strategy.position_avg_price - (RR_TP_ATR * rewardRatioATR)// Plot take profit values for confirmationplot(series=(strategy.position_size > 0 and useTakeProfit) ? TPlongPrice : na, color=color.green, style=plot.style_circles, linewidth=3, title="Long Take Profit")plot(series=(strategy.position_size < 0 and useTakeProfit) ? TPshortPrice : na, color=color.red, style=plot.style_circles, linewidth=3, title="Short Take Profit")// Used for debug and check the ATR TP valueplot(use_TP_ATR and strategy.position_size != 0 ? RR_TP_ATR * rewardRatioATR : na, color=color.green, transp=100, title="ATR TP Value")// Session calculations// The BarInSession function returns true when// the current bar is inside the session parameterBarInSession(sess) => time(timeframe.period, sess) != 0in_session = BarInSession(Session)okToTradeInSession = CloseSession ? in_session : truenew_session = in_session and not in_session[1]bgcolor(color=(CloseSession and BarInSession(Session)[1]) ? color.green : na, title="Trading Session", transp=85)// consolidation of the conditionsokToTrade = okToTradeWeekly and okToTradeLossStreak and okToTradeWinStreak and TradeDateIsAllowed() and okToTradeInSession// and TradeHourlyIsAllowed()// Orders partlongs_opened = strategy.position_size > 0 shorts_opened = strategy.position_size < 0trades_opened = strategy.position_size != 0longs_opened_in_session = CloseSession and longs_openedshorts_opened_in_session = CloseSession and shorts_opened// trades_opened_in_session = CloseSession and trades_openedopen_all = OpenDirection == "ALL"open_all_longs = OpenDirection != "SHORT"open_all_shorts = OpenDirection != "LONG"// Go longlongCondition = bullif (longCondition and okToTrade and okToTradeInSession and open_all_longs) strategy.entry("Long", strategy.long, alert_message="{{ticker}} Long Signal - Entry Price: " + tostring(close) + " Timeframe: {{interval}}") alert(syminfo.tickerid + " Long Signal - Entry Price: " + tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close) // Go ShortshortCondition = bearif (shortCondition and okToTrade and okToTradeInSession and open_all_shorts) strategy.entry("Short", strategy.short, alert_message="{{ticker}} Short Signal - Entry Price: " + tostring(close) + " Timeframe: {{interval}}") alert(syminfo.tickerid + " Short Signal - Entry Price: " + tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close)// Execute Exitsif closeOnOpposite and strategy.position_size > 0 and shortCondition// and open_all_shorts strategy.close(id="Long", alert_message="{{ticker}} Short Signal - Close Long Signal - Timeframe: {{interval}}", comment="Short Signal\nClose Long")if closeOnOpposite and strategy.position_size < 0 and longCondition// and open_all_longs strategy.close(id="Short", alert_message="{{ticker}} Long Signal - Close Short Signal - Timeframe: {{interval}}", comment="Long Signal\nClose Short")// Custom closeif (strategy.position_size > 0 and exit_bull) strategy.close(id="Long", alert_message="{{ticker}} Custom Close Long Signal - Timeframe: {{interval}}", comment="Custom Close Signal\nClose Long") alert(syminfo.tickerid + " Custom Close Long Signal - Entry Price: " + tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close)if (strategy.position_size < 0 and exit_bear) strategy.close(id="Short", alert_message="{{ticker}} Custom Close Short Signal - Timeframe: {{interval}}", comment="Custom Close Signal\nClose Short") alert(syminfo.tickerid + " Custom Close Short Signal - Entry Price: " + tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close)close_all = CloseDirection == "ALL"close_all_longs = CloseDirection != "SHORT"close_all_shorts = CloseDirection != "LONG"if (strategy.position_size > 0 and close_all_longs) strategy.exit(id="Exit Long", from_entry="Long", stop=(useSL) ? final_SL_Long : na, limit=(useTakeProfit) ? TPlongPrice : na, alert_message="{{ticker}} Close Long Signal - Timeframe: {{interval}}") alert(syminfo.tickerid + " Exit Long Signal - Exit Price: " + tostring(close) + " Timeframe: " + timeframe.period, alert.freq_once_per_bar_close)if (strategy.position_size < 0 and close_all_shorts) strategy.exit(id="Exit Short", from_entry="Short", stop=(useSL) ? final_SL_Short : na, limit=(useTakeProfit) ? TPshortPrice : na, alert_message="{{ticker}} Close Short Signal - Timeframe: {{interval}}") alert(syminfo.tickerid + " Exit Short Signal - Exit Price: " + tostring(close) + "Timeframe: " + timeframe.period, alert.freq_once_per_bar_close)// // Close all Longs only// if not okToTradeInSession and close_all_longs and longs_opened_in_session// strategy.close(id="Long")// // Close all Shorts only// if not okToTradeInSession and close_all_shorts and shorts_opened_in_session// strategy.close(id="Short")// Close all positions at the end of each session regardeless of their profit/lossif not okToTradeInSession and close_all and trades_opened strategy.close_all()// Flatten strategy when max losing streak is reachedclose_strat = not okToTradeWeekly or not okToTradeLossStreak or not okToTradeWinStreak or not TradeDateIsAllowed()if (close_strat) // close all existing orders strategy.close_all()// Colour code the candlesbclr = not clrBars ? na : strategy.position_size == 0 ? color.gray : longs_opened ? color.lime : shorts_opened ? color.red : color.graybarcolor(bclr, title="Trade State Bar Colouring")