Pine Script v5 · Strategy
Strategy Myth-Busting #11 - TrendMagic+SqzMom+CDV - [MYN]
A Pine Script v5 strategy built on SMA (ta.tr, 5), CCI (src, 20) and Stdev (source, 10). It has 9 order rules, 2 entries among them, and trades long and short with the default settings. Exits use a profit target and no stop loss. Each trade commits 1% of equity and pays 0.075 commission. 53 settings; defaults include CCI period 20, ATR Multiplier 2 and ATR Period 5.
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 Strategy Myth-Busting #11 - TrendMagic+SqzMom+CDV - [MYN] repaint?
- Yes
- At least one pattern in the source can repaint: intrabar recalculation.
- How did Strategy Myth-Busting #11 - TrendMagic+SqzMom+CDV - [MYN] do on BTCUSDT 1D with default settings?
- −2.32%
- From 26 Jan 2024 to 21 Oct 2026, over 9 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
- What alerts does Strategy Myth-Busting #11 - TrendMagic+SqzMom+CDV - [MYN] have?
- 5
- Cross Alert; CrossOver Alarm; CrossUnder Alarm; alertSyntaxBase + 'side:long'; and more.
- Does Strategy Myth-Busting #11 - TrendMagic+SqzMom+CDV - [MYN] run in Pine Script v6?
- No
- The v6 version does not run in Zeal Terminal's engine: Pine Script v6 Error at @L254:C7: cannot use 'int' as a condition — Pine Script v6 does not cast 'int' or 'float' to 'bool' implicitly. Wrap it in bool(). The v6 version is shown for reference and is not offered as a download.
- Does Strategy Myth-Busting #11 - TrendMagic+SqzMom+CDV - [MYN] use a stop loss?
- No
- Its exits set a profit target but no stop.
BTCUSDT · 1D · default settings
- Plot
- Winning trade
- Losing trade
- Equity
- Buy and hold
| Start: long1719619200000 |
| End: NaN |
| Net Profit: -2.32% |
| Percent Per Day NaN% |
| Percent Profitable: 77.78% |
| Profit Factor: 0.853 |
| Total Trades: 9 |
| Max Wins In A Row: 5 |
| Max Losses In A Row: 1 |
- Net profit
- −2.32%
- −$23.21
- Buy and hold
- +102.5%
- same period
- Closed trades
- 9
- 7 won · 2 lost
- Profitable
- 77.8%
- of closed trades
- Profit factor
- 0.85
- gross profit ÷ gross loss
- Max drawdown
- 12.28%
- −$134.62
One run with the author's default settings, $1,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
19 settings do nothing
“BB MultFactor”, “SMA 1”, “Ma1len”, “Ma1col”, “SMA 2”, “Ma2len”, “Ma2col”, “EMA 1”, “Ema1len”, “Ema1col”, “EMA 2”, “Ema2len”, “Ema2col”, “Body”, “Colordown”, “Border”, “Bcoldown”, “Wicks”, “Wcoldown” are declared but never read.
-
Check
No stop loss
strategy.exit is used without a stop, loss or trailing stop.
-
Note
6 settings have no label
In the settings dialog ma1len (line 89), ma2len (line 92), ema1len (line 95), ema2len (line 98), startPeriodTime (line 188), endPeriodTime (line 190) 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 250, 251, 252. The upgraded version below moves each call inside an if block.
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 |
|---|---|---|---|
| Use Heiken Ashi | true | bool | CLOSE OPEN HIGH LOW |
| Is Crypto? | true | bool | trendMagicEntryConditionLong trendMagicEntryConditionShort |
| CCI period | 20 | int | MagicTrend color1 trendMagicEntryConditionLong trendMagicEntryConditionShort |
| ATR Multiplier | 2 | int | upT downT |
| ATR Period | 5 | int | ATR |
| Number of bars to look back to validate Trend Magic trend | 17 | int | trendMagicEntryLong trendMagicEntryShort |
| BB MultFactor | 2.0 | float | unused |
| KC Length | 10 | int | ma rangema val |
| KC MultFactor | 1.5 | float | dev upperKC lowerKC |
| Use TrueRange (KC) | true | bool | range_1 |
| Number of bars to look back to validate Sqz Mom trend | 14 | int | sqzmomEntryLong sqzmomEntryShort |
| Heikin Ashi Candles? | true | bool | c_ o_ h_ l_ |
| SMA 1 | false | bool | unused |
| Ma1len (no label in the script) | 50 | int · min 1 | unused |
| Ma1col (no label in the script) | color.lime | color | unused |
| SMA 2 | false | bool | unused |
| Ma2len (no label in the script) | 200 | int · min 1 | unused |
| Ma2col (no label in the script) | color.red | color | unused |
| EMA 1 | false | bool | unused |
| Ema1len (no label in the script) | 50 | int · min 1 | unused |
| Ema1col (no label in the script) | color.lime | color | unused |
| EMA 2 | false | bool | unused |
| Ema2len (no label in the script) | 200 | int · min 1 | unused |
| Ema2col (no label in the script) | color.red | color | unused |
| Body | color.lime | color | unused |
| Colordown (no label in the script) | color.red | color | unused |
| Border | #74e05e | color | unused |
| Bcoldown (no label in the script) | #ffad7d | color | unused |
| Wicks | #b5b5b8 | color | unused |
| Wcoldown (no label in the script) | #b5b5b8 | color | unused |
| Number of bars to look back to validate CDV trend | 14 | int | cdvEntryLong cdvEntryShort |
| Squeeze Momentum | |||
| BB Length | 10 | int | basis dev |
| Cumlative Delta Volume | |||
| Style | Candle | string · options ['Candle', 'Line'] | line 122 |
| ADX | |||
| Average Directional Index (ADX) | false | bool | adxsig isADXEnabledAndAboveThreshold |
| ADX Smoothing | 14 | int | adx adxsig |
| DI Length | 14 | int | adxplus adxminus adxsig |
| ADX Threshold | 25 | int | isADXEnabledAndAboveThreshold |
| Date Range | |||
| Start | true | bool | start |
| Start Period Time (no label in the script) | timestamp('1 Jan 2019') | time | start |
| End | true | bool | end |
| End Period Time (no label in the script) | timestamp('31 Dec 2030') | time | end |
| Trade Direction | |||
| Trade Direction | Long and Short | string · options ['Long and Short', 'Long Only', 'Short Only'] | entry Long entry Short line 238 line 241 |
| Take Profit | |||
| Take Profit 1 - Target % | 2 | float · min 0.0 · step 0.5 | exit TP1 |
| % Of Position | 100 | int · min 0 | exit TP1 |
| Take Profit 2 - Target % | 100 | float · min 0.0 · step 0.5 | exit TP2 |
| % Of Position | 100 | int · min 0 | exit TP2 |
| Take Profit 3 - Target % | 100 | float · min 0.0 · step 0.5 | exit TP3 |
| % Of Position | 100 | int · min 0 | exit TP3 |
| Take Profit 4 - Target % | 100 | float · min 0.0 · step 0.5 | exit TP4 |
| Stop Loss | |||
| Stop Loss (%) | 6 | float · min 0.01 | slLongClose slShortClose |
| Leverage | |||
| Leverage | 1 | float · step .5 | contracts |
| ProfitView Alert Syntax | |||
| Alert Syntax Prefix | CRYPTANEX_99FTX_Strategy-Name-Here | string | alertSyntaxBase |
| Dashboard | |||
| Show Dashboard | true | bool | line 261 |
What it calculates
- SMAta.tr, ATR Period (5)
ATR · line 30 - CCIsrc, CCI period (20)
MagicTrend · line 35 - CCIsrc, CCI period (20)
trendMagicEntryConditionLong · line 44 - CCIsrc, CCI period (20)
trendMagicEntryConditionShort · line 45 - SMAsource, BB Length (10)
basis · line 57 - Stdevsource, BB Length (10)
dev · line 58 - SMAsource, KC Length (10)
ma · line 62 - TR
range_1 · line 63 - SMArange_1, KC Length (10)
rangema · line 64 - Linreg / Highest / Lowest / SMAsource - math.avg(math.avg(ta.highest(HIGH, lengthKC), ta.lowest(LOW, lengthKC)), ta.sma(CLOSE, lengthKC)), KC Length (10), 0
val · line 70 - CUMdelta
cumdelta · line 116 - ChangeHIGH
adxup · line 171 - ChangeLOW
adxdown · line 172 - RMAta.tr, len
adxtruerange · line 175 - RMAmath.abs(adxplus - adxminus) / (adxsum == 0 ? 1 : adxsum), ADX Smoothing (14)
adx · line 182
Signal flow
How price data and settings reach the orders. Each box is a name in the script, or several computed the same way; each arrow is a value one of them reads. Hover a box for its members.
The script has 110 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open Long long | longConditionCalc and tradeDirection != 'Short Only' and isInLongPosition == false | On | 239 |
| Open Short short | shortConditionCalc and tradeDirection != 'Long Only' and isInShortPosition == false | On | 242 |
| Exit TP1 limit | calcPeriod | On | 246 |
| Exit TP2 limit | calcPeriod | On | 247 |
| Exit TP3 limit | calcPeriod | On | 248 |
| Exit TP4 limit | calcPeriod | On | 249 |
| Close Long | slLongCloseCLOSE < strategy.position_avg_price * (1 - stoplossPercent) | On | 250 |
| Close Short | slShortCloseCLOSE > strategy.position_avg_price * (1 + stoplossPercent) | On | 251 |
| Close | closeLongCondition or closeShortCondition | On | 252 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Alerts
| Alert | Call | Message | Line |
|---|---|---|---|
| Cross Alert | alertcondition | Price - MagicTrend Crossing! | 38 |
| CrossOver Alarm | alertcondition | BUY SIGNAL! | 39 |
| CrossUnder Alarm | alertcondition | SELL SIGNAL! | 40 |
| (no title) | alert | alertSyntaxBase + 'side:long' | 240 |
| (no title) | alert | alertSyntaxBase + 'side:short' | 243 |
Does it repaint?
Yes
At least one pattern in the source can repaint; it is marked Check below.
- ClearHigher-timeframe dataThe script requests no other symbol or timeframe.
- ClearFuture-bar referencesNo negative history offsets such as close[-1].
- CheckIntrabar recalculationuses varip. Live values can differ from history.
- 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 | −2.3% | +102.5% | 9 | 78% | 0.85 | 12.3% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | −3.6% | +5.5% | 11 | 73% | 0.81 | 18.3% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | +3.2% | +9.8% | 12 | 75% | 1.11 | 18.5% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | +18.5% | +8.4% | 11 | 91% | 3.40 | 9.5% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | −35.8% | +16.7% | 14 | 57% | 0.31 | 41.6% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | +23.5% | +21.5% | 15 | 93% | 3.91 | 9.5% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | +2.5% | +148.3% | 12 | 83% | 1.15 | 15.7% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | +2.2% | +17.1% | 11 | 82% | 1.14 | 10.4% | 8 May 2026 – 21 Oct 2026 |
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 | 3 | 100% | $58.05 |
| Sideways market | 6 | 67% | −$81.26 |
| 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?
14.1%
The 95th percentile of the worst drawdown when the same 9 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 7.5% to 14.1%; the tick is what actually happened, 10.9%. Order luck alone moves it this much.
All 9 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| short | 29 Jun 2024 60,427.80 | 4 Jul 2024 59,219.30 | 5 | $18.31 |
| long | 1 Oct 2024 63,327.60 | 14 Oct 2024 64,594.20 | 13 | $18.52 |
| long | 22 Nov 2024 98,317.10 | 5 Dec 2024 100,283.00 | 13 | $19.55 |
| long | 30 Apr 2025 94,256.80 | 1 May 2025 96,142.00 | 1 | $19.45 |
| long | 2 May 2025 96,489.90 | 8 May 2025 98,419.70 | 6 | $20.08 |
| long | 23 May 2025 111,696.00 | 31 May 2025 103,985.00 | 8 | −$77.99 |
| long | 11 Jul 2025 116,010.00 | 13 Jul 2025 118,330.00 | 2 | $19.21 |
| long | 14 Jul 2025 119,087.00 | 11 Aug 2025 121,468.00 | 28 | $19.30 |
| short | 10 Jun 2026 61,730.00 | 16 Jun 2026 66,328.70 | 6 | −$79.63 |
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 |
|---|---|---|---|---|---|
| Strategy Myth-Busting #11 - TrendMagic+SqzMom+CDV - [MYN] this page | — | v5 strategy | −2.3% | 9 | 12.3% |
| ATR GOD Strategy by TradeSmart (PineConnector-compatible) by TradeSmart22 | tr lowest highest sma stdev rma | v5 strategy | No trades on this market | ||
| VixFixLinReg-Strategy by Trendoscope | highest stdev sma lowest linreg | v4 strategy | −49.3% | 12 | 51.1% |
| Strategy Myth-Busting #7 - MACDBB+SSL+VSF - [MYN] by myncrypto | stdev sma tr highest lowest rma | v5 strategy | No trades on this market | ||
| Ruckard TradingLatino by ruckard | linreg rma sma stdev highest lowest | v4 strategy | +64.6% | 240 | 15.3% |
| Bollinger Bands + ADX Strategy by tweakerID | rma sma stdev lowest highest | v4 strategy | −9.9% | 19 | 33.0% |
Upgrade and export
Written in Pine Script v5. The clean-v5 step types the settings and moves when = into if blocks, which v6 requires; it is run before and after like any upgrade.
- 3 strategy calls use the when = argument (line 250, 251, 252). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
- 15 settings use the untyped input() (line 27, 28, 29, 41, 50, 51, 52, 53, 54, 77, 87, 149, 167, 168, 169). It still compiles in v6; input.int, input.float or input.source state the type.
- No v6-only features. v6 is not needed to run this script.
Same 9 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 27: input() → input.int()
- Line 28: input() → input.int()
- Line 29: input() → input.int()
- Line 41: input() → input.int()
- Line 50: input() → input.int()
- Line 51: input() → input.float()
12 more edits
- Line 52: input() → input.int()
- Line 53: input() → input.float()
- Line 54: input() → input.bool()
- Line 77: input() → input.int()
- Line 87: input() → input.bool()
- Line 149: input() → input.int()
- Line 167: input() → input.int()
- Line 168: input() → input.int()
- Line 169: input() → input.int()
- Line 250: when = slLongClose → if block
- Line 251: when = slShortClose → if block
- Line 252: when = closeLongCondition or closeShortCondition → if block
⋯//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░-period = input(20, 'CCI period')+period = input.int(20, 'CCI period')-coeff = input(2, 'ATR Multiplier')+coeff = input.int(2, 'ATR Multiplier')-AP = input(5, 'ATR Period')+AP = input.int(5, 'ATR Period')ATR = ta.sma(ta.tr, AP)⋯alertcondition(ta.crossunder(HIGH, MagicTrend), title='CrossUnder Alarm', message='SELL SIGNAL!')-i_numLookbackBarsTM = input(17,title="Number of bars to look back to validate Trend Magic trend")+i_numLookbackBarsTM = input.int(17,title="Number of bars to look back to validate Trend Magic trend")//trendMagicEntryLong = trendMagicEntryConditionLong and f_priorBarsSatisfied(trendMagicEntryConditionLong,i_numLookbackBarsTM)⋯//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░-length = input(10, title='BB Length', group="Squeeze Momentum")+length = input.int(10, title='BB Length', group="Squeeze Momentum")-mult = input(2.0, title='BB MultFactor')+mult = input.float(2.0, title='BB MultFactor')-lengthKC = input(10, title='KC Length')+lengthKC = input.int(10, title='KC Length')-multKC = input(1.5, title='KC MultFactor')+multKC = input.float(1.5, title='KC MultFactor')-useTrueRange = input(true, title='Use TrueRange (KC)')+useTrueRange = input.bool(true, title='Use TrueRange (KC)')// Calculate BB⋯//plot(0, color=scolor, style=plot.style_cross, linewidth=2)-i_numLookbackBarsSM = input(14,title="Number of bars to look back to validate Sqz Mom trend")+i_numLookbackBarsSM = input.int(14,title="Number of bars to look back to validate Sqz Mom trend")//sqzmomEntryLong = val > 0 and f_priorBarsSatisfied(val > 0,i_numLookbackBarsSM)⋯linestyle = input.string(defval='Candle', title='Style', options=['Candle', 'Line'], group="Cumlative Delta Volume")-hacandle = input(defval=true, title='Heikin Ashi Candles?')+hacandle = input.bool(defval=true, title='Heikin Ashi Candles?')showma1 = input.bool(defval=false, title='SMA 1', inline='ma1')⋯//plot(showema2 and linestyle == 'Candle' ? ta.ema(c_, ema2len) : na, title='EMA 2', color=ema2col)-i_numLookbackBarsCDV = input(14,title="Number of bars to look back to validate CDV trend")+i_numLookbackBarsCDV = input.int(14,title="Number of bars to look back to validate CDV trend")//cdvEntryLong = o_ < c_ and f_priorBarsSatisfied(o_ < c_,i_numLookbackBarsCDV)⋯adxEnabled = input.bool(defval = false , title = "Average Directional Index (ADX)", tooltip = "", group ="ADX" ) -adxlen = input(14, title="ADX Smoothing", group="ADX")+adxlen = input.int(14, title="ADX Smoothing", group="ADX")-adxdilen = input(14, title="DI Length", group="ADX")+adxdilen = input.int(14, title="DI Length", group="ADX")-adxabove = input(25, title="ADX Threshold", group="ADX")+adxabove = input.int(25, title="ADX Threshold", group="ADX")adxdirmov(len) =>⋯ strategy.exit('TP4', profit=per(tp4))- strategy.close('Long', qty_percent=100, comment='SL Long', when=slLongClose)+ if slLongClose+ strategy.close('Long', qty_percent=100, comment='SL Long')- strategy.close('Short', qty_percent=100, comment='SL Short', when=slShortClose)+ if slShortClose+ strategy.close('Short', qty_percent=100, comment='SL Short')- strategy.close_all(when=closeLongCondition or closeShortCondition, comment='Close Postion')+ if closeLongCondition or closeShortCondition+ strategy.close_all(comment='Close Postion')/// Dashboard⋯Does it run in Pine Script v6?
No
The v6 version does not run in Zeal Terminal's engine: Pine Script v6 Error at @L254:C7: cannot use 'int' as a condition — Pine Script v6 does not cast 'int' or 'float' to 'bool' implicitly. Wrap it in bool(). The v6 version is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.
⋯// © myn-//@version=5+//@version=6strategy('Strategy Myth-Busting #11 - TrendMagic+SqzMom+CDV - [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=1000, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=1, commission_value=0.075, use_bar_magnifier = false)⋯Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 152 ms | With a workaround 1,000 bars in 207 ms | Not measured |
| PineTS | Not tested | Not tested | 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.
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/// © myn//@version=5strategy('Strategy Myth-Busting #11 - TrendMagic+SqzMom+CDV - [MYN]', max_bars_back=5000, overlay=true, pyramiding=0, initial_capital=1000, currency='USD', default_qty_type=strategy.percent_of_equity, default_qty_value=1, commission_value=0.075, use_bar_magnifier = false)// HA to Regular Candlestick resoloveruseHA = input.bool(true, "Use Heiken Ashi")CLOSE = closeOPEN = openHIGH = highLOW = lowCLOSE := useHA ? (OPEN + CLOSE + HIGH + LOW) / 4 : CLOSEOPEN := useHA ? na(OPEN[1]) ? (OPEN + CLOSE) / 2: (OPEN[1] + CLOSE[1]) / 2 : OPENHIGH := useHA ? math.max(HIGH, math.max(OPEN, CLOSE)) : HIGHLOW := useHA ? math.min(LOW, math.min(OPEN, CLOSE)) : LOWisCrypto = input.bool(true, "Is Crypto?")// Functionsf_priorBarsSatisfied(_objectToEval, _numOfBarsToLookBack) => returnVal = false for i = 0 to _numOfBarsToLookBack if (_objectToEval[i] == true) returnVal = true///////////////////////////////////////* Put your strategy logic below *///////////////////////////////////////// Trend Magic by KivancOzbilgic//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░period = input(20, 'CCI period')coeff = input(2, 'ATR Multiplier')AP = input(5, 'ATR Period')ATR = ta.sma(ta.tr, AP)src = CLOSEupT = LOW - ATR * coeffdownT = HIGH + ATR * coeffMagicTrend = 0.0MagicTrend := ta.cci(src, period) >= 0 ? upT < nz(MagicTrend[1]) ? nz(MagicTrend[1]) : upT : downT > nz(MagicTrend[1]) ? nz(MagicTrend[1]) : downTcolor1 = ta.cci(src, period) >= 0 ? #0022FC : #FC0400plot(MagicTrend, color=color1, linewidth=3)alertcondition(ta.cross(CLOSE, MagicTrend), title='Cross Alert', message='Price - MagicTrend Crossing!')alertcondition(ta.crossover(LOW, MagicTrend), title='CrossOver Alarm', message='BUY SIGNAL!')alertcondition(ta.crossunder(HIGH, MagicTrend), title='CrossUnder Alarm', message='SELL SIGNAL!')i_numLookbackBarsTM = input(17,title="Number of bars to look back to validate Trend Magic trend")//trendMagicEntryLong = trendMagicEntryConditionLong and f_priorBarsSatisfied(trendMagicEntryConditionLong,i_numLookbackBarsTM)//trendMagicEntryShort = trendMagicEntryConditionShort and f_priorBarsSatisfied(trendMagicEntryConditionShort,i_numLookbackBarsTM)trendMagicEntryConditionLong = ta.cci(src, period) >= 0 and src > MagicTrend + (isCrypto ? 5 : 0 )trendMagicEntryConditionShort = ta.cci(src, period) < 0 and src < MagicTrend - (isCrypto ? 5 : 0) trendMagicEntryLong = trendMagicEntryConditionLong and ta.barssince(trendMagicEntryConditionShort) > i_numLookbackBarsTM trendMagicEntryShort = trendMagicEntryConditionShort and ta.barssince(trendMagicEntryConditionLong) > i_numLookbackBarsTM // Squeeze Momentum by LazyBear//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░length = input(10, title='BB Length', group="Squeeze Momentum")mult = input(2.0, title='BB MultFactor')lengthKC = input(10, title='KC Length')multKC = input(1.5, title='KC MultFactor')useTrueRange = input(true, title='Use TrueRange (KC)')// Calculate BBsource = CLOSEbasis = ta.sma(source, length)dev = multKC * ta.stdev(source, length)upperBB = basis + devlowerBB = basis - dev// Calculate KCma = ta.sma(source, lengthKC)range_1 = useTrueRange ? ta.tr : HIGH - LOWrangema = ta.sma(range_1, lengthKC)upperKC = ma + rangema * multKClowerKC = ma - rangema * multKCsqzOn = lowerBB > lowerKC and upperBB < upperKCsqzOff = lowerBB < lowerKC and upperBB > upperKCnoSqz = sqzOn == false and sqzOff == falseval = ta.linreg(source - math.avg(math.avg(ta.highest(HIGH, lengthKC), ta.lowest(LOW, lengthKC)), ta.sma(CLOSE, lengthKC)), lengthKC, 0)iff_1 = val > nz(val[1]) ? color.lime : color.greeniff_2 = val < nz(val[1]) ? color.red : color.maroonbcolor = val > 0 ? iff_1 : iff_2scolor = noSqz ? color.blue : sqzOn ? color.black : color.gray//plot(val, color=bcolor, style=plot.style_histogram, linewidth=4)//plot(0, color=scolor, style=plot.style_cross, linewidth=2)i_numLookbackBarsSM = input(14,title="Number of bars to look back to validate Sqz Mom trend")//sqzmomEntryLong = val > 0 and f_priorBarsSatisfied(val > 0,i_numLookbackBarsSM)//sqzmomEntryShort = val < 0 and f_priorBarsSatisfied(val < 0,i_numLookbackBarsSM)sqzmomEntryConditionLong = val > 0 sqzmomEntryConditionShort = val < 0sqzmomEntryLong = sqzmomEntryConditionLong and ta.barssince(sqzmomEntryConditionShort) > i_numLookbackBarsSM sqzmomEntryShort = sqzmomEntryConditionShort and ta.barssince(sqzmomEntryConditionLong) > i_numLookbackBarsSM // Cumulative Delta Volume by LonesomeTheBlue//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░linestyle = input.string(defval='Candle', title='Style', options=['Candle', 'Line'], group="Cumlative Delta Volume")hacandle = input(defval=true, title='Heikin Ashi Candles?')showma1 = input.bool(defval=false, title='SMA 1', inline='ma1')ma1len = input.int(defval=50, title='', minval=1, inline='ma1')ma1col = input.color(defval=color.lime, title='', inline='ma1')showma2 = input.bool(defval=false, title='SMA 2', inline='ma2')ma2len = input.int(defval=200, title='', minval=1, inline='ma2')ma2col = input.color(defval=color.red, title='', inline='ma2')showema1 = input.bool(defval=false, title='EMA 1', inline='ema1')ema1len = input.int(defval=50, title='', minval=1, inline='ema1')ema1col = input.color(defval=color.lime, title='', inline='ema1')showema2 = input.bool(defval=false, title='EMA 2', inline='ema2')ema2len = input.int(defval=200, title='', minval=1, inline='ema2')ema2col = input.color(defval=color.red, title='', inline='ema2')colorup = input.color(defval=color.lime, title='Body', inline='bcol')colordown = input.color(defval=color.red, title='', inline='bcol')bcolup = input.color(defval=#74e05e, title='Border', inline='bocol')bcoldown = input.color(defval=#ffad7d, title='', inline='bocol')wcolup = input.color(defval=#b5b5b8, title='Wicks', inline='wcol')wcoldown = input.color(defval=#b5b5b8, title='', inline='wcol')tw = HIGH - math.max(OPEN, CLOSE)bw = math.min(OPEN, CLOSE) - LOWbody = math.abs(CLOSE - OPEN)_rate(cond) => ret = 0.5 * (tw + bw + (cond ? 2 * body : 0)) / (tw + bw + body) ret := nz(ret) == 0 ? 0.5 : ret retdeltaup = volume * _rate(OPEN <= CLOSE)deltadown = volume * _rate(OPEN > CLOSE)delta = CLOSE >= OPEN ? deltaup : -deltadowncumdelta = ta.cum(delta)float ctl = nafloat o = nafloat h = nafloat l = nafloat c = naif linestyle == 'Candle' o := cumdelta[1] h := math.max(cumdelta, cumdelta[1]) l := math.min(cumdelta, cumdelta[1]) c := cumdelta ctlelse ctl := cumdelta ctlplot(ctl, title='CDV Line', color=color.new(color.blue, 0), linewidth=2)float haclose = nafloat haopen = nafloat hahigh = nafloat halow = nahaclose := (o + h + l + c) / 4haopen := na(haopen[1]) ? (o + c) / 2 : (haopen[1] + haclose[1]) / 2hahigh := math.max(h, math.max(haopen, haclose))halow := math.min(l, math.min(haopen, haclose))c_ = hacandle ? haclose : co_ = hacandle ? haopen : oh_ = hacandle ? hahigh : hl_ = hacandle ? halow : l//plotcandle(o_, h_, l_, c_, title='CDV Candles', color=o_ <= c_ ? colorup : colordown, bordercolor=o_ <= c_ ? bcolup : bcoldown, wickcolor=o_ <= c_ ? bcolup : bcoldown)//plot(showma1 and linestyle == 'Candle' ? ta.sma(c_, ma1len) : na, title='SMA 1', color=ma1col)//plot(showma2 and linestyle == 'Candle' ? ta.sma(c_, ma2len) : na, title='SMA 2', color=ma2col)//plot(showema1 and linestyle == 'Candle' ? ta.ema(c_, ema1len) : na, title='EMA 1', color=ema1col)//plot(showema2 and linestyle == 'Candle' ? ta.ema(c_, ema2len) : na, title='EMA 2', color=ema2col)i_numLookbackBarsCDV = input(14,title="Number of bars to look back to validate CDV trend")//cdvEntryLong = o_ < c_ and f_priorBarsSatisfied(o_ < c_,i_numLookbackBarsCDV)//cdvEntryShort = o_ > c_ and f_priorBarsSatisfied(o_ > c_,i_numLookbackBarsCDV)cdvEntryConditionLong = o_ <= c_cdvEntryConditionShort = o_ > c_cdvEntryLong = cdvEntryConditionLong and ta.barssince(cdvEntryConditionShort) > i_numLookbackBarsCDV cdvEntryShort = cdvEntryConditionShort and ta.barssince(cdvEntryConditionLong) > i_numLookbackBarsCDV ////////////////////////////////////////* Put your strategy rules below *///////////////////////////////////////longCondition = trendMagicEntryLong and sqzmomEntryLong and cdvEntryLongshortCondition = trendMagicEntryShort and sqzmomEntryShort and cdvEntryShort//define as 0 if do not want to usecloseLongCondition = 0closeShortCondition = 0// ADX//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░adxEnabled = input.bool(defval = false , title = "Average Directional Index (ADX)", tooltip = "", group ="ADX" ) adxlen = input(14, title="ADX Smoothing", group="ADX")adxdilen = input(14, title="DI Length", group="ADX")adxabove = input(25, title="ADX Threshold", group="ADX")adxdirmov(len) => adxup = ta.change(HIGH) adxdown = -ta.change(LOW) adxplusDM = na(adxup) ? na : (adxup > adxdown and adxup > 0 ? adxup : 0) adxminusDM = na(adxdown) ? na : (adxdown > adxup and adxdown > 0 ? adxdown : 0) adxtruerange = ta.rma(ta.tr, len) adxplus = fixnan(100 * ta.rma(adxplusDM, len) / adxtruerange) adxminus = fixnan(100 * ta.rma(adxminusDM, len) / adxtruerange) [adxplus, adxminus]adx(adxdilen, adxlen) => [adxplus, adxminus] = adxdirmov(adxdilen) adxsum = adxplus + adxminus adx = 100 * ta.rma(math.abs(adxplus - adxminus) / (adxsum == 0 ? 1 : adxsum), adxlen)adxsig = adxEnabled ? adx(adxdilen, adxlen) : naisADXEnabledAndAboveThreshold = adxEnabled ? (adxsig > adxabove) : true//Backtesting Time Period (Input.time not working as expected as of 03/30/2021. Giving odd start/end dates//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░useStartPeriodTime = input.bool(true, 'Start', group='Date Range', inline='Start Period')startPeriodTime = input.time(timestamp('1 Jan 2019'), '', group='Date Range', inline='Start Period')useEndPeriodTime = input.bool(true, 'End', group='Date Range', inline='End Period')endPeriodTime = input.time(timestamp('31 Dec 2030'), '', group='Date Range', inline='End Period')start = useStartPeriodTime ? startPeriodTime >= time : falseend = useEndPeriodTime ? endPeriodTime <= time : falsecalcPeriod = not start and not end// Trade Direction // ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░tradeDirection = input.string('Long and Short', title='Trade Direction', options=['Long and Short', 'Long Only', 'Short Only'], group='Trade Direction')// Percent as Points// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░per(pcnt) => strategy.position_size != 0 ? math.round(pcnt / 100 * strategy.position_avg_price / syminfo.mintick) : float(na)// Take profit 1// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░tp1 = input.float(title='Take Profit 1 - Target %', defval=2, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 1')q1 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 1')// Take profit 2// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░tp2 = input.float(title='Take Profit 2 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 2')q2 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 2')// Take profit 3// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░tp3 = input.float(title='Take Profit 3 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit', inline='Take Profit 3')q3 = input.int(title='% Of Position', defval=100, minval=0, group='Take Profit', inline='Take Profit 3')// Take profit 4// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░tp4 = input.float(title='Take Profit 4 - Target %', defval=100, minval=0.0, step=0.5, group='Take Profit')/// Stop Loss// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░stoplossPercent = input.float(title='Stop Loss (%)', defval=6, minval=0.01, group='Stop Loss') * 0.01slLongClose = CLOSE < strategy.position_avg_price * (1 - stoplossPercent)slShortClose = CLOSE > strategy.position_avg_price * (1 + stoplossPercent)/// Leverage// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░leverage = input.float(1, 'Leverage', step=.5, group='Leverage')contracts = math.min(math.max(.000001, strategy.equity / CLOSE * leverage), 1000000000)/// Trade State Management// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░isInLongPosition = strategy.position_size > 0isInShortPosition = strategy.position_size < 0/// ProfitView Alert Syntax String Generation// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░alertSyntaxPrefix = input.string(defval='CRYPTANEX_99FTX_Strategy-Name-Here', title='Alert Syntax Prefix', group='ProfitView Alert Syntax')alertSyntaxBase = alertSyntaxPrefix + '\n#' + str.tostring(OPEN) + ',' + str.tostring(HIGH) + ',' + str.tostring(LOW) + ',' + str.tostring(CLOSE) + ',' + str.tostring(volume) + ','/// Trade Execution// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░longConditionCalc = (longCondition and isADXEnabledAndAboveThreshold)shortConditionCalc = (shortCondition and isADXEnabledAndAboveThreshold)if calcPeriod if longConditionCalc and tradeDirection != 'Short Only' and isInLongPosition == false strategy.entry('Long', strategy.long, qty=contracts) alert(message=alertSyntaxBase + 'side:long', freq=alert.freq_once_per_bar_close) if shortConditionCalc and tradeDirection != 'Long Only' and isInShortPosition == false strategy.entry('Short', strategy.short, qty=contracts) alert(message=alertSyntaxBase + 'side:short', freq=alert.freq_once_per_bar_close) //Inspired from Multiple %% profit exits example by adolgo https://www.tradingview.com/script/kHhCik9f-Multiple-profit-exits-example/ strategy.exit('TP1', qty_percent=q1, profit=per(tp1)) strategy.exit('TP2', qty_percent=q2, profit=per(tp2)) strategy.exit('TP3', qty_percent=q3, profit=per(tp3)) strategy.exit('TP4', profit=per(tp4)) strategy.close('Long', qty_percent=100, comment='SL Long', when=slLongClose) strategy.close('Short', qty_percent=100, comment='SL Short', when=slShortClose) strategy.close_all(when=closeLongCondition or closeShortCondition, comment='Close Postion')/// Dashboard// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░// Inspired by https://www.tradingview.com/script/uWqKX6A2/ - Thanks VertMTshowDashboard = input.bool(group="Dashboard", title="Show Dashboard", defval=true)f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) => _cellText = _title + "\n" + _value table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor, text_size=size.auto)// Draw dashboard tableif showDashboard var bgcolor = color.new(color.black,0) // Keep track of Wins/Losses streaks newWin = (strategy.wintrades > strategy.wintrades[1]) and (strategy.losstrades == strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1]) newLoss = (strategy.wintrades == strategy.wintrades[1]) and (strategy.losstrades > strategy.losstrades[1]) and (strategy.eventrades == strategy.eventrades[1]) varip int winRow = 0 varip int lossRow = 0 varip int maxWinRow = 0 varip int maxLossRow = 0 if newWin lossRow := 0 winRow := winRow + 1 if winRow > maxWinRow maxWinRow := winRow if newLoss winRow := 0 lossRow := lossRow + 1 if lossRow > maxLossRow maxLossRow := lossRow // Prepare stats table var table dashTable = table.new(position.bottom_right, 1, 15, border_width=1) if barstate.islastconfirmedhistory // Update table dollarReturn = strategy.netprofit f_fillCell(dashTable, 0, 0, "Start:", str.format("{0,date,long}", strategy.closedtrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.closedtrades.entry_time(0)) f_fillCell(dashTable, 0, 1, "End:", str.format("{0,date,long}", strategy.opentrades.entry_time(0)) , bgcolor, color.white) // + str.format(" {0,time,HH:mm}", strategy.opentrades.entry_time(0)) _profit = (strategy.netprofit / strategy.initial_capital) * 100 f_fillCell(dashTable, 0, 2, "Net Profit:", str.tostring(_profit, '##.##') + "%", _profit > 0 ? color.green : color.red, color.white) _numOfDaysInStrategy = (strategy.opentrades.entry_time(0) - strategy.closedtrades.entry_time(0)) / (1000 * 3600 * 24) f_fillCell(dashTable, 0, 3, "Percent Per Day", str.tostring(_profit / _numOfDaysInStrategy, '#########################.#####')+"%", _profit > 0 ? color.green : color.red, color.white) _winRate = ( strategy.wintrades / strategy.closedtrades ) * 100 f_fillCell(dashTable, 0, 4, "Percent Profitable:", str.tostring(_winRate, '##.##') + "%", _winRate < 50 ? color.red : _winRate < 75 ? #999900 : color.green, color.white) f_fillCell(dashTable, 0, 5, "Profit Factor:", str.tostring(strategy.grossprofit / strategy.grossloss, '##.###'), strategy.grossprofit > strategy.grossloss ? color.green : color.red, color.white) f_fillCell(dashTable, 0, 6, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white) f_fillCell(dashTable, 0, 8, "Max Wins In A Row:", str.tostring(maxWinRow, '######') , bgcolor, color.white) f_fillCell(dashTable, 0, 9, "Max Losses In A Row:", str.tostring(maxLossRow, '######') , bgcolor, color.white)