Zeal Terminal Open in Zeal Terminal

Pine Script v5 · Strategy

BB and KC Strategy

A Pine Script v5 strategy built on BB (close, 20), KC (close, 20) and SMA (volume, 10). It has 5 order rules, 2 entries among them, and trades long and short with the default settings. Exits use a stop loss. Each trade commits 1000 in cash and pays no commission. 8 settings; defaults include KC Length 20, KC StdDev 2.2 and BB Length 20.

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 BB and KC Strategy 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 BB and KC Strategy do on BTCUSDT 1D with default settings?
+0.00%
From 26 Jan 2024 to 21 Oct 2026, over 22 closed trades, against +102.5% for buy and hold. A backtest, not investment advice.
Does BB and KC Strategy run in Pine Script v6?
Yes
Same 22 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. Both versions were run on Zeal Terminal's engine, and the results are identical. The v6 script can be downloaded below.
Does BB and KC Strategy use a stop loss?
Yes
strategy.exit sets a stop on line 52, 54.
Does BB and KC Strategy run in Zeal Terminal?
Yes
It compiles in 27 ms and runs 1,000 bars in 41 ms, in the browser.

BTCUSDT · 1D · default settings

  • 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 (8)
40,00060,00080,000100,000120,000AprJulOct2025AprJulOct2026AprJulOct$1,000,130$2,025,273Equity from $1,000,000
Binance BTCUSDT 1D candles, 26 Jan 2024 to 21 Oct 2026, 1,000 bars, default settings. Triangles mark entries; circles mark exits. Lines are what the script plots.
Net profit
+0.00%
$49.03
Buy and hold
+102.5%
same period
Closed trades
22
10 won · 9 lost
Profitable
45.5%
of closed trades
Profit factor
1.07
gross profit ÷ gross loss
Max drawdown
0.05%
−$502.85

One run with the author's default settings, $1,000,000 starting capital, commission as the script sets it. A long position was still open at the last bar. 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 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.

Settings

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

SettingDefaultType and rangeFeeds
KC Length20int · min 1kc_middle kc_upper kc_lower
KC StdDev2.2floatkc_middle kc_upper kc_lower
BB Length20int · min 1bb_middle bb_upper bb_lower
BB StdDev2floatbb_middle bb_upper bb_lower
Volume MA Length10int · min 1vol_ma
Stop Loss (%)1.5floatexit Sell exit Buy
Trail Stop (%)2floatexit Sell exit Buy
Bars in trade before exit20int · min 1close_all line 47 line 48

What it calculates

  • BBclose, BB Length (20), BB StdDev (2)bb_middle · line 15
  • BBclose, BB Length (20), BB StdDev (2)bb_upper · line 15
  • BBclose, BB Length (20), BB StdDev (2)bb_lower · line 15
  • KCclose, KC Length (20), KC StdDev (2.2)kc_middle · line 16
  • KCclose, KC Length (20), KC StdDev (2.2)kc_upper · line 16
  • KCclose, KC Length (20), KC StdDev (2.2)kc_lower · line 16
  • SMAvolume, Volume MA Length (10)vol_ma · line 18

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 databbLengthBB Lengthsetting · 20bbStdDevBB StdDevsetting · 2kcLengthKC Lengthsetting · 20kcStdDevKC StdDevsetting · 2.2volumevolumeprice datavolumeLengthVolume MA Lengthsetting · 10barsInTradeBars in trade before ex…setting · 20bb_middleBB→ bb_middlebb_upperBB→ bb_upperbb_lowerBB→ bb_lowerkc_middleKC→ kc_middlekc_upperKC→ kc_upperkc_lowerKC→ kc_lowervol_maSMA→ vol_maentry_priceentry_pricevaluebar_counterbar_countervaluelongCondlongCondconditionshortCondshortCondconditionentry:BuyOpen Buystrategy.entryentry:SellOpen Sellstrategy.entryclose_all:close_all strategy.close_allexit:Sellexit Sellstrategy.exitexit:Buyexit Buystrategy.exitplot:20plotplotplot:21plotplotplot:22plotplotplot:23plotplotplot:24plotplotplot:25plotplot

Order rules

OrderFires whenBy defaultLine
Open Buy long(longCond)On35
Open Sell short(shortCond)On39
Close (bar_counter >= barsInTrade)On49
Exit Sell stop(strategy.position_size > 0)On52
Exit Buy stop(strategy.position_size < 0)On54

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.

4/4trades identical when replayed liveThe last 300 bars, from 26 Dec 2025, were fed to the engine as live ticks, four per bar, and compared with the historical run. Orders are decided once per closed bar, so nothing can change mid-bar.
  • 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+0.0%+102.5%2245%1.070.1%26 Jan 2024 – 21 Oct 2026
BTCUSDT 4h+0.0%+5.5%3330%1.040.0%8 May 2026 – 21 Oct 2026
ETHUSDT 1D−0.1%+9.8%3037%0.440.2%26 Jan 2024 – 21 Oct 2026
ETHUSDT 4h−0.0%+8.4%2339%0.510.0%8 May 2026 – 21 Oct 2026
SOLUSDT 1D−0.0%+16.7%2836%0.940.1%26 Jan 2024 – 21 Oct 2026
SOLUSDT 4h−0.0%+21.5%2343%0.690.0%8 May 2026 – 21 Oct 2026
BNBUSDT 1D−0.1%+148.3%2934%0.540.1%26 Jan 2024 – 21 Oct 2026
BNBUSDT 4h−0.0%+17.1%2635%0.670.0%8 May 2026 – 21 Oct 2026

Backtests are simulations on historical data and are not investment advice.

Settings heatmap

Two settings that feed the entry signal, moved around their defaults. The best in-sample pair (KC Length 17, KC StdDev 1.54) made +0.1% before 26 Dec 2025 and +0.0% after it, against +0.0% for the defaults. 33% of the 64 combinations made money in-sample and 61% out-of-sample.

Before 26 Dec 2025 · in-sample
KC StdDev ↓ · KC Length →1012141720242834
1.1+0%−0%−0%−0%+0%−0%+0%+0%
1.32−0%−0%−0%−0%−0%−0%−0%−0%
1.54+0%−0%+0%+0%+0%−0%−0%−0%
1.87−0%+0%+0%+0%−0%+0%−0%−0%
2.2+0%+0%−0%−0%−0%+0%−0%−0%
2.64−0%−0%−0%−0%−0%−0%+0%+0%
3.08−0%−0%+0%−0%−0%−0%−0%+0%
3.74−0%−0%−0%−0%−0%−0%+0%+0%
From 26 Dec 2025 · out-of-sample
KC StdDev ↓ · KC Length →1012141720242834
1.1+0%−0%+0%−0%−0%−0%+0%+0%
1.32+0%−0%+0%+0%−0%+0%+0%+0%
1.54+0%+0%+0%+0%+0%−0%−0%+0%
1.87+0%+0%+0%+0%+0%+0%+0%+0%
2.2+0%+0%+0%+0%+0%−0%−0%−0%
2.64+0%+0%+0%+0%+0%−0%−0%−0%
3.08−0%−0%−0%−0%−0%+0%+0%−0%
3.74−0%−0%+0%+0%−0%−0%−0%+0%

Net P&L of trades opened in each period, as a share of starting capital. marks the defaults and the best in-sample cell. Hover a cell for its trade count. Backtests are simulations on historical data and are not investment advice.

The trades

By market direction

At entry, last 90 barsTradesWonP&L
Rising market250%$8.34
Sideways market1644%$118.45
Falling market450%−$77.75

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

How bad could the drawdown be?

0.1%

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

0%1%
All 22 trades
SideEntryExitBarsP&L
long1 Jun 2024 67,540.001 Jun 2024 67,540.000$0.00
short1 Jun 2024 67,540.0021 Jun 2024 64,870.0020$39.53
short4 Jul 2024 60,208.6025 Jul 2024 65,376.0021−$85.83
long2 Aug 2024 65,354.002 Aug 2024 65,354.000$0.00
short2 Aug 2024 65,354.004 Sep 2024 57,487.7033$120.36
long2 Oct 2024 60,804.903 Oct 2024 60,649.301−$2.56
short3 Oct 2024 60,649.3012 Oct 2024 62,540.009−$31.17
long12 Oct 2024 62,540.0031 Oct 2024 72,344.8019$156.78
long1 Nov 2024 70,292.001 Nov 2024 70,292.000$0.00
short1 Nov 2024 70,292.0021 Nov 2024 94,286.6020−$341.36
long6 Dec 2024 96,945.6026 Dec 2024 99,429.6020$25.62
long5 Mar 2025 87,282.0031 Mar 2025 82,390.0026−$56.05
long10 Jun 2025 110,263.0030 Jun 2025 108,357.0020−$17.29
short25 Sep 2025 113,307.0011 Oct 2025 112,774.0016$4.70
long11 Oct 2025 112,774.0022 Oct 2025 108,298.0011−$39.70
short22 Oct 2025 108,298.0010 Nov 2025 104,723.0019$33.01
long2 Dec 2025 86,286.004 Dec 2025 93,429.902$82.79
short4 Dec 2025 93,429.9023 Dec 2025 88,620.8019$51.47
short13 Jan 2026 91,296.209 Feb 2026 70,330.4027$229.65
short24 Feb 2026 64,656.0016 Mar 2026 72,815.3020−$126.19
short28 Apr 2026 77,371.3018 May 2026 77,457.7020−$1.12
short24 Jun 2026 62,734.6014 Jul 2026 62,334.5020$6.38

Similar scripts

Indicators and strategies built from the same calculations, run on BTCUSDT 1D with their own defaults so they can be compared directly.

ScriptSharesTypeNetTradesMax drawdown
BB and KC Strategy this page—v5 strategy+0.0%220.1%
trading YM based on pair trading by hkorange2007sma bbv5 strategyNo trades on this market
TrendMaAlignmentStrategy - Long term trades by Trendoscopesma bbv4 strategy−22.0%846.3%
BuyTheDip by Trendoscopesma bbv4 strategy+4.6%28.3%
Strategy Oil Z Score by jroche1973bb smav4 strategyNo trades on this market
Bollinger -B Candles Strategy by Trendoscopesma bbv4 strategy+17.3%295.1%

Upgrade and export

Written in Pine Script v5. The clean-v5 step types the settings and moves when = into if blocks, which v6 requires; it is run before and after like any upgrade.

  • No v6-only features. v6 is not needed to run this script.

Clean v5

Verified

Nothing to change.

Does it run in Pine Script v6?

Yes

Same 22 trades and the same P&L on BTCUSDT 1D, 1,000 bars, in Zeal Terminal's engine. Both versions were run on Zeal Terminal's engine, and the results are identical. It differs from the v5 version by 1 edit.

Download the v6 script

⋯// © jensenvilhelm-//@version=5+//@version=6strategy("BB and KC Strategy", overlay=true, default_qty_type=strategy.cash, default_qty_value=1000)⋯

Where it runs

EngineCompilesRunsMatches TradingView
Zeal Terminal · OpenPineScript v2Yes 27 msYes 1,000 bars in 41 msNot measured
PineTSNot testedNot testedNot measured

“Matches TradingView” needs this script's own output exported from TradingView and compared bar by bar, which has not been done for this script. The engine is built on OpenPineScript, whose conformance results are in its conformance report.

Source

Copied verbatim from the author's published script, with its licence header intact. The author may have updated the original since this snapshot.

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/// © jensenvilhelm//@version=5strategy("BB and KC Strategy", overlay=true, default_qty_type=strategy.cash, default_qty_value=1000)// Define the input parameters for the strategy, these can be changed by the user to adjust the strategykcLength = input.int(20, "KC Length", minval=1) // Length for Keltner Channel calculationkcStdDev = input.float(2.2, "KC StdDev") // Standard Deviation for Keltner Channel calculationbbLength = input.int(20, "BB Length", minval=1) // Length for Bollinger Bands calculationbbStdDev = input.float(2, "BB StdDev") // Standard Deviation for Bollinger Bands calculationvolumeLength = input.int(10, "Volume MA Length", minval=1) // Length for moving average of volume calculationstopLossPercent = input.float(1.5, "Stop Loss (%)") // Percent of price for Stop loss trailStopPercent = input.float(2, "Trail Stop (%)") // Percent of price for Trailing StopbarsInTrade = input.int(20, "Bars in trade before exit", minval = 1) // Minimum number of bars in trade before considering exit// Calculate Bollinger Bands and Keltner Channel[bb_middle, bb_upper, bb_lower] = ta.bb(close, bbLength, bbStdDev) // Bollinger Bands calculation[kc_middle, kc_upper, kc_lower] = ta.kc(close, kcLength, kcStdDev) // Keltner Channel calculation// Calculate moving average of volumevol_ma = ta.sma(volume, volumeLength) // Moving average of volume calculation// Plotting Bollinger Bands and Keltner Channels on the chartplot(bb_upper, color=color.red) // Bollinger Bands upper lineplot(bb_middle, color=color.blue) // Bollinger Bands middle lineplot(bb_lower, color=color.red) // Bollinger Bands lower lineplot(kc_upper, color=color.rgb(105, 255, 82)) // Keltner Channel upper lineplot(kc_middle, color=color.blue) // Keltner Channel middle lineplot(kc_lower, color=color.rgb(105, 255, 82)) // Keltner Channel lower line// Define entry conditions: long position if upper KC line crosses above upper BB line and volume is above MA of volume// and short position if lower KC line crosses below lower BB line and volume is above MA of volumelongCond = ta.crossover(kc_upper, bb_upper) and volume > vol_ma // Entry condition for long positionshortCond = ta.crossunder(kc_lower, bb_lower) and volume > vol_ma // Entry condition for short position// Define variables to store entry price and bar counter at entry pointvar float entry_price = na // variable to store entry pricevar int bar_counter = na // variable to store bar counter at entry point// Check entry conditions and if met, open long or short positionif (longCond)    strategy.entry("Buy", strategy.long) // Open long position    entry_price := close // Store entry price    bar_counter := 1 // Start bar counterif (shortCond)    strategy.entry("Sell", strategy.short) // Open short position    entry_price := close // Store entry price    bar_counter := 1 // Start bar counter// If in a position and bar counter is not na, increment bar counterif (strategy.position_size != 0 and na(bar_counter) == false)    bar_counter := bar_counter + 1 // Increment bar counter// Define exit conditions: close position if been in trade for more than specified bars// or if price drops by more than specified percent for long or rises by more than specified percent for shortif (bar_counter > barsInTrade) // Only consider exit after minimum bars in trade    if (bar_counter >= barsInTrade)        strategy.close_all() // Close all positions    // Stop loss and trailing stop    if (strategy.position_size > 0)        strategy.exit("Sell", "Buy", stop=entry_price * (1 - stopLossPercent/100), trail_points=entry_price * trailStopPercent/100) // Set stop loss and trailing stop for long position    else if (strategy.position_size < 0)        strategy.exit("Buy", "Sell", stop=entry_price * (1 + stopLossPercent/100), trail_points=entry_price * trailStopPercent/100) // Set stop loss and trailing stop for short position