Pine Editor Script question about a function

38 Views Asked by At

I am trying to executes a basic strategy that buys when the close has remained under the lower band (1 standard deviation band) for 3 days then crosses the lower band. Is there a certain function I need to use? Im having a lot of trouble figuring this out.

//@version=5
strategy(shorttitle="BB", title="BBands Buy/Sell", overlay=true)

// Bollinger Bands - First Band
length = input.int(20, minval=1)
src = input(close, title="Source")
mult = input.float(1.0, minval=0.001, maxval=50, title="StdDev 1")

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=#ff6f0000, 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))

// Bollinger Bands - Second Band
mult2 = input.float(2.0, minval=0.001, maxval=50, title="StdDev 2") // Adjust the value for the second band

dev2 = mult2 * ta.stdev(src, length)
upper2 = basis + dev2
lower2 = basis - dev2

// Plotting the Second Band
p3 = plot(upper2, "Upper 2", color=color.orange, offset = offset)
p4 = plot(lower2, "Lower 2", color=color.orange, offset = offset)
fill(p3, p4, title = "Background 2", color=color.rgb(255, 165, 0, 70))

// Trades
longCondition = ta.crossover(close, lower) // Entry when close crosses above the lower band

if (longCondition)
    strategy.entry("long", strategy.long)

if (strategy.opentrades > 0)
    strategy.exit("exitlong", "long", profit = 2000, loss = 2000) // Exit long position at 2% profit

A buy when the close remains under the lower band for 3 days then crosses the lower band on the next closse.

1

There are 1 best solutions below

0
Guardian667 On

You can compare the historic data (values on previous bars) of the series values close and lower.

longCondition = close[3] < lower[3] and close[2] < lower[2] and close[1] < lower[1] and ta.crossover(close, lower)

E.G. close[3] < lower[3]checks if the close price of the bar which is 3 bars left from the current bar, was lower then the lower value on this bar.

Obviously you don't have to use the crossover then anymore

longCondition = close[3] < lower[3] and close[2] < lower[2] and close[1] < lower[1] and close > lower

Comment: I am currently working on a library that handle states and transitions between states, for exactly such investigations. In your case it could be the the states closeWasBelowLowerFor3Bars and closeCrossesUpLower. If you wish I keep this post in mind and add a link to the library in a comment, when I am finished.