Coding Double Bollinger Bands in Pine Script

I am trying to code a Double Bollinger Bands script in tradingview with pine-script for both standard deviation 1 and 2. Though the script itself is not generating any error during saving and adding it on the chart. But it is neither working, because the second standard deviation option is not working or staying non-functional. My code is as follows -

//@version=5
indicator(shorttitle="DBB", title="Double Bollinger Bands", overlay=true, timeframe="", timeframe_gaps=true)
length = input.int(20, minval=1)
src = input(close, title="Source")
mult = input.float(2.0, minval=0.001, maxval=50, title="StdDev")
basis = ta.sma(src, length)
dev = mult * ta.stdev(src, length)
upper = basis + dev
lower = basis - dev
offset = input.int(0, "Offset", minval = -500, maxval = 500)
plot(basis, "Basis", color=#FF6D00, offset = offset)
p1 = plot(upper, "Upper", color=#2962FF, offset = offset)
p2 = plot(lower, "Lower", color=#2962FF, offset = offset)
fill(p1, p2, title = "Background", color=color.rgb(33, 150, 243, 95))

//BB
length_BB = input.int(20, minval=1)
src_BB = input(close, title="Source")
mult_BB = input.float(2.0, minval=0.001, maxval=50, title="StdDev")
basis_BB = ta.sma(src_BB, length_BB)
dev_BB = mult * ta.stdev(src_BB, length_BB)
upper_BB = basis_BB + dev_BB
lower_BB = basis_BB - dev_BB
offset_BB = input.int(0, "Offset", minval = -500, maxval = 500)
plot(basis_BB, "Basis_BB", color=#FF6D00, offset = offset_BB)
p1_BB = plot(upper_BB, "Upper_BB", color=#2962FF, offset = offset_BB)
p2_BB = plot(lower_BB, "Lower_BB", color=#2962FF, offset = offset_BB)
fill(p1_BB, p2_BB, title = "Background", color=color.rgb(33, 150, 243, 95))

Please help me to resolve this issue. Thanks & regards.

Upvotes: 1

Views: 4642

Answers (1)

beeholder
beeholder

Reputation: 1699

You have the mult_BB input, but it is unused. Instead, you use the mult input in both dev and dev_BB. As a result, both pairs of bands are multiplied by the same number and they return the same values and overlap on the chart, even if you specify a different multiplier for each of them. Replacing the following should fix this:

Before:
dev_BB = mult * ta.stdev(src_BB, length_BB)
After:
dev_BB = mult_BB * ta.stdev(src_BB, length_BB)

Upvotes: 3

Related Questions