Zeal Terminal Open in Zeal Terminal

Pine Script v5 · Strategy

Strategy Myth-Busting #8 - TrendSurfers+TrendOsc - [MYN]

A Pine Script v5 strategy built on Highest (high, 168), Lowest (low, 168) and ATR (10). 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 100.0% of equity and pays 0.075 commission. 30 settings; defaults include Max % risk 2, How many pairs 1 and Highest High Period 168.

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 #8 - TrendSurfers+TrendOsc - [MYN] repaint?
Yes
At least one pattern in the source can repaint: intrabar recalculation.
How did Strategy Myth-Busting #8 - TrendSurfers+TrendOsc - [MYN] do on BTCUSDT 1D with default settings?
Not measured
It closed no trades there from 26 Jan 2024 to 21 Oct 2026 with the default settings; it opened a short position that was still open on the last bar, so there is no result to report. Its code limits trading to a date window, which can leave this period out. It closed no trades on the other markets either. A backtest, not investment advice.
What alerts does Strategy Myth-Busting #8 - TrendSurfers+TrendOsc - [MYN] have?
2
alertSyntaxBase + 'side:long'; alertSyntaxBase + 'side:short'.
Does Strategy Myth-Busting #8 - TrendSurfers+TrendOsc - [MYN] run in Pine Script v6?
No
The v6 version does not run in Zeal Terminal's engine: Pine Script v6 Error at @L268:C7: cannot use 'int' as a condition — Pine Script v6 does not cast 'int' or 'float' to 'bool' implicitly. Wrap it in bool(). The v6 version is shown for reference and is not offered as a download.
Does Strategy Myth-Busting #8 - TrendSurfers+TrendOsc - [MYN] use a stop loss?
No
Its exits set a profit target but no stop.

BTCUSDT · 1D · default settings

  • Highest High
  • Lowest Low
  • Trailing Stop
  • Fixed Stop
  • 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 (30)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$22,077$40,505Equity from $20,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.
Table drawn by the script, as it stood on the last bar
Start: NaN
End: long1763164800000
Net Profit: -0.08%
Percent Per Day NaN%
Percent Profitable: NaN%
Profit Factor: 0
Total Trades: 0
Max Wins In A Row: 0
Max Losses In A Row: 0
Net profit
−0.07%
−$15.00
Buy and hold
+102.5%
same period
Closed trades
0
0 won · 0 lost
Profitable
0.0%
of closed trades
Profit factor
0.00
gross profit ÷ gross loss
Max drawdown
3.60%
−$719.16

One run with the author's default settings, $20,000 starting capital, commission as the script sets it. A short 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

    No stop loss

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

  • Check

    Every trade uses all the equity

    default_qty_value is 100% of equity.

  • Note

    2 settings have no label

    In the settings dialog startPeriodTime (line 202), endPeriodTime (line 204) 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 264, 265, 266. 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
Risk Management
Max % riskRisk % over total equity / Position2floatpositionsizelong positionsizeshort
How many pairsHow many pairs are you trading with the strategy?1intposperclong pospercshort
Entry Condition
Highest High PeriodHighest High of X bars - This will trigger a Long Entry when close is above. (Thin Green Line)168inthighestHigh
Lowest Low PeriodLowest low of X bars - This will trigger a Short Entry when close is under. (Thin Red Line)168intlowestLow
Exit Condition
Trailing ATR PediodAverage True Range for the Trailing Stop. (Thick Green Line) 10inttrailingAtr
Trailing ATR Multiplier8floattrailingAtr
Fix ATR PediodAverage True Range for the Fix Stoloss. (Thick Yellow Line)10intfixAtr
Fix ATR Multiplier2floatfixAtr
DI Length14int · min 1f28 f30 f38 f40 f48 f50 range_1 plus_di minus_di adxtruerange adxplus adxminus
Sensitivity25floatadj_adx
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 252 line 255
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 275

What it calculates

  • Highesthigh, Highest High Period (168)highestHigh · line 38
  • Lowestlow, Lowest Low Period (168)lowestLow · line 39
  • ATRTrailing ATR Pediod (10)trailingAtr · line 40
  • Crossoverclose, highestHighlongConditionTrendSurfers · line 42
  • Crossunderclose, lowestLowshortConditionTrendSurfers · line 43
  • ATRFix ATR Pediod (10)fixAtr · line 45
  • EMAseries, DI Length (14)f28 · line 147
  • EMAf28, DI Length (14)f30 · line 148
  • EMAvC, DI Length (14)f38 · line 150
  • EMAf38, DI Length (14)f40 · line 151
  • EMAv10, DI Length (14)f48 · line 153
  • EMAf48, DI Length (14)f50 · line 154
  • Changehighup · line 157
  • Changelowdown · line 158
  • RMAta.tr, DI Length (14)range_1 · line 161
  • RMAplus_dm, DI Length (14)plus_di · line 162
  • RMAminus_dm, DI Length (14)minus_di · line 163
  • Changehighadxup · line 185
  • Changelowadxdown · line 186
  • RMAta.tr, DI Length (14)adxtruerange · line 189
  • RMAmath.abs(adxplus - adxminus) / (adxsum == 0 ? 1 : adxsum), ADX Smoothing (14)adx · line 196

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 112 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 == falseOn253
Open Short shortshortConditionCalc and tradeDirection != 'Long Only' and isInShortPosition == falseOn256
Exit TP1 limitcalcPeriodOn260
Exit TP2 limitcalcPeriodOn261
Exit TP3 limitcalcPeriodOn262
Exit TP4 limitcalcPeriodOn263
Close LongslLongCloseclose < strategy.position_avg_price * (1 - stoplossPercent)On264
Close ShortslShortCloseclose > strategy.position_avg_price * (1 + stoplossPercent)On265
Close closeLongCondition or closeShortConditionOn266

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

Alerts

AlertCallMessageLine
(no title)alertalertSyntaxBase + 'side:long'254
(no title)alertalertSyntaxBase + 'side:short'257

Does it repaint?

Yes

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

Not measuredNo trades to compareThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, but neither the live nor the historical run produced any trades in them, so the replay says nothing either way.
  • 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−0.1%+102.5%00%0.003.6%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h−0.1%+5.5%00%0.001.1%8 May 2026 – 21 Oct 2026
ETHUSDT 1D0.0%+9.8%00%—0.0%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h−0.1%+8.4%00%0.006.6%8 May 2026 – 21 Oct 2026
SOLUSDT 1D0.0%+16.7%00%—0.0%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h0.0%+21.5%00%—0.0%8 May 2026 – 21 Oct 2026
BNBUSDT 1D0.0%+148.3%00%—0.0%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h−0.1%+17.1%00%0.003.6%8 May 2026 – 21 Oct 2026

Backtests are simulations on historical data and are not investment advice.

Similar scripts

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

ScriptSharesTypeNetTradesMax drawdown
Strategy Myth-Busting #8 - TrendSurfers+TrendOsc - [MYN] this page—v5 strategy−0.1%03.6%
Jigga - Survival Level by jigneshjcrma highest lowest ema atrv5 strategyNo trades on this market
R19 STRATEGY by SenatorVonShaftatr rma ema highest lowestv4 strategyNo trades on this market
Richard's Strategy by Deepak8369highest lowest atr emav4 strategy+34.6%7026.3%
Classic Long Term Trend Following System by Robrecht99ema highest lowest atrv5 strategy+2.9%51.1%
Strategy Myth-Busting #1 - UT Bot+STC+Hull [MYN] by myncryptoatr ema lowest highestv5 strategy−30.7%1063.5%

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 264, 265, 266). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
  • 3 settings use the untyped input() (line 181, 182, 183). 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

Neither version placed a trade on any of the 8 markets, so there was nothing to compare.

  • Line 181: input() → input.int()
  • Line 182: input() → input.int()
  • Line 183: input() → input.int()
  • Line 264: when = slLongClose → if block
  • Line 265: when = slShortClose → if block
  • Line 266: when = closeLongCondition or closeShortCondition → if block
⋯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?

No

The v6 version does not run in Zeal Terminal's engine: Pine Script v6 Error at @L268:C7: cannot use 'int' as a condition — Pine Script v6 does not cast 'int' or 'float' to 'bool' implicitly. Wrap it in bool(). 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 #8 - TrendSurfers+TrendOsc - [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=20000, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=100.0, commission_value=0.075, use_bar_magnifier = false)⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 239 msYes 1,000 bars in 222 msNot 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 #8 - TrendSurfers+TrendOsc - [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=20000, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=100.0, commission_value=0.075, use_bar_magnifier = false)///////////////////////////////////////* Put your strategy logic below */////////////////////////////////////////cAe9It4ynO4// Strategies// Trend Surfers - Premium Indicator// Mawreez' Trend Oscillator Indicator// Trading Setup / Rules// Long Condition // Trend Surfers Trailing stop line goes below (Crosses) lowest low// Bullish Candle (red)// Mawreeze Trend Oscilator Indicator is green// Short Condition// Trend Surfers Trailing stop line goes above (Crosses) highest high// Bearish Candle (red)// Mawreeze Trend Oscilator Indicator is red// Stop loss middle between high and low Risk 1:2//@version=5//strategy(shorttitle='Trend Surfers - Breakout', title='Trend Surfers - Premium Breakout', overlay=true, calc_on_every_tick=false, initial_capital=100000, default_qty_type=strategy.percent_of_equity, default_qty_value=100, commission_type='percent', commission_value=0.04)// Risk for position and pyramidmaxriskval = input.float(2, 'Max % risk', tooltip='Risk % over total equity / Position', group='Risk Management')pairnumber = input.int(title='How many pairs', defval=1, tooltip='How many pairs are you trading with the strategy?', group='Risk Management')// Emtry ExithighPeriod = input.int(title='Highest High Period', defval=168, tooltip='Highest High of X bars - This will trigger a Long Entry when close is above. (Thin Green Line)', group='Entry Condition')lowPeriod = input.int(title='Lowest Low Period', defval=168, tooltip='Lowest low of X bars - This will trigger a Short Entry when close is under. (Thin Red Line)', group='Entry Condition')// StoplosstrailingAtrPeriod = input.int(title='Trailing ATR Pediod', defval=10, tooltip='Average True Range for the Trailing Stop. (Thick Green Line) ', group='Exit Condition')trailingAtrMultiplier = input.float(title='Trailing ATR Multiplier', defval=8, group='Exit Condition')fixAtrPeriod = input.int(title='Fix ATR Pediod', defval=10, tooltip='Average True Range for the Fix Stoloss. (Thick Yellow Line)', group='Exit Condition')fixAtrMultiplier = input.float(title='Fix ATR Multiplier', defval=2, group='Exit Condition')// Pair info pair = syminfo.basecurrency + syminfo.currency// High Low VariablehighestHigh = ta.highest(high, highPeriod)[1]lowestLow = ta.lowest(low, lowPeriod)[1]trailingAtr = ta.atr(trailingAtrPeriod) * trailingAtrMultiplier// Trade ConditionlongConditionTrendSurfers = ta.crossover(close, highestHigh)shortConditionTrendSurfers = ta.crossunder(close, lowestLow)// Risk VariablefixAtr = ta.atr(fixAtrPeriod) * fixAtrMultiplierstopvaluelong = close[1] - fixAtr[1]stopvalueshort = close[1] + fixAtr[1]// Position size Longmaxpossize = strategy.equity / closepositionsizelong = maxriskval / 100 * strategy.equity / (close - stopvaluelong)stopperclong = (close - stopvaluelong) / close * 100leveragelong = math.max(1, math.ceil(positionsizelong / maxpossize)) * 2posperclong = positionsizelong * close / strategy.equity * 100 / leveragelong / pairnumberrealposlong = posperclong / 100 * strategy.equity * leveragelong / close// Position size Shortpositionsizeshort = maxriskval / 100 * strategy.equity / (stopvalueshort - close)stoppercshort = (close - stopvalueshort) / close * 100leverageshort = math.max(1, math.ceil(positionsizeshort / maxpossize)) * 2pospercshort = positionsizeshort * close / strategy.equity * 100 / leverageshort / pairnumberrealposshort = pospercshort / 100 * strategy.equity * leverageshort / close// Alert Messageentry_long_message = '\nGo Long for ' + pair + 'NOW!' + '\nPosition Size % =' + str.tostring(posperclong) + '\nLeverage' + str.tostring(leveragelong) + '\nStoploss Price =' + str.tostring(stopvaluelong) + '\nClose any Short position that are open for ' + pair + '!' + '\n\nVisit TrendSurfersSignals.com' + '\nFor automated premium signals (FREE)'entry_short_message = '\nGo Short for ' + pair + 'NOW!' + '\nPosition Size % =' + str.tostring(pospercshort) + '\nLeverage' + str.tostring(leverageshort) + '\nStoploss Price =' + str.tostring(stopvalueshort) + '\nClose any Long position that are open for ' + pair + '!' + '\n\nVisit TrendSurfersSignals.com' + '\nFor automated premium signals (FREE)'exit_short_message = '\nExit Short for ' + pair + 'NOW!' + '\n\nVisit TrendSurfersSignals.com' + '\nFor automated premium signals (FREE)'exit_long_message = '\nExit Long for ' + pair + 'NOW!' + '\n\nVisit TrendSurfersSignals.com' + '\nFor automated premium signals (FREE)'// Order// if longCondition//     strategy.entry('Long', strategy.long, stop=highestHigh, comment='Long', qty=realposlong, alert_message=entry_long_message)// if shortCondition//     strategy.entry('Short', strategy.short, stop=lowestLow, comment='Short', qty=realposshort, alert_message=entry_short_message)// Stoploss TrailinglongTrailing = close - trailingAtrshortTrailing = close + trailingAtrvar longTrailingStop = 0.0var shortTrailingStop = 999999.9trailingStopLine = 0.0trailingStopLine := nafixedStopLine = 0.0fixedStopLine := navar inTrade = 0if longConditionTrendSurfers or shortConditionTrendSurfers    if 0 == inTrade        if longConditionTrendSurfers            inTrade := 1            inTrade        else            inTrade := -1            inTradeif 1 == inTrade and (shortConditionTrendSurfers or low <= math.max(fixedStopLine[1], longTrailingStop))    inTrade := 0    inTradeif -1 == inTrade and (longConditionTrendSurfers or high >= math.min(fixedStopLine[1], shortTrailingStop))    inTrade := 0    inTradelongTrailingStop := if 1 == inTrade    stopValue = longTrailing    math.max(stopValue, longTrailingStop[1])else    0shortTrailingStop := if -1 == inTrade    stopValue = shortTrailing    math.min(stopValue, shortTrailingStop[1])else    999999// Fix StoplossfirstPrice = 0.0firstFixAtr = 0.0firstPrice := nafirstFixAtr := naif 0 != inTrade    firstPrice := ta.valuewhen(inTrade != inTrade[1] and 0 != inTrade, close, 0)    firstFixAtr := ta.valuewhen(inTrade != inTrade[1] and 0 != inTrade, fixAtr, 0)    if 1 == inTrade        fixedStopLine := firstPrice - firstFixAtr        trailingStopLine := longTrailingStop        trailingStopLine    else        fixedStopLine := firstPrice + firstFixAtr        trailingStopLine := shortTrailingStop        trailingStopLine// if strategy.position_size > 0//     strategy.exit(id='L Stop', stop=math.max(fixedStopLine, longTrailingStop), alert_message=exit_long_message)// if strategy.position_size < 0//     strategy.exit(id='S Stop', stop=math.min(fixedStopLine, shortTrailingStop), alert_message=exit_short_message)// Plotplot(highestHigh, color=color.new(color.green, 0), linewidth=1, title='Highest High')plot(lowestLow, color=color.new(color.red, 0), linewidth=1, title='Lowest Low')plot(trailingStopLine, color=color.new(color.lime, 0), linewidth=2, offset=1, title='Trailing Stop')plot(fixedStopLine, color=color.new(color.orange, 0), linewidth=2, offset=1, title='Fixed Stop')// Trend Surfers Trailing stop line goes above (Crossesover) highest high// Bearish Candle (red)// Mawreeze Trend Oscilator Indicator is redtrendSurfersShortEntry = trailingStopLine > highestHigh and close < close[1]trendSurfersLongEntry = trailingStopLine < lowestLow and close > close[1]//@version=5// Taken from the TradingView house rules regarding scripts:// "All open source scripts that do not mention a specific open source license// in their comments are licensed under the Mozilla Public License 2.0.// Following the Mozilla License, any script reusing open source code originally// published by someone else must also be open source, unless specific// permission is granted by the original author."//indicator('Mawreez\' Trend Oscillator', precision=3)len = input.int(title='DI Length', minval=1, defval=14)sens = input.float(title='Sensitivity', defval=25)// Lag-free smoothing of a given seriessmooth(series, len) =>    f28 = ta.ema(series, len)    f30 = ta.ema(f28, len)    vC = f28 * 1.5 - f30 * 0.5    f38 = ta.ema(vC, len)    f40 = ta.ema(f38, len)    v10 = f38 * 1.5 - f40 * 0.5    f48 = ta.ema(v10, len)    f50 = ta.ema(f48, len)    f48 * 1.5 - f50 * 0.5// Constructing the +DI and -DIup = ta.change(high)down = -ta.change(low)plus_dm = up > 0 and up > down ? up : 0minus_dm = down > 0 and down > up ? down : 0range_1 = ta.rma(ta.tr, len)plus_di = smooth(ta.rma(plus_dm, len) / range_1, 3)minus_di = smooth(ta.rma(minus_dm, len) / range_1, 3)// Constructing and plotting the modified ADXadj_adx = 100 * math.abs(plus_di - minus_di) / (plus_di + minus_di) - sensadj_adx := (minus_di > plus_di ? -1 : 1) * (adj_adx < 0 ? 0 : adj_adx)//plot(smooth(adj_adx, 3), color=plus_di > minus_di ? color.green : color.red, style=plot.style_columns)trendOscShortEntry = plus_di < minus_ditrendOscLongEntry = plus_di > minus_di////////////////////////////////////////* Put your strategy rules below *///////////////////////////////////////longCondition = trendSurfersLongEntry and trendOscLongEntryshortCondition = trendSurfersShortEntry and trendOscShortEntry//define as 0 if do not want to usecloseLongCondition = 0closeShortCondition = 0// 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)