Zeal Terminal Open in Zeal Terminal

Pine Script v4 · Strategy

BuyHigh-SellLow Strategy

A Pine Script v4 strategy built on SMA or EMA or HMA or RMA or VWMA or WMA (source, length), Highest (rangeLength) and Lowest (rangeLength). It has 3 order rules, 1 entry among them, and trades long only with the default settings. Exits use a stop loss. Each trade commits 100% of equity and pays 0.01% commission. 13 settings; defaults include Donchian Entry Length 40, Donchian Exit Length 20 and Short High Low Period 120.

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 BuyHigh-SellLow Strategy repaint?
No
No repainting patterns were found in the source. The live replay was not measured: it had no trades to compare.
How did BuyHigh-SellLow Strategy do on BTCUSDT 1D with default settings?
+12.38%
From 26 Jan 2024 to 21 Oct 2026, over 4 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Can BuyHigh-SellLow Strategy 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 BuyHigh-SellLow Strategy use a stop loss?
Yes
strategy.exit sets a stop on line 97, 98.
Does BuyHigh-SellLow Strategy run in Zeal Terminal?
Yes
It compiles in 48 ms and runs 1,000 bars in 139 ms, in the browser.

BTCUSDT · 1D · default settings

  • Trailing Stop
  • Winning trade
  • Losing trade
  • Equity
  • Buy and hold
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$11,238$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. The live re-run is not offered here: the script requests BINANCE:BTCUSDT 12M, which this page cannot load in your browser.
Net profit
+12.38%
$1,238.15
Buy and hold
+102.5%
same period
Closed trades
4
2 won · 2 lost
Profitable
50.0%
of closed trades
Profit factor
2.39
gross profit ÷ gross loss
Max drawdown
6.67%
−$802.94

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

    Every trade uses all the equity

    default_qty_value is 100% of equity.

  • Note

    11 settings have no label

    In the settings dialog donchianEntryLength (line 5), donchianExitLength (line 6), considerNewLongTermHighLows (line 7), shortHighLowPeriod (line 8), longHighLowPeriod (line 9), considerMAAlignment (line 10), LookbackPeriod (line 12), atrLength (line 13), atrMult (line 14), considerYearlyHighLow (line 16), backtestYears (line 17) 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 96, 97, 98. 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, max → math.max, highest → ta.highest, lowest → ta.lowest, security → request.security, min → math.min, atr → ta.atr, crossover → ta.crossover, crossunder → ta.crossunder.
  • 3 strategy calls use the when = argument (line 96, 97, 98). It is deprecated in v5 and removed in v6, where each call moves inside an if block.

v4 → v5

Verified

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

  • Line 3: //@version=4 → //@version=5
  • Line 19: sma → ta.sma
  • Line 21: ema → ta.ema
  • Line 23: hma → ta.hma
  • Line 25: rma → ta.rma
  • Line 27: vwma → ta.vwma
22 more edits
  • Line 29: wma → ta.wma
  • Line 33: max → math.max
  • Line 57: highest → ta.highest
  • Line 57: highest → ta.highest
  • Line 58: lowest → ta.lowest
  • Line 58: lowest → ta.lowest
  • Line 62: security → request.security
  • Line 63: security → request.security
  • Line 69: max → math.max
  • Line 69: max → math.max
  • Line 69: min → math.min
  • Line 71: min → math.min
  • Line 71: min → math.min
  • Line 71: max → math.max
  • Line 77: highest → ta.highest
  • Line 78: lowest → ta.lowest
  • Line 87: highest → ta.highest
  • Line 88: atr → ta.atr
  • Line 92: crossover → ta.crossover
  • Line 93: crossunder → ta.crossunder
  • Line 94: crossunder → ta.crossunder
  • Line 95: crossover → ta.crossover
⋯// © HeWhoMustNotBeNamed-//@version=4+//@version=5strategy("BuyHigh-SellLow Strategy", overlay=true, initial_capital = 10000, 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⋯    stop = close - atrMult*atr-    stop := strategy.position_size > 0 ? max(stop, stop[1]) : stop+    stop := strategy.position_size > 0 ? math.max(stop, stop[1]) : stop    stop⋯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⋯donchian(rangeLength)=>-    upper = highest(rangeLength)+    upper = ta.highest(rangeLength)-    lower = lowest(rangeLength)+    lower = ta.lowest(rangeLength)    middle = (upper+lower)/2⋯[newHigh,newLow] = f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)-maAlignmentLongCondition = highest(maAlignment, LookbackPeriod) == 1 or not considerMAAlignment +maAlignmentLongCondition = ta.highest(maAlignment, LookbackPeriod) == 1 or not considerMAAlignment -atr = atr(atrLength)+atr = ta.atr(atrLength)tsl = f_getTrailingStop(atr, atrMult)⋯//D = plot(exLower, title="Ex Low", color=color.red, linewidth=2, style=plot.style_linebr)-longCondition = crossover(close, eUpper[1]) and yearlyHighCondition and newHigh and maAlignmentLongCondition+longCondition = ta.crossover(close, eUpper[1]) and yearlyHighCondition and newHigh and maAlignmentLongCondition-exitLongCondition = crossunder(close, exLower[1])+exitLongCondition = ta.crossunder(close, exLower[1])-shortCondition = crossunder(close, eLower[1]) and yearlyLowCondition and newLow+shortCondition = ta.crossunder(close, eLower[1]) and yearlyLowCondition and newLow-exitShortCondition = crossover(close, exUpper[1])+exitShortCondition = ta.crossover(close, exUpper[1])strategy.entry("Buy", strategy.long, when=longCondition and inDateRange, oca_name="oca_buy", oca_type=strategy.oca.none)⋯

Clean v5

VerifiedDownload the v5 script

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

  • Line 5: input() → input.int()
  • Line 6: input() → input.int()
  • Line 7: input() → input.bool()
  • Line 8: input() → input.int()
  • Line 9: input() → input.int()
  • Line 10: input() → input.bool()
10 more edits
  • Line 11: input() → input.string()
  • Line 12: input() → input.int()
  • Line 13: input() → input.int()
  • Line 14: input() → input.int()
  • Line 15: input() → input.string()
  • Line 16: input() → input.bool()
  • Line 17: input() → input.int()
  • Line 96: when = longCondition and inDateRange → if block
  • Line 97: when = exitStrategy=='dc' → if block
  • Line 98: when = exitStrategy=='tsl' → if block
⋯strategy("BuyHigh-SellLow Strategy", overlay=true, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)-donchianEntryLength = input(40, step=10)+donchianEntryLength = input.int(40, step=10)-donchianExitLength = input(20, step=10)+donchianExitLength = input.int(20, step=10)-considerNewLongTermHighLows = input(true)+considerNewLongTermHighLows = input.bool(true)-shortHighLowPeriod = input(120, step=10)+shortHighLowPeriod = input.int(120, step=10)-longHighLowPeriod = input(180, step=10)+longHighLowPeriod = input.int(180, step=10)-considerMAAlignment = input(true)+considerMAAlignment = input.bool(true)-MAType = input(title="Moving Average Type", defval="ema", options=["ema", "sma", "hma", "rma", "vwma", "wma"])+MAType = input.string(title="Moving Average Type", defval="ema", options=["ema", "sma", "hma", "rma", "vwma", "wma"])-LookbackPeriod = input(40, minval=10,step=10)+LookbackPeriod = input.int(40, minval=10,step=10)-atrLength = input(22)+atrLength = input.int(22)-atrMult = input(4)+atrMult = input.int(4)-exitStrategy = input(title="Exit Strategy", defval="tsl", options=["dc", "tsl"])+exitStrategy = input.string(title="Exit Strategy", defval="tsl", options=["dc", "tsl"])-considerYearlyHighLow = input(true)+considerYearlyHighLow = input.bool(true)-backtestYears = input(10, minval=1, step=1)+backtestYears = input.int(10, minval=1, step=1)f_getMovingAverage(source, MAType, length)=>⋯exitShortCondition = ta.crossover(close, exUpper[1])-strategy.entry("Buy", strategy.long, when=longCondition and inDateRange, oca_name="oca_buy", oca_type=strategy.oca.none)+if longCondition and inDateRange+    strategy.entry("Buy", strategy.long, oca_name="oca_buy", oca_type=strategy.oca.none)-strategy.exit("ExitBuyDC", "Buy", when=exitStrategy=='dc', stop=exLower)+if exitStrategy=='dc'+    strategy.exit("ExitBuyDC", "Buy", stop=exLower)-strategy.exit("ExitBuyTSL", "Buy", when=exitStrategy=='tsl', stop=tsl)+if exitStrategy=='tsl'+    strategy.exit("ExitBuyTSL", "Buy", stop=tsl)plot(strategy.position_size > 0 ? (exitStrategy=='dc'?exLower:tsl) : na, title="Trailing Stop", color=color.red, linewidth=2, style=plot.style_linebr)⋯

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: 4 before, 7 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("BuyHigh-SellLow Strategy", overlay=true, initial_capital = 10000, 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
Donchian Entry Length (no label in the script)40int · step 10eMiddle eUpper eLower
Donchian Exit Length (no label in the script)20int · step 10exMiddle exUpper exLower
Consider New Long Term High Lows (no label in the script)trueboolnewHigh newLow
Short High Low Period (no label in the script)120int · step 10newHigh newLow
Long High Low Period (no label in the script)180int · step 10newHigh newLow
Consider MAAlignment (no label in the script)trueboolmaAlignmentLongCondition
Moving Average Typeemastring · options ["ema", "sma", "hma", "rma", "vwma", "wma"]ma5 ma10 ma20 ma30 ma50 ma100 ma200 maAlignment line 20 line 22 line 24 line 26 line 28
Lookback Period (no label in the script)40int · min 10 · step 10maAlignmentLongCondition
ATR Length (no label in the script)22intatr
ATR Mult (no label in the script)4intstop tsl
Exit Strategytslstring · options ["dc", "tsl"]exit ExitBuyDC exit ExitBuyTSL Trailing Stop
Consider Yearly High Low (no label in the script)trueboolyearlyHighCondition yearlyLowCondition
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 19
  • Highest (highest, ta.highest in v5)rangeLengthupper · line 77
  • Lowest (lowest, ta.lowest in v5)rangeLengthlower · line 78
  • ATR (atr, ta.atr in v5)ATR Length (22)atr · line 88
  • Crossunder (crossunder, ta.crossunder in v5)close, exLower[1]exitLongCondition · line 93
  • Crossover (crossover, ta.crossover in v5)close, exUpper[1]exitShortCondition · line 95

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 dataatrLengthATR Lengthsetting · 22closecloseprice dataatrMultATR Multsetting · 4MATypeMoving Average Typesetting · emashortHighLowPeriodShort High Low Periodsetting · 120longHighLowPeriodLong High Low Periodsetting · 180highhighprice datalowlowprice datatimetimeprice datadonchianEntryLengthDonchian Entry Lengthsetting · 40donchianExitLengthDonchian Exit Lengthsetting · 20backtestYearsBacktest Yearssetting · 10LookbackPeriodLookback Periodsetting · 40exitStrategyExit Strategysetting · tslmaSMA / EMA / HMA / RMA /…→ maupperHighest→ upperlowerLowest→ loweratrATR→ atrexitLongConditionCrossunder→ exitLongConditionexitShortConditionCrossover→ exitShortConditionstopstopvaluema5, ma10, ma20, ma30, ma50, ma100, ma200ma5 · ma10 +57 valuesupwardScoreupwardScorevaluenewHigh, newLownewHigh · newLow2 valuesyhighyhighvalueylowylowvalueyhighlast, yhighllastyhighlast · yhighllast2 valuesylowlast, ylowllastylowlast · ylowllast2 valuesyearlyTrendUpyearlyTrendUpvalueyearlyHighCondition, yearlyLowConditionyearlyHighCondition · y…2 valuesyearlyTrendDownyearlyTrendDownvaluelabel_xlabel_xvaluemiddlemiddlevalueeMiddle, eUpper, eLowereMiddle · eUpper +13 valuesexMiddle, exUpper, exLowerexMiddle · exUpper +13 valuesmaAlignmentmaAlignmentvaluetsltslvalueupwards, downwardsupwards · downwards2 conditionsinDateRangeinDateRangeconditionmaAlignmentLongConditionmaAlignmentLongConditionconditionlongConditionlongConditionconditionshortConditionshortConditionconditionentry:BuyOpen Buystrategy.entryexit:ExitBuyDCexit ExitBuyDCstrategy.exitexit:ExitBuyTSLexit ExitBuyTSLstrategy.exitplot:99Trailing Stopplot

Order rules

OrderFires whenBy defaultLine
Open Buy longlongCondition and inDateRangeOn96
Exit ExitBuyDC stopexitStrategy=='dc'On97
Exit ExitBuyTSL stopexitStrategy=='tsl'On98

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.

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 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+12.4%+102.5%450%2.396.7%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h0.0%+5.5%00%—0.0%8 May 2026 – 21 Oct 2026
ETHUSDT 1D−14.6%+9.8%20%0.0014.6%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h0.0%+8.4%00%—0.0%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−12.3%+16.7%333%0.6430.9%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h0.0%+21.5%00%—0.0%8 May 2026 – 21 Oct 2026
BNBUSDT 1D−0.4%+148.3%333%0.9825.7%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h−4.0%+17.1%10%0.004.0%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 market2100%$2,128.62
Sideways market20%−$890.47
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?

7.4%

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

0%8%
All 4 trades
SideEntryExitBarsP&L
long7 Nov 2024 75,572.0013 Jan 2025 91,015.1067$2,041.09
long9 May 2025 103,262.0022 Jun 2025 99,522.3044−$438.35
long10 Jul 2025 111,234.0021 Aug 2025 112,096.0042$87.53
long2 Oct 2025 118,595.0010 Oct 2025 114,031.008−$452.12

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
BuyHigh-SellLow Strategy this page—v4 strategy+12.4%46.7%
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
MACD Willy Strategy by PtGamblerrma sma ema highest lowest wmav5 strategyNo trades on this market
Multi Trend Cross Strategy Template by TradeAutomationema hma rma sma vwma wma highest lowestv5 strategy+33.0%37.3%

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 48 msWith a workaround 1,000 bars in 139 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("BuyHigh-SellLow Strategy", overlay=true, initial_capital = 10000, default_qty_type = strategy.percent_of_equity, default_qty_value = 100, commission_type = strategy.commission.percent, pyramiding = 1, commission_value = 0.01)donchianEntryLength = input(40, step=10)donchianExitLength = input(20, step=10)considerNewLongTermHighLows = input(true)shortHighLowPeriod = input(120, step=10)longHighLowPeriod = input(180, step=10)considerMAAlignment = input(true)MAType = input(title="Moving Average Type", defval="ema", options=["ema", "sma", "hma", "rma", "vwma", "wma"])LookbackPeriod = input(40, minval=10,step=10)atrLength = input(22)atrMult = input(4)exitStrategy = input(title="Exit Strategy", defval="tsl", options=["dc", "tsl"])considerYearlyHighLow = input(true)backtestYears = input(10, 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)    maf_getTrailingStop(atr, atrMult)=>    stop = close - atrMult*atr    stop := strategy.position_size > 0 ? max(stop, stop[1]) : stop    stopf_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) : 0//////////////////////////////////// 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 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        label_x = time+(60*60*24*1000*1)    [yearlyHighCondition,yearlyLowCondition]donchian(rangeLength)=>    upper = highest(rangeLength)    lower = lowest(rangeLength)    middle = (upper+lower)/2    [middle, upper, lower]inDateRange = time >= timestamp(syminfo.timezone, year(timenow) - backtestYears, 01, 01, 0, 0)[eMiddle, eUpper, eLower] = donchian(donchianEntryLength)[exMiddle, exUpper, exLower] = donchian(donchianExitLength)maAlignment = f_getMaAlignment(MAType, false)[yearlyHighCondition, yearlyLowCondition] = f_getYearlyHighLowCondition(considerYearlyHighLow)[newHigh,newLow] = f_calculateNewHighLows(shortHighLowPeriod, longHighLowPeriod, considerNewLongTermHighLows)maAlignmentLongCondition = highest(maAlignment, LookbackPeriod) == 1 or not considerMAAlignment atr = atr(atrLength)tsl = f_getTrailingStop(atr, atrMult)//U = plot(eUpper, title="Up", color=color.green, linewidth=2, style=plot.style_linebr)//D = plot(exLower, title="Ex Low", color=color.red, linewidth=2, style=plot.style_linebr)longCondition = crossover(close, eUpper[1]) and yearlyHighCondition and newHigh and maAlignmentLongConditionexitLongCondition = crossunder(close, exLower[1])shortCondition = crossunder(close, eLower[1]) and yearlyLowCondition and newLowexitShortCondition = crossover(close, exUpper[1])strategy.entry("Buy", strategy.long, when=longCondition and inDateRange, oca_name="oca_buy", oca_type=strategy.oca.none)strategy.exit("ExitBuyDC", "Buy", when=exitStrategy=='dc', stop=exLower)strategy.exit("ExitBuyTSL", "Buy", when=exitStrategy=='tsl', stop=tsl)plot(strategy.position_size > 0 ? (exitStrategy=='dc'?exLower:tsl) : na, title="Trailing Stop", color=color.red, linewidth=2, style=plot.style_linebr)//strategy.close("Buy", when=exitLongCondition)