Zeal Terminal Open in Zeal Terminal

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
Prerendered with the defaults. Change anything and run it here. The script runs in your browser.
Settings (13)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$73$203Equity from $100
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. 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.
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

Verified

Same 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⋯

Clean v5

VerifiedDownload the v5 script

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.

SettingDefaultType and rangeFeeds
Base Calculations
Max Bases3int (written input.integer) · min 1 · max 10line 50
Base Area Deviation0.005float · min 0.0 · max 1.0line 45
Unique Base Deviation0.05float · min 0.0 · max 1.0line 47
Base SourceClose or Openstring · options ["Close or Open", "Low"]currentBot bot
Lookback100int (written input.integer)line 43 line 47
Confidence Level0.01float · min 0.0 · max 1.0line 47
Base Break Detection
Break Threshold0.02float · min 0.0 · max 1.0entry Long line 73
Break Window5int (written input.integer)line 59
Order Settings
Initial Order Capital0.2float · min 0.0 · max 1.0safetyOrderQty entry Long
Safety Order Max Count3int (written input.integer) · min 0 · max 5safetyOrderQty entry Long line 78
Safter Order Threshold0.03float · min 0.0 · max 1.0entry Long line 78
Stop Loss0.2float · min 0.0 · max 1.0exit Long plot
Stop Loss TypeFrom Price Averagestring · 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.

closecloseprice datai_initialOrderInitial Order Capitalsetting · 0.2i_safetyCountSafety Order Max Countsetting · 3openopenprice datalowlowprice datai_baseSourceBase Sourcesetting · Close or Openi_breakThreshBreak Thresholdsetting · 0.02i_safetyThreshSafter Order Thresholdsetting · 0.03i_stopLossTypeStop Loss Typesetting · From Price Averagei_stopLossStop Losssetting · 0.2closestBase, baseBreakIndexclosestBase · baseBreak…2 valuesbrokenBasebrokenBasevaluetakeProfittakeProfitvaluesafetyOrderQtysafetyOrderQtyvaluesafetyCountsafetyCountvaluecurrentBot, botcurrentBot · bot2 valuescountcountvalueplotTimerplotTimerconditionentry:LongOpen Longstrategy.entryexit:Longexit Longstrategy.exitclose:LongClose Longstrategy.closeplot:88plotplotplot:89plotplotplot:90plotplotplot:91plotplotplot:92plotplotplot:93plotplotplot:94plotplotplot:95plotplotplot:96plotplotplot:97plotplotplot:98plotplotplot:99plotplotplot:100plotplotplot:101plotplot

Order rules

OrderFires whenBy defaultLine
Open Long longclose < (brokenBase * (1-i_breakThresh)) and strategy.position_size == 0 and barstate.isconfirmedOn74
Open Long longclose < (strategy.position_avg_price * (1-i_safetyThresh)) and safetyCount < i_safetyCountOn80
Exit Long stopevery barOn82
Close Long(close > strategy.position_avg_price * (1+takeProfit)) and barstate.isconfirmedOn84

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.

Not measuredAn engine gap, not the scriptThe 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. The answer comes from the checks on the source alone.
  • 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.

MarketNetBuy and holdTradesWonProfit factorMax drawdownPeriod
BTCUSDT 1D−26.5%+102.5%5571%0.6242.4%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h−14.2%+5.5%1471%0.2920.4%8 May 2026 – 21 Oct 2026
ETHUSDT 1D−29.4%+9.8%9164%0.7850.8%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h−13.1%+8.4%1464%0.3726.5%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−2.7%+16.7%11867%0.9845.7%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h−5.3%+21.5%2467%0.7525.4%8 May 2026 – 21 Oct 2026
BNBUSDT 1D+2.5%+148.3%5973%1.0432.1%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h+4.0%+17.1%786%8.1019.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 barsTradesWonP&L
Rising market1788%$4.29
Sideways market2552%−$30.62
Falling market1385%−$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.

0%43%
All 55 trades
SideEntryExitBarsP&L
long17 Mar 2024 65,300.6018 Mar 2024 68,393.501$0.91
long20 Mar 2024 61,937.4021 Mar 2024 67,840.501$1.86
long3 Apr 2024 65,464.005 Apr 2024 68,487.802$0.88
long14 Apr 2024 63,924.5023 Apr 2024 66,819.309$0.86
long18 Apr 2024 61,277.4023 Apr 2024 66,819.305$2.36
long2 May 2024 58,365.004 May 2024 62,882.002$1.51
long14 Jun 2024 66,773.0017 Jul 2024 65,044.0033−$0.56
long22 Jun 2024 64,143.6017 Jul 2024 65,044.0025$0.32
long24 Jun 2024 63,210.0017 Jul 2024 65,044.0023$0.72
long25 Jun 2024 60,293.3017 Jul 2024 65,044.0022$2.05
long3 Aug 2024 61,498.305 Aug 2024 49,198.702−$4.04
long5 Aug 2024 58,161.005 Aug 2024 49,198.700−$4.16
long6 Aug 2024 54,018.8024 Aug 2024 64,037.2018$3.67
long6 Sep 2024 56,180.0010 Sep 2024 57,042.004$0.27
long7 Sep 2024 53,963.0010 Sep 2024 57,042.003$1.47
long2 Oct 2024 60,804.9015 Oct 2024 66,084.0013$1.69
long24 Oct 2024 66,668.6029 Oct 2024 69,962.205$0.95
long26 Nov 2024 93,010.0030 Nov 2024 97,460.004$0.92
long23 Dec 2024 95,186.3025 Dec 2024 98,663.602$0.69
long28 Dec 2024 94,299.004 Jan 2025 98,174.207$0.78
long9 Jan 2025 95,060.6016 Jan 2025 100,497.007$1.10
long20 Jan 2025 101,332.0022 Jan 2025 106,144.002$0.91
long29 Jan 2025 101,336.0031 Jan 2025 104,723.002$0.63
long2 Feb 2025 100,636.007 Apr 2025 74,995.6064−$5.13
long6 Feb 2025 96,612.407 Apr 2025 74,995.6060−$6.01
long25 Feb 2025 91,552.907 Apr 2025 74,995.6041−$4.87
long26 Feb 2025 88,680.407 Apr 2025 74,995.6040−$4.16
long6 Jun 2025 101,509.007 Jun 2025 104,288.001$0.51
long23 Jun 2025 100,964.0024 Jun 2025 105,334.001$0.82
long2 Aug 2025 113,298.008 Aug 2025 117,472.006$0.70
long20 Aug 2025 112,873.0012 Sep 2025 115,483.0023$0.42
long30 Aug 2025 108,377.0012 Sep 2025 115,483.0013$1.69
long11 Oct 2025 112,774.0027 Oct 2025 114,559.0016$0.28
long17 Oct 2025 108,194.0027 Oct 2025 114,559.0010$1.51
long18 Oct 2025 106,432.0027 Oct 2025 114,559.009$1.98
long4 Nov 2025 106,583.0031 Jan 2026 80,017.8088−$5.02
long5 Nov 2025 101,497.0031 Jan 2026 80,017.8087−$5.69
long14 Nov 2025 99,692.0031 Jan 2026 80,017.8078−$5.31
long15 Nov 2025 94,594.0031 Jan 2026 80,017.8077−$4.16
long12 Feb 2026 67,082.5015 Feb 2026 69,822.903$0.78
long18 Feb 2026 67,503.5026 Feb 2026 67,988.008$0.10
long24 Feb 2026 64,656.0026 Feb 2026 67,988.002$1.32
long9 Mar 2026 65,971.2010 Mar 2026 68,432.201$0.71
long22 Mar 2026 68,918.1024 Mar 2026 70,906.402$0.54
long27 Mar 2026 68,820.308 Apr 2026 71,924.2012$0.86
long28 Mar 2026 66,407.308 Apr 2026 71,924.2011$2.16
long17 May 2026 78,148.105 Jun 2026 59,496.8019−$4.81
long23 May 2026 75,539.505 Jun 2026 59,496.8013−$5.71
long29 May 2026 73,617.505 Jun 2026 59,496.807−$5.16
long2 Jun 2026 71,408.905 Jun 2026 59,496.803−$4.50
long19 Jun 2026 62,958.004 Jul 2026 62,583.3015−$0.16
long26 Jun 2026 59,794.604 Jul 2026 62,583.308$1.19
long1 Jul 2026 58,624.704 Jul 2026 62,583.303$1.75
long1 Aug 2026 62,887.908 Aug 2026 64,923.207$0.61
long15 Aug 2026 63,043.6019 Aug 2026 64,725.404$0.49

Similar scripts

No other indicator or strategy here shares enough of its calculations.

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 82 msWith a workaround 1,000 bars in 417 msNot measured
PineTSNo 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