Certainly! Here's the updated trading strategy code that buys when the close price is below the lower Bollinger Band and sells when the close price is above the upper Bollinger Band.
// @version=5
strategy("Bollinger Bands Strategy - Close Price Outside Bands", overlay=true)
// Inputs for Bollinger Bands
length = input.int(20, minval=1, title="BB Length")
mult = input.float(2.0, minval=0.0, title="BB Standard Deviation")
// Calculate Bollinger Bands
basis = ta.sma(close, length)
dev = mult * ta.stdev(close, length)
upper = basis + dev
lower = basis - dev
// Plot Bollinger Bands
plot(basis, color=color.orange, title="Middle Band")
p1 = plot(upper, color=color.blue, title="Upper Band")
p2 = plot(lower, color=color.blue, title="Lower Band")
fill(p1, p2, color=color.blue, title="Bollinger Bands Fill", transp=90)
// Buy when close price is below the lower band
buyCondition = close < lower
// Sell when close price is above the upper band
sellCondition = close > upper
// Execute buy order
if (buyCondition)
strategy.entry("Long", strategy.long)
// Close position when sell condition is met
if (sellCondition)
strategy.close("Long")
// Plot Buy/Sell signals on chart
plotshape(buyCondition, title="Buy Signal", location=location.belowbar, color=color.green, style=shape.triangleup, size=size.tiny)
plotshape(sellCondition, title="Sell Signal", location=location.abovebar, color=color.red, style=shape.triangledown, size=size.tiny)
Explanation:
How to Use:
- Apply the Script: Copy the code into a new Pine Script editor window on TradingView.
- Customize Inputs:
- Adjust the
BB Length and BB Standard Deviation to suit your trading preferences.
- Test the Strategy:
- Use the
Strategy Tester tab to review the performance of the strategy on historical data.
- Adjust as Needed:
- Modify the strategy parameters and conditions to optimize performance for your specific trading instrument and timeframe.
Note:
- This strategy assumes that prices moving below the lower band may be oversold (potential buying opportunities) and prices moving above the upper band may be overbought (potential selling opportunities).
- Always backtest strategies thoroughly before applying them to live trading to understand their behavior under different market conditions.
Let me know if you need further adjustments or explanations!