Pine Script v5 · Strategy
[fpemehd] SSL Baseline Strategy
A Pine Script v5 strategy built on EMA (src, len), SMA or Linreg or EMA or WMA (math.floor(len / 2) + 1) and Highest (dev, 10). It has 3 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. 26 settings; defaults include SL Type ATR, SL % 3 and SL ATR Length 14.
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] SSL Baseline Strategy repaint?
- Yes
- At least one pattern in the source can repaint: intrabar recalculation.
- How did [fpemehd] SSL Baseline Strategy do on BTCUSDT 1D with default settings?
- +2.31%
- From 26 Jan 2024 to 21 Oct 2026, over 71 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
- Does [fpemehd] SSL Baseline Strategy run in Pine Script v6?
- Yes
- Same 71 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] SSL Baseline Strategy use a stop loss?
- Yes
- strategy.exit sets a stop on line 296.
- Does [fpemehd] SSL Baseline Strategy run in Zeal Terminal?
- Yes
- It compiles in 143 ms and runs 1,000 bars in 140 ms, in the browser.
BTCUSDT · 1D · default settings
- MA Baseline
- Baseline Upper Channel
- Basiline Lower Channel
- Stop Loss Price
- Take Profit Price
- Winning trade
- Losing trade
- Equity
- Buy and hold
| Start: long1708905600000 |
| End: long1792540800000 |
| Net Profit: 2.31% |
| Percent Per Day 0.00238% |
| Percent Profitable: 23.94% |
| Profit Factor: 1.173 |
| Total Trades: 71 |
| Max Wins In A Row: 2 |
| Max Losses In A Row: 9 |
- Net profit
- +2.31%
- $2,308.44
- Buy and hold
- +102.5%
- same period
- Closed trades
- 71
- 17 won · 54 lost
- Profitable
- 23.9%
- of closed trades
- Profit factor
- 1.17
- gross profit ÷ gross loss
- Max drawdown
- 3.72%
- −$3,800.68
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
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 | inDateRange |
| End DateChoose Backtest End Date | timestamp("20 Dec 2030 00:00 +0900") | time | inDateRange |
| Strategy: Stop Loss Conditions | |||
| SL Type Stop Loss based on %? ATR? | ATR | string · options ["Percent", "ATR", "Previous LL / HH"] | slPercent |
| SL % | 3 | float | slPercent |
| SL ATR Length | 14 | int · min 0 · max 10000 | atr |
| SL ATR MultiplierLength of ATR used to calculate Stop Loss. \nSize of StopLoss is determined by multiplication of ATR value. Take Profit is derived from this also by multiplying the StopLoss value by the Risk:Reward multiplier. | 4 | float · min 0 · step 0.1 | slAmount |
| 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 | lowestLow highestHigh |
| Strategy: Risk Management | |||
| Risk : Reward Ratio Previous high or low (long/short dependant) is used to determine TP level. 'Risk : Reward' ratio is then used to calculate SL based of previous high/low level.\n\nIn short, the higher the R:R ratio, the smaller the SL since TP target is fixed by previous high/low price data. | 2 | float · min 0 · step 0.1 | tpPercent |
| Portfolio Risk %Percentage of portfolio you lose if trade hits SL.\n\nYou then stand to gain\n Portfolio Risk % * Risk : Reward\nif trade hits TP. | 1 | float · min 0 · step 0.1 | riskAmt |
| Strategy: Drawings | |||
| Show TP / SL BoxesShow or hide TP and SL position boxes.\n\nNote: TradingView limits the maximum number of boxes that can be displayed to 500 so they may not appear for all price data under test. | true | bool | line 77 line 85 |
| 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 93 |
| Show DashboardShow Backtest Results | true | bool | line 334 |
| Color Bars | true | bool | barcolor |
| 1: SSL Hybrid | |||
| use true range for Keltner Channel? | true | bool | range_1 |
| Baseline Type | EMA | string · options ['SMA', 'EMA', 'DEMA', 'TEMA', 'LSMA', 'WMA', 'MF', 'VAMA', 'TMA', 'HMA', 'JMA', 'Kijun v2', 'EDSMA', 'McGinley'] | BBMC Keltma |
| Baseline Length | 30 | int | BBMC Keltma rangema |
| Base Channel Multiplier | 0.2 | float · step 0.05 | upperk lowerk |
| Kijun MOD Divider | 1 | int · min 0 · max 4 | conversionLine |
| Baseline Type = JMA -> Jurik Phase | 3 | int | phaseRatio |
| Baseline Type = JMA -> Jurik Power | 1 | int | alpha |
| Baseline Type = VAMA -> Volatility lookback length | 10 | int | vol_up vol_down |
| Baseline Type = MF (Modular Filter, General Filter) ->Beta | 0.8 | float · min 0 · max 1 · step 0.1 | upper lower |
| Baseline Type = MF (Modular Filter) -> Use Feedback? | false | bool | a |
| Baseline Type = MF (Modular Filter) -> Feedback Weighting | 0.5 | float · min 0 · max 1 · step 0.1 | a |
| EDSMA - Super Smoother Filter Length | 20 | int · min 1 | ssf |
| EDSMA - Super Smoother Filter Poles | 2 | int · options [2, 3] | ssf |
What it calculates
- EMAsrc, len
ema1 · line 106 - EMAema1, len
ema2 · line 107 - EMAema2, len
ema3 · line 108 - SMA / Linreg / EMA / WMAta.sma(src, math.ceil(len / 2)), math.floor(len / 2) + 1
result · line 138 - EMAsrc, len
e · line 172 - EMAsrc, len
mid · line 180 - Highestdev, Baseline Type = VAMA -> Volatility lookback length (10)
vol_up · line 182 - Lowestdev, Baseline Type = VAMA -> Volatility lookback length (10)
vol_down · line 183 - Lowest / Highestlen
kijun · line 206 - Lowest / Highestlen / i_kidiv
conversionLine · line 207 - EMAsrc, len
mg · line 213 - Stdevssf, len
stdev · line 222 - TR
range_1 · line 233 - EMArange_1, Baseline Length (30)
rangema · line 234 - Lowestsource = low, length = Lowest Price Before Entry (30)
lowestLow · line 262 - Highestsource = high, length = Lowest Price Before Entry (30)
highestHigh · line 263 - ATRSL ATR Length (14)
atr · line 265
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 105 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 | 277 |
| Open Short short | openShort | On | 285 |
| Exit TP/SL stop and limit | every bar | On | 296 |
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 | +2.3% | +102.5% | 71 | 24% | 1.17 | 3.7% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | −6.1% | +5.5% | 72 | 24% | 0.68 | 7.7% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +6.4% | +9.8% | 62 | 26% | 1.44 | 4.1% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | −1.4% | +8.4% | 77 | 19% | 0.93 | 8.3% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | +2.9% | +16.7% | 73 | 30% | 1.26 | 3.5% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | −1.1% | +21.5% | 82 | 24% | 0.93 | 4.8% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | +5.6% | +148.3% | 65 | 34% | 1.49 | 3.2% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | −2.7% | +17.1% | 78 | 23% | 0.85 | 7.6% | 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 | 26 | 23% | −$398.77 |
| Sideways market | 29 | 28% | $927.48 |
| Falling market | 16 | 19% | $1,789.95 |
Rising and falling mean the market moved more than 15% over the 90 bars before entry.
How bad could the drawdown be?
6.2%
The 95th percentile of the worst drawdown when the same 71 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 2.6% to 6.2%; the tick is what actually happened, 3.6%. Order luck alone moves it this much.
All 71 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 26 Feb 2024 51,728.80 | 28 Feb 2024 62,823.70 | 2 | $1,979.35 |
| long | 1 Mar 2024 61,131.00 | 20 Mar 2024 61,937.40 | 19 | $80.11 |
| short | 20 Mar 2024 61,937.40 | 21 Mar 2024 67,840.50 | 1 | −$406.36 |
| long | 21 Mar 2024 67,840.50 | 3 Apr 2024 65,464.00 | 13 | −$157.85 |
| short | 3 Apr 2024 65,464.00 | 5 Apr 2024 68,487.80 | 2 | −$232.80 |
| long | 5 Apr 2024 68,487.80 | 14 Apr 2024 63,924.50 | 9 | −$346.50 |
| short | 14 Apr 2024 63,924.50 | 23 Apr 2024 66,819.30 | 9 | −$209.02 |
| long | 23 Apr 2024 66,819.30 | 25 Apr 2024 64,289.60 | 2 | −$189.99 |
| short | 25 Apr 2024 64,289.60 | 16 May 2024 66,206.50 | 21 | −$152.14 |
| long | 16 May 2024 66,206.50 | 12 Jun 2024 67,314.20 | 27 | $86.51 |
| short | 12 Jun 2024 67,314.20 | 16 Jul 2024 64,724.10 | 34 | $296.19 |
| long | 16 Jul 2024 64,724.10 | 3 Aug 2024 61,498.30 | 18 | −$342.18 |
| short | 3 Aug 2024 61,498.30 | 24 Aug 2024 64,037.20 | 21 | −$256.94 |
| long | 24 Aug 2024 64,037.20 | 28 Aug 2024 59,415.00 | 4 | −$401.12 |
| short | 28 Aug 2024 59,415.00 | 14 Sep 2024 60,498.00 | 17 | −$106.59 |
| long | 14 Sep 2024 60,498.00 | 17 Sep 2024 58,214.00 | 3 | −$243.53 |
| short | 17 Sep 2024 58,214.00 | 18 Sep 2024 60,314.00 | 1 | −$242.01 |
| long | 18 Sep 2024 60,314.00 | 2 Oct 2024 60,804.90 | 14 | $38.51 |
| short | 2 Oct 2024 60,804.90 | 7 Oct 2024 62,819.90 | 5 | −$242.99 |
| long | 7 Oct 2024 62,819.90 | 10 Oct 2024 60,636.00 | 3 | −$288.00 |
| short | 10 Oct 2024 60,636.00 | 12 Oct 2024 62,540.00 | 2 | −$252.46 |
| long | 12 Oct 2024 62,540.00 | 10 Nov 2024 79,366.30 | 29 | $1,951.76 |
| long | 12 Nov 2024 88,648.00 | 23 Dec 2024 95,186.30 | 41 | $521.63 |
| short | 23 Dec 2024 95,186.30 | 25 Dec 2024 98,663.60 | 2 | −$216.35 |
| long | 25 Dec 2024 98,663.60 | 27 Dec 2024 95,791.60 | 2 | −$176.22 |
| short | 27 Dec 2024 95,791.60 | 3 Jan 2025 96,984.80 | 7 | −$82.03 |
| long | 3 Jan 2025 96,984.80 | 9 Jan 2025 95,060.60 | 6 | −$140.89 |
| short | 9 Jan 2025 95,060.60 | 16 Jan 2025 100,497.00 | 7 | −$374.45 |
| long | 16 Jan 2025 100,497.00 | 3 Feb 2025 97,700.60 | 18 | −$202.71 |
| short | 3 Feb 2025 97,700.60 | 13 Apr 2025 85,276.90 | 69 | $740.46 |
| long | 13 Apr 2025 85,276.90 | 6 Jun 2025 101,509.00 | 54 | $960.96 |
| short | 6 Jun 2025 101,509.00 | 8 Jun 2025 105,552.00 | 2 | −$373.51 |
| long | 8 Jun 2025 105,552.00 | 18 Jun 2025 104,551.00 | 10 | −$105.00 |
| short | 18 Jun 2025 104,551.00 | 24 Jun 2025 105,334.00 | 6 | −$84.15 |
| long | 24 Jun 2025 105,334.00 | 2 Aug 2025 113,298.00 | 39 | $588.65 |
| short | 2 Aug 2025 113,298.00 | 8 Aug 2025 117,472.00 | 6 | −$394.36 |
| long | 8 Aug 2025 117,472.00 | 20 Aug 2025 112,873.00 | 12 | −$449.84 |
| short | 20 Aug 2025 112,873.00 | 23 Aug 2025 116,936.00 | 3 | −$371.99 |
| long | 23 Aug 2025 116,936.00 | 24 Aug 2025 115,438.00 | 1 | −$141.78 |
| short | 24 Aug 2025 115,438.00 | 11 Sep 2025 113,960.00 | 18 | $103.59 |
| long | 11 Sep 2025 113,960.00 | 23 Sep 2025 112,651.00 | 12 | −$139.04 |
| short | 23 Sep 2025 112,651.00 | 30 Sep 2025 114,312.00 | 7 | −$209.59 |
| long | 30 Sep 2025 114,312.00 | 10 Oct 2025 104,804.00 | 10 | −$1,021.29 |
| short | 11 Oct 2025 112,774.00 | 27 Oct 2025 114,559.00 | 16 | −$118.43 |
| long | 27 Oct 2025 114,559.00 | 30 Oct 2025 110,021.00 | 3 | −$307.76 |
| short | 30 Oct 2025 110,021.00 | 3 Jan 2026 89,995.10 | 65 | $1,286.73 |
| long | 3 Jan 2026 89,995.10 | 21 Jan 2026 88,427.70 | 18 | −$166.39 |
| short | 21 Jan 2026 88,427.70 | 5 Feb 2026 68,635.10 | 15 | $1,974.14 |
| short | 7 Feb 2026 70,580.30 | 5 Mar 2026 72,666.80 | 26 | −$121.07 |
| long | 5 Mar 2026 72,666.80 | 7 Mar 2026 68,114.00 | 2 | −$324.99 |
| short | 7 Mar 2026 68,114.00 | 14 Mar 2026 70,930.00 | 7 | −$206.69 |
| long | 14 Mar 2026 70,930.00 | 20 Mar 2026 69,930.00 | 6 | −$88.65 |
| short | 20 Mar 2026 69,930.00 | 26 Mar 2026 71,336.50 | 6 | −$128.14 |
| long | 26 Mar 2026 71,336.50 | 27 Mar 2026 68,820.30 | 1 | −$233.73 |
| short | 27 Mar 2026 68,820.30 | 8 Apr 2026 71,924.20 | 12 | −$281.83 |
| long | 8 Apr 2026 71,924.20 | 18 May 2026 77,457.70 | 40 | $516.59 |
| short | 18 May 2026 77,457.70 | 5 Jun 2026 60,387.40 | 18 | $1,995.78 |
| short | 7 Jun 2026 60,884.60 | 11 Jul 2026 64,161.70 | 34 | −$349.79 |
| long | 11 Jul 2026 64,161.70 | 14 Jul 2026 62,334.50 | 3 | −$232.93 |
| short | 14 Jul 2026 62,334.50 | 15 Jul 2026 65,044.00 | 1 | −$364.00 |
| long | 15 Jul 2026 65,044.00 | 28 Jul 2026 63,755.90 | 13 | −$175.85 |
| short | 28 Jul 2026 63,755.90 | 31 Jul 2026 64,780.00 | 3 | −$169.91 |
| long | 31 Jul 2026 64,780.00 | 1 Aug 2026 62,887.90 | 1 | −$305.97 |
| short | 1 Aug 2026 62,887.90 | 6 Aug 2026 64,665.20 | 5 | −$272.86 |
| long | 6 Aug 2026 64,665.20 | 12 Aug 2026 63,600.00 | 6 | −$188.69 |
| short | 12 Aug 2026 63,600.00 | 18 Aug 2026 64,532.10 | 6 | −$191.38 |
| long | 18 Aug 2026 64,532.10 | 21 Aug 2026 74,702.80 | 3 | $1,979.52 |
| long | 23 Aug 2026 77,074.90 | 13 Oct 2026 81,850.00 | 51 | $552.07 |
| short | 13 Oct 2026 81,850.00 | 14 Oct 2026 83,169.00 | 1 | −$181.48 |
| long | 14 Oct 2026 83,169.00 | 15 Oct 2026 81,682.00 | 1 | −$194.83 |
| short | 15 Oct 2026 81,682.00 | 21 Oct 2026 83,028.10 | 6 | −$174.84 |
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] SSL Baseline Strategy this page | — | v5 strategy | +2.3% | 71 | 3.7% |
| SSL + Wave Trend Strategy by kevinmck100 | ema sma highest lowest stdev tr atr | v5 strategy | −1.0% | 1 | 1.0% |
| BTC 15 min by RafaelZioni | sma ema wma linreg stdev highest lowest | v4 strategy | −25.7% | 119 | 38.9% |
| Athena Momentum Squeeze - Short, Lean, and Mean by jrandolph1046 | ema sma stdev tr linreg atr | v5 strategy | +3.7% | 10 | 0.6% |
| Multi MA Trend Following Strategy Template by TradeAutomation | ema linreg sma wma stdev atr highest lowest | v5 strategy | +12.3% | 3 | 26.9% |
| CHOP Zone Entry Strategy + DMI-PSAR Exit by IronCasper | atr highest lowest sma linreg ema | v4 strategy | +17.1% | 8 | 20.0% |
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 71 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.
⋯// @fpemehd-// @version=5+// @version=6strategy(title = '[fpemehd] SSL Baseline Strategy',⋯Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 143 ms | With a workaround 1,000 bars in 140 ms | Not measured |
| PineTS | Not tested | Not tested | 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.
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/// Thanks to @kevinmck100 for opensource strategy template and @Mihkel00 for SSL Hybrid// @fpemehd// @version=5strategy(title = '[fpemehd] SSL Baseline Strategy', shorttitle = '[f] SSL', overlay = true, pyramiding = 0, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, commission_value = 0.1, initial_capital = 100000, max_lines_count = 150, max_labels_count = 300)// # ========================================================================= #// # Inputs // # ========================================================================= #// 1. Timei_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" ) inDateRange = 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 = "1", group = "Long / Short" )// i_shortEnabled = input.bool(defval = true , title = "Short?", tooltip = "Enable Short Position Trade?", inline = "1", group = "Long / Short" )// 3. Shared inputs for Long and Short//// 3-1. Inputs for Stop Loss Type: ATR or Percent?i_slType = input.string (defval = "ATR", title = "SL Type ", group = "Strategy: Stop Loss Conditions", options = ["Percent", "ATR", "Previous LL / HH"], tooltip = "Stop Loss based on %? ATR?", inline = "1") i_slPercent = input.float (defval = 3, title = "SL % ", group = "Strategy: Stop Loss Conditions", inline = "2")i_slAtrLength = input.int (14, "SL ATR Length ", group = "Strategy: Stop Loss Conditions", inline = "3", minval = 0, maxval = 10000)i_slAtrMultiplier = input.float (4, "SL ATR Multiplier", group = "Strategy: Stop Loss Conditions", inline = "3", minval = 0, step = 0.1, tooltip = "Length of ATR used to calculate Stop Loss. \nSize of StopLoss is determined by multiplication of ATR value. Take Profit is derived from this also by multiplying the StopLoss value by the Risk:Reward multiplier.")i_slLookBack = input.int(30, "Lowest Price Before Entry", group = "Strategy: Stop Loss Conditions", inline = "4", 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.")//// 3-2. Inputs for Quantity & Risk Manangement: Take Profiti_riskReward = input.float(2, "Risk : Reward Ratio ", group = "Strategy: Risk Management", inline = "1", minval = 0, step = 0.1, tooltip = "Previous high or low (long/short dependant) is used to determine TP level. 'Risk : Reward' ratio is then used to calculate SL based of previous high/low level.\n\nIn short, the higher the R:R ratio, the smaller the SL since TP target is fixed by previous high/low price data.")i_accountRiskPercent = input.float(1, "Portfolio Risk %", group = "Strategy: Risk Management", inline = "1", minval = 0, step = 0.1, tooltip = "Percentage of portfolio you lose if trade hits SL.\n\nYou then stand to gain\n Portfolio Risk % * Risk : Reward\nif trade hits TP.")// 4. Inputs for Drawingsi_showTpSlBoxes = input.bool(true, "Show TP / SL Boxes", group = "Strategy: Drawings", inline = "1", tooltip = "Show or hide TP and SL position boxes.\n\nNote: TradingView limits the maximum number of boxes that can be displayed to 500 so they may not appear for all price data under test.")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 = "1", tooltip = "Show Backtest Results")i_show_color_bar = input.bool(true , "Color Bars", group = "Strategy: Drawings", inline = "1") // 5. Inputs for Indicators//// 5-1. Inputs for Indicator - 1: SSL Hybridi_useTrueRange = input.bool(defval = true , title = "use true range for Keltner Channel?", tooltip = "", inline = " ", group = "1: SSL Hybrid") i_maType = input.string(defval='EMA', title='Baseline Type', options=['SMA', 'EMA', 'DEMA', 'TEMA', 'LSMA', 'WMA', 'MF', 'VAMA', 'TMA', 'HMA', 'JMA', 'Kijun v2', 'EDSMA', 'McGinley'],group = "1: SSL Hybrid")i_len = input.int(defval=30,title='Baseline Length', group = "1: SSL Hybrid")i_multy = input.float(0.2, step=0.05, title='Base Channel Multiplier', group = "1: SSL Hybrid")// Input for Baselinei_kidiv = input.int(defval=1, maxval=4, minval=0, title='Kijun MOD Divider',inline="Kijun v2", group="1: SSL Hybrid")i_jurik_phase = input.int(defval=3, title='Baseline Type = JMA -> Jurik Phase', inline='JMA',group="1: SSL Hybrid")i_jurik_power = input.int(defval=1, title='Baseline Type = JMA -> Jurik Power', inline='JMA',group="1: SSL Hybrid")i_volatility_lookback = input.int(defval=10, title='Baseline Type = VAMA -> Volatility lookback length', inline='VAMA',group="1: SSL Hybrid")// MFi_beta = input.float(0.8, minval=0, maxval=1, step=0.1, title='Baseline Type = MF (Modular Filter, General Filter) ->Beta', inline='MF',group="1: SSL Hybrid")i_feedback = input.bool(defval=false, title='Baseline Type = MF (Modular Filter) -> Use Feedback?', inline='MF',group="1: SSL Hybrid")i_z = input.float(0.5, title='Baseline Type = MF (Modular Filter) -> Feedback Weighting', step=0.1, minval=0, maxval=1, inline='MF',group="1: SSL Hybrid")// EDSMAi_ssfLength = input.int(title='EDSMA - Super Smoother Filter Length', minval=1, defval=20, inline='EDSMA',group="1: SSL Hybrid")i_ssfPoles = input.int(title='EDSMA - Super Smoother Filter Poles', defval=2, options=[2, 3], inline='EDSMA',group="1: SSL Hybrid")// # ========================================================================= #// # Functions for Stop Loss & Take Profit & Plots// # ========================================================================= #percentAsPoints(pcnt) => math.round(pcnt / 100 * close / syminfo.mintick) calcStopLossPrice(pointsOffset, isLong) => priceOffset = pointsOffset * syminfo.mintick if isLong close - priceOffset else close + priceOffsetcalcProfitTrgtPrice(pointsOffset, isLong) => calcStopLossPrice(-pointsOffset, isLong) printLabel(barIndex, msg) => label.new(barIndex, close, msg)printTpSlHitBox(left, right, slHit, tpHit, entryPrice, slPrice, tpPrice) => if i_showTpSlBoxes box.new (left = left, top = entryPrice, right = right, bottom = slPrice, bgcolor = slHit ? color.new(color.red, 60) : color.new(color.gray, 90), border_width = 0) box.new (left = left, top = entryPrice, right = right, bottom = tpPrice, bgcolor = tpHit ? color.new(color.green, 60) : color.new(color.gray, 90), border_width = 0) line.new(x1 = left, y1 = entryPrice, x2 = right, y2 = entryPrice, color = color.new(color.yellow, 20)) line.new(x1 = left, y1 = slPrice, x2 = right, y2 = slPrice, color = color.new(color.red, 20)) line.new(x1 = left, y1 = tpPrice, x2 = right, y2 = tpPrice, color = color.new(color.green, 20)) printTpSlNotHitBox(left, right, entryPrice, slPrice, tpPrice) => if i_showTpSlBoxes box.new (left = left, top = entryPrice, right = right, bottom = slPrice, bgcolor = color.new(color.gray, 90), border_width = 0) box.new (left = left, top = entryPrice, right = right, bottom = tpPrice, bgcolor = color.new(color.gray, 90), border_width = 0) line.new(x1 = left, y1 = entryPrice, x2 = right, y2 = entryPrice, color = color.new(color.yellow, 20)) line.new(x1 = left, y1 = slPrice, x2 = right, y2 = slPrice, color = color.new(color.red, 20)) line.new(x1 = left, y1 = tpPrice, x2 = right, y2 = tpPrice, color = color.new(color.green, 20)) printTradeExitLabel(x, y, posSize, entryPrice, pnl) => if i_showLabels labelStr = "Position Size: " + str.tostring(math.abs(posSize), "#.##") + "\nPNL: " + str.tostring(pnl, "#.##") + "\nCapital: " + str.tostring(strategy.equity, "#.##") + "\nEntry Price: " + str.tostring(entryPrice, "#.##") + "\nExit Price: " + str.tostring(close,"#.##") 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)// # ========================================================================= #// # Entry, Close Logic // # ========================================================================= #// 1. Calculate Indicators//// 1-1. Calculate Indicators for SSL Hybrid Baseline////// TEMAtema(src, len) => ema1 = ta.ema(src, len) ema2 = ta.ema(ema1, len) ema3 = ta.ema(ema2, len) 3 * ema1 - 3 * ema2 + ema3////// EDSMAget2PoleSSF(src, length) => PI = 2 * math.asin(1) arg = math.sqrt(2) * PI / length a1 = math.exp(-arg) b1 = 2 * a1 * math.cos(arg) c2 = b1 c3 = -math.pow(a1, 2) c1 = 1 - c2 - c3 ssf = 0.0 ssf := c1 * src + c2 * nz(ssf[1]) + c3 * nz(ssf[2]) ssfget3PoleSSF(src, length) => PI = 2 * math.asin(1) arg = PI / length a1 = math.exp(-arg) b1 = 2 * a1 * math.cos(1.738 * arg) c1 = math.pow(a1, 2) coef2 = b1 + c1 coef3 = -(c1 + b1 * c1) coef4 = math.pow(c1, 2) coef1 = 1 - coef2 - coef3 - coef4 ssf = 0.0 ssf := coef1 * src + coef2 * nz(ssf[1]) + coef3 * nz(ssf[2]) + coef4 * nz(ssf[3]) ssfma(type, src, len) => float result = 0 if type == 'TMA' result := ta.sma(ta.sma(src, math.ceil(len / 2)), math.floor(len / 2) + 1) result if type == 'MF' ts = 0. b = 0. c = 0. os = 0. //---- alpha = 2 / (len + 1) a = i_feedback ? i_z * src + (1 - i_z) * nz(ts[1], src) : src //---- b := a > alpha * a + (1 - alpha) * nz(b[1], a) ? a : alpha * a + (1 - alpha) * nz(b[1], a) c := a < alpha * a + (1 - alpha) * nz(c[1], a) ? a : alpha * a + (1 - alpha) * nz(c[1], a) os := a == b ? 1 : a == c ? 0 : os[1] //---- upper = i_beta * b + (1 - i_beta) * c lower = i_beta * c + (1 - i_beta) * b ts := os * upper + (1 - os) * lower result := ts result if type == 'LSMA' result := ta.linreg(src, len, 0) result if type == 'SMA' // Simple result := ta.sma(src, len) result if type == 'EMA' // Exponential result := ta.ema(src, len) result if type == 'DEMA' // Double Exponential e = ta.ema(src, len) result := 2 * e - ta.ema(e, len) result if type == 'TEMA' // Triple Exponential e = ta.ema(src, len) result := 3 * (e - ta.ema(e, len)) + ta.ema(ta.ema(e, len), len) result if type == 'WMA' // Weighted result := ta.wma(src, len) result if type == 'VAMA' // Volatility Adjusted /// Copyright © 2019 to present, Joris Duyck (JD) mid = ta.ema(src, len) dev = src - mid vol_up = ta.highest(dev, i_volatility_lookback) vol_down = ta.lowest(dev, i_volatility_lookback) result := mid + math.avg(vol_up, vol_down) result if type == 'HMA' // Hull result := ta.wma(2 * ta.wma(src, len / 2) - ta.wma(src, len), math.round(math.sqrt(len))) result if type == 'JMA' // Jurik /// Copyright © 2018 Alex Orekhov (everget) /// Copyright © 2017 Jurik Research and Consulting. phaseRatio = i_jurik_phase < -100 ? 0.5 : i_jurik_phase > 100 ? 2.5 : i_jurik_phase / 100 + 1.5 beta = 0.45 * (len - 1) / (0.45 * (len - 1) + 2) alpha = math.pow(beta, i_jurik_power) jma = 0.0 e0 = 0.0 e0 := (1 - alpha) * src + alpha * nz(e0[1]) e1 = 0.0 e1 := (src - e0) * (1 - beta) + beta * nz(e1[1]) e2 = 0.0 e2 := (e0 + phaseRatio * e1 - nz(jma[1])) * math.pow(1 - alpha, 2) + math.pow(alpha, 2) * nz(e2[1]) jma := e2 + nz(jma[1]) result := jma result if type == 'Kijun v2' kijun = math.avg(ta.lowest(len), ta.highest(len)) //, (open + close)/2) conversionLine = math.avg(ta.lowest(len / i_kidiv), ta.highest(len / i_kidiv)) delta = (kijun + conversionLine) / 2 result := delta result if type == 'McGinley' mg = 0.0 mg := na(mg[1]) ? ta.ema(src, len) : mg[1] + (src - mg[1]) / (len * math.pow(src / mg[1], 4)) result := mg result if type == 'EDSMA' zeros = src - nz(src[2]) avgZeros = (zeros + zeros[1]) / 2 // Ehlers Super Smoother Filter ssf = i_ssfPoles == 2 ? get2PoleSSF(avgZeros, i_ssfLength) : get3PoleSSF(avgZeros, i_ssfLength) // Rescale filter in terms of Standard Deviations stdev = ta.stdev(ssf, len) scaledFilter = stdev != 0 ? ssf / stdev : 0 alpha = 5 * math.abs(scaledFilter) / len edsma = 0.0 edsma := alpha * src + (1 - alpha) * nz(edsma[1]) result := edsma result result////// Keltner Baseline Channel (Baseline) BBMC = ma(i_maType, close, i_len)Keltma = ma(i_maType, close, i_len)range_1 = i_useTrueRange ? ta.tr : high - lowrangema = ta.ema(range_1, i_len)upperk = Keltma + rangema * i_multylowerk = Keltma - rangema * i_multy// 2. Entry Condition for Long and Short// Condition 1bullSSL = close > upperkbearSSL = close < lowerk// Enter Position based on Condition 1goLong = inDateRange and bullSSL goShort = inDateRange and bearSSL // # ========================================================================= #// # Position Control Logic (Entry & Exit)// # ========================================================================= #// 1. Trade entry and exit variablesvar tradeEntryBar = bar_indexvar profitPoints = 0.var lossPoints = 0.var slPrice = 0.var tpPrice = 0.var inLong = false var inShort = false// 2. Entry decisionsopenLong = (goLong and not inLong) // Long entry condition & not in long positionopenShort = (goShort and not inShort) // Short entry condition & not in short positionflippingSides = (goLong and inShort) or (goShort and inLong) // (Long entry condition & in short position) and the oppositeenteringTrade = openLong or openShort // Entering Long or Short ConditioninTrade = inLong or inShort// 3. Stop Loss & Take Profit PercentlowestLow = ta.lowest(source = low, length = i_slLookBack) highestHigh = ta.highest(source = high, length = i_slLookBack) llhhSLPercent = openLong ? math.abs((close - lowestLow) / close) * 100 : openShort ? math.abs((highestHigh - close) / close) * 100 : naatr = ta.atr(i_slAtrLength)slAmount = atr * i_slAtrMultiplierslPercent = i_slType == 'ATR' ? math.abs((1 - (close - slAmount) / close) * 100) : i_slType == 'Percent' ? i_slPercent : llhhSLPercenttpPercent = slPercent * i_riskReward// 4. Risk calculations & Quantity ManagementriskAmt = strategy.equity * i_accountRiskPercent / 100entryQty = math.abs(riskAmt / slPercent * 100) / close// 5. Open Positionif openLong if strategy.position_size < 0 printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice) printTradeExitLabel(bar_index + 1, math.max(tpPrice, slPrice), strategy.position_size, strategy.position_avg_price, strategy.openprofit) strategy.entry("Long", strategy.long, qty = entryQty, alert_message = "Long Entry") enteringTrade := true inLong := true inShort := falseif openShort if strategy.position_size > 0 printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice) printTradeExitLabel(bar_index + 1, math.max(tpPrice, slPrice), strategy.position_size, strategy.position_avg_price, strategy.openprofit) strategy.entry("Short", strategy.short, qty = entryQty, alert_message = "Short Entry") enteringTrade := true inShort := true inLong := falseif enteringTrade profitPoints := percentAsPoints(tpPercent) lossPoints := percentAsPoints(slPercent) slPrice := calcStopLossPrice(lossPoints, openLong) tpPrice := calcProfitTrgtPrice(profitPoints, openLong) tradeEntryBar := bar_index// Can add more take profit Actions strategy.exit("TP/SL", profit = profitPoints, loss = lossPoints, comment_profit = "TP Hit", comment_loss = "SL Hit", alert_profit = "TP Hit Alert", alert_loss = "SL Hit Alert")// # ========================================================================= #// # Plots (Bar Color, Plot, Label, Boxes)// # ========================================================================= #// 1. SSL Hybrid Baseline longColor = #00c3ffshortColor = #ff0062color_bar = close > upperk ? longColor : close < lowerk ? shortColor : color.grayp1 = plot(BBMC, color=color.new(color=color_bar, transp=0), linewidth=4, title='MA Baseline')// 2. Bar color Based On SSL Hybrid Baselinebarcolor(i_show_color_bar ? color_bar : na)up_channel = plot(upperk, color=color_bar, title='Baseline Upper Channel')low_channel = plot(lowerk, color=color_bar, title='Basiline Lower Channel')fill(up_channel, low_channel, color.new(color=color_bar, transp=90))// 3. Stoploss BoxesslHit = (inShort and high >= slPrice) or (inLong and low <= slPrice)tpHit = (inLong and high >= tpPrice) or (inShort and low <= tpPrice)exitTriggered = slHit or tpHitentryPrice = strategy.closedtrades.entry_price (strategy.closedtrades - 1)pnl = strategy.closedtrades.profit (strategy.closedtrades - 1)posSize = strategy.closedtrades.size (strategy.closedtrades - 1)if (inTrade and exitTriggered) inShort := false inLong := false printTpSlHitBox(tradeEntryBar + 1, bar_index, slHit, tpHit, entryPrice, slPrice, tpPrice) printTradeExitLabel(bar_index, math.max(tpPrice, slPrice), posSize, entryPrice, pnl)if barstate.islastconfirmedhistory and strategy.position_size != 0 printTpSlNotHitBox(tradeEntryBar + 1, bar_index + 1, strategy.position_avg_price, slPrice, tpPrice) // 4. Data Windowsplotchar(slPrice, "Stop Loss Price", "")plotchar(tpPrice, "Take Profit Price", "")// 5. Showing LabelsplotDebugLabels = falseif plotDebugLabels if bar_index == tradeEntryBar printLabel(bar_index, "Position size: " + str.tostring(entryQty * close, "#.##"))// 6. Showing Dashboardif i_showDashboard var bgcolor = color.new(color.black,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.bottom_right, 1, 15, border_width=1) if barstate.islastconfirmedhistory // Update table 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 ? color.green : color.red, 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 ? color.green : color.red, color.white) _winRate = ( strategy.wintrades / strategy.closedtrades ) * 100 f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? color.red : _winRate < 75 ? #999900 : color.green, color.white) f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? color.green : color.red, 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)