Zeal Terminal Open in Zeal Terminal

Pine Script v4 · Strategy

AlignedMA and Cumulative HighLow Strategy V2

A Pine Script v4 strategy built on SMA or EMA or HMA or RMA or VWMA or WMA (source, length), ATR (22) and Supertrend (3, 22). It has 6 order rules, 2 entries among them, and trades long and short with the default settings. Exits use a stop loss. Each trade commits 100% of equity and pays 0.01% commission. 15 settings; defaults include Moving Average Type hma, High Low Period 22 and Lookback Period 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 AlignedMA and Cumulative HighLow Strategy V2 repaint?
No
No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 5 of 5 trades.
How did AlignedMA and Cumulative HighLow Strategy V2 do on BTCUSDT 1D with default settings?
−40.79%
From 26 Jan 2024 to 21 Oct 2026, over 16 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Can AlignedMA and Cumulative HighLow Strategy V2 be converted to Pine Script v5?
Yes
The upgrade takes 1 step, from v4; each was run before and after on the same candles with identical results, and the v5 script can be downloaded below.
Does AlignedMA and Cumulative HighLow Strategy V2 use a stop loss?
Yes
strategy.exit sets a stop on line 122, 125.
Does AlignedMA and Cumulative HighLow Strategy V2 run in Zeal Terminal?
Yes
It compiles in 36 ms and runs 1,000 bars in 183 ms, in the browser.

BTCUSDT · 1D · default settings

  • Supertrend
  • MA
  • Shift
  • Winning trade
  • Losing trade
  • Equity
  • Buy and hold
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$754$2,025Equity from $1,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. The live re-run is not offered here: the script requests BINANCE:BTCUSDT 12M, which this page cannot load in your browser.
Net profit
−40.79%
−$407.91
Buy and hold
+102.5%
same period
Closed trades
16
5 won · 11 lost
Profitable
31.3%
of closed trades
Profit factor
0.39
gross profit ÷ gross loss
Max drawdown
50.94%
−$509.42

One run with the author's default settings, $1,000 starting capital, commission as the script sets it. A long position was still open at the last bar. A single backtest says little about future results and is not a recommendation. Backtests are simulations on historical data and are not investment advice.

Review

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

  • Check

    Every trade uses all the equity

    default_qty_value is 100% of equity.

  • Note

    12 settings have no label

    In the settings dialog includePartiallyAligned (line 6), HighLowPeriod (line 7), LookbackPeriod (line 8), considerYearlyHighLow (line 9), dirTBars (line 10), dirRBars (line 11), PMALength (line 13), shift (line 14), supertrendMult (line 16), supertrendLength (line 17), riskReward (line 18), backtestYears (line 20) 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 121, 123, 124, 126. The upgraded version below moves each call inside an if block.

  • Note

    Uses transp =, which v5 removed line 115

    transp = on line 115, 116, 117. v5 folds the transparency into the colour with color.new(c, transp).

Upgrade and export

Written in Pine Script v4. The upgrade to v5 takes 1 step, one per version, each applied to the result of the one before. A last clean-v5 pass then types the settings and moves when = into if blocks, which v6 requires. Every step runs before and after on the same candles in Zeal Terminal's engine; a step whose results differ is shown but not offered as a download. Upgrades preserve behaviour: bugs are fixed in the Review, never silently here.

  • Upgrading to v5 renames sma → ta.sma, ema → ta.ema, hma → ta.hma, rma → ta.rma, vwma → ta.vwma, wma → ta.wma, highest → ta.highest, lowest → ta.lowest, security → request.security, max → math.max, min → math.min, sum → math.sum, atr → ta.atr, supertrend → ta.supertrend.
  • 4 strategy calls use the when = argument (line 121, 123, 124, 126). It is deprecated in v5 and removed in v6, where each call moves inside an if block.

v4 → v5

Verified

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

  • Line 3: //@version=4 → //@version=5
  • Line 22: sma → ta.sma
  • Line 24: ema → ta.ema
  • Line 26: hma → ta.hma
  • Line 28: rma → ta.rma
  • Line 30: vwma → ta.vwma
19 more edits
  • Line 32: wma → ta.wma
  • Line 56: highest → ta.highest
  • Line 57: lowest → ta.lowest
  • Line 70: security → request.security
  • Line 71: security → request.security
  • Line 77: max → math.max
  • Line 77: max → math.max
  • Line 77: min → math.min
  • Line 79: min → math.min
  • Line 79: min → math.min
  • Line 79: max → math.max
  • Line 90: sum → math.sum
  • Line 92: atr → ta.atr
  • Line 94: sum → math.sum
  • Line 97: supertrend → ta.supertrend
  • Line 98: supertrend → ta.supertrend
  • Line 115: transp = 50 → color.new(color.red, 50)
  • Line 116: transp = 50 → color.new(color.green, 50)
  • Line 117: transp = 40 → color.new(bandColor, 40)
⋯// © HeWhoMustNotBeNamed-//@version=4+//@version=5strategy("AlignedMA and Cumulative HighLow Strategy V2", overlay=true, initial_capital = 1000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)⋯f_getMovingAverage(source, MAType, length)=>-    ma = sma(source, length)+    ma = ta.sma(source, length)    if(MAType == "ema")-        ma := ema(source,length)+        ma := ta.ema(source,length)    if(MAType == "hma")-        ma := hma(source,length)+        ma := ta.hma(source,length)    if(MAType == "rma")-        ma := rma(source,length)+        ma := ta.rma(source,length)    if(MAType == "vwma")-        ma := vwma(source,length)+        ma := ta.vwma(source,length)    if(MAType == "wma")-        ma := wma(source,length)+        ma := ta.wma(source,length)    ma⋯f_getHighLowValue(HighLowPeriod)=>-    currentHigh = highest(high,HighLowPeriod) == high+    currentHigh = ta.highest(high,HighLowPeriod) == high-    currentLow = lowest(low,HighLowPeriod) == low+    currentLow = ta.lowest(low,HighLowPeriod) == low    currentHigh?1:currentLow?-1:0⋯f_getYearlyHighLowCondition(considerYearlyHighLow)=>-    yhigh = security(syminfo.tickerid, '12M', high[1]) +    yhigh = request.security(syminfo.tickerid, '12M', high[1]) -    ylow = security(syminfo.tickerid, '12M', low[1]) +    ylow = request.security(syminfo.tickerid, '12M', low[1])     yhighlast = yhigh[365]⋯    -    yearlyTrendUp = na(yhigh)? true : na(yhighlast)? close > yhigh : na(yhighllast)? close > max(yhigh,yhighlast) : close > max(yhigh, min(yhighlast, yhighllast))+    yearlyTrendUp = na(yhigh)? true : na(yhighlast)? close > yhigh : na(yhighllast)? close > math.max(yhigh,yhighlast) : close > math.max(yhigh, math.min(yhighlast, yhighllast))    yearlyHighCondition = (  (na(yhigh) or na(yhighlast) ? true : (yhigh > yhighlast) ) and ( na(yhigh) or na(yhighllast) ? true : (yhigh > yhighllast))) or yearlyTrendUp or not considerYearlyHighLow-    yearlyTrendDown = na(ylow)? true : na(ylowlast)? close < ylow : na(ylowllast)? close < min(ylow,ylowlast) : close < min(ylow, max(ylowlast, ylowllast))+    yearlyTrendDown = na(ylow)? true : na(ylowlast)? close < ylow : na(ylowllast)? close < math.min(ylow,ylowlast) : close < math.min(ylow, math.max(ylowlast, ylowllast))    yearlyLowCondition = (  (na(ylow) or na(ylowlast) ? true : (ylow < ylowlast) ) and ( na(ylow) or na(ylowllast) ? true : (ylow < ylowllast))) or yearlyTrendDown or not considerYearlyHighLow⋯maAlignment = f_getMaAlignment(MAType,includePartiallyAligned)-alignedMaIndex = sum(maAlignment,LookbackPeriod)+alignedMaIndex = math.sum(maAlignment,LookbackPeriod)maAlignmentDirection=f_getDirectionT(alignedMaIndex,dirTBars, dirRBars)-atr = atr(22)+atr = ta.atr(22)highLowIndex = f_getHighLowValue(HighLowPeriod)-cumulativeHighLowIndex = sum(highLowIndex,LookbackPeriod)+cumulativeHighLowIndex = math.sum(highLowIndex,LookbackPeriod)hlDirection = f_getDirectionT(cumulativeHighLowIndex,dirTBars,dirRBars)[yearlyHighCondition,yearlyLowCondition] = f_getYearlyHighLowCondition(considerYearlyHighLow)-[supertrend, dir] = supertrend(supertrendMult, supertrendLength)+[supertrend, dir] = ta.supertrend(supertrendMult, supertrendLength)-[esupertrend, edir] = supertrend(supertrendMult+1, supertrendLength)+[esupertrend, edir] = ta.supertrend(supertrendMult+1, supertrendLength)movingAverage = f_getMovingAverage(close, PMAType, PMALength)⋯sellEntry = sellFilter and secondarySellFilter and not closeSellFilter and low < trailingStop-Fi1 = plot(movingAverage[shift], title="MA", color=color.red, linewidth=1, transp=50)+Fi1 = plot(movingAverage[shift], title="MA", color=color.new(color.red, 50), linewidth=1)-Fi2 = plot(movingAverage, title="Shift", color=color.green, linewidth=1, transp=50)+Fi2 = plot(movingAverage, title="Shift", color=color.new(color.green, 50), linewidth=1)-fill(Fi1, Fi2, title="Band Filler", color=bandColor, transp=40)+fill(Fi1, Fi2, title="Band Filler", color=color.new(bandColor, 40))barcolor(barColor)⋯

Clean v5

VerifiedDownload the v5 script

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

  • Line 5: input() → input.string()
  • Line 6: input() → input.bool()
  • Line 7: input() → input.int()
  • Line 8: input() → input.int()
  • Line 9: input() → input.bool()
  • Line 10: input() → input.int()
12 more edits
  • Line 11: input() → input.int()
  • Line 12: input() → input.string()
  • Line 13: input() → input.int()
  • Line 14: input() → input.int()
  • Line 16: input() → input.int()
  • Line 17: input() → input.int()
  • Line 18: input() → input.int()
  • Line 20: input() → input.int()
  • Line 121: when = buyEntry and inDateRange and (riskFree or strategy.position_size==0) → if block
  • Line 123: when = closeBuyFilter → if block
  • Line 124: when = sellEntry and inDateRange and (riskFree or strategy.position_size==0) → if block
  • Line 126: when = closeSellFilter → if block
⋯strategy("AlignedMA and Cumulative HighLow Strategy V2", overlay=true, initial_capital = 1000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)-MAType = input(title="Moving Average Type", defval="hma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])+MAType = input.string(title="Moving Average Type", defval="hma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])-includePartiallyAligned = input(true)+includePartiallyAligned = input.bool(true)-HighLowPeriod = input(22, minval=1,step=1)+HighLowPeriod = input.int(22, minval=1,step=1)-LookbackPeriod = input(10, minval=1,step=1)+LookbackPeriod = input.int(10, minval=1,step=1)-considerYearlyHighLow = input(false)+considerYearlyHighLow = input.bool(false)-dirTBars = input(1)+dirTBars = input.int(1)-dirRBars = input(30)+dirRBars = input.int(30)-PMAType = input(title="Moving Average Type", defval="ema", options=["ema", "sma", "hma", "rma", "vwma", "wma"])+PMAType = input.string(title="Moving Average Type", defval="ema", options=["ema", "sma", "hma", "rma", "vwma", "wma"])-PMALength = input(10, minval=2, step=10)+PMALength = input.int(10, minval=2, step=10)-shift = input(2, minval=1, step=1)+shift = input.int(2, minval=1, step=1)//Use 2 for ASX stocks-supertrendMult = input(3, minval=1, maxval=10, step=0.5)+supertrendMult = input.int(3, minval=1, maxval=10, step=0.5)-supertrendLength = input(22, minval=1)+supertrendLength = input.int(22, minval=1)-riskReward = input(2, minval=1, maxval=10, step=0.5)+riskReward = input.int(2, minval=1, maxval=10, step=0.5)tradeDirection = input(title="Trade Direction", defval=strategy.direction.all, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])-backtestYears = input(1, minval=1, step=1)+backtestYears = input.int(1, minval=1, step=1)f_getMovingAverage(source, MAType, length)=>⋯strategy.risk.allow_entry_in(tradeDirection)-strategy.entry("Buy", strategy.long, when=buyEntry and inDateRange and (riskFree or strategy.position_size==0), oca_name="oca_buy", oca_type=strategy.oca.none)+if buyEntry and inDateRange and (riskFree or strategy.position_size==0)+    strategy.entry("Buy", strategy.long, oca_name="oca_buy", oca_type=strategy.oca.none)strategy.exit("ExitBuy", "Buy", stop = trailingStop)-strategy.close("Buy", when=closeBuyFilter)+if closeBuyFilter+    strategy.close("Buy")-strategy.entry("Sell", strategy.short, when=sellEntry and inDateRange and (riskFree or strategy.position_size==0), oca_name="oca_sell", oca_type=strategy.oca.none)+if sellEntry and inDateRange and (riskFree or strategy.position_size==0)+    strategy.entry("Sell", strategy.short, oca_name="oca_sell", oca_type=strategy.oca.none)strategy.exit("ExitSell", "Buy", stop = trailingStop)-strategy.close("Sell", when=closeSellFilter)+if closeSellFilter+    strategy.close("Sell")

Does it run in Pine Script v6?

No

The v6 version runs in Zeal Terminal's engine, but its results differ from the v5 version: Trades differ: 16 before, 124 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.

⋯// © HeWhoMustNotBeNamed-//@version=5+//@version=6strategy("AlignedMA and Cumulative HighLow Strategy V2", overlay=true, initial_capital = 1000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)⋯

Settings

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

SettingDefaultType and rangeFeeds
Moving Average Typehmastring · options ["ema", "sma", "hma", "rma", "vwma", "wma"]ma5 ma10 ma20 ma30 ma50 ma100 ma200 openMA closeMA maAlignment line 23 line 25 line 27 line 29 line 31
Include Partially Aligned (no label in the script)trueboolmaAlignment line 54
High Low Period (no label in the script)22int · min 1 · step 1currentHigh currentLow highLowIndex
Lookback Period (no label in the script)10int · min 1 · step 1alignedMaIndex cumulativeHighLowIndex
Consider Yearly High Low (no label in the script)falseboolyearlyHighCondition yearlyLowCondition
Dir TBars (no label in the script)1intmaAlignmentDirection hlDirection
Dir RBars (no label in the script)30intmaAlignmentDirection hlDirection
Moving Average Typeemastring · options ["ema", "sma", "hma", "rma", "vwma", "wma"]movingAverage
PMALength (no label in the script)10int · min 2 · step 10movingAverage
Shift (no label in the script)2int · min 1 · step 1secondaryBuyFilter secondarySellFilter MA
Supertrend Mult (no label in the script)3int · min 1 · max 10 · step 0.5supertrend dir esupertrend edir compound
Supertrend Length (no label in the script)22int · min 1supertrend dir esupertrend edir
Risk Reward (no label in the script)2int · min 1 · max 10 · step 0.5compound
Trade Directionstrategy.direction.allvalue · options [strategy.direction.all, strategy.direction.long, strategy.direction.short]line 120
Backtest Years (no label in the script)1int · min 1 · step 1inDateRange

What it calculates

  • SMA / EMA / HMA / RMA / VWMA / WMA (sma, ta.sma in v5)source, lengthma · line 22
  • ATR (atr, ta.atr in v5)22atr · line 92
  • Supertrend (supertrend, ta.supertrend in v5)Supertrend Mult (3), Supertrend Length (22)supertrend · line 97
  • Supertrend (supertrend, ta.supertrend in v5)Supertrend Mult (3), Supertrend Length (22)dir · line 97
  • Supertrend (supertrend, ta.supertrend in v5)supertrendMult+1, Supertrend Length (22)esupertrend · line 98
  • Supertrend (supertrend, ta.supertrend in v5)supertrendMult+1, Supertrend Length (22)edir · line 98

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

Order rules

OrderFires whenBy defaultLine
Open Buy longbuyEntry and inDateRange and (riskFree or strategy.position_size==0)On121
Exit ExitBuy stopevery barOn122
Close BuycloseBuyFilterdir == 1On123
Open Sell shortsellEntry and inDateRange and (riskFree or strategy.position_size==0)On124
Exit ExitSell stopevery barOn125
Close SellcloseSellFilterdir == -1On126

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

Does it repaint?

No

No repainting patterns in the source, and the live replay matched history.

5/5trades identical when replayed liveThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, four per bar, and compared with the historical run. Orders are decided once per closed bar, so nothing can change mid-bar.
  • ClearHigher-timeframe data2 security call(s), none with lookahead on.
  • ClearFuture-bar referencesNo negative history offsets such as close[-1].
  • ClearIntrabar recalculationNo varip, calc_on_every_tick or realtime-only state. Orders are decided once per closed bar.
  • 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−40.8%+102.5%1631%0.3950.9%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h+7.1%+5.5%2528%1.1715.6%8 May 2026 – 21 Oct 2026
ETHUSDT 1D+45.3%+9.8%1250%1.4839.6%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+20.9%+8.4%1942%1.5313.7%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−18.9%+16.7%1553%0.7953.4%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+21.9%+21.5%2138%1.4022.6%8 May 2026 – 21 Oct 2026
BNBUSDT 1D+6.5%+148.3%1540%1.1124.1%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h−5.5%+17.1%2348%0.8311.1%8 May 2026 – 21 Oct 2026

Higher-timeframe data for request.security(): BINANCE:BTCUSDT 12M (aggregated from Binance BTCUSDT 1M), fetched from Binance's public market data for each market.

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

The trades

By market direction

At entry, last 90 barsTradesWonP&L
Rising market50%−$349.35
Sideways market838%−$22.99
Falling market367%−$35.50

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

How bad could the drawdown be?

56.0%

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

0%64%
All 16 trades
SideEntryExitBarsP&L
short2 Jan 2025 94,591.8018 Jan 2025 104,077.0016−$100.48
long24 Jan 2025 103,910.003 Feb 2025 92,650.1010−$97.64
short25 Feb 2025 91,552.903 Mar 2025 94,270.006−$23.96
short14 Mar 2025 81,115.8023 Apr 2025 93,443.0040−$118.38
long24 Apr 2025 93,691.105 Jun 2025 101,448.0042$54.46
short23 Jun 2025 100,964.0010 Jul 2025 111,234.0017−$72.77
long11 Jul 2025 116,010.002 Aug 2025 112,625.0022−$18.83
short3 Aug 2025 112,546.0014 Aug 2025 123,306.0011−$59.63
short20 Aug 2025 112,873.002 Oct 2025 118,595.0043−$28.64
long3 Oct 2025 120,529.0010 Oct 2025 116,671.007−$17.20
short16 Oct 2025 110,763.0015 Jan 2026 96,951.8091$64.35
long15 Jan 2026 96,951.8020 Jan 2026 88,007.605−$53.74
short30 Jan 2026 84,650.2017 Mar 2026 74,884.7046$60.75
long17 Mar 2026 74,884.7029 Mar 2026 65,359.3012−$74.94
long10 Apr 2026 71,788.0023 May 2026 74,896.4043$22.12
short28 May 2026 74,449.3022 Jul 2026 66,556.1055$56.67

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
AlignedMA and Cumulative HighLow Strategy V2 this page—v4 strategy−40.8%1650.9%
Multi MA Trend Following Strategy Template by TradeAutomationema hma rma sma vwma wma atr highest lowestv5 strategy+12.3%326.9%
Ultra Moving Average Rating Trend Strategy by exlux99ema wma highest lowest sma rma vwma hmav5 strategy+2.8%52.4%
VCP pivot buy by perrycc007sma ema rma vwma wma lowest highestv4 strategydoes not run in Zeal Terminal
Multi Trend Cross Strategy Template by TradeAutomationema hma rma sma vwma wma highest lowestv5 strategy+33.0%37.3%
MACD Willy Strategy by PtGamblerrma sma ema highest lowest wmav5 strategyNo trades on this market

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 36 msWith a workaround 1,000 bars in 183 msNot measured
PineTSNo v5 and v6 only—Not measured

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

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

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/// © HeWhoMustNotBeNamed//@version=4strategy("AlignedMA and Cumulative HighLow Strategy V2", overlay=true, initial_capital = 1000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)MAType = input(title="Moving Average Type", defval="hma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])includePartiallyAligned = input(true)HighLowPeriod = input(22, minval=1,step=1)LookbackPeriod = input(10, minval=1,step=1)considerYearlyHighLow = input(false)dirTBars = input(1)dirRBars = input(30)PMAType = input(title="Moving Average Type", defval="ema", options=["ema", "sma", "hma", "rma", "vwma", "wma"])PMALength = input(10, minval=2, step=10)shift = input(2, minval=1, step=1)//Use 2 for ASX stockssupertrendMult = input(3, minval=1, maxval=10, step=0.5)supertrendLength = input(22, minval=1)riskReward = input(2, minval=1, maxval=10, step=0.5)tradeDirection = input(title="Trade Direction", defval=strategy.direction.all, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])backtestYears = input(1, minval=1, step=1)f_getMovingAverage(source, MAType, length)=>    ma = sma(source, length)    if(MAType == "ema")        ma := ema(source,length)    if(MAType == "hma")        ma := hma(source,length)    if(MAType == "rma")        ma := rma(source,length)    if(MAType == "vwma")        ma := vwma(source,length)    if(MAType == "wma")        ma := wma(source,length)    ma    f_getMaAlignment(MAType, includePartiallyAligned)=>    ma5 = f_getMovingAverage(close,MAType,5)    ma10 = f_getMovingAverage(close,MAType,10)    ma20 = f_getMovingAverage(close,MAType,20)    ma30 = f_getMovingAverage(close,MAType,30)    ma50 = f_getMovingAverage(close,MAType,50)    ma100 = f_getMovingAverage(close,MAType,100)    ma200 = f_getMovingAverage(close,MAType,200)    upwardScore = 0    upwardScore := close > ma5? upwardScore+1:upwardScore    upwardScore := ma5 > ma10? upwardScore+1:upwardScore    upwardScore := ma10 > ma20? upwardScore+1:upwardScore    upwardScore := ma20 > ma30? upwardScore+1:upwardScore    upwardScore := ma30 > ma50? upwardScore+1:upwardScore    upwardScore := ma50 > ma100? upwardScore+1:upwardScore    upwardScore := ma100 > ma200? upwardScore+1:upwardScore        upwards = close > ma5 and ma5 > ma10 and ma10 > ma20 and ma20 > ma30 and ma30 > ma50 and ma50 > ma100 and ma100 > ma200    downwards = close < ma5 and ma5 < ma10 and ma10 < ma20 and ma20 < ma30 and ma30 < ma50 and ma50 < ma100 and ma100 < ma200    upwards?1:downwards?-1:includePartiallyAligned ? (upwardScore > 5? 0.5: upwardScore < 2?-0.5:upwardScore>3?0.25:-0.25) : 0f_getHighLowValue(HighLowPeriod)=>    currentHigh = highest(high,HighLowPeriod) == high    currentLow = lowest(low,HighLowPeriod) == low    currentHigh?1:currentLow?-1:0f_getDirection(Series)=>    direction = Series > Series[1] ? 1 : Series < Series[1] ? -1 : 0    direction := direction == 0? nz(direction[1],0):direction    directionf_getDirectionT(Series, tBars, rBars)=>    compH = Series > 0? Series[tBars] : Series[rBars]    compL = Series < 0? Series[tBars] : Series[rBars]    direction = Series > compH ? 1 : Series < compL ? -1 : 0    direction := direction == 0? nz(direction[1],0):direction    directionf_getYearlyHighLowCondition(considerYearlyHighLow)=>    yhigh = security(syminfo.tickerid, '12M', high[1])     ylow = security(syminfo.tickerid, '12M', low[1])     yhighlast = yhigh[365]    ylowlast = ylow[365]    yhighllast = yhigh[2 * 365]    ylowllast = ylow[2 * 365]        yearlyTrendUp = na(yhigh)? true : na(yhighlast)? close > yhigh : na(yhighllast)? close > max(yhigh,yhighlast) : close > max(yhigh, min(yhighlast, yhighllast))    yearlyHighCondition = (  (na(yhigh) or na(yhighlast) ? true : (yhigh > yhighlast) ) and ( na(yhigh) or na(yhighllast) ? true : (yhigh > yhighllast))) or yearlyTrendUp or not considerYearlyHighLow    yearlyTrendDown = na(ylow)? true : na(ylowlast)? close < ylow : na(ylowllast)? close < min(ylow,ylowlast) : close < min(ylow, max(ylowlast, ylowllast))    yearlyLowCondition = (  (na(ylow) or na(ylowlast) ? true : (ylow < ylowlast) ) and ( na(ylow) or na(ylowllast) ? true : (ylow < ylowllast))) or yearlyTrendDown or not considerYearlyHighLow        [yearlyHighCondition,yearlyLowCondition]f_getOpenCloseMA(MAType, length)=>    openMA = f_getMovingAverage(open, MAType, length)    closeMA = f_getMovingAverage(close, MAType, length)    direction = openMA < closeMA ? 1 : -1    [openMA, closeMA, direction]inDateRange = time >= timestamp(syminfo.timezone, year(timenow) - backtestYears, 01, 01, 0, 0)maAlignment = f_getMaAlignment(MAType,includePartiallyAligned)alignedMaIndex = sum(maAlignment,LookbackPeriod)maAlignmentDirection=f_getDirectionT(alignedMaIndex,dirTBars, dirRBars)atr = atr(22)highLowIndex = f_getHighLowValue(HighLowPeriod)cumulativeHighLowIndex = sum(highLowIndex,LookbackPeriod)hlDirection = f_getDirectionT(cumulativeHighLowIndex,dirTBars,dirRBars)[yearlyHighCondition,yearlyLowCondition] = f_getYearlyHighLowCondition(considerYearlyHighLow)[supertrend, dir] = supertrend(supertrendMult, supertrendLength)[esupertrend, edir] = supertrend(supertrendMult+1, supertrendLength)movingAverage = f_getMovingAverage(close, PMAType, PMALength)secondaryBuyFilter = movingAverage > movingAverage[shift]secondarySellFilter = movingAverage < movingAverage[shift]closeBuyFilter = dir == 1closeSellFilter = dir == -1buyFilter = (maAlignmentDirection == 1 and hlDirection == 1 and yearlyHighCondition)sellFilter = (maAlignmentDirection == -1 and hlDirection == -1 and yearlyLowCondition)barColor = buyFilter?color.lime:sellFilter?color.orange:color.graybandColor = secondaryBuyFilter ? color.green : secondarySellFilter ? color.red : color.graycompound = strategy.position_size > 0? strategy.position_avg_price + (atr* supertrendMult * riskReward) : strategy.position_size < 0 ? strategy.position_avg_price - (atr* supertrendMult * riskReward) : nariskFree = na(compound)?false:strategy.position_size > 0 ? supertrend > compound : strategy.position_size < 0 ? supertrend < compound : falsetrailingStop = riskFree?(dir==-1?supertrend - 2*atr : supertrend + 2*atr) :supertrendtrailingStop := (strategy.position_size > 0 and trailingStop < trailingStop[1]) ? trailingStop[1] :  ((strategy.position_size < 0 and trailingStop > trailingStop[1])? trailingStop[1] :trailingStop)plot(trailingStop, title="Supertrend", color=riskFree? color.blue:dir==-1?color.green:color.red, linewidth=2)buyEntry = buyFilter and secondaryBuyFilter and not closeBuyFilter and low > trailingStopsellEntry = sellFilter and secondarySellFilter and not closeSellFilter and low < trailingStopFi1 = plot(movingAverage[shift], title="MA", color=color.red, linewidth=1, transp=50)Fi2 = plot(movingAverage, title="Shift", color=color.green, linewidth=1, transp=50)fill(Fi1, Fi2, title="Band Filler", color=bandColor, transp=40)barcolor(barColor)//plot(compound, title="Compound"mzn, color=dir==-1?color.lime:color.orange, linewidth=2)strategy.risk.allow_entry_in(tradeDirection)strategy.entry("Buy", strategy.long, when=buyEntry and inDateRange and (riskFree or strategy.position_size==0), oca_name="oca_buy", oca_type=strategy.oca.none)strategy.exit("ExitBuy", "Buy", stop = trailingStop)strategy.close("Buy", when=closeBuyFilter)strategy.entry("Sell", strategy.short, when=sellEntry and inDateRange and (riskFree or strategy.position_size==0), oca_name="oca_sell", oca_type=strategy.oca.none)strategy.exit("ExitSell", "Buy", stop = trailingStop)strategy.close("Sell", when=closeSellFilter)