Zeal Terminal Open in Zeal Terminal

Pine Script v5 · Strategy

Strategy Myth-Busting #20 - HalfTrend+HullButterfly - [MYN]

A Pine Script v5 strategy built on Cross (hso, cmean), CUM (hso) and ATR (100). It has 10 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 1.0% of equity and pays 0.075 commission. 39 settings; defaults include Length 11, Levels Multiplier 2. and Src close.

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 #20 - HalfTrend+HullButterfly - [MYN] repaint?
Yes
At least one pattern in the source can repaint: intrabar recalculation.
How did Strategy Myth-Busting #20 - HalfTrend+HullButterfly - [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, so there is no result to report. Its code limits trading to a date window, which can leave this period out. On ETHUSDT 1D it did trade; that row of the markets table below has its figures. A backtest, not investment advice.
What alerts does Strategy Myth-Busting #20 - HalfTrend+HullButterfly - [MYN] have?
4
Alert: HalfTrend Buy; Alert: HalfTrend Sell; alertSyntaxBase + 'side:long'; alertSyntaxBase + 'side:short'.
Does Strategy Myth-Busting #20 - HalfTrend+HullButterfly - [MYN] run in Pine Script v6?
No
The v6 version does not run in Zeal Terminal's engine: Pine Script v6 Error at @L291: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 #20 - HalfTrend+HullButterfly - [MYN] use a stop loss?
No
Its exits set a profit target but no stop.

BTCUSDT · 1D · default settings

  • Arrow Up
  • Arrow Down
  • HalfTrend
  • Arrow Up
  • Arrow Down
  • 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 (35)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$10,000$20,253Equity from $10,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. 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: NaN
End: NaN
Net Profit: 0%
Percent Per Day NaN%
Percent Profitable: NaN%
Profit Factor: NaN
Total Trades: 0
Max Wins In A Row: 0
Max Losses In A Row: 0
Net profit
0.00%
$0.00
Buy and hold
+102.5%
same period
Closed trades
0
0 won · 0 lost
Profitable
0.0%
of closed trades
Profit factor
—
gross profit ÷ gross loss
Max drawdown
0.00%
$0.00

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

  • Note

    4 settings have no label

    In the settings dialog length (line 16), src (line 18), i_startPeriodTime (line 214), i_endPeriodTime (line 216) 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 286, 287, 289, 290. 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
Hull Butterfly Oscillator
Length (no label in the script)11intshort_len hull_len den2 sum2 line 47
Levels Multiplier2.floatcmean
Src (no label in the script)closesourcehma inv_hma
Channel Deviation2intdev
Show ArrowstrueboolArrow Up Arrow Down
Show ChannelsfalseboolATR High ATR Low
Style
Bullish Gradientcolor.new(#0cb51a, 50)colorcss0
Bull css 1 (no label in the script)#0cb51acolorcss0
Bearish Gradientcolor.new(#ff1100, 50)colorcss1
Bear css 1 (no label in the script)#ff1100colorcss1
HalfTrend
Amplitude2inthighPrice lowPrice highma lowma
Global
Max Number Of Bars Between Hull and HalfTrend Trigger3intlongCondition shortCondition
EMA Filter
Enable EMA FilterEnable if you would like to conditionally have entries incorporate EMA as a filter where source is above/below the EMA linefalseboolemaValue isEMAFilterEnabledAndCloseAboveMA isEMAFilterEnabledAndCloseBelowMA
EMA Length200int · min 1emaValue
EMA SourceclosesourceemaValue isEMAFilterEnabledAndCloseAboveMA isEMAFilterEnabledAndCloseBelowMA
ADX Filter
Enable ADX FilterEnable if you would like to conditionally have entries incorporate ADX as a filterfalsebooladx isADXFilterEnabledAndAboveThreshold
ADX VariantORIGINALstring · options ['ORIGINAL', 'MASANAKAMURA']adx
ADX Smoothing14intDIPlusO DIMinusO ADXO
DI Length14intDIPlusO DIMinusO ADXO DIPlusM DIMinusM ADXM
ADX Threshold25float · step .5isADXFilterEnabledAndAboveThreshold
Date Range
StarttrueboolisStartPeriodEnabledAndInRange
I start Period Time (no label in the script)timestamp('1 Jan 2019')timeisStartPeriodEnabledAndInRange
EndtrueboolisEndPeriodEnabledAndInRange
I end Period Time (no label in the script)timestamp('31 Dec 2030')timeisEndPeriodEnabledAndInRange
Time Window
Enable Time-Of-Day WindowLimit the time of day for trade executionfalseboolisTimeFilterEnabledAndInRange
Select Local Time ZoneGMT-5string · options ["GMT-8","GMT-7", "GMT-6", "GMT-5", "GMT-4", "GMT-3", "GMT-2", "GMT-1", "GMT", "GMT+1", "GMT+2", "GMT+3","GMT+4","GMT+5","GMT+6","GMT+7","GMT+8","GMT+9","GMT+10","GMT+11","GMT+12","GMT+13"]currentTimeIsWithinWindowOfTime
Time Filter0700-0900sessionisTimeFilterEnabledAndInRange
Trade Direction
Trade DirectionLong and Shortstring · options ['Long and Short', 'Long Only', 'Short Only']entry Long entry Short line 273 line 276
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 i_takeProfitTargetPercent4
Stop Loss
Stop Loss (%)999float · min 0.01 · step 0.5slLongClose slShortClose
Leverage
Leverage1float · step .5contracts
ProfitView Alert Syntax
Alert Syntax PrefixCRYPTANEX_99FTX_Strategy-Name-HerestringalertSyntaxBase
Dashboard
Show Dashboardtrueboolline 299

What it calculates

  • Crosshso, cmeanos · line 77
  • CUMmath.abs(hso)cmean · line 76
  • ATR100atr2 · line 109
  • HighestbarsAmplitude (2)highPrice · line 111
  • LowestbarsAmplitude (2)lowPrice · line 112
  • SMAhigh, Amplitude (2)highma · line 113
  • SMAlow, Amplitude (2)lowma · line 114
  • EMAEMA Source (close), EMA Length (200)emaValue · line 182
  • DMIDI Length (14), ADX Smoothing (14)DIPlusO · line 207
  • DMIDI Length (14), ADX Smoothing (14)DIMinusO · line 207
  • DMIDI Length (14), ADX Smoothing (14)ADXO · line 207

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 i_tradeDirection != 'Short Only' and isInLongPosition == falseOn274
Open Short shortshortConditionCalc and i_tradeDirection != 'Long Only' and isInShortPosition == falseOn277
Exit TP1 limitisStartEndPeriodsAndTimeInRangeOn281
Exit TP2 limitisStartEndPeriodsAndTimeInRangeOn282
Exit TP3 limitisStartEndPeriodsAndTimeInRangeOn283
Exit i_takeProfitTargetPercent4 limitisStartEndPeriodsAndTimeInRangeOn284
Close LongslLongCloseclose < strategy.position_avg_price * (1 - i_stopLossPercent)On286
Close ShortslShortCloseclose > strategy.position_avg_price * (1 + i_stopLossPercent)On287
Close LongcloseLongConditionOn289
Close ShortcloseShortConditionOn290

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

Alerts

AlertCallMessageLine
Alert: HalfTrend BuyalertconditionHalfTrend Buy164
Alert: HalfTrend SellalertconditionHalfTrend Sell165
(no title)alertalertSyntaxBase + 'side:long'275
(no title)alertalertSyntaxBase + 'side:short'278

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 1D0.0%+102.5%00%—0.0%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h0.0%+5.5%00%—0.0%8 May 2026 – 21 Oct 2026
ETHUSDT 1D−12.1%+9.8%10%0.0022.8%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h0.0%+8.4%00%—0.0%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−43.9%+16.7%10%0.0085.7%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h−3.7%+21.5%10%0.0014.6%8 May 2026 – 21 Oct 2026
BNBUSDT 1D+132.2%+148.3%2100%—10.0%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h−0.1%+17.1%00%0.0015.2%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 #20 - HalfTrend+HullButterfly - [MYN] this page—v5 strategy0.0%00.0%
Moving Average Crossover Strategy by Decam9sma ema atr crossv5 strategy+0.0%754.3%
X48 - Strategy - BreakOut & Consecutive (11in1) + Alert - V.1.2 by X4815162342sma ema atr cross highestbars lowestbarsv5 strategydoes not run in Zeal Terminal

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.

  • 4 strategy calls use the when = argument (line 286, 287, 289, 290). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
  • 8 settings use the untyped input() (line 16, 17, 18, 95, 96, 97, 98, 171). 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 1 trades and the same P&L on ETHUSDT 1D, 1,000 bars, in Zeal Terminal's engine.

  • Line 16: input() → input.int()
  • Line 17: input() → input.float()
  • Line 18: input() → input.source()
  • Line 95: input() → input.int()
  • Line 96: input() → input.int()
  • Line 97: input() → input.bool()
6 more edits
  • Line 98: input() → input.bool()
  • Line 171: input() → input.int()
  • Line 286: when = slLongClose → if block
  • Line 287: when = slShortClose → if block
  • Line 289: when = closeLongCondition → if block
  • Line 290: when = closeShortCondition → if block
⋯//----------------------------------------------------a-------------------------{-length = input(11, group="Hull Butterfly Oscillator")+length = input.int(11, group="Hull Butterfly Oscillator")-mult = input(2., 'Levels Multiplier')+mult = input.float(2., 'Levels Multiplier')-src = input(close)+src = input.source(close)//Style⋯// Copyright (c) 2021-present, Alex Orekhov (everget)-amplitude = input(title='Amplitude', defval=2, group="HalfTrend")+amplitude = input.int(title='Amplitude', defval=2, group="HalfTrend")-channelDeviation = input(title='Channel Deviation', defval=2)+channelDeviation = input.int(title='Channel Deviation', defval=2)-showArrows = input(title='Show Arrows', defval=true)+showArrows = input.bool(title='Show Arrows', defval=true)-showChannels = input(title='Show Channels', defval=false)+showChannels = input.bool(title='Show Channels', defval=false)var int trend = 0⋯/////////////////////////////////////-i_numLookbackBarsHull = input(3,title="Max Number Of Bars Between Hull and HalfTrend Trigger", group="Global")+i_numLookbackBarsHull = input.int(3,title="Max Number Of Bars Between Hull and HalfTrend Trigger", group="Global")longCondition = halfTrendLongEntry and ta.barssince(hullLongEntry) <= i_numLookbackBarsHull ⋯    // Stop Loss-    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')    // Conditional Closes-    strategy.close('Long', qty_percent=100, comment='Close Long', when=closeLongCondition)+    if closeLongCondition+        strategy.close('Long', qty_percent=100, comment='Close Long')-    strategy.close('Short', qty_percent=100, comment='Close Short', when=closeShortCondition)+    if closeShortCondition+        strategy.close('Short', qty_percent=100, comment='Close Short')/// 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 @L291: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 #20 - HalfTrend+HullButterfly - [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=10000, currency='NONE', default_qty_type=strategy.percent_of_equity, default_qty_value=1.0, commission_value=0.075, use_bar_magnifier = false)⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 196 msWith a workaround 1,000 bars in 363 msNot measured
PineTSNot testedNot testedNot measured

The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market.

“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report.

Source

Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © myn//@version=5strategy('Strategy Myth-Busting #20 - HalfTrend+HullButterfly - [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=10000, currency='NONE', default_qty_type=strategy.percent_of_equity, default_qty_value=1.0, commission_value=0.075, use_bar_magnifier = false)///////////////////////////////////////* Put your strategy logic below *///////////////////////////////////////// Hull Butterfly gives us green column,  Wait for HalfTrend to present an up arrow and enter trade.// Hull Butterfly gives us a red column , Wait for HalfTrend present a down arrow and enter trade.  // SL at swing high/low with TP 1.5 risk// Hull Butterfly Oscillator [LuxAlgo]//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░//-----------------------------------------------------------------------------}//Settings//----------------------------------------------------a-------------------------{length = input(11, group="Hull Butterfly Oscillator")mult = input(2., 'Levels Multiplier')src = input(close)//Stylebull_css_0 = input.color(color.new(#0cb51a, 50), 'Bullish Gradient'  , inline = 'inline0'  , group = 'Style')bull_css_1 = input.color(#0cb51a, ''  , inline = 'inline0'  , group = 'Style')bear_css_0 = input.color(color.new(#ff1100, 50), 'Bearish Gradient'  , inline = 'inline1'  , group = 'Style')bear_css_1 = input.color(#ff1100, ''  , inline = 'inline1'  , group = 'Style')//-----------------------------------------------------------------------------}//Normalization variables//-----------------------------------------------------------------------------{var short_len = int(length / 2)var hull_len = int(math.sqrt(length))var den1 = short_len * (short_len + 1) / 2var den2 = length * (length + 1) / 2var den3 = hull_len * (hull_len + 1) / 2//-----------------------------------------------------------------------------}//Hull coefficients//-----------------------------------------------------------------------------{var lcwa_coeffs = array.new_float(hull_len, 0)var hull_coeffs = array.new_float(0)if barstate.isfirst    //Linearly combined WMA coeffs    for i = 0 to length-1        sum1 = math.max(short_len - i, 0)        sum2 = length - i            array.unshift(lcwa_coeffs, 2 * (sum1 / den1) - (sum2 / den2))        //Zero padding of linearly combined WMA coeffs    for i = 0 to hull_len-2        array.unshift(lcwa_coeffs, 0)        //WMA convolution of linearly combined WMA coeffs    for i = hull_len to array.size(lcwa_coeffs)-1        sum3 = 0.        for j = i-hull_len to i-1            sum3 += array.get(lcwa_coeffs, j) * (i - j)                array.unshift(hull_coeffs, sum3 / den3)//-----------------------------------------------------------------------------}//Hull squeeze oscillator//-----------------------------------------------------------------------------{var os  = 0var len = array.size(hull_coeffs)-1hma     = 0.inv_hma = 0.for i = 0 to len    hma += src[i] * array.get(hull_coeffs, i)    inv_hma += src[len-i] * array.get(hull_coeffs, i)    hso = hma - inv_hmacmean = ta.cum(math.abs(hso)) / bar_index * multos := ta.cross(hso, cmean) or ta.cross(hso, -cmean) ? 0  : hso < hso[1] and hso > cmean ? -1  : hso > hso[1] and hso < -cmean ? 1  : os//-----------------------------------------------------------------------------}//Plot//-----------------------------------------------------------------------------{//Colorscss0 = color.from_gradient(hso, 0, cmean, bull_css_0, bull_css_1)css1 = color.from_gradient(hso, -cmean, 0, bear_css_1, bear_css_0)css = hso > 0 ? css0 : css1plotshape(os > os[1] and os == 1 , title='Arrow Up', style=shape.circle, location=location.belowbar, size=size.tiny, color=color.new(color.green, 0))plotshape(os < os[1] and os == -1, title='Arrow Down', style=shape.circle, location=location.abovebar, size=size.tiny, color=color.new(color.red, 0))hullLongEntry = os > os[1] and os == 1 hullShortEntry = os < os[1] and os == -1// HalfTrend - Everget//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░// Copyright (c) 2021-present, Alex Orekhov (everget)amplitude = input(title='Amplitude', defval=2, group="HalfTrend")channelDeviation = input(title='Channel Deviation', defval=2)showArrows = input(title='Show Arrows', defval=true)showChannels = input(title='Show Channels', defval=false)var int trend = 0var int nextTrend = 0var float maxLowPrice = nz(low[1], low)var float minHighPrice = nz(high[1], high)var float up = 0.0var float down = 0.0float atrHigh = 0.0float atrLow = 0.0float arrowUp = nafloat arrowDown = naatr2 = ta.atr(100) / 2dev = channelDeviation * atr2highPrice = high[math.abs(ta.highestbars(amplitude))]lowPrice = low[math.abs(ta.lowestbars(amplitude))]highma = ta.sma(high, amplitude)lowma = ta.sma(low, amplitude)if nextTrend == 1    maxLowPrice := math.max(lowPrice, maxLowPrice)    if highma < maxLowPrice and close < nz(low[1], low)        trend := 1        nextTrend := 0        minHighPrice := highPrice        minHighPriceelse    minHighPrice := math.min(highPrice, minHighPrice)    if lowma > minHighPrice and close > nz(high[1], high)        trend := 0        nextTrend := 1        maxLowPrice := lowPrice        maxLowPriceif trend == 0    if not na(trend[1]) and trend[1] != 0        up := na(down[1]) ? down : down[1]        arrowUp := up - atr2        arrowUp    else        up := na(up[1]) ? maxLowPrice : math.max(maxLowPrice, up[1])        up    atrHigh := up + dev    atrLow := up - dev    atrLowelse    if not na(trend[1]) and trend[1] != 1        down := na(up[1]) ? up : up[1]        arrowDown := down + atr2        arrowDown    else        down := na(down[1]) ? minHighPrice : math.min(minHighPrice, down[1])        down    atrHigh := down + dev    atrLow := down - dev    atrLowht = trend == 0 ? up : downvar color buyColor = color.bluevar color sellColor = color.redhtColor = trend == 0 ? buyColor : sellColorhtPlot = plot(ht, title='HalfTrend', linewidth=2, color=htColor)atrHighPlot = plot(showChannels ? atrHigh : na, title='ATR High', style=plot.style_circles, color=color.new(sellColor, 0))atrLowPlot = plot(showChannels ? atrLow : na, title='ATR Low', style=plot.style_circles, color=color.new(buyColor, 0))fill(htPlot, atrHighPlot, title='ATR High Ribbon', color=color.new(sellColor, 90))fill(htPlot, atrLowPlot, title='ATR Low Ribbon', color=color.new(buyColor, 90))buySignal = not na(arrowUp) and trend == 0 and trend[1] == 1sellSignal = not na(arrowDown) and trend == 1 and trend[1] == 0plotshape(showArrows and buySignal ? atrLow : na, title='Arrow Up', style=shape.triangleup, location=location.absolute, size=size.tiny, color=color.new(buyColor, 0))plotshape(showArrows and sellSignal ? atrHigh : na, title='Arrow Down', style=shape.triangledown, location=location.absolute, size=size.tiny, color=color.new(sellColor, 0))alertcondition(buySignal, title='Alert: HalfTrend Buy', message='HalfTrend Buy')alertcondition(sellSignal, title='Alert: HalfTrend Sell', message='HalfTrend Sell')halfTrendLongEntry =  buySignalhalfTrendShortEntry = sellSignal////////////////////////////////////////* Put your strategy rules below *///////////////////////////////////////i_numLookbackBarsHull = input(3,title="Max Number Of Bars Between Hull and HalfTrend Trigger", group="Global")longCondition = halfTrendLongEntry and ta.barssince(hullLongEntry) <= i_numLookbackBarsHull shortCondition = halfTrendShortEntry and ta.barssince(hullShortEntry) <= i_numLookbackBarsHull //define as 0 if do not want to usecloseLongCondition = 0closeShortCondition = 0// EMA Filter//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░i_emaFilterEnabled = input.bool(defval = false , title = "Enable EMA Filter", tooltip = "Enable if you would like to conditionally have entries incorporate EMA as a filter where source is above/below the EMA line", group ="EMA Filter" ) i_emaLength = input.int(200, title="EMA Length", minval=1, group ="EMA Filter")i_emaSource = input.source(close,"EMA Source" , group ="EMA Filter")emaValue = i_emaFilterEnabled ? ta.ema(i_emaSource, i_emaLength) : nabool isEMAFilterEnabledAndCloseAboveMA = i_emaFilterEnabled ? i_emaSource > emaValue : truebool isEMAFilterEnabledAndCloseBelowMA = i_emaFilterEnabled ? i_emaSource < emaValue : true// ADX Filter//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░i_adxFilterEnabled = input.bool(defval = false , title = "Enable ADX Filter", tooltip = "Enable if you would like to conditionally have entries incorporate ADX as a filter", group ="ADX Filter" ) i_adxVariant = input.string('ORIGINAL', title='ADX Variant', options=['ORIGINAL', 'MASANAKAMURA'], group ="ADX Filter" )i_adxSmoothing = input.int(14, title="ADX Smoothing", group="ADX Filter")i_adxDILength = input.int(14, title="DI Length", group="ADX Filter")i_adxLowerThreshold = input.float(25, title="ADX Threshold", step=.5, group="ADX Filter")calcADX_Masanakamura(int _len) =>    _smoothedTrueRange = 0.0    _smoothedDirectionalMovementPlus = 0.0    _smoothed_directionalMovementMinus = 0.0    _trueRange = math.max(math.max(high - low, math.abs(high - nz(close[1]))), math.abs(low - nz(close[1])))    _directionalMovementPlus = high - nz(high[1]) > nz(low[1]) - low ? math.max(high - nz(high[1]), 0) : 0    _directionalMovementMinus = nz(low[1]) - low > high - nz(high[1]) ? math.max(nz(low[1]) - low, 0) : 0    _smoothedTrueRange := nz(_smoothedTrueRange[1]) - nz(_smoothedTrueRange[1]) / _len + _trueRange    _smoothedDirectionalMovementPlus := nz(_smoothedDirectionalMovementPlus[1]) - nz(_smoothedDirectionalMovementPlus[1]) / _len + _directionalMovementPlus    _smoothed_directionalMovementMinus := nz(_smoothed_directionalMovementMinus[1]) - nz(_smoothed_directionalMovementMinus[1]) / _len + _directionalMovementMinus    DIP = _smoothedDirectionalMovementPlus / _smoothedTrueRange * 100    DIM = _smoothed_directionalMovementMinus / _smoothedTrueRange * 100    _DX = math.abs(DIP - DIM) / (DIP + DIM) * 100    adx = ta.sma(_DX, _len)    [DIP, DIM, adx][DIPlusO, DIMinusO, ADXO] = ta.dmi(i_adxDILength, i_adxSmoothing)[DIPlusM, DIMinusM, ADXM] = calcADX_Masanakamura(i_adxDILength)adx = i_adxFilterEnabled and i_adxVariant == "ORIGINAL" ? ADXO : ADXMbool isADXFilterEnabledAndAboveThreshold = i_adxFilterEnabled ? adx > i_adxLowerThreshold : true///Start / End Time Periods//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░i_startPeriodEnabled = input.bool(true, 'Start', group='Date Range', inline='Start Period')i_startPeriodTime = input.time(timestamp('1 Jan 2019'), '', group='Date Range', inline='Start Period')i_endPeriodEnabled = input.bool(true, 'End', group='Date Range', inline='End Period')i_endPeriodTime = input.time(timestamp('31 Dec 2030'), '', group='Date Range', inline='End Period')isStartPeriodEnabledAndInRange = i_startPeriodEnabled ? i_startPeriodTime <= time : trueisEndPeriodEnabledAndInRange = i_endPeriodEnabled ? i_endPeriodTime >= time : true// Time-Of-Day Window// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░// Inspired from https://www.tradingview.com/script/3BmID7aW-Highlight-Trading-Window-Simple-Hours-Time-of-Day-Filter/i_timeFilterEnabled = input.bool(defval = false , title = "Enable Time-Of-Day Window", tooltip = "Limit the time of day for trade execution", group ="Time Window" ) i_timeZone = input.string(title="Select Local Time Zone", defval="GMT-5", options=["GMT-8","GMT-7", "GMT-6", "GMT-5", "GMT-4", "GMT-3", "GMT-2", "GMT-1", "GMT", "GMT+1", "GMT+2",  "GMT+3","GMT+4","GMT+5","GMT+6","GMT+7","GMT+8","GMT+9","GMT+10","GMT+11","GMT+12","GMT+13"], group="Time Window")i_betweenTime = input.session('0700-0900',  title = "Time Filter", group="Time Window")   // '0000-0000' is anytime to enterisWithinWindowOfTime(_position) =>                                                          currentTimeIsWithinWindowOfTime = not na(time(timeframe.period, _position + ':1234567', i_timeZone))bool isTimeFilterEnabledAndInRange = i_timeFilterEnabled ? isWithinWindowOfTime(i_betweenTime) : trueisStartEndPeriodsAndTimeInRange = isStartPeriodEnabledAndInRange and isEndPeriodEnabledAndInRange and isTimeFilterEnabledAndInRange// Trade Direction // ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░i_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// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░i_takeProfitTargetPercent1 = input.float(title='Take Profit 1 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 1')i_takeProfitQuantityPercent1 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 1')// Take profit 2// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░i_takeProfitTargetPercent2 = input.float(title='Take Profit 2 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 2')i_takeProfitQuantityPercent2 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 2')// Take profit 3// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░i_takeProfitTargetPercent3 = input.float(title='Take Profit 3 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 3')i_takeProfitQuantityPercent3 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 3')// Take profit 4// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░i_takeProfitTargetPercent4 = input.float(title='Take Profit 4 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit')/// Stop Loss// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░i_stopLossPercent = input.float(title='Stop Loss (%)', defval=999, minval=0.01, step=0.5, group='Stop Loss') * 0.01slLongClose = close < strategy.position_avg_price * (1 - i_stopLossPercent)slShortClose = close > strategy.position_avg_price * (1 + i_stopLossPercent)/// Leverage// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░i_leverage = input.float(1, 'Leverage', step=.5, group='Leverage')contracts = math.min(math.max(.000001, strategy.equity / close * i_leverage), 1000000000)/// Trade State Management// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░isInLongPosition = strategy.position_size > 0isInShortPosition = strategy.position_size < 0/// ProfitView Alert Syntax String Generation// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░i_alertSyntaxPrefix = input.string(defval='CRYPTANEX_99FTX_Strategy-Name-Here', title='Alert Syntax Prefix', group='ProfitView Alert Syntax')alertSyntaxBase = i_alertSyntaxPrefix + '\n#' + str.tostring(open) + ',' + str.tostring(high) + ',' + str.tostring(low) + ',' + str.tostring(close) + ',' + str.tostring(volume) + ','/// Trade Execution// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░longConditionCalc = (longCondition and isADXFilterEnabledAndAboveThreshold and isEMAFilterEnabledAndCloseAboveMA)shortConditionCalc = (shortCondition and isADXFilterEnabledAndAboveThreshold and isEMAFilterEnabledAndCloseBelowMA)if isStartEndPeriodsAndTimeInRange    if longConditionCalc and i_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 i_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=i_takeProfitQuantityPercent1, profit=per(i_takeProfitTargetPercent1))    strategy.exit('TP2', qty_percent=i_takeProfitQuantityPercent2, profit=per(i_takeProfitTargetPercent2))    strategy.exit('TP3', qty_percent=i_takeProfitQuantityPercent3, profit=per(i_takeProfitTargetPercent3))    strategy.exit('i_takeProfitTargetPercent4', profit=per(i_takeProfitTargetPercent4))    // Stop Loss    strategy.close('Long', qty_percent=100, comment='SL Long', when=slLongClose)    strategy.close('Short', qty_percent=100, comment='SL Short', when=slShortClose)    // Conditional Closes    strategy.close('Long', qty_percent=100, comment='Close Long', when=closeLongCondition)    strategy.close('Short', qty_percent=100, comment='Close Short', when=closeShortCondition)/// 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)