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
- 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
VerifiedSame 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)⋯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.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Donchian Entry Length (no label in the script) | 40 | int · step 10 | eMiddle eUpper eLower |
| Donchian Exit Length (no label in the script) | 20 | int · step 10 | exMiddle exUpper exLower |
| Consider New Long Term High Lows (no label in the script) | true | bool | newHigh newLow |
| Short High Low Period (no label in the script) | 120 | int · step 10 | newHigh newLow |
| Long High Low Period (no label in the script) | 180 | int · step 10 | newHigh newLow |
| Consider MAAlignment (no label in the script) | true | bool | maAlignmentLongCondition |
| Moving Average Type | ema | string · 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) | 40 | int · min 10 · step 10 | maAlignmentLongCondition |
| ATR Length (no label in the script) | 22 | int | atr |
| ATR Mult (no label in the script) | 4 | int | stop tsl |
| Exit Strategy | tsl | string · options ["dc", "tsl"] | exit ExitBuyDC exit ExitBuyTSL Trailing Stop |
| Consider Yearly High Low (no label in the script) | true | bool | yearlyHighCondition yearlyLowCondition |
| Backtest Years (no label in the script) | 10 | int · min 1 · step 1 | inDateRange |
What it calculates
- SMA / EMA / HMA / RMA / VWMA / WMA (
sma,ta.smain v5)source, lengthma · line 19 - Highest (
highest,ta.highestin v5)rangeLengthupper · line 77 - Lowest (
lowest,ta.lowestin v5)rangeLengthlower · line 78 - ATR (
atr,ta.atrin v5)ATR Length (22)atr · line 88 - Crossunder (
crossunder,ta.crossunderin v5)close, exLower[1]exitLongCondition · line 93 - Crossover (
crossover,ta.crossoverin 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.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open Buy long | longCondition and inDateRange | On | 96 |
| Exit ExitBuyDC stop | exitStrategy=='dc' | On | 97 |
| Exit ExitBuyTSL stop | exitStrategy=='tsl' | On | 98 |
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.
- 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.
| Market | Net | Buy and hold | Trades | Won | Profit factor | Max drawdown | Period |
|---|---|---|---|---|---|---|---|
| BTCUSDT 1D | +12.4% | +102.5% | 4 | 50% | 2.39 | 6.7% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | 0.0% | +5.5% | 0 | 0% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | −14.6% | +9.8% | 2 | 0% | 0.00 | 14.6% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | 0.0% | +8.4% | 0 | 0% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | −12.3% | +16.7% | 3 | 33% | 0.64 | 30.9% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | 0.0% | +21.5% | 0 | 0% | — | 0.0% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | −0.4% | +148.3% | 3 | 33% | 0.98 | 25.7% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | −4.0% | +17.1% | 1 | 0% | 0.00 | 4.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 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 2 | 100% | $2,128.62 |
| Sideways market | 2 | 0% | −$890.47 |
| Falling market | 0 | — | $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.
All 4 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 7 Nov 2024 75,572.00 | 13 Jan 2025 91,015.10 | 67 | $2,041.09 |
| long | 9 May 2025 103,262.00 | 22 Jun 2025 99,522.30 | 44 | −$438.35 |
| long | 10 Jul 2025 111,234.00 | 21 Aug 2025 112,096.00 | 42 | $87.53 |
| long | 2 Oct 2025 118,595.00 | 10 Oct 2025 114,031.00 | 8 | −$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.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| BuyHigh-SellLow Strategy this page | — | v4 strategy | +12.4% | 4 | 6.7% |
| Multi MA Trend Following Strategy Template by TradeAutomation | ema hma rma sma vwma wma atr highest lowest | v5 strategy | +12.3% | 3 | 26.9% |
| Ultra Moving Average Rating Trend Strategy by exlux99 | ema wma highest lowest sma rma vwma hma | v5 strategy | +2.8% | 5 | 2.4% |
| VCP pivot buy by perrycc007 | sma ema rma vwma wma lowest highest | v4 strategy | does not run in Zeal Terminal | ||
| MACD Willy Strategy by PtGambler | rma sma ema highest lowest wma | v5 strategy | No trades on this market | ||
| Multi Trend Cross Strategy Template by TradeAutomation | ema hma rma sma vwma wma highest lowest | v5 strategy | +33.0% | 3 | 7.3% |
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 48 ms | With a workaround 1,000 bars in 139 ms | Not measured |
| PineTS | No 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)