Pine Script v4 · Strategy
CHOP Zone Entry Strategy + DMI-PSAR Exit
A Pine Script v4 strategy built on ATR (1), Highest (14) and Lowest (14). It has 6 order rules, 4 entries among them, and trades long and short with the default settings. Exits wait for a signal; there is no stop loss. Each trade is one contract and pays no commission. 16 settings; defaults include Lookback Period 14, Smooth Length 4 and Offset 0.
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 CHOP Zone Entry Strategy + DMI-PSAR Exit repaint?
- No
- No repainting patterns were found in the source, and a live tick-by-tick replay matched history on 4 of 4 trades.
- How did CHOP Zone Entry Strategy + DMI-PSAR Exit do on BTCUSDT 1D with default settings?
- +17.11%
- From 26 Jan 2024 to 21 Oct 2026, over 8 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
- Can CHOP Zone Entry Strategy + DMI-PSAR Exit be converted to Pine Script v5?
- Yes
- The upgrade takes 1 step, from v4; each was run before and after on the same candles with identical results, and the v5 script can be downloaded below.
- Does CHOP Zone Entry Strategy + DMI-PSAR Exit use a stop loss?
- No
- Every exit waits for a signal; nothing limits a losing trade before it fires.
- Does CHOP Zone Entry Strategy + DMI-PSAR Exit run in Zeal Terminal?
- Yes
- It compiles in 40 ms and runs 1,000 bars in 118 ms, in the browser.
BTCUSDT · 1D · default settings
- HLine
- HLine
- Plot
- Winning trade
- Losing trade
- Equity
- Buy and hold
- Net profit
- +17.11%
- $17,110.50
- Buy and hold
- +102.5%
- same period
- Closed trades
- 8
- 3 won · 5 lost
- Profitable
- 37.5%
- of closed trades
- Profit factor
- 1.93
- gross profit ÷ gross loss
- Max drawdown
- 20.05%
- −$20,046.90
One run with the author's default settings, $100,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
No stop loss
Every exit waits for a signal. Nothing limits a losing trade before the exit condition fires.
-
Check
No commission
The backtest assumes free trading. Results on any real exchange will be lower.
-
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 227, 228. The upgraded version below moves each call inside an if block.
-
Note
Uses transp =, which v5 removed line 76
transp = on line 76, 100, 103. v5 folds the transparency into the colour with color.new(c, transp).
Upgrade and export
Written in Pine Script v4. The upgrade to v5 takes 1 step, one per version, each applied to the result of the one before. A last clean-v5 pass then types the settings and moves when = into if blocks, which v6 requires. Every step runs before and after on the same candles in Zeal Terminal's engine; a step whose results differ is shown but not offered as a download. Upgrades preserve behaviour: bugs are fixed in the Review, never silently here.
- Upgrading to v5 renames sum → math.sum, atr → ta.atr, highest → ta.highest, lowest → ta.lowest, log10 → math.log10, sma → ta.sma, linreg → ta.linreg, avg → math.avg, ema → ta.ema, sar → ta.sar, change → ta.change, abs → math.abs.
- 2 strategy calls use the when = argument (line 227, 228). It is deprecated in v5 and removed in v6, where each call moves inside an if block.
v4 → v5
VerifiedSame 8 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 6: //@version=4 → //@version=5
- Line 14: input(type = input.integer) → input.int()
- Line 16: input(type = input.integer) → input.int()
- Line 17: input(type = input.bool) → input.bool()
- Line 18: input(type = input.bool) → input.bool()
- Line 19: input(type = input.bool) → input.bool()
30 more edits
- Line 22: input(type = input.integer) → input.int()
- Line 23: input(type = input.bool) → input.bool()
- Line 24: input(type = input.float) → input.float()
- Line 25: input(type = input.float) → input.float()
- Line 26: input(type = input.float) → input.float()
- Line 32: sum → math.sum
- Line 32: atr → ta.atr
- Line 33: highest → ta.highest
- Line 34: lowest → ta.lowest
- Line 35: log10 → math.log10
- Line 35: log10 → math.log10
- Line 37: sma → ta.sma
- Line 55: linreg → ta.linreg
- Line 55: avg → math.avg
- Line 55: avg → math.avg
- Line 55: highest → ta.highest
- Line 55: lowest → ta.lowest
- Line 55: ema → ta.ema
- Line 65: sar → ta.sar
- Line 76: transp = 95 → color.new(color.yellow, 95)
- Line 100: transp = 70 → color.new(chopZoneColor, 70)
- Line 103: transp = 80 → color.new(chopZoneColor, 80)
- Line 115: change → ta.change
- Line 116: change → ta.change
- Line 123: ema → ta.ema
- Line 123: tr → ta.tr
- Line 124: ema → ta.ema
- Line 125: ema → ta.ema
- Line 133: abs → math.abs
- Line 134: ema → ta.ema
⋯// Author: © IronCasper-//@version=4+//@version=5strategy("CHOP Zone Entry Strategy + DMI/PSAR Exit", shorttitle="CHOP Zone Strategy", default_qty_value=1, overlay=false)⋯smoothLength = input(4, title="Smooth Length", minval=1)-offset = input(0, "Offset", type = input.integer, minval = -500, maxval = 500)+offset = input.int(0, "Offset", minval = -500, maxval = 500)tradeType = input(title="Strategy Direction", defval="Follow Trend", options=["Short Only", "Long Only", "Both", "Follow Trend"])-sensitivity = input(title="Alert Sensitivity", type=input.integer, defval=1, minval=1, maxval=10)+sensitivity = input.int(title="Alert Sensitivity", defval=1, minval=1, maxval=10)-colorBg = input(true, title="Color Background to CHOP State", type=input.bool)+colorBg = input.bool(true, title="Color Background to CHOP State")-colorBars = input(true, title="Color Candles to CHOP State", type=input.bool)+colorBars = input.bool(true, title="Color Candles to CHOP State")-enableDMI = input(true, title="════ Enable Directional Movement Index ════", type=input.bool)+enableDMI = input.bool(true, title="════ Enable Directional Movement Index ════")adxLen = input(14, title="ADX Smoothing")diLen = input(14, title="DI Length")-adxKeyLevel = input(25, title="Key Level for ADX", type=input.integer, minval=1, maxval=100)+adxKeyLevel = input.int(25, title="Key Level for ADX", minval=1, maxval=100)-enablePSAR = input(true, title="════ Enable Parabolic Stop and Reverse ════", type=input.bool)+enablePSAR = input.bool(true, title="════ Enable Parabolic Stop and Reverse ════")-psarStart = input(defval=0.015, title="Start", type=input.float, step=0.015, minval=0)+psarStart = input.float(defval=0.015, title="Start", step=0.015, minval=0)-psarIncr = input(defval=0.001, title="Increment", type=input.float, step=0.001, minval=0)+psarIncr = input.float(defval=0.001, title="Increment", step=0.001, minval=0)-psarMax = input(defval=0.2, title="Max Value", type=input.float, step=0.2, minval=0)+psarMax = input.float(defval=0.2, title="Max Value", step=0.2, minval=0)//---------------------------------------------------------------------------------------//⋯//---------------------------------------------------------------------------------------//-sumAtrOverLookback = sum(atr(1), lookbackPeriod) // sum of the Avg True Range over past n bars+sumAtrOverLookback = math.sum(ta.atr(1), lookbackPeriod) // sum of the Avg True Range over past n bars-maxHi = highest(high >= close[1] ? high : close[1], lookbackPeriod) // highest high over past n bars+maxHi = ta.highest(high >= close[1] ? high : close[1], lookbackPeriod) // highest high over past n bars-minLo = lowest(low <= close[1] ? low : close[1], lookbackPeriod) // lowest low over past n bars+minLo = ta.lowest(low <= close[1] ? low : close[1], lookbackPeriod) // lowest low over past n bars-chopIndex = 100 * log10( sumAtrOverLookback / ( maxHi - minLo ) ) / log10(lookbackPeriod)+chopIndex = 100 * math.log10( sumAtrOverLookback / ( maxHi - minLo ) ) / math.log10(lookbackPeriod)// Smooth (average) Chop Index if user selected option-chopIndex := sma(chopIndex, smoothLength) // a value of 1 has the same effect as disabiling the smooth feature+chopIndex := ta.sma(chopIndex, smoothLength) // a value of 1 has the same effect as disabiling the smooth feature//----------------------------//⋯// Borrowed from script by LazyBear-val = linreg(close - avg(avg(highest(high, lookbackPeriod), lowest(low, lookbackPeriod)), ema(close, lookbackPeriod)), lookbackPeriod, 0)+val = ta.linreg(close - math.avg(math.avg(ta.highest(high, lookbackPeriod), ta.lowest(low, lookbackPeriod)), ta.ema(close, lookbackPeriod)), lookbackPeriod, 0)// Determine Momenteum State⋯// Use built-in parabolic sar function-psar = sar(psarStart, psarIncr, psarMax)+psar = ta.sar(psarStart, psarIncr, psarMax)// Determine psar trending state⋯hli2 = hline(showChopAs != "Columns" ? 61.8 : na, linestyle=hline.style_dotted, editable=false) // Loose Chop Upper Limit-fill(hli1, hli2, color=color.yellow, transp=95, editable=false)+fill(hli1, hli2, color=color.new(color.yellow, 95), editable=false)// Plot Chop Index Line⋯// Plot columns vs bgcolor if Chop Index is not shown-plot(showChopAs == "Columns" ? 1 : na, color=chopZoneColor, style=plot.style_columns, transp=70, editable=false)+plot(showChopAs == "Columns" ? 1 : na, color=color.new(chopZoneColor, 70), style=plot.style_columns, editable=false)// Plot as bgcolor if selected in Line viewchopZoneColor := colorBg and showChopAs != "Columns" ? chopZoneColor : na-bgcolor(color=chopZoneColor, transp=80, editable=false)+bgcolor(color=color.new(chopZoneColor, 80), editable=false)//-----------------------------------------------------------------------------------------//⋯ // Determine Directional Movement- upMove = change(high) // current high - previous high+ upMove = ta.change(high) // current high - previous high- downMove = -change(low) // current low - previous low+ downMove = -ta.change(low) // current low - previous low ⋯ // Update DM based on the number of user defined periods- trueRange = ema(tr, diLen)+ trueRange = ta.ema(ta.tr, diLen)- plusDI := fixnan(100 * ema(plusDI, diLen) / trueRange)+ plusDI := fixnan(100 * ta.ema(plusDI, diLen) / trueRange)- minusDI := fixnan(100 * ema(minusDI, diLen) / trueRange)+ minusDI := fixnan(100 * ta.ema(minusDI, diLen) / trueRange) ⋯ // Determine the ADX- tmp = abs((plusDI - minusDI) / (plusDI + minusDI))+ tmp = math.abs((plusDI - minusDI) / (plusDI + minusDI))- adx = fixnan(100 * ema(tmp, adxLen))+ adx = fixnan(100 * ta.ema(tmp, adxLen)) ⋯Same 8 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 11: input() → input.string()
- Line 12: input() → input.int()
- Line 13: input() → input.int()
- Line 15: input() → input.string()
- Line 20: input() → input.int()
- Line 21: input() → input.int()
- Line 227: when = active and goClose → if block
- Line 228: when = active and goClose → if block
⋯//-----------------------//-showChopAs = input(title="Show Chop Index as", defval="Colored Line (PSAR)", options=["Line", "Colored Line (MOM)", "Colored Line (PSAR)", "Columns"])+showChopAs = input.string(title="Show Chop Index as", defval="Colored Line (PSAR)", options=["Line", "Colored Line (MOM)", "Colored Line (PSAR)", "Columns"])-lookbackPeriod = input(14, title="Lookback Period", minval=1)+lookbackPeriod = input.int(14, title="Lookback Period", minval=1)-smoothLength = input(4, title="Smooth Length", minval=1)+smoothLength = input.int(4, title="Smooth Length", minval=1)offset = input.int(0, "Offset", minval = -500, maxval = 500)-tradeType = input(title="Strategy Direction", defval="Follow Trend", options=["Short Only", "Long Only", "Both", "Follow Trend"])+tradeType = input.string(title="Strategy Direction", defval="Follow Trend", options=["Short Only", "Long Only", "Both", "Follow Trend"])sensitivity = input.int(title="Alert Sensitivity", defval=1, minval=1, maxval=10)⋯enableDMI = input.bool(true, title="════ Enable Directional Movement Index ════")-adxLen = input(14, title="ADX Smoothing")+adxLen = input.int(14, title="ADX Smoothing")-diLen = input(14, title="DI Length")+diLen = input.int(14, title="DI Length")adxKeyLevel = input.int(25, title="Key Level for ADX", minval=1, maxval=100)⋯ -strategy.close("Long", when = active and goClose, alert_message="Close {{ticker}} from Chop Zone Strategy") // Close Long+if active and goClose+ strategy.close("Long", alert_message="Close {{ticker}} from Chop Zone Strategy") // Close Long-strategy.close("Short", when = active and goClose, alert_message="Close {{ticker}} from Chop Zone Strategy") // Close Short+if active and goClose+ strategy.close("Short", alert_message="Close {{ticker}} from Chop Zone Strategy") // Close Shortif goClose⋯Does it run in Pine Script v6?
No
The v6 version runs in Zeal Terminal's engine, but its results differ from the v5 version: Trades differ: 8 before, 8 after on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. It is shown for reference and is not offered as a download. It differs from the v5 version by 1 edit.
⋯// Author: © IronCasper-//@version=5+//@version=6strategy("CHOP Zone Entry Strategy + DMI/PSAR Exit", shorttitle="CHOP Zone Strategy", default_qty_value=1, overlay=false)⋯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 |
|---|---|---|---|
| Show Chop Index as | Colored Line (PSAR) | string · options ["Line", "Colored Line (MOM)", "Colored Line (PSAR)", "Columns"] | hli1 hli2 lineColor chopZoneColor goLong goShort plotSeries hline plot |
| Lookback Period | 14 | int · min 1 | sumAtrOverLookback maxHi minLo chopIndex val |
| Smooth Length | 4 | int · min 1 | chopIndex |
| Offset | 0 | int (written input.integer) · min -500 · max 500 | plot |
| Strategy Direction | Follow Trend | string · options ["Short Only", "Long Only", "Both", "Follow Trend"] | longSelected shortSelected reverseAllowed line 158 |
| Alert Sensitivity | 1 | int (written input.integer) · min 1 · max 10 | goLong goShort line 146 line 147 |
| Color Background to CHOP State | true | bool | chopZoneColor |
| Color Candles to CHOP State | true | bool | barcolor |
| ════ Enable Directional Movement Index ════ | true | bool | goLong goShort dmiCloseLong dmiCloseShort chopCloseLong chopCloseShort |
| ADX Smoothing | 14 | int | plusDI minusDI adx adxSignal |
| DI Length | 14 | int | plusDI minusDI trueRange adxSignal |
| Key Level for ADX | 25 | int (written input.integer) · min 1 · max 100 | goLong goShort dmiCloseLong dmiCloseShort |
| ════ Enable Parabolic Stop and Reverse ════ | true | bool | psarCloseLong psarCloseShort chopCloseLong chopCloseShort |
| Start | 0.015 | float · min 0 · step 0.015 | psar |
| Increment | 0.001 | float · min 0 · step 0.001 | psar |
| Max Value | 0.2 | float · min 0 · step 0.2 | psar |
What it calculates
- ATR (
atr,ta.atrin v5)1sumAtrOverLookback · line 32 - Highest (
highest,ta.highestin v5)high >= close[1] ? high : close[1], Lookback Period (14)maxHi · line 33 - Lowest (
lowest,ta.lowestin v5)low <= close[1] ? low : close[1], Lookback Period (14)minLo · line 34 - SMA (
sma,ta.smain v5)chopIndex, Smooth Length (4)chopIndex · line 35 - Linreg / Highest / Lowest / EMA (
linreg,ta.linregin v5)close - avg(avg(highest(high, lookbackPeriod), lowest(low, lookbackPeriod)), ema(close, lookbackPeriod)), Lookback Period (14), 0val · line 55 - SAR (
sar,ta.sarin v5)Start (0.015), Increment (0.001), Max Value (0.2)psar · line 65 - Change (
change,ta.changein v5)highupMove · line 115 - Change (
change,ta.changein v5)lowdownMove · line 116 - EMA (
ema,ta.emain v5)tr, DI Length (14)trueRange · line 123 - EMA (
ema,ta.emain v5)tmp, ADX Smoothing (14)adx · line 134
Signal flow
How price data and settings reach the orders. Each box is a name in the script, or several computed the same way; each arrow is a value one of them reads. Hover a box for its members.
Order rules
| Order | Fires when | By default | Line |
|---|---|---|---|
| Open Long long | not(activeLong) and longSelected and goLong and not(goReverse) | On | 211 |
| Open Short short | not(activeShort) and shortSelected and goShort and not(goReverse) | On | 214 |
| Open Long long | goLong and goReverse | On | 219 |
| Open Short short | goShort and goReverse | On | 223 |
| Close Long | active and goClose | On | 227 |
| Close Short | active and goClose | On | 228 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Does it repaint?
No
No repainting patterns in the source, and the live replay matched history.
- ClearHigher-timeframe dataThe script requests no other symbol or timeframe.
- ClearFuture-bar referencesNo negative history offsets such as close[-1].
- ClearIntrabar recalculationNo varip, calc_on_every_tick or realtime-only state. Orders are decided once per closed bar.
- ClearOrder timingOrders fill at the next bar's open, after the signal bar has closed.
The checks read the source; the replay runs it. Together they catch the common causes, not every possible one.
Other markets
The same script with default settings on 8 Binance markets. Each row is a separate backtest over the most recent 1,000 bars.
| Market | Net | Buy and hold | Trades | Won | Profit factor | Max drawdown | Period |
|---|---|---|---|---|---|---|---|
| BTCUSDT 1D | +17.1% | +102.5% | 8 | 38% | 1.93 | 20.0% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | +6.9% | +5.5% | 10 | 40% | 3.28 | 1.9% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | −0.2% | +9.8% | 10 | 40% | 0.87 | 1.4% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | −0.1% | +8.4% | 10 | 40% | 0.69 | 0.3% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | +0.0% | +16.7% | 9 | 67% | 1.32 | 0.1% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | −0.0% | +21.5% | 8 | 38% | 0.90 | 0.0% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | +0.0% | +148.3% | 8 | 38% | 1.08 | 0.2% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | −0.0% | +17.1% | 10 | 40% | 0.56 | 0.1% | 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 | 0 | — | $0.00 |
| Sideways market | 5 | 20% | −$9,204.42 |
| Falling market | 3 | 67% | $26,314.90 |
Rising and falling mean the market moved more than 15% over the 90 bars before entry.
How bad could the drawdown be?
18.4%
The 95th percentile of the worst drawdown when the same 8 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 8.8% to 18.4%; the tick is what actually happened, 18.1%. Order luck alone moves it this much.
All 8 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| short | 27 Jun 2024 60,865.00 | 18 Jul 2024 64,088.00 | 21 | −$3,223.01 |
| short | 8 Aug 2024 55,133.80 | 23 Aug 2024 60,375.80 | 15 | −$5,242.07 |
| short | 1 Mar 2025 84,349.90 | 24 Mar 2025 86,082.50 | 23 | −$1,732.55 |
| short | 23 Nov 2025 84,739.80 | 10 Dec 2025 92,678.80 | 17 | −$7,939.06 |
| short | 31 Jan 2026 84,260.50 | 11 Mar 2026 69,948.60 | 39 | $14,311.90 |
| long | 1 May 2026 76,346.60 | 22 May 2026 77,615.50 | 21 | $1,268.94 |
| short | 5 Jun 2026 63,886.00 | 11 Jul 2026 64,161.70 | 36 | −$275.73 |
| long | 16 Aug 2026 63,086.00 | 21 Oct 2026 83,028.10 | 66 | $19,942.10 |
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 |
|---|---|---|---|---|---|
| CHOP Zone Entry Strategy + DMI-PSAR Exit this page | — | v4 strategy | +17.1% | 8 | 20.0% |
| MACD Strategy by maxencetajet | atr highest lowest ema sar sma | v5 strategy | +5.8% | 5 | 6.9% |
| ATR + STC + MA by Romedius | ema lowest highest atr sma | v5 strategy | −1.2% | 15 | 3.3% |
| -NoSKi Hammer-Star -w angle of ema Backtester - by noski1 | atr ema sma highest lowest | v5 strategy | does not run in Zeal Terminal | ||
| LONG SAZB $ by stevenz17 | ema sma atr lowest highest | v4 strategy | No trades on this market | ||
| Multi MA MTF SandBox Strategy by dman103 | sma ema linreg highest lowest | v5 strategy | +17.4% | 48 | 9.5% |
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 40 ms | With a workaround 1,000 bars in 118 ms | Not measured |
| PineTS | No v5 and v6 only | — | Not measured |
The engine's host API cannot yet declare a chart's symbol and timeframe, so this page sets them on the engine directly for each market.
“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report. PineTS runs Pine Script v5 and v6 only.
Source
Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0///// Title: "CHOP Zone Entry Strategy + DMI/PSAR Exit"// Revision: 1.2// Author: © IronCasper//@version=4strategy("CHOP Zone Entry Strategy + DMI/PSAR Exit", shorttitle="CHOP Zone Strategy", default_qty_value=1, overlay=false)//-----------------------//// Inputs ////-----------------------//showChopAs = input(title="Show Chop Index as", defval="Colored Line (PSAR)", options=["Line", "Colored Line (MOM)", "Colored Line (PSAR)", "Columns"])lookbackPeriod = input(14, title="Lookback Period", minval=1)smoothLength = input(4, title="Smooth Length", minval=1)offset = input(0, "Offset", type = input.integer, minval = -500, maxval = 500)tradeType = input(title="Strategy Direction", defval="Follow Trend", options=["Short Only", "Long Only", "Both", "Follow Trend"])sensitivity = input(title="Alert Sensitivity", type=input.integer, defval=1, minval=1, maxval=10)colorBg = input(true, title="Color Background to CHOP State", type=input.bool)colorBars = input(true, title="Color Candles to CHOP State", type=input.bool)enableDMI = input(true, title="════ Enable Directional Movement Index ════", type=input.bool)adxLen = input(14, title="ADX Smoothing")diLen = input(14, title="DI Length")adxKeyLevel = input(25, title="Key Level for ADX", type=input.integer, minval=1, maxval=100)enablePSAR = input(true, title="════ Enable Parabolic Stop and Reverse ════", type=input.bool)psarStart = input(defval=0.015, title="Start", type=input.float, step=0.015, minval=0)psarIncr = input(defval=0.001, title="Increment", type=input.float, step=0.001, minval=0)psarMax = input(defval=0.2, title="Max Value", type=input.float, step=0.2, minval=0)//---------------------------------------------------------------------------------------//// Calculate Chop //// ... derived from TradingView Reference Manual //// https://www.tradingview.com/support/solutions/43000501980-choppiness-index-chop ////---------------------------------------------------------------------------------------//sumAtrOverLookback = sum(atr(1), lookbackPeriod) // sum of the Avg True Range over past n barsmaxHi = highest(high >= close[1] ? high : close[1], lookbackPeriod) // highest high over past n barsminLo = lowest(low <= close[1] ? low : close[1], lookbackPeriod) // lowest low over past n barschopIndex = 100 * log10( sumAtrOverLookback / ( maxHi - minLo ) ) / log10(lookbackPeriod)// Smooth (average) Chop Index if user selected optionchopIndex := sma(chopIndex, smoothLength) // a value of 1 has the same effect as disabiling the smooth feature//----------------------------//// Determine Chop conditions ////----------------------------//condChopIndex38minus = chopIndex <= 38.2 and close[1] > close ? true : false // 38.2-condChopIndex38to45 = chopIndex >= 38.2 and chopIndex < 45 ? true : false // 38.2 to 45condChopIndex45to55 = chopIndex >= 45 and chopIndex < 55 ? true : false // 45 to 55condChopIndex55to61 = chopIndex >= 55 and chopIndex < 61.8 ? true : false // 55 to 61.8condChopIndex61plus = chopIndex >= 61.8 and close[1] < close ? true : false // 61.8+// Extra conditions for chop zone background colorcondChopIndex30minus = chopIndex <= 30 and close[1] > close ? true : false // 30-condChopIndex30to38 = chopIndex > 30 and chopIndex < 38.2 ? true : false // 30 to 38.2condChopIndex61to70 = chopIndex >= 61.8 and chopIndex < 70 ? true : false // 61.8 to 70condChopIndex70plus = chopIndex >= 70 and close[1] < close ? true : false // 70+//-----------------------------------------------------------//// Compute Momentum State for Trend Line and Entry Determination ////-----------------------------------------------------------//// Borrowed from script by LazyBearval = linreg(close - avg(avg(highest(high, lookbackPeriod), lowest(low, lookbackPeriod)), ema(close, lookbackPeriod)), lookbackPeriod, 0)// Determine Momenteum Statecurr_momUpTrend = val > nz(val[1])curr_momDnTrend = val < nz(val[1])// Determine Momentum Line ColormomentumLineColor = curr_momUpTrend ? color.green : (curr_momDnTrend ? color.maroon : na)//-----------------------------------------------------------------------//// Calculate Parabolic SAR for Trend Line and Entry/Exit Determination ////-----------------------------------------------------------------------//// Use built-in parabolic sar functionpsar = sar(psarStart, psarIncr, psarMax)// Determine psar trending statepsarTrendState = psar < close ? "up" : "dn"// Determine PSAR Line ColorpsarLineColor = psarTrendState == "up" ? color.green : (psarTrendState == "dn" ? color.maroon : na)//------------------------------------------------------//// Color Candles & Chop Index Line based on Chop State ////------------------------------------------------------//// Create user defined chop limithli1 = hline(showChopAs != "Columns" ? 38.2 : na, linestyle=hline.style_dotted, editable=false) // Loose Chop Lower Limithli2 = hline(showChopAs != "Columns" ? 61.8 : na, linestyle=hline.style_dotted, editable=false) // Loose Chop Upper Limitfill(hli1, hli2, color=color.yellow, transp=95, editable=false)// Plot Chop Index LinelineColor = showChopAs == "Colored Line (PSAR)" ? psarLineColor : (showChopAs == "Colored Line (MOM)" ? momentumLineColor : color.gray)plot(showChopAs != "Columns" ? chopIndex : na, style=plot.style_linebr, linewidth=2, color=lineColor, offset=offset, editable=false)// Plot bars to match chop statevar color candleColor = nacandleColor := condChopIndex38minus ? #800080 : candleColor // ShortcandleColor := condChopIndex38to45 ? color.yellow : candleColor // Loose ChopcandleColor := condChopIndex45to55 ? #000000 : candleColor // Tight ChopcandleColor := condChopIndex55to61 ? color.yellow : candleColor // Loose ChopcandleColor := condChopIndex61plus ? #0000FF : candleColor // Longbarcolor(colorBars ? candleColor : na, editable=false)//-----------------------//// Plot Chop Zone ////-----------------------//var color chopZoneColor = nachopZoneColor := condChopIndex30minus ? #800080 : chopZoneColor // Dark PurplechopZoneColor := condChopIndex30to38 ? color.purple : chopZoneColorchopZoneColor := condChopIndex38to45 ? color.yellow : chopZoneColorchopZoneColor := condChopIndex45to55 ? #000000 : chopZoneColor // BlackchopZoneColor := condChopIndex55to61 ? color.yellow : chopZoneColorchopZoneColor := condChopIndex61to70 ? color.blue : chopZoneColorchopZoneColor := condChopIndex70plus ? #0000FF : chopZoneColor // Dark Blue// Plot columns vs bgcolor if Chop Index is not shownplot(showChopAs == "Columns" ? 1 : na, color=chopZoneColor, style=plot.style_columns, transp=70, editable=false)// Plot as bgcolor if selected in Line viewchopZoneColor := colorBg and showChopAs != "Columns" ? chopZoneColor : nabgcolor(color=chopZoneColor, transp=80, editable=false)//-----------------------------------------------------------------------------------------//// Compute DMI //// ... derived from TradingView Reference Manual //// https://www.tradingview.com/chart/?solution=43000502250 //// //// This is the same script as used in my DMI study //// https://www.tradingview.com/script/9OoEHrv5-Directional-Movement-Index-DMI-Alerts ////-----------------------------------------------------------------------------------------//// Part 1 - Calculate +DI and -DIdirmov(diLen) => // Determine Directional Movement upMove = change(high) // current high - previous high downMove = -change(low) // current low - previous low // Determine +DM and -DI by High, Low, and Close for each period plusDI = upMove > downMove and upMove > 0 ? upMove : 0 minusDI = downMove > upMove and downMove > 0 ? downMove : 0 // Update DM based on the number of user defined periods trueRange = ema(tr, diLen) plusDI := fixnan(100 * ema(plusDI, diLen) / trueRange) minusDI := fixnan(100 * ema(minusDI, diLen) / trueRange) [plusDI, minusDI] // Return// Part 2 - Calculate ADXadx(diLen, adxLen) => [plusDI, minusDI] = dirmov(diLen) // Determine the ADX tmp = abs((plusDI - minusDI) / (plusDI + minusDI)) adx = fixnan(100 * ema(tmp, adxLen)) [adx, plusDI, minusDI] // Return// Get ADX and DI from function[adxSignal, plusDI, minusDI] = adx(diLen, adxLen)//-------------------------------------------------------//// Determine Trade State for Long/Short Entry ////-------------------------------------------------------//// Establish long and short actionsgoLong = condChopIndex61plus and not(condChopIndex61plus[sensitivity]) and (enableDMI ? adxSignal > adxKeyLevel : true)goShort = condChopIndex38minus and not(condChopIndex38minus[sensitivity]) and (enableDMI ? adxSignal > adxKeyLevel : true)// Increment to user selected sensitivity to only trigger actions on the n-th candleif sensitivity != 1 and (goLong or goShort) // bypass if sensitivity equals one or no active go for i = 1 to sensitivity-1 // Update long action based on past states if( condChopIndex61plus[i] != condChopIndex61plus ) goLong := false //break // break loop if any candles aren't in a long state //bool(na) // required to trick compiler to return from loop // Update short action based on past states if( condChopIndex38minus[i] != condChopIndex38minus ) goShort := false//, break, bool(na)// Clear action if it doesn't follow the trend, if user selectedif tradeType == "Follow Trend" goLong := showChopAs == "Colored Line (Momentum)" ? (curr_momUpTrend ? goLong : na) : (psarTrendState == "up" ? goLong : na) goShort := showChopAs == "Colored Line (Momentum)" ? (curr_momDnTrend ? goShort : na) : (psarTrendState == "dn" ? goShort : na)//-------------------------------------------------------//// Determine Trade State for Exit and Reverse ////-------------------------------------------------------//// Declare Active Position Identifiersvar bool activeLong = falsevar bool activeShort = false// Determine DMI Close Trade Action, if applicabledmiCloseLong = enableDMI ? adxSignal < adxKeyLevel and minusDI > plusDI : falsedmiCloseShort = enableDMI ? adxSignal < adxKeyLevel and plusDI > minusDI : false// Determine PSAR Close Trade Action, if applicablepsarCloseLong = enablePSAR ? psarTrendState == "dn" and psarTrendState[1] == "up" : falsepsarCloseShort = enablePSAR ? psarTrendState == "up" and psarTrendState[1] == "dn" : false// Determine Default Close Trade Action (Chop Index Reversal), if PSAR or DMI not selectedchopCloseLong = enablePSAR or enableDMI ? false : chopIndex < 38.2chopCloseShort = enablePSAR or enableDMI ? false : chopIndex > 61.8// Consolidate close actions to a single variablecloseLongState = activeLong and (psarCloseLong or dmiCloseLong or chopCloseLong or goShort)closeShortState = activeShort and (psarCloseShort or dmiCloseShort or chopCloseShort or goLong)// Determine if in a Reverse Position StategoReverse = (closeLongState and goShort) or (closeShortState and goLong) ? true : false// Determine new close action based on reverse stategoClose = not(goReverse) and (closeLongState or closeShortState) ? true : false//--------------------------------//// Plot Entry and Exits ////--------------------------------//// Determine User Selected Trade TypeslongSelected = tradeType == "Both" or tradeType == "Follow Trend" ? true : tradeType == "Long Only" ? true : falseshortSelected = tradeType == "Both" or tradeType == "Follow Trend" ? true : tradeType == "Short Only" ? true : falsereverseAllowed = tradeType == "Both" or tradeType == "Follow Trend"// Identify series for when plotting shapes at the absolute locationplotSeries = showChopAs != "Columns" ? chopIndex : 0// Plot Long and Short Indicators only on first entering state (i.e., position not already active)plotshape(not(activeLong) and longSelected and goLong and not(goReverse) ? plotSeries : na , style=shape.circle, location=location.absolute, size=size.tiny, color=color.lime, text="Long", title="Long")plotshape(not(activeShort) and shortSelected and goShort and not(goReverse) ? plotSeries : na , style=shape.circle, location=location.absolute, size=size.tiny, color=color.red, text="Short", title="Short")// Consolidate active actions to one variableactive = activeLong or activeShort// Plot Close Indicatorplotshape(active and goClose ? plotSeries : na , style=shape.xcross, location=location.absolute, size=size.tiny, color=color.olive, text="Close", title="Close")// Plot Reverse Indicatorplotshape(active and reverseAllowed and goReverse ? plotSeries : na , style=shape.diamond, location=location.absolute, size=size.tiny, color=color.blue, text="Reverse", title="Reverse")//-------------------------------------//// Chop Alerts + Strategy ////-------------------------------------//// Create Long/Short/Close/Reverse Strategies with Custom Alert Messages// ... and log active long and short positions to prevent pyramiding before a close or reverseif not(activeLong) and longSelected and goLong and not(goReverse) strategy.entry("Long", strategy.long, alert_message="Buy {{ticker}} from Chop Zone Strategy") // Open Long activeLong := trueif not(activeShort) and shortSelected and goShort and not(goReverse) strategy.entry("Short", strategy.short, alert_message="Sell {{ticker}} from Chop Zone Strategy") // Open Short activeShort := true if active and reverseAllowed if goLong and goReverse strategy.entry("Long", strategy.long, alert_message="Reverse {{ticker}} from Chop Zone Strategy") // Reverse Short to Long activeLong := true activeShort := false if goShort and goReverse strategy.entry("Short", strategy.short, alert_message="Reverse {{ticker}} from Chop Zone Strategy") // Reverse Long to Short activeShort := true activeLong := false strategy.close("Long", when = active and goClose, alert_message="Close {{ticker}} from Chop Zone Strategy") // Close Longstrategy.close("Short", when = active and goClose, alert_message="Close {{ticker}} from Chop Zone Strategy") // Close Shortif goClose activeLong := false activeShort := false