Zeal Terminal Open in Zeal Terminal

Pine Script v4 · Strategy

TrendMaAlignmentStrategy - Long term trades

A Pine Script v4 strategy built on SMA or EMA or HMA or RMA or VWMA or WMA (source, length), ATR (22) and BB (close, 20). 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 2 commission. 11 settings; defaults include Moving Average Type sma, Lookback Period 5 and Short High Low 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 TrendMaAlignmentStrategy - Long term trades repaint?
No
No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 1 of 1 trades.
How did TrendMaAlignmentStrategy - Long term trades do on BTCUSDT 1D with default settings?
−21.97%
From 26 Jan 2024 to 21 Oct 2026, over 8 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Can TrendMaAlignmentStrategy - Long term trades 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 TrendMaAlignmentStrategy - Long term trades use a stop loss?
Yes
strategy.exit sets a stop on line 111, 114.
Does TrendMaAlignmentStrategy - Long term trades run in Zeal Terminal?
Yes
It compiles in 34 ms and runs 1,000 bars in 118 ms, in the browser.

BTCUSDT · 1D · default settings

  • BuyStop
  • SellStop
  • Winning trade
  • Losing trade
  • Equity
  • Buy and hold
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$1,789$4,051Equity from $2,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
−21.97%
−$439.35
Buy and hold
+102.5%
same period
Closed trades
8
3 won · 5 lost
Profitable
37.5%
of closed trades
Profit factor
0.59
gross profit ÷ gross loss
Max drawdown
46.29%
−$1,051.38

One run with the author's default settings, $2,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

    9 settings have no label

    In the settings dialog LookbackPeriod (line 6), shortHighLowPeriod (line 7), longHighLowPeriod (line 8), atrlength (line 9), stopMultiplyer (line 10), compoundMultiplyer (line 11), reentryStopMultiplyer (line 12), exitOnSignal (line 13), backtestYears (line 15) 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 109, 110, 112, 113. The upgraded version below moves each call inside an if block.

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, atr → ta.atr, bb → ta.bb.
  • 4 strategy calls use the when = argument (line 109, 110, 112, 113). It is deprecated in v5 and removed in v6, where each call moves inside an if block.

v4 → v5

Verified

Same 8 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
17 more edits
  • Line 32: wma → ta.wma
  • Line 57: highest → ta.highest
  • Line 57: lowest → ta.lowest
  • Line 60: highest → ta.highest
  • Line 60: highest → ta.highest
  • Line 61: lowest → ta.lowest
  • Line 61: lowest → ta.lowest
  • Line 80: security → request.security
  • Line 81: security → request.security
  • Line 87: max → math.max
  • Line 87: max → math.max
  • Line 87: min → math.min
  • Line 89: min → math.min
  • Line 89: min → math.min
  • Line 89: max → math.max
  • Line 94: atr → ta.atr
  • Line 97: bb → ta.bb
⋯// © HeWhoMustNotBeNamed-//@version=4+//@version=5strategy("TrendMaAlignmentStrategy", overlay=true, initial_capital = 2000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.cash_per_order, pyramiding = 1, commission_value = 2)⋯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⋯    maAlignment = f_getMaAlignment(MAType,includePartiallyAligned)-    [highest(maAlignment, LookbackPeriod), lowest(maAlignment, LookbackPeriod)]+    [ta.highest(maAlignment, LookbackPeriod), ta.lowest(maAlignment, LookbackPeriod)]//////////////////////////////////// Calculate new high low condition //////////////////////////////////////////////////f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)=>-    newHigh = highest(shortHighLowPeriod) == highest(longHighLowPeriod) or not considerNewLongTermHighLows+    newHigh = ta.highest(shortHighLowPeriod) == ta.highest(longHighLowPeriod) or not considerNewLongTermHighLows-    newLow = lowest(shortHighLowPeriod) == lowest(longHighLowPeriod) or not considerNewLongTermHighLows+    newLow = ta.lowest(shortHighLowPeriod) == ta.lowest(longHighLowPeriod) or not considerNewLongTermHighLows    [newHigh,newLow]⋯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⋯    -atr = atr(atrlength)    +atr = ta.atr(atrlength)    [maAlignmentHigh, maAlignmentLow] = f_getMaAlignmentHighLow(MAType, includePartiallyAligned, LookbackPeriod)[newHigh,newLow] = f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)-[middle, upper, lower] = bb(close, 20, 2)+[middle, upper, lower] = ta.bb(close, 20, 2)barState = (maAlignmentLow > 0 or maAlignmentHigh == 1) and newHigh ? 1 : (maAlignmentHigh < 0 or maAlignmentLow == -1) and newLow ? -1 : 0⋯

Clean v5

VerifiedDownload the v5 script

Same 8 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.int()
  • Line 7: input() → input.int()
  • Line 8: input() → input.int()
  • Line 9: input() → input.int()
  • Line 10: input() → input.int()
8 more edits
  • Line 11: input() → input.int()
  • Line 12: input() → input.int()
  • Line 13: input() → input.bool()
  • Line 15: input() → input.int()
  • Line 109: when = buyEntry → if block
  • Line 110: when = buyExit and exitOnSignal → if block
  • Line 112: when = sellEntry → if block
  • Line 113: when = sellExit and exitOnSignal → if block
⋯strategy("TrendMaAlignmentStrategy", overlay=true, initial_capital = 2000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.cash_per_order, pyramiding = 1, commission_value = 2)-MAType = input(title="Moving Average Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])+MAType = input.string(title="Moving Average Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])-LookbackPeriod = input(5, step=10)+LookbackPeriod = input.int(5, step=10)-shortHighLowPeriod = input(10, step=10)+shortHighLowPeriod = input.int(10, step=10)-longHighLowPeriod = input(20, step=10)+longHighLowPeriod = input.int(20, step=10)-atrlength=input(22)+atrlength=input.int(22)-stopMultiplyer = input(6, minval=1, maxval=10, step=0.5)+stopMultiplyer = input.int(6, minval=1, maxval=10, step=0.5)-compoundMultiplyer = input(1, minval=1, maxval=10, step=0.5)+compoundMultiplyer = input.int(1, minval=1, maxval=10, step=0.5)-reentryStopMultiplyer = input(3, minval=1, maxval=10, step=0.5)+reentryStopMultiplyer = input.int(3, minval=1, maxval=10, step=0.5)-exitOnSignal = input(false)+exitOnSignal = input.bool(false)tradeDirection = input(title="Trade Direction", defval=strategy.direction.long, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])-backtestYears = input(10, minval=1, step=1)+backtestYears = input.int(10, minval=1, step=1)inDateRange = time >= timestamp(syminfo.timezone, year(timenow) - backtestYears, 01, 01, 0, 0)⋯strategy.risk.allow_entry_in(tradeDirection)-strategy.entry("Buy", strategy.long, when=buyEntry)+if buyEntry+    strategy.entry("Buy", strategy.long)-strategy.close("Buy", when=buyExit and exitOnSignal)+if buyExit and exitOnSignal+    strategy.close("Buy")strategy.exit("ExitBuy", "Buy", stop = buyStop)-strategy.entry("Sell", strategy.short, when=sellEntry)+if sellEntry+    strategy.entry("Sell", strategy.short)-strategy.close("Sell", when=sellExit and exitOnSignal)+if sellExit and exitOnSignal+    strategy.close("Sell")strategy.exit("ExitSell", "Sell", stop = sellStop)

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: 8 before, 187 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("TrendMaAlignmentStrategy", overlay=true, initial_capital = 2000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.cash_per_order, pyramiding = 1, commission_value = 2)⋯

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 Typesmastring · options ["ema", "sma", "hma", "rma", "vwma", "wma"]ma5 ma10 ma20 ma30 ma50 ma100 ma200 maAlignment maAlignmentHigh maAlignmentLow line 23 line 25 line 27 line 29 line 31
Lookback Period (no label in the script)5int · step 10maAlignmentHigh maAlignmentLow line 57
Short High Low Period (no label in the script)10int · step 10newHigh newLow
Long High Low Period (no label in the script)20int · step 10newHigh newLow
Atrlength (no label in the script)22intatr
Stop Multiplyer (no label in the script)6int · min 1 · max 10 · step 0.5buyStop sellStop
Compound Multiplyer (no label in the script)1int · min 1 · max 10 · step 0.5buyStop sellStop
Reentry Stop Multiplyer (no label in the script)3int · min 1 · max 10 · step 0.5buyEntry sellEntry
Exit On Signal (no label in the script)falseboolclose Buy close Sell
Trade Directionstrategy.direction.longvalue · options [strategy.direction.all, strategy.direction.long, strategy.direction.short]line 108
Backtest Years (no label in the script)10int · 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)Atrlength (22)atr · line 94
  • BB (bb, ta.bb in v5)close, 20, 2middle · line 97
  • BB (bb, ta.bb in v5)close, 20, 2upper · line 97
  • BB (bb, ta.bb in v5)close, 20, 2lower · line 97

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.

high · low · closehigh · low · closeprice dataatrlengthAtrlengthsetting · 22closecloseprice dataMATypeMoving Average Typesetting · smashortHighLowPeriodShort High Low Periodsetting · 10longHighLowPeriodLong High Low Periodsetting · 20stopMultiplyerStop Multiplyersetting · 6compoundMultiplyerCompound Multiplyersetting · 1highhighprice datalowlowprice dataLookbackPeriodLookback Periodsetting · 5reentryStopMultiplyerReentry Stop Multiplyersetting · 3timetimeprice databacktestYearsBacktest Yearssetting · 10maSMA / EMA / HMA / RMA /…→ maatrATR→ atrmiddleBB→ middleupperBB→ upperlowerBB→ lowerma5, ma10, ma20, ma30, ma50, ma100, ma200ma5 · ma10 +57 valuesupwardScoreupwardScorevaluemaAlignmentmaAlignmentvaluenewHigh, newLownewHigh · newLow2 valuesbuyStop, sellStopbuyStop · sellStop2 valuesyhighyhighvalueylowylowvalueyhighlast, yhighllastyhighlast · yhighllast2 valuesylowlast, ylowllastylowlast · ylowllast2 valuesyearlyTrendUpyearlyTrendUpvalueyearlyHighCondition, yearlyLowConditionyearlyHighCondition · y…2 valuesyearlyTrendDownyearlyTrendDownvaluemaAlignmentHigh, maAlignmentLowmaAlignmentHigh · maAli…2 valuesbarStatebarStatevaluebuyEntrybuyEntryconditionsellEntrysellEntryconditioninDateRangeinDateRangeconditionupwards, downwardsupwards · downwards2 conditionsbuyExit, sellExitbuyExit · sellExit2 conditionsentry:BuyOpen Buystrategy.entryclose:BuyClose Buystrategy.closeexit:ExitBuyexit ExitBuystrategy.exitentry:SellOpen Sellstrategy.entryclose:SellClose Sellstrategy.closeexit:ExitSellexit ExitSellstrategy.exitbarcolor:101barcolorbarcolorplot:102BuyStopplotplot:103SellStopplot

Order rules

OrderFires whenBy defaultLine
Open Buy longbuyEntrybarState == 1 and close - reentryStopMultiplyer*atr > buyStop and yearlyHighCondition and inDateRangeOn109
Close BuybuyExit and exitOnSignalOn110
Exit ExitBuy stopevery barOn111
Open Sell shortsellEntrybarState == -1 and close + reentryStopMultiplyer*atr < sellStop and yearlyLowCondition and inDateRangeOn112
Close SellsellExit and exitOnSignalOn113
Exit ExitSell stopevery barOn114

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.

1/1trades 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−22.0%+102.5%838%0.5946.3%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h+19.8%+5.5%250%21.793.1%8 May 2026 – 21 Oct 2026
ETHUSDT 1D−75.0%+9.8%70%0.0075.7%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h+2.9%+8.4%333%1.725.7%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−89.7%+16.7%1010%0.0691.2%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h+0.0%+21.5%367%1.009.5%8 May 2026 – 21 Oct 2026
BNBUSDT 1D+1.7%+148.3%633%1.0252.2%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+4.2%+17.1%520%1.2618.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 market250%−$43.64
Sideways market633%−$393.71
Falling market0—$0.00

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

How bad could the drawdown be?

43.2%

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

0%50%
All 8 trades
SideEntryExitBarsP&L
long2 Mar 2024 62,387.9016 Apr 2024 63,420.0045$29.09
long25 May 2024 68,550.0016 Jun 2024 66,228.3022−$72.72
long26 Aug 2024 64,220.005 Sep 2024 57,970.9010−$194.37
long1 Oct 2024 63,327.6011 Oct 2024 60,326.4010−$87.50
long19 Oct 2024 68,428.0028 Feb 2025 81,756.60132$322.16
long23 Apr 2025 93,443.0010 Oct 2025 106,490.00170$274.79
long31 Oct 2025 108,323.0020 Nov 2025 87,996.1020−$430.24
long19 Jan 2026 93,673.1031 Jan 2026 79,705.1012−$278.55

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
TrendMaAlignmentStrategy - Long term trades this page—v4 strategy−22.0%846.3%
Smoothed Heikin Ashi Trend on Chart - TraderHalai BACKTEST by TraderHalaisma ema hma vwma rmav5 strategy+1.3%1135.6%
Multi MA Trend Following Strategy Template by TradeAutomationema hma rma sma vwma wma atrv5 strategy+12.3%326.9%
High-Low Channel Multi averages Crypto Swing strategy by exlux99sma ema wma rma vwmav4 strategyNo trades on this market
Open Close Cross Strategy plus Explorer by roses27sma ema wma vwma atrv4 strategydoes not run in Zeal Terminal
Ultra Moving Average Rating Trend Strategy by exlux99ema wma sma rma vwma hmav5 strategy+2.8%52.4%

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 34 msWith a workaround 1,000 bars in 118 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("TrendMaAlignmentStrategy", overlay=true, initial_capital = 2000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.cash_per_order, pyramiding = 1, commission_value = 2)MAType = input(title="Moving Average Type", defval="sma", options=["ema", "sma", "hma", "rma", "vwma", "wma"])LookbackPeriod = input(5, step=10)shortHighLowPeriod = input(10, step=10)longHighLowPeriod = input(20, step=10)atrlength=input(22)stopMultiplyer = input(6, minval=1, maxval=10, step=0.5)compoundMultiplyer = input(1, minval=1, maxval=10, step=0.5)reentryStopMultiplyer = input(3, minval=1, maxval=10, step=0.5)exitOnSignal = input(false)tradeDirection = input(title="Trade Direction", defval=strategy.direction.long, options=[strategy.direction.all, strategy.direction.long, strategy.direction.short])backtestYears = input(10, minval=1, step=1)inDateRange = time >= timestamp(syminfo.timezone, year(timenow) - backtestYears, 01, 01, 0, 0)includePartiallyAligned = trueconsiderYearlyHighLow = trueconsiderNewLongTermHighLows = true//////////////////////////////////// Get Moving average ///////////////////////////////////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_getMaAlignmentHighLow(MAType, includePartiallyAligned, LookbackPeriod)=>    maAlignment = f_getMaAlignment(MAType,includePartiallyAligned)    [highest(maAlignment, LookbackPeriod), lowest(maAlignment, LookbackPeriod)]//////////////////////////////////// Calculate new high low condition //////////////////////////////////////////////////f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)=>    newHigh = highest(shortHighLowPeriod) == highest(longHighLowPeriod) or not considerNewLongTermHighLows    newLow = lowest(shortHighLowPeriod) == lowest(longHighLowPeriod) or not considerNewLongTermHighLows    [newHigh,newLow]//////////////////////////////////// Calculate stop and compound //////////////////////////////////////////////////f_calculateStopAndCompound(target, atr, stopMultiplyer, compoundMultiplyer, barState)=>    buyStop = target - (stopMultiplyer * atr)    sellStop = target + (stopMultiplyer * atr)    if(barState > 0 or strategy.position_size > 0)        buyStop := target - (stopMultiplyer * atr)        sellStop := target + (compoundMultiplyer * atr)        buyStop := (buyStop < buyStop[1] or close < sellStop[1])? buyStop[1] : buyStop        sellStop := (sellStop < sellStop[1] or close < sellStop[1]) ? sellStop[1] : sellStop    else if(barState < 0 or strategy.position_size < 0)        buyStop := target - (compoundMultiplyer * atr)        sellStop := target + (stopMultiplyer * atr)        sellStop := (sellStop > sellStop[1] or close > buyStop[1])? sellStop[1] : sellStop        buyStop := (buyStop > buyStop[1] or close > buyStop[1]) ? buyStop[1] : buyStop    [buyStop, sellStop]//////////////////////////////////// Calculate Yearly High Low //////////////////////////////////////////////////f_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]    atr = atr(atrlength)    [maAlignmentHigh, maAlignmentLow] = f_getMaAlignmentHighLow(MAType, includePartiallyAligned, LookbackPeriod)[newHigh,newLow] = f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)[middle, upper, lower] = bb(close, 20, 2)barState = (maAlignmentLow > 0 or maAlignmentHigh == 1) and newHigh ? 1 : (maAlignmentHigh < 0 or maAlignmentLow == -1) and newLow ? -1 : 0[buyStop, sellStop] = f_calculateStopAndCompound(close, atr, stopMultiplyer, compoundMultiplyer, barState)[yearlyHighCondition,yearlyLowCondition] = f_getYearlyHighLowCondition(considerYearlyHighLow)barcolor(barState == 1?color.lime : barState == -1? color.orange: color.silver)plot(barState == 1 or strategy.position_size != 0 ?buyStop:na, title="BuyStop", color=color.red, linewidth=2, style=plot.style_linebr)plot(barState == -1 or strategy.position_size != 0 ?sellStop:na, title="SellStop", color=color.green, linewidth=2, style=plot.style_linebr)buyEntry = barState == 1 and close - reentryStopMultiplyer*atr > buyStop and yearlyHighCondition and inDateRangesellEntry = barState == -1 and close + reentryStopMultiplyer*atr < sellStop and yearlyLowCondition and inDateRangebuyExit = barState == -1sellExit = barState == 1strategy.risk.allow_entry_in(tradeDirection)strategy.entry("Buy", strategy.long, when=buyEntry)strategy.close("Buy", when=buyExit and exitOnSignal)strategy.exit("ExitBuy", "Buy", stop = buyStop)strategy.entry("Sell", strategy.short, when=sellEntry)strategy.close("Sell", when=sellExit and exitOnSignal)strategy.exit("ExitSell", "Sell", stop = sellStop)