Zeal Terminal Open in Zeal Terminal

Pine Script v5 · Strategy

[Sniper] SuperTrend + SSL Hybrid + QQE MOD

A Pine Script v5 strategy built on ATR or SMA (14), EMA (200) and SMA (len). 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. 47 settings; defaults include Length for ATR Filter 14, SMA Length for ATR SMA 40 and EMA Length 200.

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 [Sniper] SuperTrend + SSL Hybrid + QQE MOD repaint?
Yes
At least one pattern in the source can repaint: intrabar recalculation.
How did [Sniper] SuperTrend + SSL Hybrid + QQE MOD do on BTCUSDT 1D with default settings?
−8.08%
From 26 Jan 2024 to 21 Oct 2026, over 34 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Does [Sniper] SuperTrend + SSL Hybrid + QQE MOD run in Pine Script v6?
Yes
Same 34 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 [Sniper] SuperTrend + SSL Hybrid + QQE MOD use a stop loss?
Yes
strategy.exit sets a stop on line 472, 473, 475, 476.
Does [Sniper] SuperTrend + SSL Hybrid + QQE MOD run in Zeal Terminal?
Yes
It compiles in 211 ms and runs 1,000 bars in 314 ms, in the browser.

BTCUSDT · 1D · default settings

  • Plot
  • Up Trend
  • Down Trend
  • MA Baseline
  • Baseline Upper Channel
  • Basiline Lower Channel
  • Long Stop Loss
  • Short Stop Loss
  • Long Take Profit
  • Short Take Profit
  • Position Entry Price
  • Winning trade
  • Losing trade
  • Equity
  • Buy and hold
Prerendered with the defaults. Change anything and run it here. The script runs in your browser.
Settings (47)
Trade StartTrade StartTrade ResultTrade StartTrade ResultTrade StartTrade ResultTrade StartTrade ResultTrade StartTrade ResultTrade StartTrade ResultTrade StartTrade ResultTrade StartTrade ResultTrade ResultTrade StartTrade ResultTrade ResultTrade StartTrade StartTrade ResultTrade StartTrade ResultTrade ResultTrade StartTrade StartTrade ResultTrade StartTrade ResultTrade ResultTrade StartTrade StartTrade ResultTrade StartTrade ResultTrade StartTrade ResultTrade StartTrade ResultTrade StartTrade ResultTrade StartTrade Result40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$96,350$202,527Equity from $100,000
Binance BTCUSDT 1D candles, 26 Jan 2024 to 21 Oct 2026, 1,000 bars, default settings. Triangles mark entries; circles mark exits. Lines are what the script plots. Lines, boxes and labels are the script's own drawings, the most recent ones its limits keep. 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 458, 463) 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.
Table drawn by the script, as it stood on the last bar
Start: long1716249600000
End: long1784678400000
Net Profit: -8.08%
Percent Per Day -0.0102%
Percent Profitable: 35.29%
Profit Factor: 0.768
Total Trades: 34
Max Wins In A Row: 4
Max Losses In A Row: 5
Net profit
−8.08%
−$8,077.53
Buy and hold
+102.5%
same period
Closed trades
34
12 won · 22 lost
Profitable
35.3%
of closed trades
Profit factor
0.77
gross profit ÷ gross loss
Max drawdown
16.49%
−$16,493.70

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

    2 settings do nothing

    “Thresh-hold”, “Use Take Profit?” are 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.

SettingDefaultType and rangeFeeds
Time
Start DateChoose Backtest Start Datetimestamp("20 Jan 1990 00:00 +0900")timeinTime
End DateChoose Backtest End Datetimestamp("20 Dec 2030 00:00 +0900")timeinTime
Long / Short
Long?Enable Long Position Trade?trueboollongCond closeLong
Short?Enable Short Position Trade?trueboolshortCond closeShort
Filters
ATR Filter On?ATR Filter On? Order will not be made unless filter condition is fulfilledfalseboollongFilterFilled shortFilterFilled
Length for ATR Filter14int · min 1 · max 100 · step 1ATRFilter
SMA Length for ATR SMAATR should be bigger than this40int · min 1 · max 100000 · step 1ATRFilter
EMA Filter On?EMA Filter On? Order will not be made unless filter condition is fulfilledfalseboollongFilterFilled shortFilterFilled EMA Filter
EMA LengthEMA Length200int · min 1 · max 100000 · step 1longEMAFilter shortEMAFilter EMA Filter
ADX Filter On?ADX Filter On? Order will not be made unless filter condition is fulfilledfalseboollongFilterFilled shortFilterFilled
DMI Filter On?DMI (Directional Moving Index) Filter On? Order will not be made unless filter condition is fulfilledfalseboollongFilterFilled shortFilterFilled
ADX LengthADX Length20int · min 1 · max 100000 · step 1len
ADX ThresholdADX should be bigger than threshold25int · min 1 · max 100000 · step 1th
1: SuperTrend
ATR LengthSuper Trend ATR Length10int · min 1 · max 100000 · step 1supertrend direction
FactorSuper Trend ATR Factor3float · min 1 · max 100000 · step 0.1supertrend direction
2: SSL Hybrid
use true range for Keltner Channel?trueboolrange_1
Baseline TypeEMAstring · options ['SMA', 'EMA', 'DEMA', 'TEMA', 'LSMA', 'WMA', 'VAMA', 'TMA', 'HMA', 'McGinley']BBMC Keltma
Baseline Length30intBBMC Keltma rangema
Base Channel Multiplier0.2float · min 0 · max 100 · step 0.05upperk lowerk
Volatility lookback length(for VAMA)10intvol_up vol_down
3: QQE MOD
RSI Length6intWilders_Period Rsi
RSI Smoothing5intRsiMa
Fast QQE Factor3floatdar
Thresh-hold3intunused
Bollinger Length50int · min 1dev basis
BB Multiplier0.35float · min 0.01 · max 5 · step 0.1dev
RSI 2 Length6intWilders_Period2 Rsi2
RSI Smoothing5intRsiMa2
Fast QQE2 Factor1.61floatdar2
Thresh-hold3inthcolor2 Greenbar1 Redbar1
RSI SourceclosesourceRsi2
RSI Sourceclosesourceema1 result e mid mg Rsi dev
Stop Loss
Enable SL & TP?trueboollongSLPrice shortSLPrice longTPPrice shortTPPrice
Enable Trailing SL?Enable Stop Loss & Take Profit? \n\Enable Trailing SL?falseboollongSLPrice shortSLPrice
Stop Loss TypeStop Loss based on %? ATR?ATRstring · options ["Percent", "ATR", "Previous LL / HH"]line 306 line 312
ATR Length14int · min 1 · max 200 · step 1openAtr
ATR Multiplier3float · min 1 · max 200 · step 0.1line 308 line 314
Percent3floatline 307 line 313
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.30int · min 30 · step 1openLowest openHighest
Take Profit
Use Take Profit?trueboolunused
R:R RatioR:R Ratio > Risk Reward Ratio? It will automatically set Take Profit % based on Stop Loss1.8float · min 0.1 · max 200 · step 0.1line 362 line 364 line 459 line 464
Take Profit Quantity %% of position closed when tp target is met.50float · min 0.0 · max 100 · step 1.0exit Long TP / SL exit Short TP / SL
Quantity
Use Risk Manangement?trueboolline 396 labelStr
Risk Per Trade (%)Use Risk Manangement by Quantity Control?3float · min 0 · max 100 · step 0.1riskPerTrade labelStr
Strategy: Drawings
Show Simple Label for Entry?falseboolline 419 line 422
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.trueboolline 429 line 441
Show DashboardShow Backtest Results. Backtest Dates, Win/Lose Rates, Etc.trueboolline 486

What it calculates

  • ATR / SMALength for ATR Filter (14)ATRFilter · line 35
  • EMAsource = close, length = EMA Length (200)longEMAFilter · line 39
  • EMAsource = close, length = EMA Length (200)shortEMAFilter · line 40
  • SMAsource = DX, length = lenADX · line 67
  • Supertrendfactor = Factor (3), atrPeriod = ATR Length (10)supertrend · line 98
  • Supertrendfactor = Factor (3), atrPeriod = ATR Length (10)direction · line 98
  • EMARSI Source (close), lenema1 · line 106
  • EMAema1, lenema2 · line 107
  • EMAema2, lenema3 · line 108
  • SMA / Linreg / EMA / WMAta.sma(src, math.ceil(len / 2)), math.floor(len / 2) + 1result · line 113
  • EMARSI Source (close), lene · line 129
  • EMARSI Source (close), lenmid · line 137
  • StdevFastAtrRsiTL - 50, Bollinger Length (50)dev · line 187
  • Highestdev, Volatility lookback length(for VAMA) (10)vol_up · line 139
  • Lowestdev, Volatility lookback length(for VAMA) (10)vol_down · line 140
  • EMARSI Source (close), lenmg · line 148
  • TRrange_1 · line 155
  • EMArange_1, Baseline Length (30)rangema · line 156
  • RSIRSI Source (close), RSI Length (6)Rsi · line 166
  • EMARsi, RSI Smoothing (5)RsiMa · line 167
  • EMAAtrRsi, Wilders_PeriodMaAtrRsi · line 169
  • EMAMaAtrRsi, Wilders_Perioddar · line 170
  • CrossRSIndex, shortband[1]trend · line 181
  • Crosslongband[1], RSIndexcross_1 · line 180
  • SMAFastAtrRsiTL - 50, Bollinger Length (50)basis · line 186
  • RSIRSI Source (close), RSI 2 Length (6)Rsi2 · line 210
  • EMARsi2, RSI Smoothing (5)RsiMa2 · line 211
  • EMAAtrRsi2, Wilders_Period2MaAtrRsi2 · line 213
  • EMAMaAtrRsi2, Wilders_Period2dar2 · line 214
  • CrossRSIndex2, shortband2[1]trend2 · line 225
  • Crosslongband2[1], RSIndex2cross_2 · line 224
  • Valuewhen / ATRcondition = enteringTrade, source = ta.atr(i_slATRLen), occurrence = 0openAtr · line 302
  • Valuewhen / Lowestcondition = openLong, source = ta.lowest(low, i_slLookBack), occurrence = 0openLowest · line 303
  • Valuewhen / Highestcondition = openShort, source = ta.highest(high, i_slLookBack), occurrence = 0openHighest · line 304

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 153 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.

Order rules

OrderFires whenBy defaultLine
Open Long long(openLong)On458
Open Short short(openShort)On463
Close Long(closeLong)On466
Close Short(closeShort)On469
Exit Long TP / SL stop and limit(inLong)On472
Exit Long SL stop(inLong)On473
Exit Short TP / SL stop and limit(inShort)On475
Exit Short SL stop(inShort)On476

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.

10/10trades identical when replayed liveThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, four per bar, and compared with the historical run. On 3 of them the position changed while the bar was forming before it settled. Anyone watching live sees those changes; once the bar closes it matches history.
  • 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.

MarketNetBuy and holdTradesWonProfit factorMax drawdownPeriod
BTCUSDT 1D−8.1%+102.5%3435%0.7716.5%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h+13.3%+5.5%2938%1.4810.8%8 May 2026 – 21 Oct 2026
ETHUSDT 1D+12.8%+9.8%3746%1.4413.2%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+5.6%+8.4%2836%1.1714.9%8 May 2026 – 21 Oct 2026
SOLUSDT 1D+6.3%+16.7%3043%1.259.5%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+3.6%+21.5%3336%1.1014.2%8 May 2026 – 21 Oct 2026
BNBUSDT 1D−9.2%+148.3%3330%0.7122.1%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h−8.1%+17.1%3336%0.7521.3%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 barsTradesWonP&L
Rising market714%−$10,386.00
Sideways market1644%$4,754.69
Falling market1136%−$2,429.95

Rising and falling mean the market moved more than 15% over the 90 bars before entry.

How bad could the drawdown be?

20.8%

The 95th percentile of the worst drawdown when the same 34 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 10.4% to 20.8%; the tick is what actually happened, 15.2%. Order luck alone moves it this much.

0%24%
All 34 trades
SideEntryExitBarsP&L
long21 May 2024 71,446.6022 Jun 2024 64,143.6032−$2,694.93
short22 Jun 2024 64,143.605 Jul 2024 53,666.1013$2,598.32
short22 Jun 2024 64,143.6016 Jul 2024 64,724.1024−$177.92
long16 Jul 2024 64,724.104 Aug 2024 60,698.0019−$1,678.17
short4 Aug 2024 60,698.0024 Aug 2024 64,037.2020−$1,314.25
long24 Aug 2024 64,037.206 Sep 2024 56,180.0013−$2,605.61
short6 Sep 2024 56,180.0019 Sep 2024 63,812.4013−$1,434.39
short6 Sep 2024 56,180.0019 Sep 2024 63,812.4013−$1,434.39
long20 Sep 2024 62,948.006 Nov 2024 75,852.0047$2,437.48
long20 Sep 2024 62,948.0024 Dec 2024 94,881.5095$6,067.48
short24 Dec 2024 94,881.5018 Jan 2025 104,077.0025−$2,199.92
long18 Jan 2025 104,077.003 Feb 2025 92,562.3016−$1,488.82
long18 Jan 2025 104,077.003 Feb 2025 92,562.3016−$1,488.82
short25 Feb 2025 91,552.903 Mar 2025 94,270.006−$864.61
short11 Mar 2025 78,595.9022 Apr 2025 93,587.4042−$1,421.97
short11 Mar 2025 78,595.9022 Apr 2025 93,587.4042−$1,421.97
long23 Apr 2025 93,443.0022 May 2025 111,926.0029$2,426.43
long23 Apr 2025 93,443.0023 Jun 2025 100,964.0061$972.64
short23 Jun 2025 100,964.003 Jul 2025 110,189.0010−$1,446.72
short23 Jun 2025 100,964.003 Jul 2025 110,189.0010−$1,446.72
long10 Jul 2025 111,234.0022 Aug 2025 112,500.0043$379.89
short22 Aug 2025 112,500.002 Oct 2025 118,595.0041−$2,037.10
long2 Oct 2025 118,595.0010 Oct 2025 111,018.008−$1,387.26
long2 Oct 2025 118,595.0010 Oct 2025 111,018.008−$1,387.26
long14 Jan 2026 95,414.0021 Jan 2026 88,427.707−$2,459.18
short21 Jan 2026 88,427.702 Feb 2026 75,067.7012$2,254.18
short21 Jan 2026 88,427.705 Mar 2026 72,666.8043$2,664.71
long5 Mar 2026 72,666.8030 Mar 2026 66,010.9025−$1,660.48
short30 Mar 2026 66,010.9013 Apr 2026 74,346.8014−$1,338.67
short30 Mar 2026 66,010.9013 Apr 2026 74,346.8014−$1,338.67
long14 Apr 2026 74,418.0023 May 2026 75,539.5039$318.20
short23 May 2026 75,539.503 Jun 2026 64,736.4011$2,276.29
short23 May 2026 75,539.5022 Jul 2026 66,556.1060$1,887.42
long22 Jul 2026 66,556.1021 Aug 2026 76,471.4030$2,383.49

Similar scripts

Indicators and strategies built from the same calculations, run on BTCUSDT 1D with their own defaults so they can be compared directly.

ScriptSharesTypeNetTradesMax drawdown
[Sniper] SuperTrend + SSL Hybrid + QQE MOD this page—v5 strategy−8.1%3416.5%
[Sniper] SSL Hybrid + QQE MOD + Waddah Attar Strategy by DuDu95atr ema sma supertrend stdev highest lowest tr rsi cross valuewhenv5 strategy+8.5%5210.7%
BTC 15 min by RafaelZionisma ema rsi wma linreg stdev highest lowestv4 strategy−25.7%11938.9%
VuManChu Cipher B + Divergences Strategy by nattichai001valuewhen ema cross lowest highest rsi sma wmav4 strategy+76.6%17518.4%
Investments-swing trading strategy for different assets by StrategiesForEveryonesma stdev tr linreg ema rsi atrv5 strategy+4.2%1717.6%
[fpemehd] SSL Baseline Strategy by DuDu95ema sma highest lowest stdev tr atrv5 strategy+2.3%713.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.

  • 2 settings use the untyped input() (line 164, 206). It still compiles in v6; input.int, input.float or input.source state the type.
  • No v6-only features. v6 is not needed to run this script.

Clean v5

VerifiedDownload the v5 script

Same 34 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.

  • Line 164: input() → input.source()
  • Line 206: input() → input.source()
⋯ThreshHold              = input.int   (defval = 3,     title = 'Thresh-hold',     inline = "4",       group = "3: QQE MOD")-src                     = input       (defval = close, title='RSI Source')+src                     = input.source       (defval = close, title='RSI Source')Wilders_Period          = RSI_Period * 2 - 1⋯ThreshHold2             = input.int   (defval = 3,     title = 'Thresh-hold', group = "3: QQE MOD")-src2                    = input       (defval = close, title = 'RSI Source', group = "3: QQE MOD")+src2                    = input.source       (defval = close, title = 'RSI Source', group = "3: QQE MOD")//⋯

Does it run in Pine Script v6?

Yes

Same 34 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.

Download the v6 script

⋯// Thanks to myncrypto, jason5480, kevinmck100-// @version=5+// @version=6strategy(title          = '[D] SuperTrend + SSL Hybrid + QQE MOD',⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 211 msWith a workaround 1,000 bars in 314 msNot measured
PineTSNot testedNot testedNot 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 458, 463) 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          = '[D] SuperTrend + SSL Hybrid + QQE MOD',      shorttitle        = '[D] SSQ Strategy',      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?//// 3-1. ATR Filteri_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 ATRFilter          = ta.atr(i_ATRFilterLen) >= ta.sma(ta.atr(length = i_ATRFilterLen), i_ATRSMALen) ? true : false//// 3-2. EMA Filteri_EMAFilterOn           = input.bool (defval = false , title = "EMA Filter On?", tooltip = "EMA Filter On? Order will not be made unless filter condition is fulfilled", inline = "3", group =  "Filters") i_EMALen                = input.int  (defval = 200,    title = "EMA Length", minval = 1 , maxval = 100000 , step = 1 , tooltip = "EMA Length", inline = "4", group = "Filters") bool longEMAFilter      = close >= ta.ema(source = close, length = i_EMALen) ? true : falsebool shortEMAFilter     = close <= ta.ema(source = close, length = i_EMALen) ? true : falseplot(i_EMAFilterOn ? ta.ema(source = close, length = i_EMALen) : na, title = "EMA Filter", color = color.new(color = color.orange , transp = 0), linewidth = 1)//// 3-3. ADX Filter////3-4. DMI Filter (Uses same ADX Length)i_ADXFilterOn           = input.bool (defval = false , title = "ADX Filter On?", tooltip = "ADX Filter On? Order will not be made unless filter condition is fulfilled", inline = "5", group =  "Filters") i_DMIFilterOn           = input.bool (defval = false , title = "DMI Filter On?", tooltip = "DMI (Directional Moving Index) Filter On? Order will not be made unless filter condition is fulfilled", inline = "6", group =  "Filters") i_ADXLength             = input.int  (defval = 20,     title = "ADX Length", minval = 1 , maxval = 100000 , step = 1 , tooltip = "ADX Length", inline = "7", group = "Filters") i_ADXThreshold          = input.int  (defval = 25,     title = "ADX Threshold", minval = 1 , maxval = 100000 , step = 1 , tooltip = "ADX should be bigger than threshold", inline = "8", group = "Filters") //// 3-4. SuperTrend Filter// i_superTrendFilterOn    = input.bool (defval = false , title = "Super Trend Filter On?", tooltip = "Super Trend Filter On? Order will not be made unless filter condition is fulfilled", inline = "9", group =  "Filters") // i_superTrendATRLen      = input.int  (defval = 10,     title = "ATR Length", minval = 1 , maxval = 100000 , step = 1 , tooltip = "Super Trend ATR Length", inline = "10", group = "Filters") // i_superTrendATRFactor   = input.float (defval = 3,     title = "Factor", minval = 1 , maxval = 100000 , step = 0.1 , tooltip = "Super Trend ATR Factor", inline = "11", group = "Filters") // ADX and DI Thanks to @BeikabuOyajiint len                 = i_ADXLengthfloat th                = i_ADXThresholdTR                      = math.max(math.max(high - low, math.abs(high - nz(close[1]))), math.abs(low - nz(close[1])))DMPlus                  = high - nz(high[1]) > nz(low[1]) - low ? math.max(high - nz(high[1]), 0) : 0DMMinus                 = nz(low[1]) - low > high - nz(high[1]) ? math.max(nz(low[1]) - low, 0) : 0SmoothedTR              = 0.0SmoothedTR              := nz(SmoothedTR[1]) - nz(SmoothedTR[1]) / len + TRSmoothedDMPlus          = 0.0SmoothedDMPlus          := nz(SmoothedDMPlus[1]) - nz(SmoothedDMPlus[1]) / len + DMPlusSmoothedDMMinus         = 0.0SmoothedDMMinus         := nz(SmoothedDMMinus[1]) - nz(SmoothedDMMinus[1]) / len + DMMinusDIPlus                  = SmoothedDMPlus / SmoothedTR * 100DIMinus                 = SmoothedDMMinus / SmoothedTR * 100DX                      = math.abs(DIPlus - DIMinus) / (DIPlus + DIMinus) * 100ADX                     = ta.sma(source = DX, length = len)// plot(DIPlus, color=color.new(color.green, 0), title='DI+')// plot(DIMinus, color=color.new(color.red, 0), title='DI-')// plot(ADX, color=color.new(color.navy, 0), title='ADX')// hline(th, color=color.white)bool ADXFilter          = ADX > th ? true : falsebool longDMIFilter      = DIPlus >= DIMinus ? true : falsebool shortDMIFilter     = DIPlus <= DIMinus ? true : false// Calculate Super Trend for Filter// i_superTrendFilterOn    = input.bool (defval = false , title = "Super Trend Filter On?", tooltip = "Super Trend Filter On? Order will not be made unless filter condition is fulfilled", inline = "9", group =  "Filters") // i_superTrendATRLen      = input.int  (defval = 10,     title = "ATR Length", minval = 1 , maxval = 100000 , step = 1 , tooltip = "Super Trend ATR Length", inline = "10", group = "Filters") // i_superTrendATRFactor   = input.float (defval = 3,     title = "Factor", minval = 1 , maxval = 100000 , step = 0.1 , tooltip = "Super Trend ATR Factor", inline = "11", group = "Filters") // [supertrend, direction] = ta.supertrend(factor = i_superTrendATRFactor, atrPeriod = i_superTrendATRLen) // bodyMiddle              = plot((open + close) / 2, display=display.none)// upTrend                 = plot(i_superTrendFilterOn ? direction < 0 ? supertrend : na : na, "Up Trend", color = color.green, style=plot.style_linebr)// downTrend               = plot(i_superTrendFilterOn ? direction < 0 ? na : supertrend : na, "Down Trend", color = color.red, style=plot.style_linebr)// fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)// fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)// bool longSTFilter       = direction <= 0// bool shortSTFilter      = direction >= 0// Filter bool longFilterFilled   = (not i_ATRFilterOn or ATRFilter) and (not i_EMAFilterOn or longEMAFilter) and (not i_ADXFilterOn or ADXFilter) and (not i_DMIFilterOn or longDMIFilter) // and (not i_superTrendFilterOn or longSTFilter)bool shortFilterFilled  = (not i_ATRFilterOn or ATRFilter) and (not i_EMAFilterOn or shortEMAFilter) and (not i_ADXFilterOn or ADXFilter) and (not i_DMIFilterOn or shortDMIFilter) // and (not i_superTrendFilterOn or shortSTFilter)// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░//                      Strategy Logic (Entry & Exit Condition) - Inputs, Indicators for Strategy// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░//// Indicators// Inputs for Strategy Indicators//// 1. Super Trendi_superTrendATRLen      = input.int  (defval = 10,     title = "ATR Length", minval = 1 , maxval = 100000 , step = 1 , tooltip = "Super Trend ATR Length", inline = "1", group = "1: SuperTrend") i_superTrendATRFactor   = input.float (defval = 3,     title = "Factor", minval = 1 , maxval = 100000 , step = 0.1 , tooltip = "Super Trend ATR Factor", inline = "2", group = "1: SuperTrend") [supertrend, direction] = ta.supertrend(factor = i_superTrendATRFactor, atrPeriod = i_superTrendATRLen) //// 2. SSL Hybrid Baselinei_useTrueRange          = input.bool   (defval = true, title = "use true range for Keltner Channel?", tooltip = "", inline = "1", group = "2: SSL Hybrid") i_maType                = input.string (defval ='EMA', title='Baseline Type', options=['SMA', 'EMA', 'DEMA', 'TEMA', 'LSMA', 'WMA', 'VAMA', 'TMA', 'HMA', 'McGinley'], inline="2", group = "2: SSL Hybrid")i_len                   = input.int    (defval =30,    title='Baseline Length', inline="2", group = "2: SSL Hybrid")i_multy                 = input.float  (defval = 0.2,  title='Base Channel Multiplier', minval = 0, maxval = 100,  step=0.05, inline="3", group = "2: SSL Hybrid")i_volatility_lookback   = input.int    (defval =10,    title='Volatility lookback length(for VAMA)', inline='4',group="2: SSL Hybrid")tema(src, len) =>    ema1 = ta.ema(src, len)    ema2 = ta.ema(ema1, len)    ema3 = ta.ema(ema2, len)    3 * ema1 - 3 * ema2 + ema3f_ma(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 == '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 == '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    result//// 2-1. SSL Hybrid Keltner Baseline Channel BBMC                    = f_ma (i_maType, close, i_len) // BaseLoneKeltma                  = f_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//// 3. QQE MOD, thanks to Mihkel100RSI_Period              = input.int   (defval = 6,     title = 'RSI Length',      inline = "1",       group = "3: QQE MOD")SF                      = input.int   (defval = 5,     title = 'RSI Smoothing',   inline = "2",       group = "3: QQE MOD")QQE                     = input.float (defval = 3,     title = 'Fast QQE Factor', inline = "3",       group = "3: QQE MOD")ThreshHold              = input.int   (defval = 3,     title = 'Thresh-hold',     inline = "4",       group = "3: QQE MOD")src                     = input       (defval = close, title='RSI Source')Wilders_Period          = RSI_Period * 2 - 1Rsi                     = ta.rsi(src, RSI_Period)RsiMa                   = ta.ema(Rsi, SF)AtrRsi                  = math.abs(RsiMa[1] - RsiMa)MaAtrRsi                = ta.ema(AtrRsi, Wilders_Period)dar                     = ta.ema(MaAtrRsi, Wilders_Period) * QQElongband                = 0.0shortband               = 0.0trend                   = 0DeltaFastAtrRsi         = darRSIndex                 = RsiManewshortband            = RSIndex + DeltaFastAtrRsinewlongband             = RSIndex - DeltaFastAtrRsilongband                := RSIndex[1] > longband[1] and RSIndex > longband[1] ? math.max(longband[1], newlongband) : newlongbandshortband               := RSIndex[1] < shortband[1] and RSIndex < shortband[1] ? math.min(shortband[1], newshortband) : newshortbandcross_1                 = ta.cross(longband[1], RSIndex)trend                   := ta.cross(RSIndex, shortband[1]) ? 1 : cross_1 ? -1 : nz(trend[1], 1)FastAtrRsiTL            = trend == 1 ? longband : shortband////////////////////length                  = input.int     (defval = 50,   minval = 1,                            title = 'Bollinger Length', group = "3: QQE MOD")mult                    = input.float   (defval = 0.35, minval = 0.01, maxval = 5, step = 0.1, title = 'BB Multiplier', group = "3: QQE MOD")basis                   = ta.sma(FastAtrRsiTL - 50, length)dev                     = mult * ta.stdev(FastAtrRsiTL - 50, length)upper                   = basis + devlower                   = basis - devcolor_bar               = RsiMa - 50 > upper ? #00c3ff : RsiMa - 50 < lower ? #ff0062 : color.gray//// Zero crossQQEzlong                = 0QQEzlong                := nz(QQEzlong[1])QQEzshort               = 0QQEzshort               := nz(QQEzshort[1])QQEzlong                := RSIndex >= 50 ? QQEzlong + 1 : 0QQEzshort               := RSIndex < 50 ? QQEzshort + 1 : 0//  // Zero                    = hline(0, color=color.white, linestyle=hline.style_dotted, linewidth=1)////////////////////////////////////////////////////////////////RSI_Period2             = input.int   (defval = 6,     title = 'RSI 2  Length', group = "3: QQE MOD")SF2                     = input.int   (defval = 5,     title = 'RSI Smoothing', group = "3: QQE MOD")QQE2                    = input.float (defval = 1.61,  title = 'Fast QQE2 Factor', group = "3: QQE MOD")ThreshHold2             = input.int   (defval = 3,     title = 'Thresh-hold', group = "3: QQE MOD")src2                    = input       (defval = close, title = 'RSI Source', group = "3: QQE MOD")////Wilders_Period2 = RSI_Period2 * 2 - 1Rsi2                    = ta.rsi(src2, RSI_Period2)RsiMa2                  = ta.ema(Rsi2, SF2)AtrRsi2                 = math.abs(RsiMa2[1] - RsiMa2)MaAtrRsi2               = ta.ema(AtrRsi2, Wilders_Period2)dar2                    = ta.ema(MaAtrRsi2, Wilders_Period2) * QQE2longband2               = 0.0shortband2              = 0.0trend2                  = 0DeltaFastAtrRsi2        = dar2RSIndex2                = RsiMa2newshortband2           = RSIndex2 + DeltaFastAtrRsi2newlongband2            = RSIndex2 - DeltaFastAtrRsi2longband2               := RSIndex2[1] > longband2[1] and RSIndex2 > longband2[1] ? math.max(longband2[1], newlongband2) : newlongband2shortband2              := RSIndex2[1] < shortband2[1] and RSIndex2 < shortband2[1] ? math.min(shortband2[1], newshortband2) : newshortband2cross_2                 = ta.cross(longband2[1], RSIndex2)trend2                  := ta.cross(RSIndex2, shortband2[1]) ? 1 : cross_2 ? -1 : nz(trend2[1], 1)FastAtrRsi2TL           = trend2 == 1 ? longband2 : shortband2//// Zero crossQQE2zlong               = 0QQE2zlong               := nz(QQE2zlong[1])QQE2zshort              = 0QQE2zshort              := nz(QQE2zshort[1])QQE2zlong               := RSIndex2 >= 50 ? QQE2zlong + 1 : 0QQE2zshort              := RSIndex2 < 50 ? QQE2zshort + 1 : 0//  hcolor2                 = RsiMa2 - 50 > ThreshHold2 ? color.silver : RsiMa2 - 50 < 0 - ThreshHold2 ? color.silver : naGreenbar1               = RsiMa2 - 50 > ThreshHold2Greenbar2               = RsiMa - 50 > upperRedbar1                 = RsiMa2 - 50 < 0 - ThreshHold2Redbar2                 = RsiMa - 50 < lower// Plot: Indicators//// 1. Super TrendbodyMiddle              = plot((open + close) / 2, display=display.none)upTrend                 = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style=plot.style_linebr)downTrend               = plot(direction < 0 ? na : supertrend, "Down Trend", color = color.red, style=plot.style_linebr)fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)//// 2. SSL Hybridvar bullSSLColor        = #00c3ffvar bearSSLColor        = #ff0062// color_bar               = color.new(color = close > upperk ? bullSSLColor : close < lowerk ? bearSSLColor : color.gray, transp = 0)// i_show_color_bar        = input.bool(defval = true , title = "Color Bars") // barcolor(i_show_color_bar ? color_bar : na)plot(series = BBMC, title = 'MA Baseline', color = color_bar, linewidth = 1, style = plot.style_line)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. QQE MOD: No Plotting because of overlay option// plot(FastAtrRsi2TL - 50, title='QQE Line', color=color.new(color.white, 0), linewidth=2)// plot(RsiMa2 - 50, color=hcolor2, title='Histo2', style=plot.style_columns, transp=50)// plot(Greenbar1 and Greenbar2 == 1 ? RsiMa2 - 50 : na, title='QQE Up', style=plot.style_columns, color=color.new(#00c3ff, 0))// plot(Redbar1 and Redbar2 == 1 ? RsiMa2 - 50 : na, title='QQE Down', style=plot.style_columns, color=color.new(#ff0062, 0))////// Entry, Exit// Long, Short Logic with Indicatorbool longSTCond         = direction[1] >= 0 and direction <= 0bool shortSTCond        = direction[1] <= 0 and direction >= 0bool longSSLCond        = close > upperkbool shortSSLCond       = close < lowerkbool longQQECond        = Greenbar1 and Greenbar2 == 1bool shortQQECond       = Redbar1 and Redbar2 == 1// Basic Cond + Long, Short Entry Conditionbool longCond           = (i_longEnabled and inTime) and (longSTCond and longSSLCond and longQQECond) bool shortCond          = (i_shortEnabled and inTime) and (shortSTCond and shortSSLCond and shortQQECond) // Basic Cond + Long, Short Exit Conditionbool closeLong          = (i_longEnabled) and (shortSTCond)bool closeShort         = (i_shortEnabled) and (longSTCond)// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░//                      Position Control// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░// Long, Short Entry Condition + Not entered Position Yetbool openLong           = longCond and not (strategy.opentrades.size(strategy.opentrades - 1) > 0) and longFilterFilledbool openShort          = shortCond and not (strategy.opentrades.size(strategy.opentrades - 1) < 0) and shortFilterFilledbool 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)