Pine Script v4 · Strategy
(IK) Base Break Buy
A Pine Script v4 strategy with no technical-analysis calculation. It has 4 order rules, 2 entries among them, and trades long only with the default settings. Exits use a stop loss. Each trade commits 1 in cash and pays 0.1% commission. 13 settings; defaults include Max Bases 3, Base Area Deviation 0.005 and Unique Base Deviation 0.05.
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 (IK) Base Break Buy repaint?
- No
- No repainting patterns were found in the source. The live replay was not measured: the script acts only when barstate.isconfirmed is true, which Zeal Terminal's engine never reports during a live replay (it does not run a bar's closing update in live mode), so the replay cannot test this script.
- How did (IK) Base Break Buy do on BTCUSDT 1D with default settings?
- −26.51%
- From 26 Jan 2024 to 21 Oct 2026, over 55 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
- Can (IK) Base Break Buy 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 (IK) Base Break Buy use a stop loss?
- Yes
- strategy.exit sets a stop on line 82.
- Does (IK) Base Break Buy run in Zeal Terminal?
- Yes
- It compiles in 82 ms and runs 1,000 bars in 417 ms, in the browser.
BTCUSDT · 1D · default settings
- Plot
- Plot
- Plot
- Plot
- Plot
- Plot
- Plot
- Winning trade
- Losing trade
- Equity
- Buy and hold
- Net profit
- −26.51%
- −$26.51
- Buy and hold
- +102.5%
- same period
- Closed trades
- 55
- 39 won · 16 lost
- Profitable
- 70.9%
- of closed trades
- Profit factor
- 0.62
- gross profit ÷ gross loss
- Max drawdown
- 42.44%
- −$49.14
One run with the author's default settings, $100 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.
-
Note
No slippage
Fills are assumed at the exact open price. Add slippage in the properties for a more realistic test.
-
Note
Uses long =, which v5 renamed line 74
long = on line 74, 80. v5 writes it as direction = strategy.long or strategy.short.
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 min → math.min, crossunder → ta.crossunder.
v4 → v5
VerifiedSame 55 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 3: //@version=4 → //@version=5
- Line 6: input(type = input.integer) → input.int()
- Line 7: input(type = input.float) → input.float()
- Line 8: input(type = input.float) → input.float()
- Line 10: input(type = input.integer) → input.int()
- Line 11: input(type = input.float) → input.float()
11 more edits
- Line 12: input(type = input.float) → input.float()
- Line 13: input(type = input.integer) → input.int()
- Line 14: input(type = input.float) → input.float()
- Line 15: input(type = input.integer) → input.int()
- Line 16: input(type = input.float) → input.float()
- Line 17: input(type = input.float) → input.float()
- Line 41: min → math.min
- Line 44: min → math.min
- Line 54: crossunder → ta.crossunder
- Line 74: long = strategy.long → direction = strategy.long
- Line 80: long = strategy.long → direction = strategy.long
⋯// © userIan-//@version=4+//@version=5strategy("(IK) Base Break Buy", overlay=true, pyramiding=6, precision=2, default_qty_type=strategy.cash, initial_capital=100.0, currency="USD", commission_type=strategy.commission.percent, commission_value=0.1)// == INPUT ==-i_baseMax = input(group="Base Calculations", title="Max Bases", type=input.integer, defval=3, minval=1, maxval=10) // max amount of bases on the chart at any specific time+i_baseMax = input.int(group="Base Calculations", title="Max Bases", defval=3, minval=1, maxval=10) // max amount of bases on the chart at any specific time-i_dev = input(group="Base Calculations", title="Base Area Deviation", type=input.float, defval=0.005, minval=0.0, maxval=1.0) // if enough recent bars had bottoms within this deviation of the current bar's bottom, a base is created +i_dev = input.float(group="Base Calculations", title="Base Area Deviation", defval=0.005, minval=0.0, maxval=1.0) // if enough recent bars had bottoms within this deviation of the current bar's bottom, a base is created -i_baseDev = input(group="Base Calculations", title="Unique Base Deviation", type=input.float, defval=0.05, minval=0.0, maxval=1.0) // bases cannot be created if they fall within this deviation of an extant base+i_baseDev = input.float(group="Base Calculations", title="Unique Base Deviation", defval=0.05, minval=0.0, maxval=1.0) // bases cannot be created if they fall within this deviation of an extant basei_baseSource = input(group="Base Calculations", title="Base Source", options=["Close or Open", "Low"], defval="Close or Open") // should base calcuations be based off of candlestick closes and opens (whichever is lower), or candlestick lows-i_lookback = input(group="Base Calculations", title="Lookback", type=input.integer, defval=100) // how many bars back do we check to confirm current bases+i_lookback = input.int(group="Base Calculations", title="Lookback", defval=100) // how many bars back do we check to confirm current bases-i_confLevel = input(group="Base Calculations", title="Confidence Level", type=input.float, defval=0.01, minval=0.0, maxval=1.0) // what percentage of historical bars bottoming within deviation are needed to confirm a base+i_confLevel = input.float(group="Base Calculations", title="Confidence Level", defval=0.01, minval=0.0, maxval=1.0) // what percentage of historical bars bottoming within deviation are needed to confirm a base-i_breakThresh = input(group="Base Break Detection", title="Break Threshold", type=input.float, defval=0.02, minval=0.0, maxval=1.0) // how far (by percentage) does price have to fall below a base to constitute a 'break'+i_breakThresh = input.float(group="Base Break Detection", title="Break Threshold", defval=0.02, minval=0.0, maxval=1.0) // how far (by percentage) does price have to fall below a base to constitute a 'break'-i_breakWindow = input(group="Base Break Detection", title="Break Window", type=input.integer, defval=5) // how many bars should we allow for price to fall below the break threshold before it's no longer a tradable break+i_breakWindow = input.int(group="Base Break Detection", title="Break Window", defval=5) // how many bars should we allow for price to fall below the break threshold before it's no longer a tradable break-i_initialOrder = input(group="Order Settings", title="Initial Order Capital", type=input.float, defval=0.2, minval=0.0, maxval=1.0) // what percentage of capital to use in initial trade entry+i_initialOrder = input.float(group="Order Settings", title="Initial Order Capital", defval=0.2, minval=0.0, maxval=1.0) // what percentage of capital to use in initial trade entry-i_safetyCount = input(group="Order Settings", title="Safety Order Max Count", type=input.integer, defval=3, minval=0, maxval=5) // maximum amount of safety orders per trade. remaining capital after initial entry will be divided evenly among these +i_safetyCount = input.int(group="Order Settings", title="Safety Order Max Count", defval=3, minval=0, maxval=5) // maximum amount of safety orders per trade. remaining capital after initial entry will be divided evenly among these -i_safetyThresh = input(group="Order Settings", title="Safter Order Threshold", type=input.float, defval=0.03, minval=0.0, maxval=1.0) // what percentage does price need to fall to activate a safety order+i_safetyThresh = input.float(group="Order Settings", title="Safter Order Threshold", defval=0.03, minval=0.0, maxval=1.0) // what percentage does price need to fall to activate a safety order-i_stopLoss = input(group="Order Settings", title="Stop Loss", type=input.float, defval=0.2, minval=0.0, maxval=1.0) // what percentage does price need to fall to activate a stop loss+i_stopLoss = input.float(group="Order Settings", title="Stop Loss", defval=0.2, minval=0.0, maxval=1.0) // what percentage does price need to fall to activate a stop lossi_stopLossType = input(group="Order Settings", title="Stop Loss Type", options=['From Initial Entry', 'From Price Average'], defval='From Price Average') // calculate static stop loss based on price at first entry, or dynamic stop loass based on position average price⋯// detect bases and add unique bases to base array-currentBot = i_baseSource == "Low" ? low : min(close,open)+currentBot = i_baseSource == "Low" ? low : math.min(close,open)count = 0for i = 1 to i_lookback- bot = i_baseSource == "Low" ? low[i] : min(close[i],open[i])+ bot = i_baseSource == "Low" ? low[i] : math.min(close[i],open[i]) if f_isCloseTo(currentBot, bot, i_dev)⋯// detect base break-if crossunder(close, closestBase) and strategy.position_size == 0+if ta.crossunder(close, closestBase) and strategy.position_size == 0 baseBreakIndex := bar_index⋯if close < (brokenBase * (1-i_breakThresh)) and strategy.position_size == 0 and barstate.isconfirmed- strategy.entry(id="Long", long=strategy.long, qty=(strategy.initial_capital * i_initialOrder)/close, comment='buy')+ strategy.entry(id="Long", direction = strategy.long, qty=(strategy.initial_capital * i_initialOrder)/close, comment='buy') takeProfit := 1-(close/brokenBase) ⋯ safetyCount := safetyCount + 1- strategy.entry(id="Long", long=strategy.long, qty=(strategy.initial_capital * safetyOrderQty)/close, comment='safety')+ strategy.entry(id="Long", direction = strategy.long, qty=(strategy.initial_capital * safetyOrderQty)/close, comment='safety')// exit trade⋯Same 55 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine.
- Line 9: input() → input.string()
- Line 18: input() → input.string()
⋯i_baseDev = input.float(group="Base Calculations", title="Unique Base Deviation", defval=0.05, minval=0.0, maxval=1.0) // bases cannot be created if they fall within this deviation of an extant base-i_baseSource = input(group="Base Calculations", title="Base Source", options=["Close or Open", "Low"], defval="Close or Open") // should base calcuations be based off of candlestick closes and opens (whichever is lower), or candlestick lows+i_baseSource = input.string(group="Base Calculations", title="Base Source", options=["Close or Open", "Low"], defval="Close or Open") // should base calcuations be based off of candlestick closes and opens (whichever is lower), or candlestick lowsi_lookback = input.int(group="Base Calculations", title="Lookback", defval=100) // how many bars back do we check to confirm current bases⋯i_stopLoss = input.float(group="Order Settings", title="Stop Loss", defval=0.2, minval=0.0, maxval=1.0) // what percentage does price need to fall to activate a stop loss-i_stopLossType = input(group="Order Settings", title="Stop Loss Type", options=['From Initial Entry', 'From Price Average'], defval='From Price Average') // calculate static stop loss based on price at first entry, or dynamic stop loass based on position average price+i_stopLossType = input.string(group="Order Settings", title="Stop Loss Type", options=['From Initial Entry', 'From Price Average'], defval='From Price Average') // calculate static stop loss based on price at first entry, or dynamic stop loass based on position average price// == FUNCTIONS ==⋯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: 55 before, 54 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.
⋯// © userIan-//@version=5+//@version=6strategy("(IK) Base Break Buy", overlay=true, pyramiding=6, precision=2, default_qty_type=strategy.cash, initial_capital=100.0, currency="USD", commission_type=strategy.commission.percent, commission_value=0.1)⋯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 |
|---|---|---|---|
| Base Calculations | |||
| Max Bases | 3 | int (written input.integer) · min 1 · max 10 | line 50 |
| Base Area Deviation | 0.005 | float · min 0.0 · max 1.0 | line 45 |
| Unique Base Deviation | 0.05 | float · min 0.0 · max 1.0 | line 47 |
| Base Source | Close or Open | string · options ["Close or Open", "Low"] | currentBot bot |
| Lookback | 100 | int (written input.integer) | line 43 line 47 |
| Confidence Level | 0.01 | float · min 0.0 · max 1.0 | line 47 |
| Base Break Detection | |||
| Break Threshold | 0.02 | float · min 0.0 · max 1.0 | entry Long line 73 |
| Break Window | 5 | int (written input.integer) | line 59 |
| Order Settings | |||
| Initial Order Capital | 0.2 | float · min 0.0 · max 1.0 | safetyOrderQty entry Long |
| Safety Order Max Count | 3 | int (written input.integer) · min 0 · max 5 | safetyOrderQty entry Long line 78 |
| Safter Order Threshold | 0.03 | float · min 0.0 · max 1.0 | entry Long line 78 |
| Stop Loss | 0.2 | float · min 0.0 · max 1.0 | exit Long plot |
| Stop Loss Type | From Price Average | string · options ['From Initial Entry', 'From Price Average'] | exit Long plot |
What it calculates
No technical-analysis calculation: the script works on prices and settings directly.
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 | close < (brokenBase * (1-i_breakThresh)) and strategy.position_size == 0 and barstate.isconfirmed | On | 74 |
| Open Long long | close < (strategy.position_avg_price * (1-i_safetyThresh)) and safetyCount < i_safetyCount | On | 80 |
| Exit Long stop | every bar | On | 82 |
| Close Long | (close > strategy.position_avg_price * (1+takeProfit)) and barstate.isconfirmed | On | 84 |
Each order is guarded by the setting shown. “Off” orders never fire unless that setting is switched on.
Does it repaint?
No
No repainting patterns in the source.
- ClearHigher-timeframe 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 | −26.5% | +102.5% | 55 | 71% | 0.62 | 42.4% | 26 Jan 2024 – 21 Oct 2026 |
| BTCUSDT 4h | −14.2% | +5.5% | 14 | 71% | 0.29 | 20.4% | 8 May 2026 – 21 Oct 2026 |
| ETHUSDT 1D | −29.4% | +9.8% | 91 | 64% | 0.78 | 50.8% | 26 Jan 2024 – 21 Oct 2026 |
| ETHUSDT 4h | −13.1% | +8.4% | 14 | 64% | 0.37 | 26.5% | 8 May 2026 – 21 Oct 2026 |
| SOLUSDT 1D | −2.7% | +16.7% | 118 | 67% | 0.98 | 45.7% | 26 Jan 2024 – 21 Oct 2026 |
| SOLUSDT 4h | −5.3% | +21.5% | 24 | 67% | 0.75 | 25.4% | 8 May 2026 – 21 Oct 2026 |
| BNBUSDT 1D | +2.5% | +148.3% | 59 | 73% | 1.04 | 32.1% | 26 Jan 2024 – 21 Oct 2026 |
| BNBUSDT 4h | +4.0% | +17.1% | 7 | 86% | 8.10 | 19.8% | 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 | 17 | 88% | $4.29 |
| Sideways market | 25 | 52% | −$30.62 |
| Falling market | 13 | 85% | −$0.17 |
Rising and falling mean the market moved more than 15% over the 90 bars before entry.
How bad could the drawdown be?
35.5%
The 95th percentile of the worst drawdown when the same 55 trades are reshuffled 5,000 times. The bar spans the 5th to 95th percentile, 23.8% to 35.5%; the tick is what actually happened, 37.4%. Order luck alone moves it this much.
All 55 trades
| Side | Entry | Exit | Bars | P&L |
|---|---|---|---|---|
| long | 17 Mar 2024 65,300.60 | 18 Mar 2024 68,393.50 | 1 | $0.91 |
| long | 20 Mar 2024 61,937.40 | 21 Mar 2024 67,840.50 | 1 | $1.86 |
| long | 3 Apr 2024 65,464.00 | 5 Apr 2024 68,487.80 | 2 | $0.88 |
| long | 14 Apr 2024 63,924.50 | 23 Apr 2024 66,819.30 | 9 | $0.86 |
| long | 18 Apr 2024 61,277.40 | 23 Apr 2024 66,819.30 | 5 | $2.36 |
| long | 2 May 2024 58,365.00 | 4 May 2024 62,882.00 | 2 | $1.51 |
| long | 14 Jun 2024 66,773.00 | 17 Jul 2024 65,044.00 | 33 | −$0.56 |
| long | 22 Jun 2024 64,143.60 | 17 Jul 2024 65,044.00 | 25 | $0.32 |
| long | 24 Jun 2024 63,210.00 | 17 Jul 2024 65,044.00 | 23 | $0.72 |
| long | 25 Jun 2024 60,293.30 | 17 Jul 2024 65,044.00 | 22 | $2.05 |
| long | 3 Aug 2024 61,498.30 | 5 Aug 2024 49,198.70 | 2 | −$4.04 |
| long | 5 Aug 2024 58,161.00 | 5 Aug 2024 49,198.70 | 0 | −$4.16 |
| long | 6 Aug 2024 54,018.80 | 24 Aug 2024 64,037.20 | 18 | $3.67 |
| long | 6 Sep 2024 56,180.00 | 10 Sep 2024 57,042.00 | 4 | $0.27 |
| long | 7 Sep 2024 53,963.00 | 10 Sep 2024 57,042.00 | 3 | $1.47 |
| long | 2 Oct 2024 60,804.90 | 15 Oct 2024 66,084.00 | 13 | $1.69 |
| long | 24 Oct 2024 66,668.60 | 29 Oct 2024 69,962.20 | 5 | $0.95 |
| long | 26 Nov 2024 93,010.00 | 30 Nov 2024 97,460.00 | 4 | $0.92 |
| long | 23 Dec 2024 95,186.30 | 25 Dec 2024 98,663.60 | 2 | $0.69 |
| long | 28 Dec 2024 94,299.00 | 4 Jan 2025 98,174.20 | 7 | $0.78 |
| long | 9 Jan 2025 95,060.60 | 16 Jan 2025 100,497.00 | 7 | $1.10 |
| long | 20 Jan 2025 101,332.00 | 22 Jan 2025 106,144.00 | 2 | $0.91 |
| long | 29 Jan 2025 101,336.00 | 31 Jan 2025 104,723.00 | 2 | $0.63 |
| long | 2 Feb 2025 100,636.00 | 7 Apr 2025 74,995.60 | 64 | −$5.13 |
| long | 6 Feb 2025 96,612.40 | 7 Apr 2025 74,995.60 | 60 | −$6.01 |
| long | 25 Feb 2025 91,552.90 | 7 Apr 2025 74,995.60 | 41 | −$4.87 |
| long | 26 Feb 2025 88,680.40 | 7 Apr 2025 74,995.60 | 40 | −$4.16 |
| long | 6 Jun 2025 101,509.00 | 7 Jun 2025 104,288.00 | 1 | $0.51 |
| long | 23 Jun 2025 100,964.00 | 24 Jun 2025 105,334.00 | 1 | $0.82 |
| long | 2 Aug 2025 113,298.00 | 8 Aug 2025 117,472.00 | 6 | $0.70 |
| long | 20 Aug 2025 112,873.00 | 12 Sep 2025 115,483.00 | 23 | $0.42 |
| long | 30 Aug 2025 108,377.00 | 12 Sep 2025 115,483.00 | 13 | $1.69 |
| long | 11 Oct 2025 112,774.00 | 27 Oct 2025 114,559.00 | 16 | $0.28 |
| long | 17 Oct 2025 108,194.00 | 27 Oct 2025 114,559.00 | 10 | $1.51 |
| long | 18 Oct 2025 106,432.00 | 27 Oct 2025 114,559.00 | 9 | $1.98 |
| long | 4 Nov 2025 106,583.00 | 31 Jan 2026 80,017.80 | 88 | −$5.02 |
| long | 5 Nov 2025 101,497.00 | 31 Jan 2026 80,017.80 | 87 | −$5.69 |
| long | 14 Nov 2025 99,692.00 | 31 Jan 2026 80,017.80 | 78 | −$5.31 |
| long | 15 Nov 2025 94,594.00 | 31 Jan 2026 80,017.80 | 77 | −$4.16 |
| long | 12 Feb 2026 67,082.50 | 15 Feb 2026 69,822.90 | 3 | $0.78 |
| long | 18 Feb 2026 67,503.50 | 26 Feb 2026 67,988.00 | 8 | $0.10 |
| long | 24 Feb 2026 64,656.00 | 26 Feb 2026 67,988.00 | 2 | $1.32 |
| long | 9 Mar 2026 65,971.20 | 10 Mar 2026 68,432.20 | 1 | $0.71 |
| long | 22 Mar 2026 68,918.10 | 24 Mar 2026 70,906.40 | 2 | $0.54 |
| long | 27 Mar 2026 68,820.30 | 8 Apr 2026 71,924.20 | 12 | $0.86 |
| long | 28 Mar 2026 66,407.30 | 8 Apr 2026 71,924.20 | 11 | $2.16 |
| long | 17 May 2026 78,148.10 | 5 Jun 2026 59,496.80 | 19 | −$4.81 |
| long | 23 May 2026 75,539.50 | 5 Jun 2026 59,496.80 | 13 | −$5.71 |
| long | 29 May 2026 73,617.50 | 5 Jun 2026 59,496.80 | 7 | −$5.16 |
| long | 2 Jun 2026 71,408.90 | 5 Jun 2026 59,496.80 | 3 | −$4.50 |
| long | 19 Jun 2026 62,958.00 | 4 Jul 2026 62,583.30 | 15 | −$0.16 |
| long | 26 Jun 2026 59,794.60 | 4 Jul 2026 62,583.30 | 8 | $1.19 |
| long | 1 Jul 2026 58,624.70 | 4 Jul 2026 62,583.30 | 3 | $1.75 |
| long | 1 Aug 2026 62,887.90 | 8 Aug 2026 64,923.20 | 7 | $0.61 |
| long | 15 Aug 2026 63,043.60 | 19 Aug 2026 64,725.40 | 4 | $0.49 |
Similar scripts
No other indicator or strategy here shares enough of its calculations.
Where it runs
| Engine | Compiles | Runs | Matches TradingView |
|---|---|---|---|
| Zeal Terminal · OpenPineScript v2 | Yes 82 ms | With a workaround 1,000 bars in 417 ms | Not measured |
| PineTS | No v5 and v6 only | — | Not measured |
Zeal Terminal's engine currently reads an order side written as long = strategy.long as a short, whatever it says; this page passes the same side as strategy.long or strategy.short (lines 74, 80) so the engine trades the way the script says.
“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/// © userIan//@version=4strategy("(IK) Base Break Buy", overlay=true, pyramiding=6, precision=2, default_qty_type=strategy.cash, initial_capital=100.0, currency="USD", commission_type=strategy.commission.percent, commission_value=0.1)// == INPUT ==i_baseMax = input(group="Base Calculations", title="Max Bases", type=input.integer, defval=3, minval=1, maxval=10) // max amount of bases on the chart at any specific timei_dev = input(group="Base Calculations", title="Base Area Deviation", type=input.float, defval=0.005, minval=0.0, maxval=1.0) // if enough recent bars had bottoms within this deviation of the current bar's bottom, a base is created i_baseDev = input(group="Base Calculations", title="Unique Base Deviation", type=input.float, defval=0.05, minval=0.0, maxval=1.0) // bases cannot be created if they fall within this deviation of an extant basei_baseSource = input(group="Base Calculations", title="Base Source", options=["Close or Open", "Low"], defval="Close or Open") // should base calcuations be based off of candlestick closes and opens (whichever is lower), or candlestick lowsi_lookback = input(group="Base Calculations", title="Lookback", type=input.integer, defval=100) // how many bars back do we check to confirm current basesi_confLevel = input(group="Base Calculations", title="Confidence Level", type=input.float, defval=0.01, minval=0.0, maxval=1.0) // what percentage of historical bars bottoming within deviation are needed to confirm a basei_breakThresh = input(group="Base Break Detection", title="Break Threshold", type=input.float, defval=0.02, minval=0.0, maxval=1.0) // how far (by percentage) does price have to fall below a base to constitute a 'break'i_breakWindow = input(group="Base Break Detection", title="Break Window", type=input.integer, defval=5) // how many bars should we allow for price to fall below the break threshold before it's no longer a tradable breaki_initialOrder = input(group="Order Settings", title="Initial Order Capital", type=input.float, defval=0.2, minval=0.0, maxval=1.0) // what percentage of capital to use in initial trade entryi_safetyCount = input(group="Order Settings", title="Safety Order Max Count", type=input.integer, defval=3, minval=0, maxval=5) // maximum amount of safety orders per trade. remaining capital after initial entry will be divided evenly among these i_safetyThresh = input(group="Order Settings", title="Safter Order Threshold", type=input.float, defval=0.03, minval=0.0, maxval=1.0) // what percentage does price need to fall to activate a safety orderi_stopLoss = input(group="Order Settings", title="Stop Loss", type=input.float, defval=0.2, minval=0.0, maxval=1.0) // what percentage does price need to fall to activate a stop lossi_stopLossType = input(group="Order Settings", title="Stop Loss Type", options=['From Initial Entry', 'From Price Average'], defval='From Price Average') // calculate static stop loss based on price at first entry, or dynamic stop loass based on position average price// == FUNCTIONS ==// is _val1 within the deviation (_dev) of _val2?f_isCloseTo(_val1, _val2, _dev) => (_val1 <= _val2*(1+_dev)) and (_val1 >= _val2*(1-_dev)) // is this confirmed base (_val) distant enough (outside of deviation _dev) from another confirmed base (in _arr)?f_newBase(_val, _arr, _dev) => result = true if array.size(_arr) > 0 for i = 0 to array.size(_arr)-1 if (_val <= array.get(_arr, i)*(1+_dev)) and (_val >= array.get(_arr, i)*(1-_dev)) result := false result // == VARIABLES ==var bases = array.new_float() // reference to every current basevar closestBase = float(na) // the closest base to currenct price (only below price)var brokenBase = float(na) // the base that has been recently brokenvar baseBreakIndex = int(na) // when the most recent base was brokenvar takeProfit = float(na) // dynamic take profit percentage base on severity of base breakvar safetyOrderQty = ((strategy.initial_capital*(1-i_initialOrder))/i_safetyCount)/100 // percentage of capital to use for each safety ordervar safetyCount = 0 // keep track of how many safety orders we've made// == LOGIC ==// detect bases and add unique bases to base arraycurrentBot = i_baseSource == "Low" ? low : min(close,open)count = 0for i = 1 to i_lookback bot = i_baseSource == "Low" ? low[i] : min(close[i],open[i]) if f_isCloseTo(currentBot, bot, i_dev) count := count +1 if count >= (i_lookback * i_confLevel) and f_newBase(currentBot, bases, i_baseDev) array.unshift(bases, currentBot) // prune base array if array.size(bases) > i_baseMax array.pop(bases) // detect base breakif crossunder(close, closestBase) and strategy.position_size == 0 baseBreakIndex := bar_index brokenBase := closestBase // reset baseBreak if window has expired; this is no longer a tradable breakif (bar_index - baseBreakIndex > i_breakWindow) and strategy.position_size == 0 brokenBase := na// update closest baseif array.size(bases) > 0 array.sort(bases, order.descending) for i = 0 to array.size(bases)-1 if array.get(bases, i) < close closestBase := array.get(bases,i) break// reset safety count if a trade has just been exitedif strategy.position_size == 0 safetyCount := 0// == ENTRY AND EXIT ==// enter trade if break is confirmed and set the takeProfit percentageif close < (brokenBase * (1-i_breakThresh)) and strategy.position_size == 0 and barstate.isconfirmed strategy.entry(id="Long", long=strategy.long, qty=(strategy.initial_capital * i_initialOrder)/close, comment='buy') takeProfit := 1-(close/brokenBase) // safety orderif close < (strategy.position_avg_price * (1-i_safetyThresh)) and safetyCount < i_safetyCount safetyCount := safetyCount + 1 strategy.entry(id="Long", long=strategy.long, qty=(strategy.initial_capital * safetyOrderQty)/close, comment='safety')// exit tradestrategy.exit(id="Long", stop=i_stopLossType == "From Price Average" ? strategy.position_avg_price * (1-i_stopLoss) : brokenBase * (1-i_stopLoss), comment='sell-stop')if (close > strategy.position_avg_price * (1+takeProfit)) and barstate.isconfirmed strategy.close("Long", comment='sell-profit') brokenBase := na// == PLOT == plotTimer = bar_index % 2 == 0 // this creates a dashed line plot(array.size(bases) > 0 and plotTimer ? array.get(bases,0) : na, color=color.white, style=plot.style_linebr)plot(array.size(bases) > 1 and plotTimer ? array.get(bases,1) : na, color=color.white, style=plot.style_linebr)plot(array.size(bases) > 2 and plotTimer ? array.get(bases,2) : na, color=color.white, style=plot.style_linebr)plot(array.size(bases) > 3 and plotTimer ? array.get(bases,3) : na, color=color.white, style=plot.style_linebr)plot(array.size(bases) > 4 and plotTimer ? array.get(bases,4) : na, color=color.white, style=plot.style_linebr)plot(array.size(bases) > 5 and plotTimer ? array.get(bases,5) : na, color=color.white, style=plot.style_linebr)plot(array.size(bases) > 6 and plotTimer ? array.get(bases,6) : na, color=color.white, style=plot.style_linebr)plot(array.size(bases) > 7 and plotTimer ? array.get(bases,7) : na, color=color.white, style=plot.style_linebr)plot(array.size(bases) > 8 and plotTimer ? array.get(bases,8) : na, color=color.white, style=plot.style_linebr)plot(array.size(bases) > 9 and plotTimer ? array.get(bases,9) : na, color=color.white, style=plot.style_linebr)plot(closestBase == closestBase[1] and strategy.position_size == 0 ? closestBase : na, color=color.yellow, style=plot.style_linebr) // yellow line for closest base (if not in trade)plot(brokenBase, color=color.purple, style=plot.style_linebr) // purple line for the broken base that triggered the tradeplot(strategy.position_avg_price * (1+takeProfit), color=color.silver, style=plot.style_linebr) // silver line for target profitplot(i_stopLossType == "From Price Average" ? strategy.position_avg_price * (1-i_stopLoss) : brokenBase * (1-i_stopLoss), color=color.red, style=plot.style_linebr) // red line for stop loss