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
- 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
VerifiedSame 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⋯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.
| Setting | Default | Type and range | Feeds |
|---|---|---|---|
| Moving Average Type | sma | string · 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) | 5 | int · step 10 | maAlignmentHigh maAlignmentLow line 57 |
| Short High Low Period (no label in the script) | 10 | int · step 10 | newHigh newLow |
| Long High Low Period (no label in the script) | 20 | int · step 10 | newHigh newLow |
| Atrlength (no label in the script) | 22 | int | atr |
| Stop Multiplyer (no label in the script) | 6 | int · min 1 · max 10 · step 0.5 | buyStop sellStop |
| Compound Multiplyer (no label in the script) | 1 | int · min 1 · max 10 · step 0.5 | buyStop sellStop |
| Reentry Stop Multiplyer (no label in the script) | 3 | int · min 1 · max 10 · step 0.5 | buyEntry sellEntry |
| Exit On Signal (no label in the script) | false | bool | close Buy close Sell |
| Trade Direction | strategy.direction.long | value · options [strategy.direction.all, strategy.direction.long, strategy.direction.short] | line 108 |
| 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 22 - ATR (
atr,ta.atrin v5)Atrlength (22)atr · line 94 - BB (
bb,ta.bbin v5)close, 20, 2middle · line 97 - BB (
bb,ta.bbin v5)close, 20, 2upper · line 97 - BB (
bb,ta.bbin 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.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open Buy long | buyEntrybarState == 1 and close - reentryStopMultiplyer*atr > buyStop and yearlyHighCondition and inDateRange | On | 109 |
| Close Buy | buyExit and exitOnSignal | On | 110 |
| Exit ExitBuy stop | every bar | On | 111 |
| Open Sell short | sellEntrybarState == -1 and close + reentryStopMultiplyer*atr < sellStop and yearlyLowCondition and inDateRange | On | 112 |
| Close Sell | sellExit and exitOnSignal | On | 113 |
| Exit ExitSell stop | every bar | On | 114 |
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.
- 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 | −22.0% | +102.5% | 8 | 38% | 0.59 | 46.3% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | +19.8% | +5.5% | 2 | 50% | 21.79 | 3.1% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | −75.0% | +9.8% | 7 | 0% | 0.00 | 75.7% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | +2.9% | +8.4% | 3 | 33% | 1.72 | 5.7% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | −89.7% | +16.7% | 10 | 10% | 0.06 | 91.2% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | +0.0% | +21.5% | 3 | 67% | 1.00 | 9.5% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | +1.7% | +148.3% | 6 | 33% | 1.02 | 52.2% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | +4.2% | +17.1% | 5 | 20% | 1.26 | 18.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 bars | Trades | Won | P&L |
|---|---|---|---|
| Rising market | 2 | 50% | −$43.64 |
| Sideways market | 6 | 33% | −$393.71 |
| 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?
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.
All 8 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 2 Mar 2024 62,387.90 | 16 Apr 2024 63,420.00 | 45 | $29.09 |
| long | 25 May 2024 68,550.00 | 16 Jun 2024 66,228.30 | 22 | −$72.72 |
| long | 26 Aug 2024 64,220.00 | 5 Sep 2024 57,970.90 | 10 | −$194.37 |
| long | 1 Oct 2024 63,327.60 | 11 Oct 2024 60,326.40 | 10 | −$87.50 |
| long | 19 Oct 2024 68,428.00 | 28 Feb 2025 81,756.60 | 132 | $322.16 |
| long | 23 Apr 2025 93,443.00 | 10 Oct 2025 106,490.00 | 170 | $274.79 |
| long | 31 Oct 2025 108,323.00 | 20 Nov 2025 87,996.10 | 20 | −$430.24 |
| long | 19 Jan 2026 93,673.10 | 31 Jan 2026 79,705.10 | 12 | −$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.
| Script | Shares | Type | Net | Trades | Max drawdown |
|---|---|---|---|---|---|
| TrendMaAlignmentStrategy - Long term trades this page | — | v4 strategy | −22.0% | 8 | 46.3% |
| Smoothed Heikin Ashi Trend on Chart - TraderHalai BACKTEST by TraderHalai | sma ema hma vwma rma | v5 strategy | +1.3% | 113 | 5.6% |
| Multi MA Trend Following Strategy Template by TradeAutomation | ema hma rma sma vwma wma atr | v5 strategy | +12.3% | 3 | 26.9% |
| High-Low Channel Multi averages Crypto Swing strategy by exlux99 | sma ema wma rma vwma | v4 strategy | No trades on this market | ||
| Open Close Cross Strategy plus Explorer by roses27 | sma ema wma vwma atr | v4 strategy | does not run in Zeal Terminal | ||
| Ultra Moving Average Rating Trend Strategy by exlux99 | ema wma sma rma vwma hma | v5 strategy | +2.8% | 5 | 2.4% |
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 34 ms | With a workaround 1,000 bars in 118 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("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)