Zeal Terminal Open in Zeal Terminal

Pine Script v5 · Strategy

Divergence for Many [Dimkud - v5]

A Pine Script v5 strategy built on RSI (close, 14), SMA or Stoch (3) and CCI (close, 10). It has 8 order rules, 4 entries among them, and trades long and short with the default settings. Exits use a stop loss and a profit target. Each trade commits 200 in cash and pays 0.04% commission. 153 settings; defaults include Take Profit (%) 0.9, Stop Loss (%) 0.9 and Start Year 2022.

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 Divergence for Many [Dimkud - v5] repaint?
Yes
At least one pattern in the source can repaint: intrabar recalculation.
How did Divergence for Many [Dimkud - v5] do on BTCUSDT 1D with default settings?
−0.02%
From 26 Jan 2024 to 21 Oct 2026, over 24 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Does Divergence for Many [Dimkud - v5] run in Pine Script v6?
No
The v6 version does not run in Zeal Terminal's engine: Pine Script v6 Error at @L306:C10: cannot use 'float' 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 Divergence for Many [Dimkud - v5] use a stop loss?
Yes
strategy.exit sets a stop on line 1021, 1023.
Does Divergence for Many [Dimkud - v5] run in Zeal Terminal?
Yes
It compiles in 335 ms and runs 1,000 bars in 2,749 ms, in the browser.

BTCUSDT · 1D · default settings

  • UP
  • Mid
  • DOWN
  • Up Trend
  • Down Trend
  • Precio Entrada
  • SHORT Take Profit
  • Short Stop Loss
  • Winning trade
  • Losing trade
  • Equity
  • Buy and hold
Prerendered with the defaults. Change anything and run it here. The script runs in your browser.
Settings (151)
27112611127315252271111563611340,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$1,000$2,025Equity from $1,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. Lines, boxes and labels are the script's own drawings, the most recent ones its limits keep. 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.
Net profit
−0.02%
−$0.24
Buy and hold
+102.5%
same period
Closed trades
24
13 won · 11 lost
Profitable
54.2%
of closed trades
Profit factor
0.99
gross profit ÷ gross loss
Max drawdown
0.42%
−$4.24

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.

  • Likely bug

    ta.sma(ta.stoch(close, high, low, dimSTOCHlength), 3) ignores the settings line 107

    Line 107 hard-codes 3 where line 140 uses “CMF period(21)”. Changing those settings moves one band but not this one.

    ta.sma(ta.stoch(close, high, low, dimSTOCHlength), 3)ta.sma(ta.stoch(close, high, low, dimSTOCHlength), dimCMFperiod)
  • Likely bug

    ta.sma(close, 50) ignores the settings line 267

    Line 267 hard-codes 50 where line 140 uses “CMF period(21)”. Changing those settings moves one band but not this one.

    ta.sma(close, 50)ta.sma(close, dimCMFperiod)
  • Likely bug

    ta.sma(close, 200) ignores the settings line 268

    Line 268 hard-codes 200 where line 140 uses “CMF period(21)”. Changing those settings moves one band but not this one.

    ta.sma(close, 200)ta.sma(close, dimCMFperiod)
  • Likely bug

    ta.ema(ta.change(close) <= 0 ? 0 : stddevRVI, 14) ignores the settings line 222

    Line 222 hard-codes 14 where line 170 uses “Signal Line Length(5)”. Changing those settings moves one band but not this one.

    ta.ema(ta.change(close) <= 0 ? 0 : stddevRVI, 14)ta.ema(ta.change(close) <= 0 ? 0 : stddevRVI, siglenSMIO)
  • Likely bug

    ta.ema(ta.change(close) > 0 ? 0 : stddevRVI, 14) ignores the settings line 223

    Line 223 hard-codes 14 where line 170 uses “Signal Line Length(5)”. Changing those settings moves one band but not this one.

    ta.ema(ta.change(close) > 0 ? 0 : stddevRVI, 14)ta.ema(ta.change(close) > 0 ? 0 : stddevRVI, siglenSMIO)
  • Note

    4 settings have no label

    In the settings dialog testStartMonth (line 35), testStartDay (line 36), testStopMonth (line 40), testStopDay (line 41) 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.

Settings

Every input the script declares, with its default and what it feeds. Bounds are the ones the script enforces.

SettingDefaultType and rangeFeeds
Static SL/TP
Display Visualisation for TP/SL ?falsebooldisplTPSL
Use Long ?falseboolentry buy line 1008
Use Short ?trueboolentry sell line 1013
SL = TP ?falseboollongSLPerc
Use Opposite Signal SL ?falseboolline 975
New Opposite-Order after SL ?After SL - create new order with with opposite directionfalseboolline 997
Take Profit (%)0.9float · min 0.0 · step 0.1longSLPerc shortProfitPerc longExitPrice
Stop Loss (%)0.9float · min 0.0 · step 0.1shortSLPerc longSLExitPrice
Testing Period
Start Year2022inttestPeriodStart
Test Start Month (no label in the script)5inttestPeriodStart
Test Start Day (no label in the script)1inttestPeriodStart
Stop Year2030inttestPeriodStop
Test Stop Month (no label in the script)12inttestPeriodStop
Test Stop Day (no label in the script)30inttestPeriodStop
Main Divergence Settings
Pivot Period(9)9int · min 1 · max 50ph pl len plotshape
Source for Pivot PointsClosestring · options ['Close', 'High/Low']ph pl prsc new_line
Show Indicator NamesDon\'t Showstring · options ['Full', 'First Letter', 'Don\'t Show']divergence_text_top divergence_text_bottom line 278 line 279 line 280 line 281 line 282 line 283 line 284 line 285 line 286 line 287 line 288 line 289 line 290 line 291 line 292 line 293 line 294 line 295 line 296 line 590
Maximum Pivot Points to Check10int · min 10 · max 20line 338 line 369
Maximum Bars to Check100int · min 100 · max 200line 341 line 372
Show Divergence Numbertrueboolline 590 line 591 line 594
Show Only Last Divergencefalseboolline 548 line 552 line 561 line 565 line 598 line 602
Don\'t Wait for Confirmationfalseboolstartpoint line 335 line 366
Show Divergence Linesfalseboolnew_line
Show Pivot Pointsfalseboolplotshape
MACDtrueboolline 91 line 407 line 408
Fast(12):12int · min 1 · max 70macd2 signal deltamacd2
Slow(26):26int · min 1 · max 70macd2 signal deltamacd2
Sign(9):9int · min 1 · max 70macd2 signal deltamacd2
MACD Histogramtrueboolline 91 line 409 line 410
RSItrueboolline 99 line 411 line 412
RSI period (14):14int · min 1 · max 70rsi
Stochastictrueboolline 105 line 413 line 414
STOCH Length(14):14int · min 1 · max 70stk
CCItrueboolline 111 line 415 line 416
CCI Length(10)10int · min 1 · max 70cci
Momentumtrueboolline 117 line 417 line 418
Momentum Length(10)10int · min 1 · max 70moment
OBVtrueboolline 122 line 419 line 420
VWmacdtrueboolline 128 line 421 line 422
Volume Weighted Macd. Fast(12)12int · min 1 · max 70maFast
Slow(26)26int · min 1 · max 70maSlow
Chaikin Money Flowtrueboolline 136 line 423 line 424
CMF period(21)21int · min 1 · max 70cmf
Money Flow Indextrueboolline 144 line 425 line 426
Mfi length(14)14int · min 1 · max 70Mfi
Williams_Vix_Fixtrueboolline 151 line 431 line 432
Williams_Vix_Fix Period(21)21intwvf
Short period(12)12int · min 1maSlowVWMACD_LB
Long period(26)26int · min 1maFastVWMACD_LB
Smoothing period(9)9int · min 1maSignalVWMACD_LB
Check External Indicatorfalseboolline 427 line 428
External Indicatorclosesourceline 428
Positive Regular Divergencecolor.yellowvalueline 299
Negative Regular Divergencecolor.navyvalueline 300
Positive Hidden Divergencecolor.limevalueline 301
Negative Hidden Divergencecolor.redvalueline 302
Positive Divergence Text Colorcolor.blackvalueline 604
Negative Divergence Text Colorcolor.whitevalueline 600
Regular Divergence Line StyleSolidstring · options ['Solid', 'Dashed', 'Dotted']reg_div_l_style
Hdden Divergence Line StyleDashedstring · options ['Solid', 'Dashed', 'Dotted']hid_div_l_style
Regular Divergence Line Width2int · min 1 · max 5new_line
Hidden Divergence Line Width1int · min 1 · max 5new_line
Show MAs 50 & 200falseboolplot
Cma1col (no label in the script)color.limecolorplot
Cma2col (no label in the script)color.redcolorplot
Stochastic RSI
Use Stochastic RSI ?trueboolline 159 line 433 line 434
Stochastic K(3)3int · min 1StochRSIk
RSI Length(14)14int · min 1rsi1
Stochastic Length(14)14int · min 1StochRSIk
SMI Ergodic Oscillator
Use SMIO ?trueboolline 168 line 435 line 436
Long Length(20)20int · min 1ergSMIO
Short Length(5)5int · min 1ergSMIO
Signal Line Length(5)5int · min 1sigSMIO
Volume Weighted MACD [LazyBear]
Use VWMACD_LB ?trueboolline 178 line 437 line 438
Bull Bear Power
Use BBPtrueboolline 188 line 439 line 440
BBP Length(13)13int · min 1bullPowerBBP bearPowerBBP
Balance of Power
Use BOPtrueboolline 197 line 441 line 442
BOP Smooth Length(20)20int · min 1SmoothBOP
TRIPLE Smooth Length(20)20int · min 1xEMA1 xEMA2 xEMA3
Relative Volatility Index
Use RVItrueboolline 220 line 443 line 444
RVI length(10)10int · min 1stddevRVI
MA TypeWMAstring · options ['SMA', 'EMA', 'SMMA (RMA)', 'WMA', 'VWMA']rviMA
MA Length(14)14intrviMA
Logistic Settings
Logistic Dominancetrueboolline 243 line 429 line 430
Map Length(13)13int · min 1mapeq
Dominance(5)5int · min 1r
Keltner Channel
Use Channel ?falsebooldispl line 638
Channel to Use:Keltner Channelstring · options ['Keltner Channel', 'Bollinger Bands']line 626
Enter ConditionsWick out of bandstring · options ['Wick out of band', 'Wick out of the band then close in', 'Out-of-band closure', 'Close out of the band then close in']line 641 line 645 line 649
Keltner Long.14int · min 1KC_mid KC_upper KC_lower
Keltner Mult.1.5float · min 0.01 · step 0.05KC_mid KC_upper KC_lower
BB Long. 20int · min 1BB_mid BB_upper BB_lower
BB Deviation (Desv.)2.0float · min 0.01 · step 0.1BB_mid BB_upper BB_lower
RSI FILTER
RSI TF Long(14):14int · min 1rsi_tf1
RSI TimeFrame:timeframersi_tf1
Use RSI LONG Rangefalseboolline 678 line 681
(LONG) RSI is More30int · min 1 · step 5line 681
& RSI Less70int · min 1 · max 100 · step 5line 681
Use RSI SHORT Rangefalseboolline 678 line 684
(SHORT) RSI is Less70int · min 1 · max 100 · step 5line 684
& RSI More30int · min 1 · step 5line 684
RSI FILTER - Multi TimeFrame [2]
RSI TF Long(14):[2]14int · min 1rsi_tf2
RSI TimeFrame:[2]timeframersi_tf2
Use RSI LONG Range[2]falseboolline 706 line 709
(LONG) RSI is More[2]30int · min 1 · step 5line 709
& RSI Less[2]70int · min 1 · max 100 · step 5line 709
Use RSI SHORT Range[2]falseboolline 706 line 712
(SHORT) RSI is Less[2]70int · min 1 · max 100 · step 5line 712
& RSI More[2]30int · min 1 · step 5line 712
MFI FILTER
MFI TF Long:14int · min 1mfi_tf1
MFI TimeFrame:timeframemfi_tf1 mfi_tf1_falling_tf mfi_tf1_rising_tf
Use MFI LONG Rangefalseboolline 735 line 738
(LONG) MFI is More10int · min 1 · step 5line 738
& MFI Less60int · min 1 · max 100 · step 5line 738
Use MFI SHORT Rangefalseboolline 735 line 741
(SHORT) MFI is Less95int · min 1 · max 100 · step 5line 741
& MFI More50int · min 1 · max 100 · step 5line 741
Use MFI TF Rising ?falseboolline 764 line 769
MFI TF Rising Lengh:3int · min 0 · max 20mfi_tf1_rising
Use MFI TF Falling ?falseboolline 764 line 769
MFI TF Falling Lengh:3int · min 0 · max 20mfi_tf1_falling
Two ATR (Volatility Check) Base Settings
ATR length1 (20)(5)20int · min 1datr1
ATR length2 (100)(20)100int · min 1datr2
ATR SmoothingWMAstring · options ['RMA', 'SMA', 'EMA', 'WMA']line 787 line 790 line 793
Use ATR1 <> ATR2 ? falsebooldatr1todatr3 line 812
ATR1 to ATR2ATR1 < ATR2 - Volatility is Small in last bars, ATR1 > ATR2 - Volatility is High in last barsATR1 < ATR2string · options ['ATR1 < ATR2', 'ATR1 > ATR2']datr1todatr3
Volume Filter
Use VOL1 <> VOL2 ? falseboollongCondition11 line 849
VOL1 to VOL2VOL1 < VOL2 - Volume is Small in last bars, VOL1 > VOL2 - Volume is High in last barsVOL1 < VOL2string · options ['VOL1 < VOL2', 'VOL1 > VOL2']longCondition11
VOL length1 (20)(5)20int · min 1vol1
VOL length2 (100)(20)100int · min 1 · step 5vol2
VOL SmoothingWMAstring · options ['RMA', 'SMA', 'EMA', 'WMA']line 835 line 838 line 841
CCI FILTER
CCI TF Long(14):14int · min 1CCI_tf1
CCI TimeFrame:timeframeCCI_tf1
Use CCI LONG Rangefalseboolline 874 line 877
(LONG) CCI is More-400int · min -400 · step 5line 877
& CCI Less400int · min -401 · max 400 · step 5line 877
Use CCI SHORT Rangefalseboolline 874 line 880
(SHORT) CCI is Less400int · min -401 · max 400 · step 5line 880
& CCI More10int · min -401 · step 5line 880
Momentum FILTER
Momentum TF Long(14):14int · min 1sm1 sm2
Momentum TimeFrame:timeframeMOM_tf2
Use Momentum LONG Range (-100:100)falseboolline 912 line 915
(LONG) Momentum is More-100int · min -100 · max 100 · step 5line 915
& Mom Less10int · min -100 · max 100 · step 5line 915
Use Momentum SHORT Range (100:-100)falseboolline 912 line 918
(SHORT) Momentum is Less95int · min -100 · max 100 · step 5line 918
& Mom More-30int · min -100 · max 100 · step 5line 918
Momentum Sourceclosesourcemomm
SUPER TREND FILTER
Use SuperTrend ?falseboolline 961
Opposite SP Signal? (Sell on UPtrend..)falseboollongCondition5 shortCondition5
SuperTrend ATR Period10int · min 1atr2ST atrST
SuperTrend ATR Multiplier3.0float · step 0.1upST dnST
Show SuperTrend ?falsebooldisplST

What it calculates

  • RSIclose, RSI period (14): (14)rsi · line 101
  • SMA / Stochta.stoch(close, high, low, dimSTOCHlength), 3stk · line 107
  • CCIclose, CCI Length(10) (10)cci · line 113
  • MOMclose, Momentum Length(10) (10)moment · line 119
  • OBVObv · line 123
  • SMACmfv, CMF period(21) (21)cmf · line 140
  • MFIclose, Mfi length(14) (14)Mfi · line 146
  • Highestclose, Williams_Vix_Fix Period(21) (21)wvf · line 152
  • SMA / Stochta.stoch(rsi1, rsi1, rsi1, lengthStoch), Stochastic K(3) (3)StochRSIk · line 161
  • SMA / EMA / RMA / WMA / VWMArviRVI, MA Length(14) (14) · chosen by MA TyperviMA · line 225
  • MACDclose, Fast(12): (12), Slow(26): (26), Sign(9): (9)macd2 · line 93
  • MACDclose, Fast(12): (12), Slow(26): (26), Sign(9): (9)signal · line 93
  • MACDclose, Fast(12): (12), Slow(26): (26), Sign(9): (9)deltamacd2 · line 93
  • VWMAclose, Volume Weighted Macd. Fast(12) (12)maFast · line 130
  • VWMAclose, Slow(26) (26)maSlow · line 131
  • RSIclose, RSI Length(14) (14)rsi1 · line 160
  • TSIclose, Short Length(5) (5), Long Length(20) (20)ergSMIO · line 169
  • EMAergSMIO, Signal Line Length(5) (5)sigSMIO · line 170
  • EMAvolume * close, Long period(26) (26)maFastVWMACD_LB · line 179
  • EMAvolume * close, Short period(12) (12)maSlowVWMACD_LB · line 180
  • EMAdVWMACD_LB, Smoothing period(9) (9)maSignalVWMACD_LB · line 182
  • EMAclose, BBP Length(13) (13)bullPowerBBP · line 189
  • EMAclose, BBP Length(13) (13)bearPowerBBP · line 190
  • EMABOP, BOP Smooth Length(20) (20)SmoothBOP · line 208
  • EMASmoothBOP, TRIPLE Smooth Length(20) (20)xEMA1 · line 209
  • EMAxEMA1, TRIPLE Smooth Length(20) (20)xEMA2 · line 210
  • EMAxEMA2, TRIPLE Smooth Length(20) (20)xEMA3 · line 211
  • Stdevclose, RVI length(10) (10)stddevRVI · line 221
  • EMA / Changeta.change(close) <= 0 ? 0 : stddevRVI, 14upperRVI · line 222
  • EMA / Changeta.change(close) > 0 ? 0 : stddevRVI, 14lowerRVI · line 223
  • Changesource2, Dominance(5) (5)r · line 244
  • Pivothighsource == 'Close' ? close : high, Pivot Period(9) (9), Pivot Period(9) (9) · chosen by Source for Pivot Pointsph · line 304
  • Pivotlowsource == 'Close' ? close : low, Pivot Period(9) (9), Pivot Period(9) (9) · chosen by Source for Pivot Pointspl · line 305
  • KCclose, Keltner Long. (14), Keltner Mult. (1.5)KC_mid · line 618
  • KCclose, Keltner Long. (14), Keltner Mult. (1.5)KC_upper · line 618
  • KCclose, Keltner Long. (14), Keltner Mult. (1.5)KC_lower · line 618
  • BBclose, BB Long. (20), BB Deviation (Desv.) (2.0)BB_mid · line 622
  • BBclose, BB Long. (20), BB Deviation (Desv.) (2.0)BB_upper · line 622
  • BBclose, BB Long. (20), BB Deviation (Desv.) (2.0)BB_lower · line 622
  • RSIclose, RSI TF Long(14): (14)rsi_tf1 · line 674
  • RSIclose, RSI TF Long(14):[2] (14)rsi_tf2 · line 702
  • MFIhlc3, MFI TF Long: (14)mfi_tf1 · line 729
  • Fallingmfi_tf1, MFI TF Falling Lengh: (3)mfi_tf1_falling · line 754
  • Risingmfi_tf1, MFI TF Rising Lengh: (3)mfi_tf1_rising · line 755
  • TRtruedatr1 · line 797
  • TRtruedatr2 · line 798
  • CCIclose, CCI TF Long(14): (14)CCI_tf1 · line 870
  • ChangeMomentum Source (close)momm · line 898
  • SMAta.tr, SuperTrend ATR Period (10)atr2ST · line 936
  • ATRSuperTrend ATR Period (10)atrST · line 937

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 230 named inputs, calculations, conditions and outputs, too many to draw legibly here; the tables above list them.

Order rules

OrderFires whenBy defaultLine
Close sellpos_reg_div_detected and longCondition1 and longCondition2 and longCondition3 and longCondition4 and longCondition5 and longCondition8 and longCondition9 and longCondition10 and longCondition11 and longCondition12On978
Close buyneg_reg_div_detected and shortCondition1 and shortCondition2 and shortCondition3 and shortCondition4 and shortCondition5 and shortCondition8 and shortCondition9 and shortCondition10 and shortCondition11 and shortCondition12On982
Open sell222 shortwasLongOn1000
Open buy222 longwasShortOn1004
Open buy longpos_reg_div_detected and enable_long_strategy and testPeriod() and NotMultiOrders and longCondition1 and longCondition2 and longCondition3 and longCondition4 and longCondition5 and longCondition8 and longCondition9 and longCondition10 and longCondition11 and longCondition12On1009
Open sell shortneg_reg_div_detected and enable_short_strategy and testPeriod() and NotMultiOrders and shortCondition1 and shortCondition2 and shortCondition3 and shortCondition4 and shortCondition5 and shortCondition8 and shortCondition9 and shortCondition10 and shortCondition11 and shortCondition12On1014
Exit Close Long % stop and limitstrategy.position_size > 0On1021
Exit Close Short % stop and limitstrategy.position_size < 0On1023

Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.

Does it repaint?

Yes

At least one pattern in the source can repaint; it is marked Check below.

0/6trades identical when replayed liveThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, four per bar, and compared with the historical run. On 1 of them the position changed while the bar was forming before it settled. Anyone watching live sees those changes; once the bar closes it matches history.

The script reads request.security() at the chart's own timeframe, which Zeal Terminal's engine answers one bar late in live mode but not in history, so this replay cannot tell repainting from that engine issue.

  • ClearHigher-timeframe data1 request.security call(s), none with lookahead on.
  • ClearFuture-bar referencesNo negative history offsets such as close[-1].
  • CheckIntrabar recalculationreads realtime-only state. 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.

MarketNetBuy and holdTradesWonProfit factorMax drawdownPeriod
BTCUSDT 1D−0.0%+102.5%2454%0.990.4%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h+0.2%+5.5%1958%1.140.8%8 May 2026 – 21 Oct 2026
ETHUSDT 1D−0.7%+9.8%2446%0.710.7%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h−1.5%+8.4%2638%0.522.0%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−0.3%+16.7%3152%0.891.2%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h−0.6%+21.5%2548%0.771.2%8 May 2026 – 21 Oct 2026
BNBUSDT 1D−1.7%+148.3%3642%0.602.0%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h−0.4%+17.1%2450%0.840.7%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 barsTradesWonP&L
Rising market1346%−$3.88
Sideways market757%$0.68
Falling market475%$2.96

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

How bad could the drawdown be?

1.3%

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

0%1%
All 24 trades
SideEntryExitBarsP&L
short17 May 2024 65,235.2017 May 2024 65,822.300−$1.96
short19 May 2024 66,915.2019 May 2024 67,517.400−$1.96
short22 May 2024 70,148.3022 May 2024 69,517.000$1.64
short17 Oct 2024 67,620.0017 Oct 2024 67,011.400$1.64
short20 Oct 2024 68,378.0020 Oct 2024 68,993.400−$1.96
short22 Oct 2024 67,377.5022 Oct 2024 66,771.100$1.64
short31 Oct 2024 72,344.8031 Oct 2024 71,693.600$1.64
short13 Nov 2024 87,952.0013 Nov 2024 87,160.400$1.64
short15 Nov 2024 87,325.6015 Nov 2024 88,111.500−$1.96
short17 Nov 2024 90,588.0017 Nov 2024 91,403.300−$1.96
short9 Dec 2024 101,110.009 Dec 2024 100,200.000$1.64
short17 Dec 2024 106,059.0017 Dec 2024 107,013.000−$1.96
short20 Jan 2025 101,332.0020 Jan 2025 100,420.000$1.64
short23 Jan 2025 103,707.0023 Jan 2025 102,773.000$1.64
short13 Jul 2025 117,420.0013 Jul 2025 118,477.000−$1.96
short15 Jul 2025 119,841.0015 Jul 2025 118,763.000$1.64
short15 Aug 2025 118,295.0015 Aug 2025 117,230.000$1.64
short4 Oct 2025 122,232.005 Oct 2025 123,332.001−$1.96
short7 Jan 2026 93,748.007 Jan 2026 92,904.200$1.64
short18 Mar 2026 73,909.4018 Mar 2026 74,574.600−$1.96
short19 Apr 2026 75,691.8019 Apr 2026 75,010.500$1.64
short23 Jul 2026 66,114.5023 Jul 2026 65,519.500$1.64
short23 Aug 2026 77,074.9023 Aug 2026 77,768.600−$1.96
short23 Sep 2026 86,208.6023 Sep 2026 86,984.400−$1.96

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
Divergence for Many [Dimkud - v5] this page—v5 strategy−0.0%240.4%
supertrend with multiple filter strategy by mathlabelsma highest macd ema mfi cci atr stdev stoch pivothigh pivotlow wma rsiv5 strategydoes not run in Zeal Terminal

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.

  • 33 settings use the untyped input() (line 8, 13, 61, 62, 63, 64, 65, 86, 90, 97, 103, 109, 115, 121, 125, 134, 142, 149, 150, 252, 253, 254, 255, 256, 257, 258, 259, 807, 829, 897, 927, 928, 935). 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.

Clean v5

VerifiedDownload the v5 script

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

  • Line 8: input() → input.bool()
  • Line 13: input() → input.bool()
  • Line 61: input() → input.bool()
  • Line 62: input() → input.bool()
  • Line 63: input() → input.bool()
  • Line 64: input() → input.bool()
27 more edits
  • Line 65: input() → input.bool()
  • Line 86: input() → input.bool()
  • Line 90: input() → input.bool()
  • Line 97: input() → input.bool()
  • Line 103: input() → input.bool()
  • Line 109: input() → input.bool()
  • Line 115: input() → input.bool()
  • Line 121: input() → input.bool()
  • Line 125: input() → input.bool()
  • Line 134: input() → input.bool()
  • Line 142: input() → input.bool()
  • Line 149: input() → input.bool()
  • Line 150: input() → input.int()
  • Line 252: input() → input.bool()
  • Line 253: input() → input.source()
  • Line 254: input() → input.color()
  • Line 255: input() → input.color()
  • Line 256: input() → input.color()
  • Line 257: input() → input.color()
  • Line 258: input() → input.color()
  • Line 259: input() → input.color()
  • Line 807: input() → input.bool()
  • Line 829: input() → input.bool()
  • Line 897: input() → input.source()
  • Line 927: input() → input.bool()
  • Line 928: input() → input.bool()
  • Line 935: input() → input.bool()
⋯GRUPO_statSLTP = 'Static SL/TP'-USEdisplTPSL =  input(defval=false, title='Display Visualisation for TP/SL ?', group = GRUPO_statSLTP)+USEdisplTPSL =  input.bool(defval=false, title='Display Visualisation for TP/SL ?', group = GRUPO_statSLTP)enable_long_strategy = input.bool(false, title='Use Long ?', group=GRUPO_statSLTP, inline='11')⋯USE_SignSL = input.bool(false, 'Use Opposite Signal SL ?', group=GRUPO_statSLTP)-USEorderOnSL =  input(defval=false, title='New Opposite-Order after SL ?', group = GRUPO_statSLTP, tooltip = 'After SL - create new order with with opposite direction')+USEorderOnSL =  input.bool(defval=false, title='New Opposite-Order after SL ?', group = GRUPO_statSLTP, tooltip = 'After SL - create new order with with opposite direction')longProfitPerc = input.float(defval=0.9, title='Take Profit (%)', group=GRUPO_statSLTP, minval=0.0, step=0.1) / 100⋯maxbars = input.int(defval=100, title='Maximum Bars to Check', minval=100, maxval=200, group = grMAINset)-shownum = input(defval=true, title='Show Divergence Number', group = grMAINset)+shownum = input.bool(defval=true, title='Show Divergence Number', group = grMAINset)-showlast = input(defval=false, title='Show Only Last Divergence', group = grMAINset)+showlast = input.bool(defval=false, title='Show Only Last Divergence', group = grMAINset)-dontconfirm = input(defval=false, title='Don\'t Wait for Confirmation', group = grMAINset)+dontconfirm = input.bool(defval=false, title='Don\'t Wait for Confirmation', group = grMAINset)-showlines = input(defval=false, title='Show Divergence Lines', group = grMAINset)+showlines = input.bool(defval=false, title='Show Divergence Lines', group = grMAINset)-showpivot = input(defval=false, title='Show Pivot Points', group = grMAINset)+showpivot = input.bool(defval=false, title='Show Pivot Points', group = grMAINset)// declaration⋯// declaration-calcmacd = input(defval=true, title='MACD')+calcmacd = input.bool(defval=true, title='MACD')dimmacdFast = input.int(defval=12, title='Fast(12):', minval=1, maxval=70, inline='223')⋯dimmacdSignal = input.int(defval=9, title='Sign(9):', minval=1, maxval=70, inline='223')-calcmacda = input(defval=true, title='MACD Histogram')+calcmacda = input.bool(defval=true, title='MACD Histogram')if calcmacd or calcmacda⋯    deltamacd-calcrsi = input(defval=true, title='RSI')+calcrsi = input.bool(defval=true, title='RSI')dimRSI = input.int(defval=14, title='RSI period (14):', minval=1, maxval=70)⋯    rsi-calcstoc = input(defval=true, title='Stochastic')+calcstoc = input.bool(defval=true, title='Stochastic')dimSTOCHlength = input.int(defval=14, title='STOCH Length(14):', minval=1, maxval=70)⋯    stk-calccci = input(defval=true, title='CCI')+calccci = input.bool(defval=true, title='CCI')dimCCIL = input.int(defval=10, title='CCI Length(10)', minval=1, maxval=70, inline='')⋯    cci-calcmom = input(defval=true, title='Momentum')+calcmom = input.bool(defval=true, title='Momentum')dimmomentL = input.int(defval=10, title='Momentum Length(10)', minval=1, maxval=70, inline='')⋯    moment-calcobv = input(defval=true, title='OBV')+calcobv = input.bool(defval=true, title='OBV')if calcobv⋯    Obv-calcvwmacd = input(true, title='VWmacd')+calcvwmacd = input.bool(true, title='VWmacd')dimmaFast = input.int(defval=12, title='Volume Weighted Macd. Fast(12)', minval=1, maxval=70, inline='112')⋯    vwmacd-calccmf = input(true, title='Chaikin Money Flow')+calccmf = input.bool(true, title='Chaikin Money Flow')dimCMFperiod = input.int(defval=21, title='CMF period(21)', minval=1, maxval=70, inline='')⋯    cmf-calcmfi = input(true, title='Money Flow Index')+calcmfi = input.bool(true, title='Money Flow Index')dimMfilength = input.int(defval=14, title='Mfi length(14)', minval=1, maxval=70, inline='')⋯//==================================================================================-calcWVIX = input(true, title='Williams_Vix_Fix')+calcWVIX = input.bool(true, title='Williams_Vix_Fix')-pd = input(21, title='Williams_Vix_Fix Period(21)')+pd = input.int(21, title='Williams_Vix_Fix Period(21)')if calcWVIX⋯//==================================================================================-calcext = input(false, title='Check External Indicator')+calcext = input.bool(false, title='Check External Indicator')-externalindi = input(defval=close, title='External Indicator')+externalindi = input.source(defval=close, title='External Indicator')-pos_reg_div_col = input(defval=color.yellow, title='Positive Regular Divergence')+pos_reg_div_col = input.color(defval=color.yellow, title='Positive Regular Divergence')-neg_reg_div_col = input(defval=color.navy, title='Negative Regular Divergence')+neg_reg_div_col = input.color(defval=color.navy, title='Negative Regular Divergence')-pos_hid_div_col = input(defval=color.lime, title='Positive Hidden Divergence')+pos_hid_div_col = input.color(defval=color.lime, title='Positive Hidden Divergence')-neg_hid_div_col = input(defval=color.red, title='Negative Hidden Divergence')+neg_hid_div_col = input.color(defval=color.red, title='Negative Hidden Divergence')-pos_div_text_col = input(defval=color.black, title='Positive Divergence Text Color')+pos_div_text_col = input.color(defval=color.black, title='Positive Divergence Text Color')-neg_div_text_col = input(defval=color.white, title='Negative Divergence Text Color')+neg_div_text_col = input.color(defval=color.white, title='Negative Divergence Text Color')reg_div_l_style_ = input.string(defval='Solid', title='Regular Divergence Line Style', options=['Solid', 'Dashed', 'Dotted'])⋯//grATR1ATR2 = "=============== Two ATR (ATR1 <> ATR2)=============="-use_atr1toart2_more_less = input(defval=false, title='Use ATR1 <> ATR2 ? ', group = grDATR)+use_atr1toart2_more_less = input.bool(defval=false, title='Use ATR1 <> ATR2 ? ', group = grDATR)atr1toart2_more_less = input.string(title='ATR1 to ATR2', defval='ATR1 < ATR2', options=['ATR1 < ATR2', 'ATR1 > ATR2'], group = grDATR, tooltip = "ATR1 < ATR2 - Volatility is Small in last bars, ATR1 > ATR2 - Volatility is High in last bars")⋯grVOL="=======Volume Filter========="-use_VOL_more_less = input(defval=false, title='Use VOL1 <> VOL2 ? ', group = grVOL)+use_VOL_more_less = input.bool(defval=false, title='Use VOL1 <> VOL2 ? ', group = grVOL)VOL_more_less = input.string(title='VOL1 to VOL2', defval='VOL1 < VOL2', options=['VOL1 < VOL2', 'VOL1 > VOL2'], group = grVOL, tooltip = "VOL1 < VOL2 - Volume is Small in last bars, VOL1 > VOL2 - Volume is High in last bars")⋯overBought2MOMTF = input.int(title='& Mom More', group=GRUPO_MOM_TF, defval=-30, minval=-100, maxval = 100, step=5, inline='33')-srcMOM = input(close, "Momentum Source", group=GRUPO_MOM_TF)+srcMOM = input.source(close, "Momentum Source", group=GRUPO_MOM_TF)momm = ta.change(srcMOM)⋯grSUPTREND = "=============SUPER TREND FILTER============="-useSUPTREND = input(defval=false, title='Use SuperTrend ?', group = grSUPTREND)+useSUPTREND = input.bool(defval=false, title='Use SuperTrend ?', group = grSUPTREND)-opposite_SUPTREND = input(defval=false, title='Opposite SP Signal? (Sell on UPtrend..)', group = grSUPTREND)+opposite_SUPTREND = input.bool(defval=false, title='Opposite SP Signal? (Sell on UPtrend..)', group = grSUPTREND)PeriodsST = input.int(title='SuperTrend ATR Period', defval=10, minval=1, group=grSUPTREND)⋯changeATR = true-highlightingST = input(title='Show SuperTrend ?', defval=false, group=grSUPTREND)+highlightingST = input.bool(title='Show SuperTrend ?', defval=false, group=grSUPTREND)atr2ST = ta.sma(ta.tr, PeriodsST)⋯

Does it run in Pine Script v6?

No

The v6 version does not run in Zeal Terminal's engine: Pine Script v6 Error at @L306:C10: cannot use 'float' 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.

⋯// which is based on "Divergence for Many Indicator" indicator by LonesomeTheBlue-//@version=5+//@version=6strategy('Divergence for Many [Dimkud - v5]', overlay=true, calc_on_order_fills=true,  commission_type=strategy.commission.percent, commission_value=0.04, default_qty_type=strategy.cash, default_qty_value=200, initial_capital=1000)⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 335 msWith a workaround 1,000 bars in 2,749 msNot measured
PineTSNot testedNot testedNot 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.

The engine and this page's reading of the source count a different number of settings, so one of them has missed one.

“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/// Strategy based on "Divergence for Many Indicators v4 ST" by CannyTolany01// which is based on "Divergence for Many Indicator" indicator by LonesomeTheBlue//@version=5strategy('Divergence for Many [Dimkud - v5]', overlay=true, calc_on_order_fills=true,  commission_type=strategy.commission.percent, commission_value=0.04, default_qty_type=strategy.cash, default_qty_value=200, initial_capital=1000)// DIMAK  Static SL/TP - BeginGRUPO_statSLTP = 'Static SL/TP'USEdisplTPSL =  input(defval=false, title='Display Visualisation for TP/SL ?', group = GRUPO_statSLTP)enable_long_strategy = input.bool(false, title='Use Long ?', group=GRUPO_statSLTP, inline='11')enable_short_strategy = input.bool(true, title='Use Short ?', group=GRUPO_statSLTP, inline='11')SLsameTP = input.bool(false, 'SL = TP ?', group=GRUPO_statSLTP)USE_SignSL = input.bool(false, 'Use Opposite Signal SL ?', group=GRUPO_statSLTP)USEorderOnSL =  input(defval=false, title='New Opposite-Order after SL ?', group = GRUPO_statSLTP, tooltip = 'After SL - create new order with with opposite direction')longProfitPerc = input.float(defval=0.9, title='Take Profit (%)', group=GRUPO_statSLTP, minval=0.0, step=0.1) / 100longSLPerc = input.float(defval=0.9, title='Stop Loss (%)', group=GRUPO_statSLTP, minval=0.0, step=0.1) / 100longSLPerc := SLsameTP ? longProfitPerc : longSLPercshortProfitPerc = longProfitPercshortSLPerc = longSLPerclongExitPrice = strategy.position_avg_price * (1 + longProfitPerc)shortExitPrice = strategy.position_avg_price * (1 - shortProfitPerc)longSLExitPrice = strategy.position_avg_price * (1 - longSLPerc)shortSLExitPrice = strategy.position_avg_price * (1 + shortSLPerc)// use such: limit=shortExitPrice, stop=shortSLExitPrice// DIMAK  Static SL/TP - END// ===================================================================================================// DIMAK - TimeFrame request.security - Repaint-Non Repaintf_security(_sym, _res, _src, _rep) =>    request.security(_sym, _res, _src[not _rep and barstate.isrealtime ? 1 : 0])[_rep or barstate.isrealtime ? 0 : 1]// DIMAK - TimeFrame request.security - Repaint-Non Repaint// Time filter =================================grTIMEset = "Testing Period"testPeriod() =>    // Testing Start dates    testStartYear = input.int(2022, 'Start Year', inline='date1', group=grTIMEset)    testStartMonth = input.int(5, '', inline='date1', group=grTIMEset)    testStartDay = input.int(1, '', inline='date1', group=grTIMEset)    testPeriodStart = timestamp(testStartYear, testStartMonth, testStartDay, 0, 0)    //Stop date if you want to use a specific range of dates    testStopYear = input.int(2030, 'Stop Year', inline='date2', group=grTIMEset)    testStopMonth = input.int(12, '', inline='date2', group=grTIMEset)    testStopDay = input.int(30, '', inline='date2', group=grTIMEset)    testPeriodStop = timestamp(testStopYear, testStopMonth, testStopDay, 0, 0)    time >= testPeriodStart and time < testPeriodStop ? true : false    // pass some date    //testPeriodStop2 =  timestamp(2022,6,14,0,0)    //testPeriodStop3 =  timestamp(2022,6,16,0,0)    //(time >= testPeriodStart) and (time < testPeriodStop) and ((time < testPeriodStop2) or (time > testPeriodStop3)) ? true : false// Time filter =================================grMAINset = "Main Divergence Settings"prd = input.int(defval=9, title='Pivot Period(9)', minval=1, maxval=50, group = grMAINset)source = input.string(defval='Close', title='Source for Pivot Points', options=['Close', 'High/Low'], group = grMAINset)//searchdiv = input.string(defval='Regular', title='Divergence Type', options=['Regular', 'Hidden', 'Regular/Hidden'], group = grMAINset)// works only Regularsearchdiv = 'Regular'showindis = input.string(defval='Don\'t Show', title='Show Indicator Names', options=['Full', 'First Letter', 'Don\'t Show'], group = grMAINset)//showlimit = input.int(1, title='Minimum Number of Divergence', minval=1, maxval=11)// not good results and not work nowshowlimit = 1maxpp = input.int(defval=10, title='Maximum Pivot Points to Check', minval=10, maxval=20, group = grMAINset)maxbars = input.int(defval=100, title='Maximum Bars to Check', minval=100, maxval=200, group = grMAINset)shownum = input(defval=true, title='Show Divergence Number', group = grMAINset)showlast = input(defval=false, title='Show Only Last Divergence', group = grMAINset)dontconfirm = input(defval=false, title='Don\'t Wait for Confirmation', group = grMAINset)showlines = input(defval=false, title='Show Divergence Lines', group = grMAINset)showpivot = input(defval=false, title='Show Pivot Points', group = grMAINset)// declarationmacd = 0.0deltamacd = 0.0rsi = 0.0stk = 0.0cci = 0.0moment = 0.0Obv = 0.0vwmacd = 0.0cmf = 0.0Mfi = 0.0aStDev = 0.0wvf = 0.0StochRSIk = 0.0oscSMIO = 0.0dmVWMACD_LB = 0.0BBPower = 0.0SmootherBOP = 0.0rviMA = 0.0// declarationcalcmacd = input(defval=true, title='MACD')dimmacdFast = input.int(defval=12, title='Fast(12):', minval=1, maxval=70, inline='223')dimmacdSlow = input.int(defval=26, title='Slow(26):', minval=1, maxval=70, inline='223')dimmacdSignal = input.int(defval=9, title='Sign(9):', minval=1, maxval=70, inline='223')calcmacda = input(defval=true, title='MACD Histogram')if calcmacd or calcmacda    //[macd, signal, deltamacd] = macd(close, 12, 26, 9) // MACD    [macd2, signal, deltamacd2] = ta.macd(close, dimmacdFast, dimmacdSlow, dimmacdSignal)  // MACD    macd := macd2    deltamacd := deltamacd2    deltamacdcalcrsi = input(defval=true, title='RSI')dimRSI = input.int(defval=14, title='RSI period (14):', minval=1, maxval=70)if calcrsi    //rsi = rsi(close, 14) // RSI    rsi := ta.rsi(close, dimRSI)  // RSI    rsicalcstoc = input(defval=true, title='Stochastic')dimSTOCHlength = input.int(defval=14, title='STOCH Length(14):', minval=1, maxval=70)if calcstoc    //stk = sma(stoch(close, high, low, 14), 3) // Stoch    stk := ta.sma(ta.stoch(close, high, low, dimSTOCHlength), 3)  // Stoch    stkcalccci = input(defval=true, title='CCI')dimCCIL = input.int(defval=10, title='CCI Length(10)', minval=1, maxval=70, inline='')if calccci    //cci = cci(close, 10) // CCI    cci := ta.cci(close, dimCCIL)  // CCI    ccicalcmom = input(defval=true, title='Momentum')dimmomentL = input.int(defval=10, title='Momentum Length(10)', minval=1, maxval=70, inline='')if calcmom    //moment = mom(close, 10) // Momentum    moment := ta.mom(close, dimmomentL)  // Momentum    momentcalcobv = input(defval=true, title='OBV')if calcobv    Obv := ta.obv  // OBV    Obvcalcvwmacd = input(true, title='VWmacd')dimmaFast = input.int(defval=12, title='Volume Weighted Macd. Fast(12)', minval=1, maxval=70, inline='112')dimmaSlow = input.int(defval=26, title='Slow(26)', minval=1, maxval=70, inline='112')if calcvwmacd    //maFast = vwma(close, 12), maSlow = vwma(close, 26), vwmacd = maFast - maSlow // volume weighted macd    maFast = ta.vwma(close, dimmaFast)    maSlow = ta.vwma(close, dimmaSlow)    vwmacd := maFast - maSlow  // volume weighted macd    vwmacdcalccmf = input(true, title='Chaikin Money Flow')dimCMFperiod = input.int(defval=21, title='CMF period(21)', minval=1, maxval=70, inline='')if calccmf    //Cmfm = ((close-low) - (high-close)) / (high - low), Cmfv = Cmfm * volume, cmf = sma(Cmfv, 21) / sma(volume,21) // Chaikin money flow    Cmfm = (close - low - (high - close)) / (high - low)    Cmfv = Cmfm * volume    cmf := ta.sma(Cmfv, dimCMFperiod) / ta.sma(volume, dimCMFperiod)  // Chaikin money flow    cmfcalcmfi = input(true, title='Money Flow Index')dimMfilength = input.int(defval=14, title='Mfi length(14)', minval=1, maxval=70, inline='')if calcmfi    //Mfi = mfi(close, 14) // Moneyt Flow Index    Mfi := ta.mfi(close, dimMfilength)  // Moneyt Flow Index    Mfi//==================================================================================calcWVIX = input(true, title='Williams_Vix_Fix')pd = input(21, title='Williams_Vix_Fix Period(21)')if calcWVIX    wvf := (ta.highest(close, pd) - low) / ta.highest(close, pd) * -100    wvf//==================================================================================calcStochRSI = input.bool(true, title='Use Stochastic RSI ?', group='Stochastic RSI')smoothK = input.int(3, 'Stochastic K(3)', minval=1, group='Stochastic RSI')lengthSTRSI = input.int(14, 'RSI Length(14)', minval=1, group='Stochastic RSI')lengthStoch = input.int(14, 'Stochastic Length(14)', minval=1, group='Stochastic RSI')if calcStochRSI    rsi1 = ta.rsi(close, lengthSTRSI)    StochRSIk := ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)    StochRSIk//==================================================================================calcSMIO = input.bool(true, title='Use SMIO ?', group='SMI Ergodic Oscillator')longlenSMIO = input.int(20, minval=1, title='Long Length(20)', group='SMI Ergodic Oscillator')shortlenSMIO = input.int(5, minval=1, title='Short Length(5)', group='SMI Ergodic Oscillator')siglenSMIO = input.int(5, minval=1, title='Signal Line Length(5)', group='SMI Ergodic Oscillator')if calcSMIO    ergSMIO = ta.tsi(close, shortlenSMIO, longlenSMIO)    sigSMIO = ta.ema(ergSMIO, siglenSMIO)    oscSMIO := ergSMIO - sigSMIO    oscSMIO//==================================================================================calcVWMACD_LB = input.bool(true, title='Use VWMACD_LB ?', group='Volume Weighted MACD [LazyBear]')slowVWMACD_LB = input.int(12, 'Short period(12)', minval=1)fastVWMACD_LB = input.int(26, 'Long period(26)', minval=1)signalVWMACD_LB = input.int(9, 'Smoothing period(9)', minval=1)if calcVWMACD_LB    maFastVWMACD_LB = ta.ema(volume * close, fastVWMACD_LB) / ta.ema(volume, fastVWMACD_LB)    maSlowVWMACD_LB = ta.ema(volume * close, slowVWMACD_LB) / ta.ema(volume, slowVWMACD_LB)    dVWMACD_LB = maSlowVWMACD_LB - maFastVWMACD_LB    maSignalVWMACD_LB = ta.ema(dVWMACD_LB, signalVWMACD_LB)    dmVWMACD_LB := dVWMACD_LB - maSignalVWMACD_LB    dmVWMACD_LB//==================================================================================calcBBP = input.bool(true, title='Use BBP', group='Bull Bear Power')lengthInputBBP = input.int(13, title='BBP Length(13)', minval=1, group='Bull Bear Power')if calcBBP    bullPowerBBP = high - ta.ema(close, lengthInputBBP)    bearPowerBBP = low - ta.ema(close, lengthInputBBP)    BBPower := bullPowerBBP + bearPowerBBP    BBPower//==================================================================================calcBOP = input.bool(true, title='Use BOP', group='Balance of Power')EMA = input.int(20, 'BOP Smooth Length(20)', minval=1, group='Balance of Power')TEMA = input.int(20, 'TRIPLE Smooth Length(20)', minval=1, group='Balance of Power')if calcBOP    THL = high != low ? high - low : 0.01    BullOpen = (high - open) / THL    BearOpen = (open - low) / THL    BullClose = (close - low) / THL    BearClose = (high - close) / THL    BullOC = close > open ? (close - open) / THL : 0    BearOC = open > close ? (open - close) / THL : 0    BullReward = (BullOpen + BullClose + BullOC) / 3    BearReward = (BearOpen + BearClose + BearOC) / 3    BOP = BullReward - BearReward    SmoothBOP = ta.ema(BOP, EMA)    xEMA1 = ta.ema(SmoothBOP, TEMA)    xEMA2 = ta.ema(xEMA1, TEMA)    xEMA3 = ta.ema(xEMA2, TEMA)    nRes = 3 * xEMA1 - 3 * xEMA2 + xEMA3    SmootherBOP := nRes    SmootherBOP//==================================================================================calcRVI = input.bool(true, title='Use RVI', group='Relative Volatility Index')lengthRVI = input.int(10, title='RVI length(10)', minval=1, group='Relative Volatility Index')maTypeInput = input.string('WMA', title='MA Type', options=['SMA', 'EMA', 'SMMA (RMA)', 'WMA', 'VWMA'], group='Relative Volatility Index')maLengthInput = input.int(14, title='MA Length(14)', group='Relative Volatility Index')if calcRVI    stddevRVI = ta.stdev(close, lengthRVI)    upperRVI = ta.ema(ta.change(close) <= 0 ? 0 : stddevRVI, 14)    lowerRVI = ta.ema(ta.change(close) > 0 ? 0 : stddevRVI, 14)    rviRVI = upperRVI / (upperRVI + lowerRVI) * 100    rviMA := maTypeInput == 'SMA' ? ta.sma(rviRVI, maLengthInput) : maTypeInput == 'EMA' ? ta.ema(rviRVI, maLengthInput) : maTypeInput == 'SMMA (RMA)' ? ta.rma(rviRVI, maLengthInput) : maTypeInput == 'WMA' ? ta.wma(rviRVI, maLengthInput) : maTypeInput == 'VWMA' ? ta.vwma(rviRVI, maLengthInput) : ta.wma(rviRVI, maLengthInput)    rviMA//==================================================================================// Logistic DominancecalcLD = input.bool(true, title='Logistic Dominance', group='Logistic Settings')source2 = closelength = input.int(13, 'Map Length(13)', minval=1, inline='LOG', group='Logistic Settings')lenLD = input.int(5, 'Dominance(5)', minval=1, inline='LOG', group='Logistic Settings')f_logmap(_s, _r, _l) =>    _r * _s / ta.highest(_l) * (1 - _s / ta.highest(_l))f_map(_s, _r, _v) =>    mapeq = f_logmap(_s, _r, length)    lmap = mapeq    for i = 0 to 29 by 1        array.push(_v, lmap)        lmap := _r * math.abs(mapeq[i]) * (1 - mapeq[i])        lmap    lmapif calcLD    r = -f_logmap(-source2, ta.change(source2, lenLD) / source2[lenLD], lenLD) - f_logmap(source2, ta.change(source2, lenLD) / source2[lenLD], lenLD)    var v = array.new_float(0)    val = f_map(source2, r, v)    array.remove(v, 0)    aStDev := math.sign(array.avg(v)) * array.stdev(v)    array.clear(v)// Logistic Dominance//==================================================================================calcext = input(false, title='Check External Indicator')externalindi = input(defval=close, title='External Indicator')pos_reg_div_col = input(defval=color.yellow, title='Positive Regular Divergence')neg_reg_div_col = input(defval=color.navy, title='Negative Regular Divergence')pos_hid_div_col = input(defval=color.lime, title='Positive Hidden Divergence')neg_hid_div_col = input(defval=color.red, title='Negative Hidden Divergence')pos_div_text_col = input(defval=color.black, title='Positive Divergence Text Color')neg_div_text_col = input(defval=color.white, title='Negative Divergence Text Color')reg_div_l_style_ = input.string(defval='Solid', title='Regular Divergence Line Style', options=['Solid', 'Dashed', 'Dotted'])hid_div_l_style_ = input.string(defval='Dashed', title='Hdden Divergence Line Style', options=['Solid', 'Dashed', 'Dotted'])reg_div_l_width = input.int(defval=2, title='Regular Divergence Line Width', minval=1, maxval=5)hid_div_l_width = input.int(defval=1, title='Hidden Divergence Line Width', minval=1, maxval=5)showmas = input.bool(defval=false, title='Show MAs 50 & 200', inline='ma12')cma1col = input.color(defval=color.lime, title='', inline='ma12')cma2col = input.color(defval=color.red, title='', inline='ma12')plot(showmas ? ta.sma(close, 50) : na, color=showmas ? cma1col : na)plot(showmas ? ta.sma(close, 200) : na, color=showmas ? cma2col : na)// set line stylesvar reg_div_l_style = reg_div_l_style_ == 'Solid' ? line.style_solid : reg_div_l_style_ == 'Dashed' ? line.style_dashed : line.style_dottedvar hid_div_l_style = hid_div_l_style_ == 'Solid' ? line.style_solid : hid_div_l_style_ == 'Dashed' ? line.style_dashed : line.style_dotted// keep indicators names and colors in arrays// !!!!!!!! DIMAK - add num of Indicators +1var indicators_name = array.new_string(19)var div_colors = array.new_color(4)if barstate.isfirst    // names    array.set(indicators_name, 0, showindis == 'Full' ? 'MACD' : 'M')    array.set(indicators_name, 1, showindis == 'Full' ? 'Hist' : 'H')    array.set(indicators_name, 2, showindis == 'Full' ? 'RSI' : 'E')    array.set(indicators_name, 3, showindis == 'Full' ? 'Stoch' : 'S')    array.set(indicators_name, 4, showindis == 'Full' ? 'CCI' : 'C')    array.set(indicators_name, 5, showindis == 'Full' ? 'MOM' : 'M')    array.set(indicators_name, 6, showindis == 'Full' ? 'OBV' : 'O')    array.set(indicators_name, 7, showindis == 'Full' ? 'VWMACD' : 'V')    array.set(indicators_name, 8, showindis == 'Full' ? 'CMF' : 'C')    array.set(indicators_name, 9, showindis == 'Full' ? 'MFI' : 'M')    array.set(indicators_name, 10, showindis == 'Full' ? 'Extrn' : 'X')    array.set(indicators_name, 11, showindis == 'Full' ? 'Logist' : 'L')    array.set(indicators_name, 12, showindis == 'Full' ? 'WVIX' : 'VIX')    array.set(indicators_name, 13, showindis == 'Full' ? 'StochRSI' : 'SR')    array.set(indicators_name, 14, showindis == 'Full' ? 'calcSMIO' : 'SM')    array.set(indicators_name, 15, showindis == 'Full' ? 'VWMACD_LB' : 'VWM')    array.set(indicators_name, 16, showindis == 'Full' ? 'BBP' : 'BBP')    array.set(indicators_name, 17, showindis == 'Full' ? 'BOP' : 'BOP')    array.set(indicators_name, 18, showindis == 'Full' ? 'RVI' : 'RVI')// !!!!!!!!!!! DIMAK - num of Ind +1        //colors    array.set(div_colors, 0, pos_reg_div_col)    array.set(div_colors, 1, neg_reg_div_col)    array.set(div_colors, 2, pos_hid_div_col)    array.set(div_colors, 3, neg_hid_div_col)// Check if we get new Pivot High Or Pivot Lowfloat ph = ta.pivothigh(source == 'Close' ? close : high, prd, prd)float pl = ta.pivotlow(source == 'Close' ? close : low, prd, prd)plotshape(ph and showpivot, text='H', style=shape.labeldown, color=color.new(color.white, 100), textcolor=color.new(color.red, 0), location=location.abovebar, offset=-prd)plotshape(pl and showpivot, text='L', style=shape.labelup, color=color.new(color.white, 100), textcolor=color.new(color.lime, 0), location=location.belowbar, offset=-prd)// keep values and positions of Pivot Highs/Lows in the arraysvar int maxarraysize = 20var ph_positions = array.new_int(maxarraysize, 0)var pl_positions = array.new_int(maxarraysize, 0)var ph_vals = array.new_float(maxarraysize, 0.)var pl_vals = array.new_float(maxarraysize, 0.)// add PHs to the arrayif ph    array.unshift(ph_positions, bar_index)    array.unshift(ph_vals, ph)    if array.size(ph_positions) > maxarraysize        array.pop(ph_positions)        array.pop(ph_vals)// add PLs to the arrayif pl    array.unshift(pl_positions, bar_index)    array.unshift(pl_vals, pl)    if array.size(pl_positions) > maxarraysize        array.pop(pl_positions)        array.pop(pl_vals)// functions to check Regular Divergences and Hidden Divergences// function to check positive regular or negative hidden divergence// cond == 1 => positive_regular, cond == 2=> negative_hiddenpositive_regular_positive_hidden_divergence(src, cond) =>    divlen = 0    prsc = source == 'Close' ? close : low    // if indicators higher than last value and close price is higher than las close     if dontconfirm or src > src[1] or close > close[1]        startpoint = dontconfirm ? 0 : 1  // don't check last candle        // we search last 15 PPs        for x = 0 to maxpp - 1 by 1            len = bar_index - array.get(pl_positions, x) + prd            // if we reach non valued array element or arrived 101. or previous bars then we don't search more            if array.get(pl_positions, x) == 0 or len > maxbars                break            if len > 5 and (cond == 1 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(pl_vals, x)) or cond == 2 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(pl_vals, x)))                slope1 = (src[startpoint] - src[len]) / (len - startpoint)                virtual_line1 = src[startpoint] - slope1                slope2 = (close[startpoint] - close[len]) / (len - startpoint)                virtual_line2 = close[startpoint] - slope2                arrived = true                for y = 1 + startpoint to len - 1 by 1                    if src[y] < virtual_line1 or nz(close[y]) < virtual_line2                        arrived := false                        break                    virtual_line1 -= slope1                    virtual_line2 -= slope2                    virtual_line2                if arrived                    divlen := len                    break    divlen// function to check negative regular or positive hidden divergence// cond == 1 => negative_regular, cond == 2=> positive_hiddennegative_regular_negative_hidden_divergence(src, cond) =>    divlen = 0    prsc = source == 'Close' ? close : high    // if indicators higher than last value and close price is higher than las close     if dontconfirm or src < src[1] or close < close[1]        startpoint = dontconfirm ? 0 : 1  // don't check last candle        // we search last 15 PPs        for x = 0 to maxpp - 1 by 1            len = bar_index - array.get(ph_positions, x) + prd            // if we reach non valued array element or arrived 101. or previous bars then we don't search more            if array.get(ph_positions, x) == 0 or len > maxbars                break            if len > 5 and (cond == 1 and src[startpoint] < src[len] and prsc[startpoint] > nz(array.get(ph_vals, x)) or cond == 2 and src[startpoint] > src[len] and prsc[startpoint] < nz(array.get(ph_vals, x)))                slope1 = (src[startpoint] - src[len]) / (len - startpoint)                virtual_line1 = src[startpoint] - slope1                slope2 = (close[startpoint] - nz(close[len])) / (len - startpoint)                virtual_line2 = close[startpoint] - slope2                arrived = true                for y = 1 + startpoint to len - 1 by 1                    if src[y] > virtual_line1 or nz(close[y]) > virtual_line2                        arrived := false                        break                    virtual_line1 -= slope1                    virtual_line2 -= slope2                    virtual_line2                if arrived                    divlen := len                    break    divlen// calculate 4 types of divergence if enabled in the options and return divergences in an arraycalculate_divs(cond, indicator_1) =>    divs = array.new_int(4, 0)    array.set(divs, 0, cond and (searchdiv == 'Regular' or searchdiv == 'Regular/Hidden') ? positive_regular_positive_hidden_divergence(indicator_1, 1) : 0)    array.set(divs, 1, cond and (searchdiv == 'Regular' or searchdiv == 'Regular/Hidden') ? negative_regular_negative_hidden_divergence(indicator_1, 1) : 0)    array.set(divs, 2, cond and (searchdiv == 'Hidden' or searchdiv == 'Regular/Hidden') ? positive_regular_positive_hidden_divergence(indicator_1, 2) : 0)    array.set(divs, 3, cond and (searchdiv == 'Hidden' or searchdiv == 'Regular/Hidden') ? negative_regular_negative_hidden_divergence(indicator_1, 2) : 0)    divs// array to keep all divergences// !!!!!!!!!! DIMAK - add num of Indicators *4var all_divergences = array.new_int(76)  // 11 indicators * 4 divergence = 44 elements// set related array elementsarray_set_divs(div_pointer, index) =>    for x = 0 to 3 by 1        array.set(all_divergences, index * 4 + x, array.get(div_pointer, x))// set divergences array if calcmacd    array_set_divs(calculate_divs(calcmacd, macd), 0)if calcmacda    array_set_divs(calculate_divs(calcmacda, deltamacd), 1)if calcrsi    array_set_divs(calculate_divs(calcrsi, rsi), 2)if calcstoc    array_set_divs(calculate_divs(calcstoc, stk), 3)if calccci    array_set_divs(calculate_divs(calccci, cci), 4)if calcmom    array_set_divs(calculate_divs(calcmom, moment), 5)if calcobv    array_set_divs(calculate_divs(calcobv, Obv), 6)if calcvwmacd    array_set_divs(calculate_divs(calcvwmacd, vwmacd), 7)if calccmf    array_set_divs(calculate_divs(calccmf, cmf), 8)if calcmfi    array_set_divs(calculate_divs(calcmfi, Mfi), 9)if calcext    array_set_divs(calculate_divs(calcext, externalindi), 10)if calcLD    array_set_divs(calculate_divs(calcLD, aStDev), 11)if calcWVIX    array_set_divs(calculate_divs(calcWVIX, wvf), 12)if calcStochRSI    array_set_divs(calculate_divs(calcStochRSI, StochRSIk), 13)if calcSMIO    array_set_divs(calculate_divs(calcSMIO, oscSMIO), 14)if calcVWMACD_LB    array_set_divs(calculate_divs(calcVWMACD_LB, dmVWMACD_LB), 15)if calcBBP    array_set_divs(calculate_divs(calcBBP, BBPower), 16)if calcBOP    array_set_divs(calculate_divs(calcBOP, SmootherBOP), 17)if calcRVI    array_set_divs(calculate_divs(calcRVI, rviMA), 18)// !!!!!!! DIMAK - add num of Indicators // check minimum number of divergence, if less than showlimit then delete all divergencetotal_div = 0for x = 0 to array.size(all_divergences) - 1 by 1    total_div += math.round(math.sign(array.get(all_divergences, x)))if total_div < showlimit    array.fill(all_divergences, 0)// keep line in an arrayvar pos_div_lines = array.new_line(0)var neg_div_lines = array.new_line(0)var pos_div_labels = array.new_label(0)var neg_div_labels = array.new_label(0)// remove old lines and labels if showlast option is enableddelete_old_pos_div_lines() =>    if array.size(pos_div_lines) > 0        for j = 0 to array.size(pos_div_lines) - 1 by 1            line.delete(array.get(pos_div_lines, j))            1        array.clear(pos_div_lines)delete_old_neg_div_lines() =>    if array.size(neg_div_lines) > 0        for j = 0 to array.size(neg_div_lines) - 1 by 1            line.delete(array.get(neg_div_lines, j))            1        array.clear(neg_div_lines)delete_old_pos_div_labels() =>    if array.size(pos_div_labels) > 0        for j = 0 to array.size(pos_div_labels) - 1 by 1            label.delete(array.get(pos_div_labels, j))        array.clear(pos_div_labels)delete_old_neg_div_labels() =>    if array.size(neg_div_labels) > 0        for j = 0 to array.size(neg_div_labels) - 1 by 1            label.delete(array.get(neg_div_labels, j))        array.clear(neg_div_labels)// delete last creted lines and labels until we met new PH/PV delete_last_pos_div_lines_label(n) =>    if n > 0 and array.size(pos_div_lines) >= n        asz = array.size(pos_div_lines)        for j = 1 to n by 1            line.delete(array.get(pos_div_lines, asz - j))            array.pop(pos_div_lines)        if array.size(pos_div_labels) > 0            label.delete(array.get(pos_div_labels, array.size(pos_div_labels) - 1))            array.pop(pos_div_labels)delete_last_neg_div_lines_label(n) =>    if n > 0 and array.size(neg_div_lines) >= n        asz = array.size(neg_div_lines)        for j = 1 to n by 1            line.delete(array.get(neg_div_lines, asz - j))            array.pop(neg_div_lines)        if array.size(neg_div_labels) > 0            label.delete(array.get(neg_div_labels, array.size(neg_div_labels) - 1))            array.pop(neg_div_labels)// variables for Alertspos_reg_div_detected = falseneg_reg_div_detected = falsepos_hid_div_detected = falseneg_hid_div_detected = false// to remove lines/labels until we met new // PH/PLvar last_pos_div_lines = 0var last_neg_div_lines = 0var remove_last_pos_divs = falsevar remove_last_neg_divs = falseif pl    remove_last_pos_divs := false    last_pos_div_lines := 0    last_pos_div_linesif ph    remove_last_neg_divs := false    last_neg_div_lines := 0    last_neg_div_lines// draw divergences lines and labelsdivergence_text_top = ''divergence_text_bottom = ''distances = array.new_int(0)dnumdiv_top = 0dnumdiv_bottom = 0top_label_col = color.whitebottom_label_col = color.whiteold_pos_divs_can_be_removed = trueold_neg_divs_can_be_removed = truestartpoint = dontconfirm ? 0 : 1  // used for don't confirm option// !!!!!!!!!!!! DIMAK - add num of Indicators for x = 0 to 18 by 1    div_type = -1    for y = 0 to 3 by 1        if array.get(all_divergences, x * 4 + y) > 0  // any divergence?            div_type := y            if y % 2 == 1                dnumdiv_top += 1                top_label_col := array.get(div_colors, y)                top_label_col            if y % 2 == 0                dnumdiv_bottom += 1                bottom_label_col := array.get(div_colors, y)                bottom_label_col            if not array.includes(distances, array.get(all_divergences, x * 4 + y))  // line not exist ?                array.push(distances, array.get(all_divergences, x * 4 + y))                new_line = showlines ? line.new(x1=bar_index - array.get(all_divergences, x * 4 + y), y1=source == 'Close' ? close[array.get(all_divergences, x * 4 + y)] : y % 2 == 0 ? low[array.get(all_divergences, x * 4 + y)] : high[array.get(all_divergences, x * 4 + y)], x2=bar_index - startpoint, y2=source == 'Close' ? close[startpoint] : y % 2 == 0 ? low[startpoint] : high[startpoint], color=array.get(div_colors, y), style=y < 2 ? reg_div_l_style : hid_div_l_style, width=y < 2 ? reg_div_l_width : hid_div_l_width) : na                if y % 2 == 0                    if old_pos_divs_can_be_removed                        old_pos_divs_can_be_removed := false                        if not showlast and remove_last_pos_divs                            delete_last_pos_div_lines_label(last_pos_div_lines)                            last_pos_div_lines := 0                            last_pos_div_lines                        if showlast                            delete_old_pos_div_lines()                    array.push(pos_div_lines, new_line)                    last_pos_div_lines += 1                    remove_last_pos_divs := true                    remove_last_pos_divs                if y % 2 == 1                    if old_neg_divs_can_be_removed                        old_neg_divs_can_be_removed := false                        if not showlast and remove_last_neg_divs                            delete_last_neg_div_lines_label(last_neg_div_lines)                            last_neg_div_lines := 0                            last_neg_div_lines                        if showlast                            delete_old_neg_div_lines()                    array.push(neg_div_lines, new_line)                    last_neg_div_lines += 1                    remove_last_neg_divs := true                    remove_last_neg_divs            // set variables for alerts            if y == 0                pos_reg_div_detected := true                pos_reg_div_detected            if y == 1                neg_reg_div_detected := true                neg_reg_div_detected            if y == 2                pos_hid_div_detected := true                pos_hid_div_detected            if y == 3                neg_hid_div_detected := true                neg_hid_div_detected    // get text for labels    if div_type >= 0        divergence_text_top += (div_type % 2 == 1 ? showindis != 'Don\'t Show' ? array.get(indicators_name, x) + '\n' : '' : '')        divergence_text_bottom += (div_type % 2 == 0 ? showindis != 'Don\'t Show' ? array.get(indicators_name, x) + '\n' : '' : '')        divergence_text_bottom// draw labelsif showindis != 'Don\'t Show' or shownum    if shownum and dnumdiv_top > 0        divergence_text_top += str.tostring(dnumdiv_top)        divergence_text_top    if shownum and dnumdiv_bottom > 0        divergence_text_bottom += str.tostring(dnumdiv_bottom)        divergence_text_bottom    if divergence_text_top != ''        if showlast            delete_old_neg_div_labels()        array.push(neg_div_labels, label.new(x=bar_index, y=math.max(high, high[1]), text=divergence_text_top, color=top_label_col, textcolor=neg_div_text_col, style=label.style_label_down))    if divergence_text_bottom != ''        if showlast            delete_old_pos_div_labels()        array.push(pos_div_labels, label.new(x=bar_index, y=math.min(low, low[1]), text=divergence_text_bottom, color=bottom_label_col, textcolor=pos_div_text_col, style=label.style_label_up))//alertcondition(pos_reg_div_detected, title='Positive Regular Divergence Detected', message='Positive Regular Divergence Detected')//alertcondition(neg_reg_div_detected, title='Negative Regular Divergence Detected', message='Negative Regular Divergence Detected')//alertcondition(pos_hid_div_detected, title='Positive Hidden Divergence Detected', message='Positive Hidden Divergence Detected')//alertcondition(neg_hid_div_detected, title='Negative Hidden Divergence Detected', message='Negative Hidden Divergence Detected')//alertcondition(pos_reg_div_detected or pos_hid_div_detected, title='Positive Divergence Detected', message='Positive Divergence Detected')//alertcondition(neg_reg_div_detected or neg_hid_div_detected, title='Negative Divergence Detected', message='Negative Divergence Detected')// ===================================================================================================GRUPO_KC = 'Keltner Channel'use_KC = input.bool(false, 'Use Channel ?', group=GRUPO_KC)P_indicador = input.string('Keltner Channel', 'Channel to Use:', options=['Keltner Channel', 'Bollinger Bands'], group=GRUPO_KC)P_cond_entrada = input.string('Wick out of band', 'Enter Conditions', options=['Wick out of band', 'Wick out of the band then close in', 'Out-of-band closure', 'Close out of the band then close in'], group=GRUPO_KC)KC_length = input.int(title='Keltner Long.', group=GRUPO_KC, defval=14, minval=1, inline='kc')KC_mult = input.float(title='Keltner Mult.', group=GRUPO_KC, defval=1.5, minval=0.01, step=0.05, inline='kc')[KC_mid, KC_upper, KC_lower] = ta.kc(close, KC_length, KC_mult)GRUPO_BB = 'Bollinger Bands Filter'BB_length = input.int(title='BB Long. ', group=GRUPO_KC, defval=20, minval=1, inline='bb')BB_dev = input.float(title='BB Deviation (Desv.)', group=GRUPO_KC, defval=2.0, minval=0.01, step=0.1, inline='bb')[BB_mid, BB_upper, BB_lower] = ta.bb(close, BB_length, BB_dev)Kanal_upper = KC_upperKanal_mid = KC_midKanal_lower = KC_lowerif P_indicador == 'Bollinger Bands'    Kanal_upper := BB_upper    Kanal_mid := BB_mid    Kanal_lower := BB_lower    //Kanal_lower//displ= display.nonedispl = use_KC ? display.all : display.noneplot(Kanal_upper, 'UP', color.new(color.aqua, 0), display = displ)plot(Kanal_mid, 'Mid', color.new(color.orange, 0), display = displ)plot(Kanal_lower, 'DOWN', color.new(color.aqua, 0), display = displ)longCondition2 = trueshortCondition2 = trueif use_KC    longCondition2 := false    shortCondition2 := false    if P_cond_entrada == 'Wick out of band'        longCondition2 := low < Kanal_lower        shortCondition2 := high > Kanal_upper        shortCondition2    else if P_cond_entrada == 'Wick out of the band then close in'        longCondition2 := low[1] < Kanal_lower and close > Kanal_lower        shortCondition2 := high[1] > Kanal_upper and close < Kanal_upper        shortCondition2    else if P_cond_entrada == 'Out-of-band closure'        longCondition2 := close < Kanal_lower        shortCondition2 := close > Kanal_upper        shortCondition2    else        // Close out of the band then close in        longCondition2 := close[1] < Kanal_lower and close > Kanal_lower        shortCondition2 := close[1] > Kanal_upper and close < Kanal_upper        shortCondition2else    longCondition2 := true    shortCondition2 := true    shortCondition2// ===================================================================================================// ======================= dimak RSI timeframe   Begin 1111111 ====================GRUPO_RSI_TF  = "========== RSI FILTER ============"lengthRSI = input.int(title="RSI TF Long(14):", group=GRUPO_RSI_TF, defval=14, minval=1)tf_rsi_indicator = input.timeframe("",title="RSI TimeFrame:", group=GRUPO_RSI_TF)useRSITFoverSold = input.bool(false, 'Use RSI LONG Range', group=GRUPO_RSI_TF)overSoldRSITF = input.int(title='(LONG) RSI is More', group=GRUPO_RSI_TF, defval=30, step=5, minval=1, inline='22')overSold2RSITF = input.int(title='& RSI Less', group=GRUPO_RSI_TF, defval=70, minval=1, maxval = 100, step=5, inline='22')useRSITFFoverBought = input.bool(false, 'Use RSI SHORT Range', group=GRUPO_RSI_TF)overBoughtRSITF = input.int(title='(SHORT) RSI is Less', group=GRUPO_RSI_TF, defval=70, step=5, minval=1, maxval = 100, inline='33')overBought2RSITF = input.int(title='& RSI More', group=GRUPO_RSI_TF, defval=30, minval=1, step=5, inline='33')//rsi_tf1 = request.security(syminfo.tickerid, tf_rsi_indicator, ta.rsi(close, lengthRSI), barmerge.gaps_off)rsi_tf1 = f_security(syminfo.tickerid, tf_rsi_indicator, ta.rsi(close, lengthRSI), false) // Repaint = false//=====================================================    longCondition8  = trueshortCondition8 = trueif useRSITFoverSold or useRSITFFoverBought    longCondition8  := false    shortCondition8 := false    if useRSITFoverSold and (rsi_tf1 >= overSoldRSITF) and (rsi_tf1 <= overSold2RSITF)        longCondition8  := true        if useRSITFFoverBought and (rsi_tf1 <= overBoughtRSITF)  and (rsi_tf1 >= overBought2RSITF)        shortCondition8 := trueelse     longCondition8  := true    shortCondition8 := true//dimak RSI timeframe  END//=====================================================// ======================= dimak RSI timeframe   Begin 22222222 ====================GRUPO_RSI_TF2  = "======= RSI FILTER - Multi TimeFrame [2] ======="lengthRSI2 = input.int(title="RSI TF Long(14):[2]", group=GRUPO_RSI_TF2, defval=14, minval=1)tf_rsi_indicator2 = input.timeframe("",title="RSI TimeFrame:[2]", group=GRUPO_RSI_TF2)useRSITFoverSold2 = input.bool(false, 'Use RSI LONG Range[2]', group=GRUPO_RSI_TF2)overSoldRSITF2 = input.int(title='(LONG) RSI is More[2]', group=GRUPO_RSI_TF2, defval=30, step=5, minval=1, inline='22')overSold2RSITF2 = input.int(title='& RSI Less[2]', group=GRUPO_RSI_TF2, defval=70, minval=1,  maxval = 100, step=5, inline='22')useRSITFFoverBought2 = input.bool(false, 'Use RSI SHORT Range[2]', group=GRUPO_RSI_TF2)overBoughtRSITF2 = input.int(title='(SHORT) RSI is Less[2]', group=GRUPO_RSI_TF2, defval=70, maxval = 100, step=5, minval=1, inline='33')overBought2RSITF2 = input.int(title='& RSI More[2]', group=GRUPO_RSI_TF2, defval=30, minval=1, step=5, inline='33')//rsi_tf2 = request.security(syminfo.tickerid, tf_rsi_indicator2, ta.rsi(close, lengthRSI2), barmerge.gaps_off)rsi_tf2 = f_security(syminfo.tickerid, tf_rsi_indicator2, ta.rsi(close, lengthRSI2), false) // Repaint = false//=====================================================    longCondition10  = trueshortCondition10 = trueif useRSITFoverSold2 or useRSITFFoverBought2 and not na(rsi_tf2)    longCondition10  := false    shortCondition10 := false    if useRSITFoverSold2 and (rsi_tf2 >= overSoldRSITF2) and (rsi_tf2 <= overSold2RSITF2)        longCondition10  := true        if useRSITFFoverBought2 and (rsi_tf2 <= overBoughtRSITF2)  and (rsi_tf2 >= overBought2RSITF2)        shortCondition10 := trueelse     longCondition10  := true    shortCondition10 := true//dimak RSI timeframe  END//=====================================================// ============ dimak "Money Flow Index" Filter Timeframe  [111]  =============GRUPO_MFI_TF = '=========== MFI FILTER  ==========='lengthMFI = input.int(title='MFI TF Long:', group=GRUPO_MFI_TF, defval=14, minval=1)tf_mfi_indicator = input.timeframe('', title='MFI TimeFrame:', group=GRUPO_MFI_TF)useMFITFoverSold = input.bool(false, 'Use MFI LONG Range', group=GRUPO_MFI_TF)overSold = input.int(title='(LONG) MFI is More', group=GRUPO_MFI_TF, defval=10, step=5, minval=1, inline='22')overSold2 = input.int(title='& MFI Less', group=GRUPO_MFI_TF, defval=60, maxval = 100, step=5, minval=1, inline='22')useMFITFoverBought = input.bool(false, 'Use MFI SHORT Range', group=GRUPO_MFI_TF)overBought = input.int(title='(SHORT) MFI is Less', group=GRUPO_MFI_TF, defval=95, maxval = 100, step=5, minval=1, inline='33')overBought2 = input.int(title='& MFI More', group=GRUPO_MFI_TF, defval=50, maxval = 100, step=5, minval=1, inline='33')mfi_tf1 = f_security(syminfo.tickerid, tf_mfi_indicator, ta.mfi(hlc3, lengthMFI), true) // Repaint = false//mfi_tf1 = request.security(syminfo.tickerid, tf_mfi_indicator, ta.mfi(hlc3, lengthMFI), barmerge.gaps_off)// =====================================================    longCondition4 = trueshortCondition4 = true    if useMFITFoverSold or useMFITFoverBought    longCondition4 := false    shortCondition4 := false    if useMFITFoverSold and (mfi_tf1 > overSold) and (mfi_tf1 < overSold2)        longCondition4 := true          if useMFITFoverBought and (mfi_tf1 < overBought) and (mfi_tf1 > overBought2)         shortCondition4 := true                 else    longCondition4 := true    shortCondition4 := true   // dimak MFI timeframe [111] END// =====================================================    use_mfi_tf1_rising = input.bool(false, 'Use MFI TF Rising ?', group=GRUPO_MFI_TF)mfi_tf1_rising_len = input.int(3, title='MFI TF Rising Lengh:', group=GRUPO_MFI_TF, minval=0, maxval=20)use_mfi_tf1_falling = input.bool(false, 'Use MFI TF Falling ?', group=GRUPO_MFI_TF)mfi_tf1_falling_len = input.int(3, title='MFI TF Falling Lengh:', group=GRUPO_MFI_TF, minval=0, maxval=20)mfi_tf1_falling = ta.falling(mfi_tf1, mfi_tf1_falling_len)mfi_tf1_rising = ta.rising(mfi_tf1, mfi_tf1_rising_len)//mfi_tf1_falling_tf = request.security(syminfo.tickerid, tf_mfi_indicator, mfi_tf1_falling, barmerge.gaps_off)//mfi_tf1_rising_tf = request.security(syminfo.tickerid, tf_mfi_indicator, mfi_tf1_rising, barmerge.gaps_off)mfi_tf1_falling_tf = f_security(syminfo.tickerid, tf_mfi_indicator, mfi_tf1_falling, true) // Repaint = falsemfi_tf1_rising_tf = f_security(syminfo.tickerid, tf_mfi_indicator, mfi_tf1_rising, true) // Repaint = false    longCondition12 = trueshortCondition12 = true    if use_mfi_tf1_falling or use_mfi_tf1_rising        longCondition12 := false    shortCondition12 := false          if (use_mfi_tf1_falling and mfi_tf1_falling_tf) or (use_mfi_tf1_rising and mfi_tf1_rising_tf)        shortCondition12 := true        longCondition12 := true        else    longCondition12 := true    shortCondition12 := true   // dimak MFI timeframe  END// =====================================================// =====================================================// Two ATR (Volatility Check)grDATR="=======Two ATR (Volatility Check) Base Settings========="//useDATR = input(defval=false, title='Use Two ATR (Volatility Check) ?', group = grDATR)lengthDATR = input.int(title='ATR length1 (20)(5)', defval=20, minval=1, group = grDATR)length2DATR = input.int(title='ATR length2 (100)(20)', defval=100, minval=1, group = grDATR)smoothingDATR = input.string(title='ATR Smoothing', defval='WMA', options=['RMA', 'SMA', 'EMA', 'WMA'], group = grDATR)DATR_ma_function(sourceDATR, lengthDATR1) =>    if smoothingDATR == 'RMA'        ta.rma(sourceDATR, lengthDATR1)    else        if smoothingDATR == 'SMA'            ta.sma(sourceDATR, lengthDATR1)        else            if smoothingDATR == 'EMA'                ta.ema(sourceDATR, lengthDATR1)            else // WMA                ta.wma(sourceDATR, lengthDATR1)datr1 = DATR_ma_function(ta.tr(true), lengthDATR)datr2 = DATR_ma_function(ta.tr(true), length2DATR)// ATR Histogramedatr_hist = datr1-datr2//plot(datr1+0.4, title='ATR', color=color.new(#77C5E1, 0))//plot(datr2+0.4, title='ATR', color=color.new(#FF5252, 0))//plot(datr_hist, color=color.red, style=plot.style_histogram)// block for filters "ATR1 < ATR2" BEGIN// "ATR1 < ATR2 - Volatility is Small in last bars, ATR1 > ATR2 - Volatility is High in last bars"//grATR1ATR2 = "=============== Two ATR (ATR1 <> ATR2)=============="use_atr1toart2_more_less = input(defval=false, title='Use ATR1 <> ATR2 ? ', group = grDATR)atr1toart2_more_less = input.string(title='ATR1 to ATR2', defval='ATR1 < ATR2', options=['ATR1 < ATR2', 'ATR1 > ATR2'], group = grDATR, tooltip = "ATR1 < ATR2 - Volatility is Small in last bars, ATR1 > ATR2 - Volatility is High in last bars")datr1todatr3 = use_atr1toart2_more_less and (atr1toart2_more_less == "ATR1 < ATR2") and (datr1 < datr2) ? true :  use_atr1toart2_more_less and (atr1toart2_more_less == "ATR1 > ATR2") and (datr1 > datr2) ? true : falselongCondition1 = trueshortCondition1 = trueif use_atr1toart2_more_less    longCondition1 := false    shortCondition1 := false       longCondition1 := datr1todatr3    shortCondition1 := longCondition1 else    longCondition1 := true    shortCondition1 := true// shortCondition1 and longCondition1 is if Fast ATR Must be higher (or Lower) than Slow ATR !!!// block for filters "ATR1 < ATR2" END// ==========================================================================// NOTE "ATR1 < ATR2" and ( Barssince_Highest/Lowest + falling/rising ) are working separately. But Same ATR settings// ==========================================================================// ========== Two Average True Range ===============================// ==================== Volume Filter =================== BegingrVOL="=======Volume Filter========="use_VOL_more_less = input(defval=false, title='Use VOL1 <> VOL2 ? ', group = grVOL)VOL_more_less = input.string(title='VOL1 to VOL2', defval='VOL1 < VOL2', options=['VOL1 < VOL2', 'VOL1 > VOL2'], group = grVOL, tooltip = "VOL1 < VOL2 - Volume is Small in last bars, VOL1 > VOL2 - Volume is High in last bars")lengthVOL = input.int(title='VOL length1 (20)(5)', defval=20, minval=1, group = grVOL)length2VOL = input.int(title='VOL length2 (100)(20)', defval=100, minval=1, step = 5, group = grVOL)smoothingVOL = input.string(title='VOL Smoothing', defval='WMA', options=['RMA', 'SMA', 'EMA', 'WMA'], group = grVOL)VOL_ma_function(sourceVOL, XlengthVOL) =>    if smoothingVOL == 'RMA'        ta.rma(sourceVOL, XlengthVOL)    else        if smoothingVOL == 'SMA'            ta.sma(sourceVOL, XlengthVOL)        else            if smoothingVOL == 'EMA'                ta.ema(sourceVOL, XlengthVOL)            else // WMA                ta.wma(sourceVOL, XlengthVOL)vol1 = VOL_ma_function(volume, lengthVOL)vol2 = VOL_ma_function(volume, length2VOL)longCondition11 = trueshortCondition11 = trueif use_VOL_more_less    longCondition11 := false    shortCondition11 := false       longCondition11 := use_VOL_more_less and (VOL_more_less == "VOL1 < VOL2") and (vol1 < vol2) ? true :  use_VOL_more_less and (VOL_more_less == "VOL1 > VOL2") and (vol1 > vol2) ? true : false    shortCondition11 := longCondition11 else    longCondition11 := true    shortCondition11 := true// ==================== Volume Filter =================== END// ======================= dimak CCI timeframe   Begin 1111111 ====================GRUPO_CCI_TF  = "========== CCI FILTER ============"lengthCCI = input.int(title="CCI TF Long(14):", group=GRUPO_CCI_TF, defval=14, minval=1)tf_CCI_indicator = input.timeframe("",title="CCI TimeFrame:", group=GRUPO_CCI_TF)useCCITFoverSold = input.bool(false, 'Use CCI LONG Range', group=GRUPO_CCI_TF)overSoldCCITF = input.int(title='(LONG) CCI is More', group=GRUPO_CCI_TF, defval=-400, step=5, minval=-400, inline='22')overSold2CCITF = input.int(title='& CCI Less', group=GRUPO_CCI_TF, defval=400, minval=-401, maxval = 400, step=5, inline='22')useCCITFFoverBought = input.bool(false, 'Use CCI SHORT Range', group=GRUPO_CCI_TF)overBoughtCCITF = input.int(title='(SHORT) CCI is Less', group=GRUPO_CCI_TF, defval=400, step=5, minval=-401, maxval = 400, inline='33')overBought2CCITF = input.int(title='& CCI More', group=GRUPO_CCI_TF, defval=10, minval=-401, step=5, inline='33')//CCI_tf1 = request.security(syminfo.tickerid, tf_CCI_indicator, ta.cci(close, lengthCCI), barmerge.gaps_off)CCI_tf1 = f_security(syminfo.tickerid, tf_CCI_indicator, ta.cci(close, lengthCCI), false) // Repaint = false//=====================================================    longCondition9  = trueshortCondition9 = trueif useCCITFoverSold or useCCITFFoverBought    longCondition9  := false    shortCondition9 := false    if useCCITFoverSold and (CCI_tf1 >= overSoldCCITF) and (CCI_tf1 <= overSold2CCITF)        longCondition9  := true        if useCCITFFoverBought and (CCI_tf1 <= overBoughtCCITF)  and (CCI_tf1 >= overBought2CCITF)        shortCondition9 := trueelse     longCondition9  := true    shortCondition9 := true//dimak CCI timeframe  END//=====================================================// ======================= dimak Momentum timeframe   Begin 1111111 ====================GRUPO_MOM_TF  = "==========Momentum FILTER ============"lengthMOM = input.int(title="Momentum TF Long(14):", group=GRUPO_MOM_TF, defval=14, minval=1)tf_MOM_indicator = input.timeframe("",title="Momentum TimeFrame:", group=GRUPO_MOM_TF)useMOMTFoverSold = input.bool(false, 'Use Momentum LONG Range (-100:100)', group=GRUPO_MOM_TF)overSoldMOMTF = input.int(title='(LONG) Momentum is More', group=GRUPO_MOM_TF, defval=-100, step=5, minval=-100, maxval = 100, inline='22')overSold2MOMTF = input.int(title='& Mom Less', group=GRUPO_MOM_TF, defval=10, minval=-100, maxval = 100, step=5, inline='22')useMOMTFFoverBought = input.bool(false, 'Use Momentum SHORT Range (100:-100)', group=GRUPO_MOM_TF)overBoughtMOMTF = input.int(title='(SHORT) Momentum is Less', group=GRUPO_MOM_TF, defval=95, step=5, minval=-100, maxval = 100, inline='33')overBought2MOMTF = input.int(title='& Mom More', group=GRUPO_MOM_TF, defval=-30, minval=-100, maxval = 100, step=5, inline='33')srcMOM = input(close, "Momentum Source", group=GRUPO_MOM_TF)momm = ta.change(srcMOM)f1(m) => m >= 0.0 ? m : 0.0f2(m) => m >= 0.0 ? 0.0 : -mm1 = f1(momm)m2 = f2(momm)sm1 = math.sum(m1, lengthMOM)sm2 = math.sum(m2, lengthMOM)percent(nom, div) => 100 * nom / divchandeMO = percent(sm1-sm2, sm1+sm2)//MOM_tf2 = request.security(syminfo.tickerid, tf_MOM_indicator, chandeMO, barmerge.gaps_off)MOM_tf2 = f_security(syminfo.tickerid, tf_MOM_indicator, chandeMO, false) // Repaint = false//=====================================================    longCondition3  = trueshortCondition3 = trueif useMOMTFoverSold or useMOMTFFoverBought    longCondition3  := false    shortCondition3 := false    if useMOMTFoverSold and (MOM_tf2 >= overSoldMOMTF) and (MOM_tf2 <= overSold2MOMTF)        longCondition3  := true        if useMOMTFFoverBought and (MOM_tf2 <= overBoughtMOMTF)  and (MOM_tf2 >= overBought2MOMTF)        shortCondition3 := trueelse     longCondition3  := true    shortCondition3 := true//dimak MOM timeframe  END//=====================================================// ========== Super Trend =============================== Begin grSUPTREND = "=============SUPER TREND FILTER============="useSUPTREND = input(defval=false, title='Use SuperTrend ?', group = grSUPTREND)opposite_SUPTREND = input(defval=false, title='Opposite SP Signal? (Sell on UPtrend..)', group = grSUPTREND)PeriodsST = input.int(title='SuperTrend ATR Period', defval=10, minval=1, group=grSUPTREND)MultiplierST = input.float(title='SuperTrend ATR Multiplier', step=0.1, defval=3.0, group=grSUPTREND)//srcST = input(hl2, title='SuperTrend Source', group=grSUPTREND)srcST = hl2//changeATR = input(title='Set ATR Smoothing to SMA ?', defval=true, group=grSUPTREND)changeATR = truehighlightingST = input(title='Show SuperTrend ?', defval=false, group=grSUPTREND)atr2ST = ta.sma(ta.tr, PeriodsST)atrST = changeATR ? ta.atr(PeriodsST) : atr2STupST = srcST - MultiplierST * atrSTup1ST = nz(upST[1], upST)upST := close[1] > up1ST ? math.max(upST, up1ST) : upSTdnST = srcST + MultiplierST * atrSTdn1ST = nz(dnST[1], dnST)dnST := close[1] < dn1ST ? math.min(dnST, dn1ST) : dnSTtrendST = 1trendST := nz(trendST[1], trendST)trendST := trendST == -1 and close > dn1ST ? 1 : trendST == 1 and close < up1ST ? -1 : trendST// check if Trend Changed. Not used now. Commented below.buySignalST = trendST == 1 and trendST[1] == -1sellSignalST = trendST == -1 and trendST[1] == 1// check if Trend Changed. Not used now. Commented below.// visualdisplST = highlightingST ? display.all : display.noneupPlot = plot(trendST == 1 ? upST : na, title='Up Trend', style=plot.style_linebr, linewidth=2, color=color.new(color.green, 0), display = displST)dnPlot = plot(trendST == 1 ? na : dnST, title='Down Trend', style=plot.style_linebr, linewidth=2, color=color.new(color.red, 0), display = displST)mPlot = plot(ohlc4, title='', style=plot.style_circles, linewidth=0)fill(mPlot, upPlot, title='UpTrend Highligter', color=color.rgb(76, 144, 175, 90), display = displST)fill(mPlot, dnPlot, title='DownTrend Highligter', color=color.rgb(255, 82, 255, 90), display = displST)// visuallongCondition5 = trueshortCondition5 = trueif useSUPTREND    longCondition5 := false    shortCondition5 := false       longCondition5 := trendST == 1 and not opposite_SUPTREND ? true : trendST == -1 and opposite_SUPTREND ? true : false    shortCondition5 := trendST == -1 and not opposite_SUPTREND ? true : trendST == 1 and opposite_SUPTREND ? true : false    // signals by change trend    //longCondition5 := not opposite_SUPTREND ? buySignalST : sellSignalST    //shortCondition5 := not opposite_SUPTREND ? sellSignalST : buySignalSTelse    longCondition5 := true    shortCondition5 := true// ========== Super Trend =============================== End // ===================================================================================================if USE_SignSL    //if pos_reg_div_detected and not enable_long_strategy    if pos_reg_div_detected and longCondition1  and longCondition2 and longCondition3 and longCondition4 and longCondition5 and longCondition8 and longCondition9  and longCondition10  and longCondition11 and longCondition12        strategy.close('sell', comment='Close Short L-Sign', alert_message='stoploss')            //if neg_reg_div_detected and not enable_short_strategy    if neg_reg_div_detected  and shortCondition1 and shortCondition2 and shortCondition3 and shortCondition4 and shortCondition5 and shortCondition8 and shortCondition9 and shortCondition10 and shortCondition11 and shortCondition12        strategy.close('buy', comment='Close Long S-Sign', alert_message='stoploss')// ===================================================================================================// ==  TEST CODE by  =================================================================================================//reverseCond = strategy.closedtrades.exit_comment(strategy.closedtrades - 1)//exitPrice = strategy.closedtrades.exit_price(strategy.closedtrades - 1)//if strategy.position_size == 0 and reverseCond == 'LSL'//    strategy.entry('sell', strategy.short, alert_message='enter_cycle')//if strategy.position_size == 0 and reverseCond == 'SSL'//    strategy.entry('buy', strategy.long, alert_message='enter_cycle')// =====  TEST CODE by   ==============================================================================================NotMultiOrders = ((strategy.closedtrades == 0) or ((bar_index != strategy.closedtrades.entry_bar_index(strategy.closedtrades - 1))))//NotMultiOrders = true// ============ New order after SL =======================================================================================var wasLong = falsevar wasShort = falseif USEorderOnSL and strategy.closedtrades.exit_bar_index(strategy.closedtrades-1) == bar_index and NotMultiOrders    if wasLong        wasLong := false        strategy.entry('sell222', strategy.short, alert_message='enter_cycle')            if wasShort        wasShort := false        strategy.entry('buy222', strategy.long, alert_message='enter_cycle') // ============= New order after SL ===================================================================        // ===================================================================================================if pos_reg_div_detected and enable_long_strategy and testPeriod()  and NotMultiOrders and longCondition1  and longCondition2 and longCondition3 and longCondition4 and longCondition5 and longCondition8 and longCondition9  and longCondition10  and longCondition11 and longCondition12    strategy.entry('buy', strategy.long, alert_message='enter_cycle')    //strategy.order('sell333',strategy.short,stop = longSLExitPrice, limit = longSLExitPrice, alert_message ='reverse_position')    wasLong := true    wasShort := falseif neg_reg_div_detected and enable_short_strategy and testPeriod()  and NotMultiOrders and shortCondition1 and shortCondition2 and shortCondition3 and shortCondition4 and shortCondition5 and shortCondition8 and shortCondition9 and shortCondition10 and shortCondition11 and shortCondition12    strategy.entry('sell', strategy.short, alert_message='enter_cycle')    //strategy.order('buy333',strategy.long,stop = shortSLExitPrice, limit = shortSLExitPrice, alert_message ='reverse_position')    wasShort := true    wasLong := false// ===================================================================================================// ===================================================================================================if strategy.position_size > 0    strategy.exit(id='Close Long %', from_entry='buy', stop=longSLExitPrice, limit=longExitPrice, alert_message='stoploss')if strategy.position_size < 0    strategy.exit(id='Close Short %', from_entry='sell', stop=shortSLExitPrice, limit=shortExitPrice, alert_message='stoploss')// ===================================================================================================displTPSL = not USEdisplTPSL ? display.none : display.all// visual TP SLavg_position_price_plot = plot(series=strategy.position_size != 0 ? strategy.position_avg_price : na, color=color.new(#c2bfbf, 25), style=plot.style_linebr, linewidth=2, title="Precio Entrada", display = displTPSL)LONG_tp_plot            = plot(strategy.position_size > 0 and longExitPrice > 0.0 ? longExitPrice : na, color=color.new(color.lime, 60), style=plot.style_linebr, linewidth=2, title="LONG Take Profit", display = displTPSL)LONG_sl_plot            = plot(strategy.position_size > 0 and longSLExitPrice > 0.0? longSLExitPrice : na, color=color.new(color.red, 60), style=plot.style_linebr, linewidth=2, title="Long Stop Loss", display = displTPSL)fill(avg_position_price_plot, LONG_tp_plot, color=color.new(color.olive, 90), display = displTPSL)fill(avg_position_price_plot, LONG_sl_plot, color=color.new(color.maroon, 90), display = displTPSL)SHORT_tp_plot            = plot(strategy.position_size < 0 and shortExitPrice > 0.0 ? shortExitPrice : na, color=color.new(color.lime, 60), style=plot.style_linebr, linewidth=2, title="SHORT Take Profit", display = displTPSL)SHORT_sl_plot            = plot(strategy.position_size < 0 and shortSLExitPrice > 0.0 ? shortSLExitPrice : na, color=color.new(color.red, 60), style=plot.style_linebr, linewidth=2, title="Short Stop Loss", display = displTPSL)fill(avg_position_price_plot, SHORT_tp_plot, color=color.new(color.olive, 90), display = displTPSL)fill(avg_position_price_plot, SHORT_sl_plot, color=color.new(color.maroon, 90), display = displTPSL)