Zeal Terminal Open Zeal Terminal

Pine Script v5 · Strategy

Strategy Myth-Busting #12 - OSGFC+SuperTrend - [MYN]

A Pine Script v5 strategy built on ATR (21), Crossover (out, sig) and Crossunder (out, sig). It has 9 order rules, 2 entries among them, and trades long and short with the default settings. Exits use a profit target and no stop loss. Each trade commits 10.0% of equity and pays 0.075 commission. 36 settings; defaults include Heiken-Ashi Better Smoothing Kaufman, Source Close and Guassian Levels Depth 10.

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 Strategy Myth-Busting #12 - OSGFC+SuperTrend - [MYN] repaint?
Yes
At least one pattern in the source can repaint: intrabar recalculation.
What alerts does Strategy Myth-Busting #12 - OSGFC+SuperTrend - [MYN] have?
4
Long; Short; alertSyntaxBase + 'side:long'; alertSyntaxBase + 'side:short'.
Does Strategy Myth-Busting #12 - OSGFC+SuperTrend - [MYN] run in Pine Script v6?
Not tested
The v5 script does not run in Zeal Terminal's engine (Pine Script v5 Error at @L15:C0: no source was supplied for the library 'loxx/loxxexpandedsourcetypes/4'. Libraries cannot be fetched from TradingView; supply the source in the 'libraries' option. No libraries were supplied.), so this step could not be checked. The v6 version is shown for reference and is not offered as a download.
Does Strategy Myth-Busting #12 - OSGFC+SuperTrend - [MYN] use a stop loss?
No
Its exits set a profit target but no stop.
Does Strategy Myth-Busting #12 - OSGFC+SuperTrend - [MYN] run in Zeal Terminal?
No
Not yet: it imports the library loxx/loxxexpandedsourcetypes/4, whose source is not available here, so it does not run here
Does not run in Zeal Terminal yetIt imports the library loxx/loxxexpandedsourcetypes/4, whose source is not available here, so it does not run here. The settings, logic and review below are read from the source, which does not need a run.

Review

What a careful reader of this script would point out, found by checking the source.

  • Check

    No stop loss

    strategy.exit is used without a stop, loss or trailing stop.

  • Note

    2 settings have no label

    In the settings dialog startPeriodTime (line 204), endPeriodTime (line 206) show an empty name. The labels on this page come from the variable names.

  • Note

    No slippage

    Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.

  • Note

    Uses an argument v6 removed

    when = on line 266, 267, 268. The upgraded version below moves each call inside an if block.

Settings

Every input the script declares, with its default and what it feeds. Bounds are the ones the script enforces.

SettingDefaultType and rangeFeeds
One-Sided Gaussian Filter w/ Channels
Heiken-Ashi Better SmoothingKaufmanstring · options ["AMA", "T3", "Kaufman"]src
SourceClosestring · options ["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)", "HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)", "HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"]src
Basic Settings
Guassian Levels Depth10int · max 100lmax out1
Extra Smoothing (2-Pole Ehlers Super Smoother) Period10intout
ATR Period21intatr
ATR Multiplier.628floatsmax smin
UI Options
Color bars?trueboolbarcolor
Show signals?trueboolLong Short
Moving Average Inputs
* Kaufman's Adaptive MA (KAMA) Only - Fast End0.666floatsrc
* Kaufman's Adaptive MA (KAMA) Only - Slow End0.0645floatsrc
* Adaptive Moving Average (AMA) Only - Fast2intsrc
* Adaptive Moving Average (AMA) Only - Slow30intsrc
Number of bars to look back to validate Trend0intOSGFCLongEntryFinal OSGFCShortgEntryFinal
Factor3.0float · step 0.01supertrend1 direction1
Number of bars to look back to validate Trend0intsuperTrendLongEntryFinal superTrendShortEntryFinal
SuperTrend
ATR Length10intsupertrend1 direction1
ADX
Average Directional Index (ADX)falsebooladxsig isADXEnabledAndAboveThreshold
ADX Smoothing14intadx adxsig
DI Length14intadxplus adxminus adxsig
ADX Threshold25intisADXEnabledAndAboveThreshold
Date Range
Starttrueboolstart
Start Period Time (no label in the script)timestamp('1 Jan 2019')timestart
Endtrueboolend
End Period Time (no label in the script)timestamp('31 Dec 2030')timeend
Trade Direction
Trade DirectionLong and Shortstring · options ['Long and Short', 'Long Only', 'Short Only']entry Long entry Short line 254 line 257
Take Profit
Take Profit 1 - Target %100float · min 0.0 · step 0.5exit TP1
% Of Position100int · min 0exit TP1
Take Profit 2 - Target %100float · min 0.0 · step 0.5exit TP2
% Of Position100int · min 0exit TP2
Take Profit 3 - Target %100float · min 0.0 · step 0.5exit TP3
% Of Position100int · min 0exit TP3
Take Profit 4 - Target %100float · min 0.0 · step 0.5exit TP4
Stop Loss
Stop Loss (%)999float · min 0.01slLongClose slShortClose
Leverage
Leverage1float · step .5contracts
ProfitView Alert Syntax
Alert Syntax PrefixCRYPTANEX_99FTX_Strategy-Name-HerestringalertSyntaxBase
Dashboard
Show Dashboardtrueboolline 277

What it calculates

  • ATRATR Period (21)atr · line 137
  • Crossoverout, siggoLong · line 144
  • Crossunderout, siggoShort · line 145
  • SupertrendFactor (3.0), ATR Length (10)supertrend1 · line 161
  • SupertrendFactor (3.0), ATR Length (10)direction1 · line 161
  • Changehighadxup · line 187
  • Changelowadxdown · line 188
  • RMAta.tr, lenadxtruerange · line 191
  • RMAmath.abs(adxplus - adxminus) / (adxsum == 0 ? 1 : adxsum), ADX Smoothing (14)adx · line 198

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

Order rules

OrderFires whenBy defaultLine
Open Long longlongConditionCalc and tradeDirection != 'Short Only' and isInLongPosition == falseOn255
Open Short shortshortConditionCalc and tradeDirection != 'Long Only' and isInShortPosition == falseOn258
Exit TP1 limitcalcPeriodOn262
Exit TP2 limitcalcPeriodOn263
Exit TP3 limitcalcPeriodOn264
Exit TP4 limitcalcPeriodOn265
Close LongslLongCloseclose < strategy.position_avg_price * (1 - stoplossPercent)On266
Close ShortslShortCloseclose > strategy.position_avg_price * (1 + stoplossPercent)On267
Close closeLongCondition or closeShortConditionOn268

Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.

Alerts

AlertCallMessageLine
LongalertconditionOne-Sided Gaussian Filter w/ Channels [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}148
ShortalertconditionOne-Sided Gaussian Filter w/ Channels [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}149
(no title)alertalertSyntaxBase + 'side:long'256
(no title)alertalertSyntaxBase + 'side:short'259

Does it repaint?

Yes

At least one pattern in the source can repaint; it is marked Check below.

The live replay needs a run, and this script does not run in Zeal Terminal yet; the answer comes from the checks on the source alone.

  • ClearHigher-timeframe data8 request.security call(s), none with lookahead on.
  • 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.

Similar scripts

Indicators and strategies built from the same calculations.

ScriptSharesTypeNetTradesMax drawdown
DI Crossing Daily Straregy HulkTrading by TheHulkTradingrma atrv4 strategy+34.3%6518.4%
Breakout Trend Trading Strategy - V1 by Trendoscopeatr supertrendv4 strategy−23.1%332.5%
Breakout Trend Trading Strategy - V2 by Trendoscopeatr supertrendv4 strategy−1.2%19.8%

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.

  • 3 strategy calls use the when = argument (line 266, 267, 268). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
  • 6 settings use the untyped input() (line 152, 159, 169, 183, 184, 185). 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

Not verified

The v5 script does not run in Zeal Terminal's engine (Pine Script v5 Error at @L15:C0: no source was supplied for the library 'loxx/loxxexpandedsourcetypes/4'. Libraries cannot be fetched from TradingView; supply the source in the 'libraries' option. No libraries were supplied.), so this step could not be checked.

  • Line 152: input() → input.int()
  • Line 159: input() → input.int()
  • Line 169: input() → input.int()
  • Line 183: input() → input.int()
  • Line 184: input() → input.int()
  • Line 185: input() → input.int()
3 more edits
  • Line 266: when = slLongClose → if block
  • Line 267: when = slShortClose → if block
  • Line 268: when = closeLongCondition or closeShortCondition → if block
⋯OSGFCShortgEntry = goShort-i_numLookbackBarsOSGFC = input(0,title="Number of bars to look back to validate Trend")+i_numLookbackBarsOSGFC = input.int(0,title="Number of bars to look back to validate Trend")OSGFCLongEntryFinal = goLong and ta.barssince(OSGFCShortgEntry) > i_numLookbackBarsOSGFC ⋯//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░-atrPeriod1 = input(10, "ATR Length", group="SuperTrend")+atrPeriod1 = input.int(10, "ATR Length", group="SuperTrend")factor = input.float(3.0, "Factor", step = 0.01)⋯superTrendShortEntry = direction1 > 0 -i_numLookbackBarsST = input(0,title="Number of bars to look back to validate Trend")+i_numLookbackBarsST = input.int(0,title="Number of bars to look back to validate Trend")superTrendLongEntryFinal = superTrendLongEntry and ta.barssince(superTrendShortEntry) > i_numLookbackBarsST ⋯adxEnabled = input.bool(defval = false , title = "Average Directional Index (ADX)", tooltip = "", group ="ADX" ) -adxlen = input(14, title="ADX Smoothing", group="ADX")+adxlen = input.int(14, title="ADX Smoothing", group="ADX")-adxdilen = input(14, title="DI Length", group="ADX")+adxdilen = input.int(14, title="DI Length", group="ADX")-adxabove = input(25, title="ADX Threshold", group="ADX")+adxabove = input.int(25, title="ADX Threshold", group="ADX")adxdirmov(len) =>⋯    strategy.exit('TP4', profit=per(tp4))-    strategy.close('Long', qty_percent=100, comment='SL Long', when=slLongClose)+    if slLongClose+        strategy.close('Long', qty_percent=100, comment='SL Long')-    strategy.close('Short', qty_percent=100, comment='SL Short', when=slShortClose)+    if slShortClose+        strategy.close('Short', qty_percent=100, comment='SL Short')-    strategy.close_all(when=closeLongCondition or closeShortCondition, comment='Close Postion')+    if closeLongCondition or closeShortCondition+        strategy.close_all(comment='Close Postion')/// Dashboard⋯

Does it run in Pine Script v6?

Not tested

The v5 script does not run in Zeal Terminal's engine (Pine Script v5 Error at @L15:C0: no source was supplied for the library 'loxx/loxxexpandedsourcetypes/4'. Libraries cannot be fetched from TradingView; supply the source in the 'libraries' option. No libraries were supplied.), so this step could not be checked. The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯// © myn-//@version=5+//@version=6strategy('Strategy Myth-Busting #12 - OSGFC+SuperTrend - [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=1000, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=10.0, commission_value=0.075, use_bar_magnifier = false)⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2No It imports the library loxx/loxxexpandedsourcetypes/4, whose source is not available here, so it does not run hereNot measured
PineTSNot testedNot testedNot measured

“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/// © myn//@version=5strategy('Strategy Myth-Busting #12 - OSGFC+SuperTrend - [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=1000, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=10.0, commission_value=0.075, use_bar_magnifier = false)///////////////////////////////////////* Put your strategy logic below *///////////////////////////////////////// 5XVKG4ZzVvY// Trading Rules: 15 mins, Forex / Crypto// SuperTrend and OSGFC generate buy signal// Close Buy on Gaussian generating a sell signal// Gausian generates sell signal (close signal)// One-Sided Gaussian Filter w/ Channels By Loxx//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░import loxx/loxxexpandedsourcetypes/4 as loxxexpandedsourcetypesgreencolor = #2DD204redcolor = #D2042D //ehlers 2-pole super smoother_twopoless(float src, int len)=>    a1 = 0., b1 = 0.    coef1 = 0., coef2 = 0., coef3 = 0.    filt = 0., trig = 0.    a1 := math.exp(-1.414 * math.pi / len)    b1 := 2 * a1 * math.cos(1.414 * math.pi / len)    coef2 := b1    coef3 := -a1 * a1    coef1 := 1 - coef2 - coef3    filt := coef1 * src + coef2 * nz(filt[1]) + coef3 * nz(filt[2])    filt := bar_index < 3 ? src : filt    filt    _gaussian(size, x)=>    out = (math.exp(-x * x * 9 / ((size + 1) * (size + 1))))    out//calc fibonacci numbers 0, 1, 1, 2, 3, 5, 8, 13, 21 ... etc_fiblevels(len)=>    arr_levels = array.new_float(len, 0.)    t1 = 0, t2 = 1    nxt = t1 + t2    for i = 0 to len - 1         array.set(arr_levels, i, nxt)        t1 := t2        t2 := nxt        nxt := t1 + t2    arr_levels    //calc weights given fibo numbers and how many fibos chosen_gaussout(levels)=>    perin = array.size(levels)    arr_gauss = matrix.new<float>(perin, perin, 0.)    for k = 0 to array.size(levels) - 1         sum = 0.        for i = 0 to perin - 1             if (i >= array.get(levels, k))                 break            matrix.set(arr_gauss, i, k, _gaussian(array.get(levels, k), i))            sum += matrix.get(arr_gauss, i, k)        for i = 0 to perin - 1            if (i >= array.get(levels, k))                 break            temp = matrix.get(arr_gauss, i, k) / sum            matrix.set(arr_gauss, i, k, temp)    arr_gauss   //calc moving average applying fibo numbers_smthMA(level, src, per)=>    sum = 0.    lvltemp = _fiblevels(per)    gtemp = _gaussout(lvltemp)    for i = 0 to matrix.rows(gtemp) - 1        sum += matrix.get(gtemp, i, level) * nz(src[i])    sumsmthtype = input.string("Kaufman", "Heiken-Ashi Better Smoothing", options = ["AMA", "T3", "Kaufman"], group=  "One-Sided Gaussian Filter w/ Channels")srcoption = input.string("Close", "Source", group= "One-Sided Gaussian Filter w/ Channels",      options =      ["Close", "Open", "High", "Low", "Median", "Typical", "Weighted", "Average", "Average Median Body", "Trend Biased", "Trend Biased (Extreme)",      "HA Close", "HA Open", "HA High", "HA Low", "HA Median", "HA Typical", "HA Weighted", "HA Average", "HA Average Median Body", "HA Trend Biased", "HA Trend Biased (Extreme)",     "HAB Close", "HAB Open", "HAB High", "HAB Low", "HAB Median", "HAB Typical", "HAB Weighted", "HAB Average", "HAB Average Median Body", "HAB Trend Biased", "HAB Trend Biased (Extreme)"])     smthper = input.int(10, "Guassian Levels Depth", maxval = 100, group=  "Basic Settings")extrasmthper = input.int(10, "Extra Smoothing (2-Pole Ehlers Super Smoother) Period", group=  "Basic Settings")atrper = input.int(21, "ATR Period", group = "Basic Settings")mult = input.float(.628, "ATR Multiplier", group = "Basic Settings")colorbars = input.bool(true, "Color bars?", group = "UI Options")showsignals = input.bool(true, "Show signals?", group = "UI Options")kfl=input.float(0.666, title="* Kaufman's Adaptive MA (KAMA) Only - Fast End", group = "Moving Average Inputs")ksl=input.float(0.0645, title="* Kaufman's Adaptive MA (KAMA) Only - Slow End", group = "Moving Average Inputs")amafl = input.int(2, title="* Adaptive Moving Average (AMA) Only - Fast", group = "Moving Average Inputs")amasl = input.int(30, title="* Adaptive Moving Average (AMA) Only - Slow", group = "Moving Average Inputs")haclose = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close)haopen = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, open)hahigh = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, high)halow = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, low)hamedian = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hl2)hatypical = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlc3)haweighted = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, hlcc4)haaverage = request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, ohlc4)float src = switch srcoption    "Close" => loxxexpandedsourcetypes.rclose()    "Open" => loxxexpandedsourcetypes.ropen()    "High" => loxxexpandedsourcetypes.rhigh()    "Low" => loxxexpandedsourcetypes.rlow()    "Median" => loxxexpandedsourcetypes.rmedian()    "Typical" => loxxexpandedsourcetypes.rtypical()    "Weighted" => loxxexpandedsourcetypes.rweighted()    "Average" => loxxexpandedsourcetypes.raverage()    "Average Median Body" => loxxexpandedsourcetypes.ravemedbody()    "Trend Biased" => loxxexpandedsourcetypes.rtrendb()    "Trend Biased (Extreme)" => loxxexpandedsourcetypes.rtrendbext()    "HA Close" => loxxexpandedsourcetypes.haclose(haclose)    "HA Open" => loxxexpandedsourcetypes.haopen(haopen)    "HA High" => loxxexpandedsourcetypes.hahigh(hahigh)    "HA Low" => loxxexpandedsourcetypes.halow(halow)    "HA Median" => loxxexpandedsourcetypes.hamedian(hamedian)    "HA Typical" => loxxexpandedsourcetypes.hatypical(hatypical)    "HA Weighted" => loxxexpandedsourcetypes.haweighted(haweighted)    "HA Average" => loxxexpandedsourcetypes.haaverage(haaverage)    "HA Average Median Body" => loxxexpandedsourcetypes.haavemedbody(haclose, haopen)    "HA Trend Biased" => loxxexpandedsourcetypes.hatrendb(haclose, haopen, hahigh, halow)    "HA Trend Biased (Extreme)" => loxxexpandedsourcetypes.hatrendbext(haclose, haopen, hahigh, halow)    "HAB Close" => loxxexpandedsourcetypes.habclose(smthtype, amafl, amasl, kfl, ksl)    "HAB Open" => loxxexpandedsourcetypes.habopen(smthtype, amafl, amasl, kfl, ksl)    "HAB High" => loxxexpandedsourcetypes.habhigh(smthtype, amafl, amasl, kfl, ksl)    "HAB Low" => loxxexpandedsourcetypes.hablow(smthtype, amafl, amasl, kfl, ksl)    "HAB Median" => loxxexpandedsourcetypes.habmedian(smthtype, amafl, amasl, kfl, ksl)    "HAB Typical" => loxxexpandedsourcetypes.habtypical(smthtype, amafl, amasl, kfl, ksl)    "HAB Weighted" => loxxexpandedsourcetypes.habweighted(smthtype, amafl, amasl, kfl, ksl)    "HAB Average" => loxxexpandedsourcetypes.habaverage(smthtype, amafl, amasl, kfl, ksl)    "HAB Average Median Body" => loxxexpandedsourcetypes.habavemedbody(smthtype, amafl, amasl, kfl, ksl)    "HAB Trend Biased" => loxxexpandedsourcetypes.habtrendb(smthtype, amafl, amasl, kfl, ksl)    "HAB Trend Biased (Extreme)" => loxxexpandedsourcetypes.habtrendbext(smthtype, amafl, amasl, kfl, ksl)    => hacloselmax = smthper + 1out1 = _smthMA(smthper, src, lmax)out = _twopoless(out1, extrasmthper)sig = out[1]colorout = out > sig ? greencolor : redcoloratr = ta.atr(atrper)smax = out + atr * multsmin = out - atr * multplot(smax, color = bar_index % 2 ? color.silver : na, linewidth = 1)plot(smin, color = bar_index % 2 ? color.silver : na, linewidth = 1)plot(out, "GMA", color = colorout, linewidth = 4)barcolor(colorbars ? colorout : na)goLong = ta.crossover(out, sig)goShort = ta.crossunder(out, sig)plotshape(goLong and showsignals, title = "Long", color = color.yellow, textcolor = color.yellow, text = "L", style = shape.triangleup, location = location.belowbar, size = size.tiny)plotshape(goShort and showsignals, title = "Short", color = color.fuchsia, textcolor = color.fuchsia, text = "S", style = shape.triangledown, location = location.abovebar, size = size.tiny)alertcondition(goLong, title="Long", message="One-Sided Gaussian Filter w/ Channels [Loxx]: Long\nSymbol: {{ticker}}\nPrice: {{close}}")alertcondition(goShort, title="Short", message="One-Sided Gaussian Filter w/ Channels [Loxx]: Short\nSymbol: {{ticker}}\nPrice: {{close}}")OSGFCLongEntry = goLongOSGFCShortgEntry = goShorti_numLookbackBarsOSGFC = input(0,title="Number of bars to look back to validate Trend")OSGFCLongEntryFinal = goLong and ta.barssince(OSGFCShortgEntry) > i_numLookbackBarsOSGFC OSGFCShortgEntryFinal = goShort and ta.barssince(OSGFCLongEntry) > i_numLookbackBarsOSGFC OSGFCLongClose = OSGFCShortgEntryOSGFCShortClose = OSGFCLongEntry// SuperTrend (TradingView Interal)//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░atrPeriod1 = input(10, "ATR Length", group="SuperTrend")factor = input.float(3.0, "Factor", step = 0.01)[supertrend1, direction1] = ta.supertrend(factor, atrPeriod1)bodyMiddle = plot((open + close) / 2, display=display.none)upTrend = plot(direction1 < 0 ? supertrend1 : na, "Up Trend", color = color.green, style=plot.style_linebr)downTrend = plot(direction1 < 0 ? na : supertrend1, "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)superTrendLongEntry = direction1 < 0 superTrendShortEntry = direction1 > 0 i_numLookbackBarsST = input(0,title="Number of bars to look back to validate Trend")superTrendLongEntryFinal = superTrendLongEntry and ta.barssince(superTrendShortEntry) > i_numLookbackBarsST superTrendShortEntryFinal = superTrendShortEntry and ta.barssince(superTrendLongEntry) > i_numLookbackBarsST ////////////////////////////////////////* Put your strategy rules below *///////////////////////////////////////longCondition = OSGFCLongEntryFinal and superTrendLongEntryFinal shortCondition = OSGFCShortgEntryFinal and superTrendShortEntryFinal //define as 0 if do not want to usecloseLongCondition = OSGFCLongClose closeShortCondition = OSGFCShortClose // ADX//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░adxEnabled = input.bool(defval = false , title = "Average Directional Index (ADX)", tooltip = "", group ="ADX" ) adxlen = input(14, title="ADX Smoothing", group="ADX")adxdilen = input(14, title="DI Length", group="ADX")adxabove = input(25, title="ADX Threshold", group="ADX")adxdirmov(len) =>    adxup = ta.change(high)    adxdown = -ta.change(low)    adxplusDM = na(adxup) ? na : (adxup > adxdown and adxup > 0 ? adxup : 0)    adxminusDM = na(adxdown) ? na : (adxdown > adxup and adxdown > 0 ? adxdown : 0)    adxtruerange = ta.rma(ta.tr, len)    adxplus = fixnan(100 * ta.rma(adxplusDM, len) / adxtruerange)    adxminus = fixnan(100 * ta.rma(adxminusDM, len) / adxtruerange)    [adxplus, adxminus]adx(adxdilen, adxlen) =>    [adxplus, adxminus] = adxdirmov(adxdilen)    adxsum = adxplus + adxminus    adx = 100 * ta.rma(math.abs(adxplus - adxminus) / (adxsum == 0 ? 1 : adxsum), adxlen)adxsig = adxEnabled ? adx(adxdilen, adxlen) : naisADXEnabledAndAboveThreshold = adxEnabled ? (adxsig > adxabove) : true//Backtesting Time Period (Input.time not working as expected as of 03/30/2021.  Giving odd start/end dates//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░useStartPeriodTime = input.bool(true, 'Start', group='Date Range', inline='Start Period')startPeriodTime = input.time(timestamp('1 Jan 2019'), '', group='Date Range', inline='Start Period')useEndPeriodTime = input.bool(true, 'End', group='Date Range', inline='End Period')endPeriodTime = input.time(timestamp('31 Dec 2030'), '', group='Date Range', inline='End Period')start = useStartPeriodTime ? startPeriodTime >= time : falseend = useEndPeriodTime ? endPeriodTime <= time : falsecalcPeriod = not start and not end// Trade Direction // ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░tradeDirection = input.string('Long and Short', title='Trade Direction', options=['Long and Short', 'Long Only', 'Short Only'], group='Trade Direction')// Percent as Points// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░per(pcnt) =>    strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)// Take profit 1// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░tp1 = input.float(title='Take Profit 1 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 1')q1 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 1')// Take profit 2// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░tp2 = input.float(title='Take Profit 2 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 2')q2 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 2')// Take profit 3// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░tp3 = input.float(title='Take Profit 3 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 3')q3 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 3')// Take profit 4// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░tp4 = input.float(title='Take Profit 4 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit')/// Stop Loss// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░stoplossPercent = input.float(title='Stop Loss (%)', defval=999, minval=0.01, group='Stop Loss') * 0.01slLongClose = close < strategy.position_avg_price * (1 - stoplossPercent)slShortClose = close > strategy.position_avg_price * (1 + stoplossPercent)/// Leverage// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░leverage = input.float(1, 'Leverage', step=.5, group='Leverage')contracts = math.min(math.max(.000001, strategy.equity / close * leverage), 1000000000)/// Trade State Management// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░isInLongPosition = strategy.position_size > 0isInShortPosition = strategy.position_size < 0/// ProfitView Alert Syntax String Generation// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░alertSyntaxPrefix = input.string(defval='CRYPTANEX_99FTX_Strategy-Name-Here', title='Alert Syntax Prefix', group='ProfitView Alert Syntax')alertSyntaxBase = alertSyntaxPrefix + '\n#' + str.tostring(open) + ',' + str.tostring(high) + ',' + str.tostring(low) + ',' + str.tostring(close) + ',' + str.tostring(volume) + ','/// Trade Execution// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░longConditionCalc = (longCondition and isADXEnabledAndAboveThreshold)shortConditionCalc = (shortCondition and isADXEnabledAndAboveThreshold)if calcPeriod    if longConditionCalc and tradeDirection != 'Short Only' and isInLongPosition == false        strategy.entry('Long', strategy.long, qty=contracts)        alert(message=alertSyntaxBase + 'side:long', freq=alert.freq_once_per_bar_close)    if shortConditionCalc and tradeDirection != 'Long Only' and isInShortPosition == false        strategy.entry('Short', strategy.short, qty=contracts)        alert(message=alertSyntaxBase + 'side:short', freq=alert.freq_once_per_bar_close)        //Inspired from Multiple %% profit exits example by adolgo https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/    strategy.exit('TP1', qty_percent=q1, profit=per(tp1))    strategy.exit('TP2', qty_percent=q2, profit=per(tp2))    strategy.exit('TP3', qty_percent=q3, profit=per(tp3))    strategy.exit('TP4', profit=per(tp4))    strategy.close('Long', qty_percent=100, comment='SL Long', when=slLongClose)    strategy.close('Short', qty_percent=100, comment='SL Short', when=slShortClose)    strategy.close_all(when=closeLongCondition or closeShortCondition, comment='Close Postion')/// Dashboard// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░// Inspired by https://www.tradingview.com/script/uWqKX6A2/ - Thanks VertMTshowDashboard = input.bool(group="Dashboard", title="Show Dashboard", defval=true)f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>    _cellText = _title + "\n" + _value    table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto)// Draw dashboard tableif 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)