Pine Script v5 · Strategy
[fpemehd] Strategy Template
A Pine Script v5 strategy built on ATR or SMA (14), SMA (21) and Crossover (indicator1, indicator2). It has 8 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 100% of equity and pays 0.1 commission. 24 settings; defaults include Length for ATR Filter 14, SMA Length for ATR SMA 40 and Fast SMA Length 21.
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 [fpemehd] Strategy Template repaint?
- Yes
- At least one pattern in the source can repaint: intrabar recalculation.
- How did [fpemehd] Strategy Template do on BTCUSDT 1D with default settings?
- +10.54%
- From 26 Jan 2024 to 21 Oct 2026, over 41 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
- Does [fpemehd] Strategy Template run in Pine Script v6?
- Yes
- Same 41 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 [fpemehd] Strategy Template use a stop loss?
- Yes
- strategy.exit sets a stop on line 256, 257, 259, 260.
- Does [fpemehd] Strategy Template run in Zeal Terminal?
- Yes
- It compiles in 110 ms and runs 1,000 bars in 143 ms, in the browser.
BTCUSDT · 1D · default settings
- indicator1
- indicator2
- Long Stop Loss
- Short Stop Loss
- Long Take Profit
- Short Take Profit
- Position Entry Price
- Winning trade
- Losing trade
- Equity
- Buy and hold
| Start: long1713571200000 |
| End: long1787184000000 |
| Net Profit: 10.54% |
| Percent Per Day 0.01237% |
| Percent Profitable: 46.34% |
| Profit Factor: 1.372 |
| Total Trades: 41 |
| Max Wins In A Row: 5 |
| Max Losses In A Row: 5 |
- Net profit
- +10.54%
- $10,542.20
- Buy and hold
- +102.5%
- same period
- Closed trades
- 41
- 19 won · 22 lost
- Profitable
- 46.3%
- of closed trades
- Profit factor
- 1.37
- gross profit ÷ gross loss
- Max drawdown
- 14.80%
- −$14,798.30
One run with the author's default settings, $100,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.
-
Check
1 setting does nothing
“Use Take Profit?” is declared but never read.
-
Check
Every trade uses all the equity
default_qty_value is 100% of equity.
-
Note
No slippage
Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.
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 |
|---|---|---|---|
| Time | |||
| Start DateChoose Backtest Start Date | timestamp("20 Jan 1990 00:00 +0900") | time | inTime |
| End DateChoose Backtest End Date | timestamp("20 Dec 2030 00:00 +0900") | time | inTime |
| Long / Short | |||
| Long?Enable Long Position Trade? | true | bool | longCond closeLong |
| Short?Enable Short Position Trade? | true | bool | shortCond closeShort |
| Filters | |||
| ATR Filter On?ATR Filter On? Order will not be made unless filter condition is fulfilled | false | bool | filterFulfilled |
| Length for ATR Filter | 14 | int · min 1 · max 100 · step 1 | i_ATRFilter |
| SMA Length for ATR SMAATR should be bigger than this | 40 | int · min 1 · max 100000 · step 1 | i_ATRFilter |
| Strategy | |||
| Fast SMA Length | 21 | int · min 1 | indicator1 |
| Slow SMA LengthHow many candles back to calculte the fast/slow SMA. | 49 | int · min 1 | indicator2 |
| Stop Loss | |||
| Enable SL & TP? | true | bool | longSLPrice shortSLPrice longTPPrice shortTPPrice |
| Enable Trailing SL?Enable Stop Loss & Take Profit? \n\Enable Trailing SL? | false | bool | longSLPrice shortSLPrice |
| Stop Loss TypeStop Loss based on %? ATR? | ATR | string · options ["Percent", "ATR", "Previous LL / HH"] | line 90 line 96 |
| ATR Length | 14 | int · min 1 · max 200 · step 1 | openAtr |
| ATR Multiplier | 3 | float · min 1 · max 200 · step 0.1 | line 92 line 98 |
| Percent | 3 | float | line 91 line 97 |
| Lowest Price Before EntryLookback to find the Lowest Price. \nStopLoss is determined by the Lowest price of the look back period. Take Profit is derived from this also by multiplying the StopLoss value by the Risk:Reward multiplier. | 30 | int · min 30 · step 1 | openLowest openHighest |
| Take Profit | |||
| Use Take Profit? | true | bool | unused |
| R:R RatioR:R Ratio > Risk Reward Ratio? It will automatically set Take Profit % based on Stop Loss | 1.8 | float · min 0.1 · max 200 · step 0.1 | line 146 line 148 line 243 line 248 |
| Take Profit Quantity %% of position closed when tp target is met. | 50 | float · min 0.0 · max 100 · step 1.0 | exit Long TP / SL exit Short TP / SL |
| Quantity | |||
| Use Risk Manangement? | true | bool | line 180 labelStr |
| Risk Per Trade (%)Use Risk Manangement by Quantity Control? | 3 | float · min 0 · max 100 · step 0.1 | riskPerTrade labelStr |
| Strategy: Drawings | |||
| Show Simple Label for Entry? | false | bool | line 203 line 206 |
| Show Trade Exit LabelsUseful labels to identify Profit/Loss and cumulative portfolio capital after each trade closes.\n\nAlso note that TradingView limits the max number of 'boxes' that can be displayed on a chart (max 500). This means when you lookback far enough on the chart you will not see the TP/SL boxes. However you can check this option to identify where trades exited. | true | bool | line 213 line 225 |
| Show DashboardShow Backtest Results. Backtest Dates, Win/Lose Rates, Etc. | true | bool | line 270 |
What it calculates
- ATR / SMALength for ATR Filter (14)
i_ATRFilter · line 34 - SMAsource = close, length = Fast SMA Length (21)
indicator1 · line 44 - SMAsource = close, length = Slow SMA Length (49)
indicator2 · line 45 - Crossoverindicator1, indicator2
crossover · line 53 - Crossunderindicator1, indicator2
crossunder · line 54 - Valuewhen / ATRcondition = enteringTrade, source = ta.atr(i_slATRLen), occurrence = 0
openAtr · line 86 - Valuewhen / Lowestcondition = openLong, source = ta.lowest(low, i_slLookBack), occurrence = 0
openLowest · line 87 - Valuewhen / Highestcondition = openShort, source = ta.highest(high, i_slLookBack), occurrence = 0
openHighest · line 88
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 62 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 | (openLong) | On | 242 |
| Open Short short | (openShort) | On | 247 |
| Close Long | (closeLong) | On | 250 |
| Close Short | (closeShort) | On | 253 |
| Exit Long TP / SL stop and limit | (inLong) | On | 256 |
| Exit Long SL stop | (inLong) | On | 257 |
| Exit Short TP / SL stop and limit | (inShort) | On | 259 |
| Exit Short SL stop | (inShort) | On | 260 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Does it repaint?
Yes
At least one pattern in the source can repaint; it is marked Check below.
- ClearHigher-timeframe dataThe script requests no other symbol or timeframe.
- ClearFuture-bar referencesNo negative history offsets such as close[-1].
- CheckIntrabar recalculationuses varip. Live values can differ from history.
- 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 | +10.5% | +102.5% | 41 | 46% | 1.37 | 14.8% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | −3.0% | +5.5% | 27 | 33% | 0.91 | 20.2% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +22.0% | +9.8% | 27 | 56% | 2.19 | 7.4% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | +8.9% | +8.4% | 33 | 36% | 1.26 | 19.0% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | −9.3% | +16.7% | 33 | 33% | 0.67 | 14.1% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | +5.9% | +21.5% | 34 | 32% | 1.16 | 16.4% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | +10.5% | +148.3% | 28 | 43% | 1.52 | 10.3% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | −14.2% | +17.1% | 34 | 32% | 0.55 | 15.9% | 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 | 10 | 10% | −$10,206.60 |
| Sideways market | 24 | 54% | $15,444.10 |
| Falling market | 7 | 71% | $5,328.24 |
Rising and falling mean the market moved more than 15% over the 90 bars before entry.
How bad could the drawdown be?
12.7%
The 95th percentile of the worst drawdown when the same 41 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 5.3% to 12.7%; the tick is what actually happened, 12.3%. Order luck alone moves it this much.
All 41 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| short | 20 Apr 2024 63,818.00 | 26 May 2024 69,290.60 | 36 | −$1,452.08 |
| long | 26 May 2024 69,290.60 | 24 Jun 2024 61,348.10 | 29 | −$1,502.80 |
| long | 26 May 2024 69,290.60 | 24 Jun 2024 61,348.10 | 29 | −$1,502.80 |
| short | 26 Jun 2024 61,806.00 | 21 Jul 2024 67,937.10 | 25 | −$1,463.46 |
| short | 26 Jun 2024 61,806.00 | 21 Jul 2024 67,937.10 | 25 | −$1,463.46 |
| long | 29 Jul 2024 68,249.90 | 3 Aug 2024 61,146.30 | 5 | −$1,414.54 |
| long | 29 Jul 2024 68,249.90 | 3 Aug 2024 61,146.30 | 5 | −$1,414.54 |
| short | 16 Aug 2024 57,541.10 | 27 Sep 2024 65,174.00 | 42 | −$2,109.76 |
| long | 27 Sep 2024 65,174.00 | 10 Nov 2024 77,215.80 | 44 | $2,339.75 |
| long | 27 Sep 2024 65,174.00 | 6 Jan 2025 98,363.60 | 101 | $6,493.82 |
| short | 6 Jan 2025 98,363.60 | 20 Jan 2025 108,538.00 | 14 | −$1,477.39 |
| short | 6 Jan 2025 98,363.60 | 20 Jan 2025 108,538.00 | 14 | −$1,477.39 |
| long | 23 Jan 2025 103,707.00 | 17 Feb 2025 96,118.10 | 25 | −$1,622.84 |
| short | 17 Feb 2025 96,118.10 | 11 Mar 2025 77,271.10 | 22 | $2,459.88 |
| short | 17 Feb 2025 96,118.10 | 25 Apr 2025 93,980.50 | 67 | $256.55 |
| long | 25 Apr 2025 93,980.50 | 22 May 2025 111,810.00 | 27 | $2,526.36 |
| long | 25 Apr 2025 93,980.50 | 25 Jun 2025 106,083.00 | 61 | $1,706.19 |
| short | 25 Jun 2025 106,083.00 | 27 Jun 2025 106,947.00 | 2 | −$332.96 |
| long | 27 Jun 2025 106,947.00 | 1 Jul 2025 107,147.00 | 4 | −$4.76 |
| short | 1 Jul 2025 107,147.00 | 10 Jul 2025 111,234.00 | 9 | −$1,620.53 |
| long | 10 Jul 2025 111,234.00 | 25 Aug 2025 113,494.00 | 46 | $786.98 |
| short | 25 Aug 2025 113,494.00 | 29 Sep 2025 112,164.00 | 35 | $341.90 |
| long | 29 Sep 2025 112,164.00 | 5 Oct 2025 124,808.00 | 6 | $2,598.71 |
| long | 29 Sep 2025 112,164.00 | 10 Oct 2025 105,139.00 | 11 | −$1,516.82 |
| short | 25 Oct 2025 111,005.00 | 18 Nov 2025 89,504.40 | 24 | $2,651.66 |
| short | 25 Oct 2025 111,005.00 | 13 Jan 2026 91,296.20 | 80 | $2,428.37 |
| long | 13 Jan 2026 91,296.20 | 29 Jan 2026 84,363.70 | 16 | −$1,603.00 |
| long | 13 Jan 2026 91,296.20 | 29 Jan 2026 84,363.70 | 16 | −$1,603.00 |
| short | 3 Feb 2026 78,738.60 | 6 Feb 2026 61,067.10 | 3 | $2,705.64 |
| short | 3 Feb 2026 78,738.60 | 21 Mar 2026 70,510.70 | 46 | $1,246.76 |
| long | 21 Mar 2026 70,510.70 | 8 Apr 2026 71,924.20 | 18 | $449.89 |
| short | 8 Apr 2026 71,924.20 | 13 Apr 2026 70,741.60 | 5 | $420.49 |
| long | 13 Apr 2026 70,741.60 | 15 Apr 2026 74,131.60 | 2 | $1,394.19 |
| short | 15 Apr 2026 74,131.60 | 16 Apr 2026 74,810.00 | 1 | −$345.01 |
| long | 16 Apr 2026 74,810.00 | 1 Jun 2026 73,674.40 | 46 | −$543.72 |
| short | 1 Jun 2026 73,674.40 | 4 Jun 2026 63,742.00 | 3 | $2,832.19 |
| short | 1 Jun 2026 73,674.40 | 21 Jul 2026 65,255.50 | 50 | $2,394.12 |
| long | 21 Jul 2026 65,255.50 | 19 Aug 2026 64,725.40 | 29 | −$400.63 |
| short | 19 Aug 2026 64,725.40 | 19 Aug 2026 68,487.90 | 0 | −$1,727.08 |
| short | 19 Aug 2026 64,725.40 | 19 Aug 2026 68,487.90 | 0 | −$1,727.08 |
| long | 20 Aug 2026 69,334.80 | 21 Aug 2026 77,873.80 | 1 | $2,857.98 |
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 |
|---|---|---|---|---|---|
| [fpemehd] Strategy Template this page | — | v5 strategy | +10.5% | 41 | 14.8% |
| Money Flow Index 5 min Strategy by tweakerID | lowest highest valuewhen atr sma | v4 strategy | −6.8% | 18 | 28.4% |
| Trend Bounce [racer8] by racer8 | highest lowest sma valuewhen | v4 strategy | +2.4% | 22 | 32.2% |
| DC Breakout Strategy - This is simplicity at its finest. by Robrecht99 | sma highest lowest atr | v5 strategy | +10.8% | 57 | 8.3% |
| Trend Following with Donchian Channels and MACD by Robrecht99 | highest lowest sma atr | v5 strategy | −1.0% | 12 | 2.7% |
| BuyHigh-SellLow Strategy by Trendoscope | sma highest lowest atr | v4 strategy | +12.4% | 4 | 6.7% |
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.
- No v6-only features. v6 is not needed to run this script.
Clean v5
VerifiedNothing to change.
Does it run in Pine Script v6?
Yes
Same 41 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.
⋯// Thanks to myncrypto, jason5480, kevinmck100-// @version=5+// @version=6strategy(title = '[fpemehd] Strategy Template',⋯Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 110 ms | With a workaround 1,000 bars in 143 ms | Not measured |
| PineTS | Not tested | Not tested | Not measured |
Zeal Terminal's engine currently reads an order side written as direction = strategy.long, direction = strategy.short as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 242, 247) so the engine trades the way the script says. 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.
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/// © fpemehd// Thanks to myncrypto, jason5480, kevinmck100// @version=5strategy(title = '[fpemehd] Strategy Template', shorttitle = '[f] Template', overlay = true, pyramiding = 0, currency = currency.USD, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_value = 0.1, initial_capital = 100000, max_bars_back = 500, max_lines_count = 150, max_labels_count = 300)// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░// Time, Direction, Etc - Basic Settings Inputs// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░// 1. Time: Based on UTC +09:00i_start = input.time (defval = timestamp("20 Jan 1990 00:00 +0900"), title = "Start Date", tooltip = "Choose Backtest Start Date", inline = "Start Date", group = "Time" ) i_end = input.time (defval = timestamp("20 Dec 2030 00:00 +0900"), title = "End Date", tooltip = "Choose Backtest End Date", inline = "End Date", group = "Time" ) inTime = time >= i_start and time <= i_end// 2. Inputs for direction: Long? Short? Both? i_longEnabled = input.bool (defval = true , title = "Long?", tooltip = "Enable Long Position Trade?", inline = "Long / Short", group = "Long / Short" )i_shortEnabled = input.bool (defval = true , title = "Short?", tooltip = "Enable Short Position Trade?", inline = "Long / Short", group = "Long / Short" )// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░// Filter - Inputs, Indicaotrs// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░// 3. Use Filters? What Filters?i_ATRFilterOn = input.bool (defval = false , title = "ATR Filter On?", tooltip = "ATR Filter On? Order will not be made unless filter condition is fulfilled", inline = "1", group = "Filters") i_ATRFilterLen = input.int (defval = 14 , title = "Length for ATR Filter", minval = 1 , maxval = 100 , step = 1 , tooltip = "", inline = "2", group = "Filters") i_ATRSMALen = input.int (defval = 40 , title = "SMA Length for ATR SMA", minval = 1 , maxval = 100000 , step = 1 , tooltip = "ATR should be bigger than this", inline = "2", group = "Filters") bool i_ATRFilter = ta.atr(i_ATRFilterLen) >= ta.sma(ta.atr(length = i_ATRFilterLen), i_ATRSMALen) ? true : falsebool filterFulfilled = not i_ATRFilterOn or i_ATRFilter// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░// Strategy Logic (Entry & Exit Condition) - Inputs, Indicators for Strategy// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░//// Indicators// Inputs for Strategy Indicatorsi_fastMALen = input.int (defval = 21, title = 'Fast SMA Length', minval = 1, inline = 'MA Length', group = 'Strategy')i_slowMALen = input.int (defval = 49, title = 'Slow SMA Length', minval = 1, tooltip = 'How many candles back to calculte the fast/slow SMA.', inline = 'MA Length', group = 'Strategy')// Calculate Indicatorsfloat indicator1 = ta.sma(source = close, length = i_fastMALen)float indicator2 = ta.sma(source = close, length = i_slowMALen)// Plot: Indicatorsvar indicator1Color = color.new(color = color.yellow, transp = 0)plot(series = indicator1, title = 'indicator1', color = indicator1Color, linewidth = 1, style = plot.style_line)var indicator2Color = color.new(color = color.orange, transp = 0)plot(series = indicator2, title = 'indicator2', color = indicator2Color, linewidth = 1, style = plot.style_line)////// Entry, Exit// Long, Short Logic with Indicatorbool crossover = ta.crossover (indicator1, indicator2)bool crossunder = ta.crossunder (indicator1, indicator2)// Basic Cond + Long, Short Entry Conditionbool longCond = (i_longEnabled and inTime) and (crossover) bool shortCond = (i_shortEnabled and inTime) and (crossunder) // Basic Cond + Long, Short Exit Conditionbool closeLong = (i_longEnabled) and (crossunder)bool closeShort = (i_shortEnabled) and (crossover)// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░// Position Control// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░// Long, Short Entry Condition + Not entered Position Yetbool openLong = longCond and not (strategy.opentrades.size(strategy.opentrades - 1) > 0) and filterFulfilledbool openShort = shortCond and not (strategy.opentrades.size(strategy.opentrades - 1) < 0) and filterFulfilledbool enteringTrade = openLong or openShortfloat entryBarIndex = bar_index// Long, Short Entry Fulfilled or Already Enteredbool inLong = openLong or strategy.opentrades.size(strategy.opentrades - 1) > 0 and not closeLongbool inShort = openShort or strategy.opentrades.size(strategy.opentrades - 1) < 0 and not closeShort// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░// Stop Loss - Inputs, Indicaotrs// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░//// Use SL? TSL? i_useSLTP = input.bool (defval = true, title = "Enable SL & TP?", tooltip = "", inline = "1", group = "Stop Loss") i_tslEnabled = input.bool (defval = false , title = "Enable Trailing SL?", tooltip = "Enable Stop Loss & Take Profit? \n\Enable Trailing SL?", inline = "1", group = "Stop Loss") // i_breakEvenAfterTP = input.bool (defval = false, title = 'Enable Break Even After TP?', tooltip = 'When Take Profit price target is hit, move the Stop Loss to the entry price (or to a more strict price defined by the Stop Loss %/ATR Multiplier).', inline = '2', group = 'Stop Loss / Take Profit')//// Sl Optionsi_slType = input.string (defval = "ATR", title = "Stop Loss Type", options = ["Percent", "ATR", "Previous LL / HH"], tooltip = "Stop Loss based on %? ATR?", inline = "3", group = "Stop Loss") i_slATRLen = input.int (defval = 14, title = "ATR Length", minval = 1 , maxval = 200 , step = 1, inline = "4", group = "Stop Loss") i_slATRMult = input.float (defval = 3, title = "ATR Multiplier", minval = 1 , maxval = 200 , step = 0.1, tooltip = "", inline = "4", group = "Stop Loss") i_slPercent = input.float (defval = 3, title = "Percent", tooltip = "", inline = "5", group = "Stop Loss")i_slLookBack = input.int (defval = 30, title = "Lowest Price Before Entry", group = "Stop Loss", inline = "6", minval = 30, step = 1, tooltip = "Lookback to find the Lowest Price. \nStopLoss is determined by the Lowest price of the look back period. Take Profit is derived from this also by multiplying the StopLoss value by the Risk:Reward multiplier.")// Functions for Stop Lossfloat openAtr = ta.valuewhen(condition = enteringTrade, source = ta.atr(i_slATRLen), occurrence = 0) float openLowest = ta.valuewhen(condition = openLong, source = ta.lowest(low, i_slLookBack), occurrence = 0)float openHighest = ta.valuewhen(condition = openShort, source = ta.highest(high, i_slLookBack), occurrence = 0)f_getLongSLPrice(source) => switch i_slType "Percent" => source * (1 - (i_slPercent/100)) "ATR" => source - (i_slATRMult * openAtr) "Previous LL / HH" => openLowest => naf_getShortSLPrice(source) => switch i_slType "Percent" => source * (1 + (i_slPercent/100)) "ATR" => source + (i_slATRMult * openAtr) "Previous LL / HH" => openHighest => na// Calculate Stop Lossvar float longSLPrice = navar float shortSLPrice = nabool longTPExecuted = falsebool shortTPExecuted = falselongSLPrice := if (inLong and i_useSLTP) if (openLong) f_getLongSLPrice (close) else // 1. Trailing Stop Loss if i_tslEnabled stopLossPrice = f_getLongSLPrice (high) math.max(stopLossPrice, nz(longSLPrice[1])) // 2. Normal StopLoss else nz(source = longSLPrice[1], replacement = 0) else na shortSLPrice := if (inShort and i_useSLTP) if (openShort) f_getShortSLPrice (close) else // 1. Trailing Stop Loss if i_tslEnabled stopLossPrice = f_getShortSLPrice (low) math.min(stopLossPrice, nz(shortSLPrice[1])) // 2. Normal StopLoss else nz(source = shortSLPrice[1], replacement = 999999.9) else na // Plot: Stop Loss of Long, Short Entryvar longSLPriceColor = color.new(color.maroon, 0)plot(series = longSLPrice, title = 'Long Stop Loss', color = longSLPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1)var shortSLPriceColor = color.new(color.maroon, 0)plot(series = shortSLPrice, title = 'Short Stop Loss', color = shortSLPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1)// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░// Take Profit - Inputs, Indicaotrs// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░i_useTPExit = input.bool (defval = true, title = "Use Take Profit?", tooltip = "", inline = "1", group = "Take Profit") i_RRratio = input.float (defval = 1.8, title = "R:R Ratio", minval = 0.1 , maxval = 200 , step = 0.1, tooltip = "R:R Ratio > Risk Reward Ratio? It will automatically set Take Profit % based on Stop Loss", inline = "2", group = "Take Profit") i_tpQuantityPerc = input.float (defval = 50, title = 'Take Profit Quantity %', minval = 0.0, maxval = 100, step = 1.0, tooltip = '% of position closed when tp target is met.', inline="34", group = 'Take Profit')var float longTPPrice = navar float shortTPPrice = naf_getLongTPPrice() => close + i_RRratio * math.abs (close - f_getLongSLPrice (close))f_getShortTPPrice() => close - i_RRratio * math.abs(close - f_getShortSLPrice (close))longTPPrice := if (inLong and i_useSLTP) if (openLong) f_getLongTPPrice () else nz(source = longTPPrice[1], replacement = f_getLongTPPrice ()) else nashortTPPrice := if (inShort and i_useSLTP) if (openShort) f_getShortTPPrice () else nz(source = shortTPPrice[1], replacement = f_getShortTPPrice ()) else na// Plot: Take Profit of Long, Short Entry var longTPPriceColor = color.new(color.teal, 0)plot(series = longTPPrice, title = 'Long Take Profit', color = longTPPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1)var shortTPPriceColor = color.new(color.teal, 0)plot(series = shortTPPrice, title = 'Short Take Profit', color = shortTPPriceColor, linewidth = 1, style = plot.style_linebr, offset = 1)// Plot: Entry Price var posColor = color.new(color.white, 0)plot(series = strategy.opentrades.entry_price(strategy.opentrades - 1), title = 'Position Entry Price', color = posColor, linewidth = 1, style = plot.style_linebr)// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░// Quantity - Inputs// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░i_useRiskManangement = input.bool (defval = true, title = "Use Risk Manangement?", tooltip = "", inline = "1", group = "Quantity") i_riskPerTrade = input.float (defval = 3, title = "Risk Per Trade (%)", minval = 0, maxval = 100, step = 0.1, tooltip = "Use Risk Manangement by Quantity Control?", inline = "2", group = "Quantity") // i_leverage = input.float (defval = 2, title = "Leverage", minval = 0, maxval = 100, step = 0.1, tooltip = "Leverage", inline = "3", group = "Quantity") float qtyPercent = nafloat entryQuantity = naf_calQtyPerc() => if (i_useRiskManangement) riskPerTrade = (i_riskPerTrade) / 100 // 1번 거래시 3% 손실 stopLossPrice = openLong ? f_getLongSLPrice (close) : openShort ? f_getShortSLPrice (close) : na riskExpected = math.abs((close-stopLossPrice)/close) // 손절가랑 6% 차이 riskPerTrade / riskExpected // 0 ~ 1 else 1f_calQty(qtyPerc) => math.min (math.max (0.000001, strategy.equity / close * qtyPerc), 1000000000) // TP ExecutionlongTPExecuted := strategy.opentrades.size(strategy.opentrades - 1) > 0 and (longTPExecuted[1] or strategy.opentrades.size(strategy.opentrades - 1) < strategy.opentrades.size(strategy.opentrades - 1)[1] or strategy.opentrades.size(strategy.opentrades - 1)[1] == 0 and high >= longTPPrice)shortTPExecuted := strategy.opentrades.size(strategy.opentrades - 1) < 0 and (shortTPExecuted[1] or strategy.opentrades.size(strategy.opentrades - 1) > strategy.opentrades.size(strategy.opentrades - 1)[1] or strategy.opentrades.size(strategy.opentrades - 1)[1] == 0 and low <= shortTPPrice)// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░// Plot Label, Boxes, Results, Etc// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░i_showSimpleLabel = input.bool(false, "Show Simple Label for Entry?", group = "Strategy: Drawings", inline = "1", tooltip ="") i_showLabels = input.bool(true, "Show Trade Exit Labels", group = "Strategy: Drawings", inline = "1", tooltip = "Useful labels to identify Profit/Loss and cumulative portfolio capital after each trade closes.\n\nAlso note that TradingView limits the max number of 'boxes' that can be displayed on a chart (max 500). This means when you lookback far enough on the chart you will not see the TP/SL boxes. However you can check this option to identify where trades exited.")i_showDashboard = input.bool(true, "Show Dashboard", group = "Strategy: Drawings", inline = "2", tooltip = "Show Backtest Results. Backtest Dates, Win/Lose Rates, Etc.")// Plot: Label for Long, Short Entryvar openLongColor = color.new(#2962FF, 0)var openShortColor = color.new(#FF1744, 0)var entryTextColor = color.new(color.white, 0)if (openLong and i_showSimpleLabel) label.new (x = bar_index, y = na, text = 'Open', yloc = yloc.belowbar, color = openLongColor, style = label.style_label_up, textcolor = entryTextColor) entryBarIndex := bar_indexif (openShort and i_showSimpleLabel) label.new (x = bar_index, y = na, text = 'Close', yloc = yloc.abovebar, color = openShortColor, style = label.style_label_down, textcolor = entryTextColor) entryBarIndex := bar_indexfloat prevEntryPrice = strategy.closedtrades.entry_price (strategy.closedtrades - 1)float pnl = strategy.closedtrades.profit (strategy.closedtrades - 1)float prevExitPrice = strategy.closedtrades.exit_price (strategy.closedtrades - 1)f_enteringTradeLabel(x, y, qty, entryPrice, slPrice, tpPrice, rrRatio, direction) => if i_showLabels labelStr = ("Trade Start" + "\nDirection: " + direction + "\nRisk Per Trade: " + str.tostring (i_useRiskManangement ? i_riskPerTrade : 100, "#.##") + "%" + "\nExpected Risk: " + str.tostring (math.abs((close-slPrice)/close) * 100, "#.##") + "%" + "\nEntry Position Qty: " + str.tostring(math.abs(qty * 100), "#.##") + "%" + "\nEntry Price: " + str.tostring(entryPrice, "#.##")) + "\nStop Loss Price: " + str.tostring(slPrice, "#.##") + "\nTake Profit Price: " + str.tostring(tpPrice, "#.##") + "\nRisk - Reward Ratio: " + str.tostring(rrRatio, "#.##") label.new(x = x, y = y, text = labelStr, color = color.new(color.blue, 60) , textcolor = color.white, style = label.style_label_up)f_exitingTradeLabel(x, y, entryPrice, exitPrice, direction) => if i_showLabels labelStr = ("Trade Result" + "\nDirection: " + direction + "\nEntry Price: " + str.tostring(entryPrice, "#.##") + "\nExit Price: " + str.tostring(exitPrice,"#.##") + "\nGain %: " + str.tostring(direction == 'Long' ? -(entryPrice-exitPrice) / entryPrice * 100 : (entryPrice-exitPrice) / entryPrice * 100 ,"#.##") + "%") label.new(x = x, y = y, text = labelStr, color = pnl > 0 ? color.new(color.green, 60) : color.new(color.red, 60), textcolor = color.white, style = label.style_label_down)f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) => _cellText = _title + " " + _value table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto)// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░// Orders// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░if (inTime) if (openLong) qtyPercent := f_calQtyPerc() entryQuantity := f_calQty(qtyPercent) strategy.entry(id = "Long", direction = strategy.long, qty = entryQuantity, comment = 'Long(' + syminfo.ticker + '): Started', alert_message = 'Long(' + syminfo.ticker + '): Started') f_enteringTradeLabel(x = bar_index + 1, y = close-3*ta.tr, entryPrice = close, qty = qtyPercent, slPrice = longSLPrice, tpPrice = longTPPrice, rrRatio = i_RRratio, direction = "Long") if (openShort) qtyPercent := f_calQtyPerc() entryQuantity := f_calQty(qtyPercent) strategy.entry(id = "Short", direction = strategy.short, qty = entryQuantity, comment = 'Short(' + syminfo.ticker + '): Started', alert_message = 'Short(' + syminfo.ticker + '): Started') f_enteringTradeLabel(x = bar_index + 1, y = close-3*ta.tr, entryPrice = close, qty = qtyPercent, slPrice = shortSLPrice, tpPrice = shortTPPrice, rrRatio = i_RRratio, direction = "Short") if (closeLong) strategy.close(id = 'Long', comment = 'Close Long', alert_message = 'Long: Closed at market price') strategy.position_size > 0 ? f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Long') : na if (closeShort) strategy.close(id = 'Short', comment = 'Close Short', alert_message = 'Short: Closed at market price') strategy.position_size < 0 ? f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Short') : na if (inLong) strategy.exit(id = 'Long TP / SL', from_entry = 'Long', qty_percent = i_tpQuantityPerc, limit = longTPPrice, stop = longSLPrice, alert_message = 'Long(' + syminfo.ticker + '): Take Profit or Stop Loss executed') strategy.exit(id = 'Long SL', from_entry = 'Long', stop = longSLPrice, alert_message = 'Long(' + syminfo.ticker + '): Stop Loss executed') if (inShort) strategy.exit(id = 'Short TP / SL', from_entry = 'Short', qty_percent = i_tpQuantityPerc, limit = shortTPPrice, stop = shortSLPrice, alert_message = 'Short(' + syminfo.ticker + '): Take Profit or Stop Loss executed') strategy.exit(id = 'Short SL', from_entry = 'Short', stop = shortSLPrice, alert_message = 'Short(' + syminfo.ticker + '): Stop Loss executed') if strategy.position_size[1] > 0 and strategy.position_size == 0 f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Long') if strategy.position_size[1] < 0 and strategy.position_size == 0 f_exitingTradeLabel(x = bar_index, y = close+3*ta.tr, entryPrice = prevEntryPrice, exitPrice = prevExitPrice, direction = 'Short')// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░// Backtest Result Dashboard// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░if i_showDashboard var bgcolor = color.new(color = color.black, transp = 100) var greenColor = color.new(color = #02732A, transp = 0) var redColor = color.new(color = #D92332, transp = 0) var yellowColor = color.new(color = #F2E313, transp = 0) // Keep track of Wins/Losses streaks newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1]) newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1]) varip int winRow = 0 varip int lossRow = 0 varip int maxWinRow = 0 varip int maxLossRow = 0 if newWin lossRow := 0 winRow := winRow + 1 if winRow > maxWinRow maxWinRow := winRow if newLoss winRow := 0 lossRow := lossRow + 1 if lossRow > maxLossRow maxLossRow := lossRow // Prepare stats table var table dashTable = table.new(position.top_right, 1, 15, border_width=1) if barstate.islastconfirmedhistory dollarReturn = strategy.netprofit f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0)) f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0)) _profit = (strategy.netprofit / strategy.initial_capital) * 100 f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? greenColor : redColor, color.white) _numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24) f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? greenColor : redColor, color.white) _winRate = ( strategy.wintrades / strategy.closedtrades ) * 100 f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? redColor : _winRate < 75 ? greenColor : yellowColor, color.white) f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? greenColor : redColor, color.white) f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white) f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white) f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white)