Strategy · Pine Script v4 · Own pane

Bayesian BBSMA Oscillator Strategy

by tistaharahap· code credited to tista

This Pine Script strategy calculates Bayesian probabilities of price breaking up or down relative to Bollinger Bands and a Simple Moving Average.

View on GitHub

GitHub stars25on the repository
Pine versionv4older, still runs
Lines of code92
Settings11inputs
LicenceNone statedfile: MPL-2.0
Last update6 years ago29 Jun 2020

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

92 lines of Pine Script v4 from bayesian/strategies/bbsmastrat.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

bbsmastrat.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tista

//@version=4
strategy("Bayesian BBSMA Oscillator Strategy", shorttitle="BayesBBSMAOscStrategy", default_qty_type=strategy.percent_of_equity, default_qty_value=100, currency="USD")

bbSmaPeriod = input(20, title="BB SMA Period")
bbStdDevMult = input(2.5, title="BB Standard Deviation", maxval=50.0)

bbBasis = sma(close, bbSmaPeriod)
bbStdDev = bbStdDevMult * stdev(close, bbSmaPeriod)

bbUpper = bbBasis + bbStdDev
bbLower = bbBasis - bbStdDev

// SMA
smaPeriod = input(20, title="SMA Period")
smaValues = sma(close, smaPeriod)


// Bayesian Theorem Starts
bayesPeriod = input(20, title="Bayesian Lookback Period")

// Next candles are breaking Down
probBbUpperUpSeq = close > bbUpper ? 1 : 0
probBbUpperUp = sum(probBbUpperUpSeq, bayesPeriod) / bayesPeriod
probBbUpperDownSeq = close < bbUpper ? 1 : 0
probBbUpperDown = sum(probBbUpperDownSeq, bayesPeriod) / bayesPeriod

probUpBbUpper = probBbUpperUp / (probBbUpperUp + probBbUpperDown)

probBbBasisUpSeq = close > bbBasis ? 1 : 0
probBbBasisUp = sum(probBbBasisUpSeq, bayesPeriod) / bayesPeriod
probBbBasisDownSeq = close < bbBasis ? 1 : 0
probBbBasisDown = sum(probBbBasisDownSeq, bayesPeriod) / bayesPeriod

probUpBbBasis = probBbBasisUp / (probBbBasisUp + probBbBasisDown)

probSmaUpSeq = close > smaValues ? 1 : 0
probSmaUp = sum(probSmaUpSeq, bayesPeriod) / bayesPeriod
probSmaDownSeq = close < smaValues ? 1 : 0
probSmaDown = sum(probSmaDownSeq, bayesPeriod) / bayesPeriod

probUpSma = probSmaUp / (probSmaUp + probSmaDown)

sigmaProbsDown = nz(probUpBbUpper * probUpBbBasis * probUpSma / probUpBbUpper * probUpBbBasis * probUpSma + ((1 - probUpBbUpper) * (1 - probUpBbBasis) * (1 - probUpSma))) * 100

// Next candles are breaking Up
probDownBbUpper = probBbUpperDown / (probBbUpperDown + probBbUpperUp)
probDownBbBasis = probBbBasisDown / (probBbBasisDown + probBbBasisUp)
probDownSma = probSmaDown / (probSmaDown + probSmaUp)

sigmaProbsUp = nz(probDownBbUpper * probDownBbBasis * probDownSma / probDownBbUpper * probDownBbBasis * probDownSma + ( (1 - probDownBbUpper) * (1 - probDownBbBasis) * (1 - probDownSma) )) * 100

showNextCandleDown = input(true, title="Plot Next Candles Breaking Down?")
plot(showNextCandleDown ? sigmaProbsDown : na, title="Next Candle Breaking Down Probs", transp=0, color=color.red)

showNextCandleUp = input(true, title="Plot Next Candles Breaking Up?")
plot(showNextCandleUp ? sigmaProbsUp : na, title="Next Candle Breaking Up Probs", transp=0, color=color.green)

longSignal = sigmaProbsUp < 100 and sigmaProbsUp[1] == 100
shortSignal = sigmaProbsDown < 100 and sigmaProbsDown[1] == 100

longTrailPerc = input(title="Trail Long Loss (%)", type=input.float, minval=0.0, step=0.1, defval=4) * 0.01
longStopPrice = 0.0

longStopPrice := if (strategy.position_size > 0)
    stopValue = close * (1 - longTrailPerc)
    max(stopValue, longStopPrice[1])
else
    0

shortTrailPerc = input(title="Trail Short Loss (%)", type=input.float, minval=0.0, step=0.1, defval=4) * 0.01
shortStopPrice = 0.0

shortStopPrice := if (strategy.position_size < 0)
    stopValue = close * (1 + shortTrailPerc)
    min(stopValue, shortStopPrice[1])
else
    999999999

startingYear = input(2019, title="Year started")

doLongs = input(true, title="Calculate longs?")
strategy.entry("Long", strategy.long, when=strategy.position_size == 0 and longSignal and year >= startingYear and doLongs)
if (strategy.position_size > 0)
    strategy.exit(id="Long Trail Stop", stop=longStopPrice)

doShorts = input(true, title="Calculate shorts?")
strategy.entry("Short", strategy.short, when=strategy.position_size == 0 and shortSignal and year >= startingYear and doShorts)
if (strategy.position_size < 0)
    strategy.exit(id="Short Trail Stop", stop=shortStopPrice)

Overview

Bayesian BBSMA Oscillator Strategy plots these breakout and breakdown probability lines as oscillators in a separate pane. Long entries trigger when the upward probability crosses down from maximum, while short entries trigger when downward probability drops from maximum. Trades are protected using a percentage-based trailing stop loss. Settings allow customization of Bollinger Band parameters, Bayesian lookback period, trailing stop percentages, start year, and directional long/short toggles.

Details

Published by

tistaharahap on GitHub

Code credit

tista, as written in the script's header

Type

Strategy, Pine Script v4

Draws

Separate pane below the chart

Category

Oscillators & momentum, Volatility & bands, Moving averages

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
BB SMA Periodint20bbSmaPeriod
BB Standard Deviationfloat2.5bbStdDevMult
SMA Periodint20smaPeriod
Bayesian Lookback Periodint20bayesPeriod
Plot Next Candles Breaking Down?booltrueshowNextCandleDown
Plot Next Candles Breaking Up?booltrueshowNextCandleUp
Trail Long Loss (%)float4longTrailPerc
Trail Short Loss (%)float4shortTrailPerc
Year startedint2019startingYear
Calculate longs?booltruedoLongs
Calculate shorts?booltruedoShorts
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

106 stars

This strategy captures strong bullish momentum by combining a 200-period SMA baseline, a custom Bollinger Band, the True Strength Index (TSI) smoothed with WMAs, and the ADX trend strength indicator. It initiates long positions when price is above the 200 SMA,

Strategy v4 TrendOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of ADX_TSI_Bol Band Trend Chaser

EMA Ribbon MACD

by iamrichardD
57 stars

This strategy combines an EMA ribbon with MACD confirmation and plots in a separate pane. It enters when ribbon alignment, optional MACD zero or signal crosses, volume, smart-money, and multi-timeframe filters agree, then exits with percentage stop loss and ta

Strategy v6 TrendMoving averages
Updated 1 year ago · Apache-2.0 GitHub repository of EMA Ribbon MACD

Greeffer BB Strategy

by SammyEnigma
18 stars

This strategy combines Bollinger Bands, Bollinger Band Width, and the Relative Strength Index (RSI) for mean-reversion trades. It enters long when price crosses below the lower band with oversold RSI, or when band width contracts under low volatility. Short en

Strategy v4 Mean reversionOscillators & momentum
Updated 6 years ago · None stated GitHub repository of Greeffer BB Strategy

AwesomeADX

by koradiyakaushal
12 stars

AwesomeADX is a Pine Script v4 strategy that combines an Awesome Oscillator, ADX directional movement, and Bollinger percent B with an optional four-length moving-average trend filter. It sizes each position as a percentage of equity and can limit trades to a

Strategy v4 Oscillators & momentumMoving averages
Updated 5 years ago · MIT GitHub repository of AwesomeADX
330 stars

This strategy plots MACD line, signal line, Bollinger Bands, and RSI on the price chart. It signals long entries on MACD crossover above signal with RSI below 50 and price below BB basis, plus optional DMI filter. Short entries are available but disabled by de

Strategy v5 Oscillators & momentumVolatility & bands
Updated 2 months ago · None stated GitHub repository of MACD + BB + RSI [Alorse]

Take Profits & Stop Losses

by PythonForForex
64 stars

This educational strategy demonstrates moving average crossovers filtered by RSI momentum, incorporating ATR-based risk management. It calculates a 10-period SMA, a 30-period SMA, a 14-period RSI, and a 14-period ATR. Long entries trigger when the fast SMA cro

Strategy v5 Moving averagesOscillators & momentum
Updated 4 years ago · None stated GitHub repository of Take Profits & Stop Losses

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers