xmd79

Bayesian BBSMA + nQQE Oscillator

May 30th, 2023
436
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 18.13 KB | None | 0 0
  1. // This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
  2. // Bayesian BBSMA: https://www.tradingview.com/v/8lXcviYm/
  3. // nQQE: https://www.tradingview.com/v/CfCuUCeE/
  4.  
  5. //@version=4
  6. study("Bayesian BBSMA + nQQE Oscillator", shorttitle="Bayesian/nQQE osc", precision=4)
  7.  
  8. rescale(_src, _oldMin, _oldMax, _newMin, _newMax) =>
  9. // Rescales series with known min/max.
  10. // _src : series to rescale.
  11. // _oldMin, _oldMax: min/max values of series to rescale.
  12. // _newMin, _newMin: min/max values of rescaled series.
  13. _newMin + (_newMax - _newMin) * (_src - _oldMin) / max(_oldMax - _oldMin, 10e-10)
  14.  
  15.  
  16. //#################### Bayesian BBSMA
  17.  
  18. bbSmaPeriod = input(20, title="BB SMA Period", group="═════ Bayesian BBSMA settings ═════")
  19. bbStdDevMult = input(2.5, title="BB Standard Deviation", maxval=50.0)
  20.  
  21. bbBasis = sma(close, bbSmaPeriod)
  22. bbStdDev = bbStdDevMult * stdev(close, bbSmaPeriod)
  23.  
  24. bbUpper = bbBasis + bbStdDev
  25. bbLower = bbBasis - bbStdDev
  26.  
  27. // AO
  28. aoFast = input(5, "AO Fast EMA Length")
  29. aoSlow = input(34, "AO Slow EMA Length")
  30. ao = sma(hl2, aoFast) - sma(hl2, aoSlow)
  31. colorAo = change(ao) > 0 ? color.green : color.red
  32.  
  33. // AC
  34. acFast = input(5, "AC Fast SMA Length")
  35. acSlow = input(34, "AC Slow SMA Length")
  36. xSMA1_hl2 = sma(hl2, acFast)
  37. xSMA2_hl2 = sma(hl2, acSlow)
  38. xSMA1_SMA2 = xSMA1_hl2 - xSMA2_hl2
  39. xSMA_hl2 = sma(xSMA1_SMA2, acFast)
  40. ac = xSMA1_SMA2 - xSMA_hl2
  41. cClr = ac > ac[1] ? color.blue : color.red
  42.  
  43. acAo = (ac + ao) / 2
  44.  
  45. maAcAoPeriod = input(13, "AC AO MA Period")
  46. showMaAcAo = input(false, "Show AC AO MA?")
  47. maAcAo = vwma(acAo, maAcAoPeriod)
  48.  
  49. // Combine AC & AO
  50. acIsBlue = ac > ac[1]
  51. acIsRed = not (ac > ac[1])
  52. aoIsGreen = change(ao) > 0
  53. aoIsRed = not (change(ao) > 0)
  54. acAoIsBullish = acIsBlue and aoIsGreen
  55. acAoIsBearish = acIsRed and acIsRed
  56. acAoColorIndex = acAoIsBullish ? 1 : acAoIsBearish ? -1 : 0
  57.  
  58. // Alligator
  59. smma(src, length) =>
  60. smma = 0.0
  61. smma := na(smma[1]) ? sma(src, length) : (smma[1] * (length - 1) + src) / length
  62. lipsLength = input(title="🐲 Lips Length", defval=5)
  63. teethLength = input(title="🐲 Teeth Length", defval=8)
  64. jawLength = input(title="🐲 Jaw Length", defval=13)
  65. lipsOffset = input(title="🐲 Lips Offset", defval=3)
  66. teethOffset = input(title="🐲 Teeth Offset", defval=5)
  67. jawOffset = input(title="🐲 Jaw Offset", defval=8)
  68. lips = smma(hl2, lipsLength)
  69. teeth = smma(hl2, teethLength)
  70. jaw = smma(hl2, jawLength)
  71.  
  72. // SMA
  73. smaPeriod = input(20, title="SMA Period")
  74. smaValues = sma(close, smaPeriod)
  75.  
  76.  
  77. // Bayesian Theorem Starts
  78. bayesPeriod = input(20, title="Bayesian Lookback Period")
  79.  
  80. // Next candles are breaking Down
  81. probBbUpperUpSeq = close > bbUpper ? 1 : 0
  82. probBbUpperUp = sum(probBbUpperUpSeq, bayesPeriod) / bayesPeriod
  83. probBbUpperDownSeq = close < bbUpper ? 1 : 0
  84. probBbUpperDown = sum(probBbUpperDownSeq, bayesPeriod) / bayesPeriod
  85.  
  86. probUpBbUpper = probBbUpperUp / (probBbUpperUp + probBbUpperDown)
  87.  
  88. probBbBasisUpSeq = close > bbBasis ? 1 : 0
  89. probBbBasisUp = sum(probBbBasisUpSeq, bayesPeriod) / bayesPeriod
  90. probBbBasisDownSeq = close < bbBasis ? 1 : 0
  91. probBbBasisDown = sum(probBbBasisDownSeq, bayesPeriod) / bayesPeriod
  92.  
  93. probUpBbBasis = probBbBasisUp / (probBbBasisUp + probBbBasisDown)
  94.  
  95. probSmaUpSeq = close > smaValues ? 1 : 0
  96. probSmaUp = sum(probSmaUpSeq, bayesPeriod) / bayesPeriod
  97. probSmaDownSeq = close < smaValues ? 1 : 0
  98. probSmaDown = sum(probSmaDownSeq, bayesPeriod) / bayesPeriod
  99.  
  100. probUpSma = probSmaUp / (probSmaUp + probSmaDown)
  101.  
  102. sigmaProbsDown = nz(probUpBbUpper * probUpBbBasis * probUpSma / probUpBbUpper * probUpBbBasis * probUpSma + ((1 - probUpBbUpper) * (1 - probUpBbBasis) * (1 - probUpSma)))
  103.  
  104. // Next candles are breaking Up
  105. probDownBbUpper = probBbUpperDown / (probBbUpperDown + probBbUpperUp)
  106. probDownBbBasis = probBbBasisDown / (probBbBasisDown + probBbBasisUp)
  107. probDownSma = probSmaDown / (probSmaDown + probSmaUp)
  108.  
  109. sigmaProbsUp = nz(probDownBbUpper * probDownBbBasis * probDownSma / probDownBbUpper * probDownBbBasis * probDownSma + ( (1 - probDownBbUpper) * (1 - probDownBbBasis) * (1 - probDownSma) ))
  110.  
  111. showNextCandleDown = input(true, title="Plot Next Candles Breaking Down?")
  112. plot(showNextCandleDown ? rescale(sigmaProbsDown * 100,0,100,0,60) : na, title="Next Candle Breaking Down Probs", style=plot.style_area, transp=60, color=color.red, linewidth=2)
  113.  
  114. showNextCandleUp = input(true, title="Plot Next Candles Breaking Up?")
  115. plot(showNextCandleUp ? rescale(sigmaProbsUp * 100,0,100,0,60) : na, title="Next Candle Breaking Up Probs", style=plot.style_area,transp=60, color=color.green, linewidth=2)
  116.  
  117. probPrime = nz(sigmaProbsDown * sigmaProbsUp / sigmaProbsDown * sigmaProbsUp + ( (1 - sigmaProbsDown) * (1 - sigmaProbsUp) ))
  118.  
  119. showPrime = input(true, title="Plot Prime Probability?")
  120. plot(showPrime ? rescale(probPrime * 100,0,100,0,60) : na, title="Prime Probability", style=plot.style_area,transp=60, color=color.blue, linewidth=2)
  121.  
  122. lowerThreshold = input(15.0, title="Lower Threshold")
  123.  
  124. sideways = probPrime < lowerThreshold / 100 and sigmaProbsUp < lowerThreshold / 100 and sigmaProbsDown < lowerThreshold / 100
  125.  
  126. longUsingProbPrime = probPrime > lowerThreshold / 100 and probPrime[1] == 0
  127. longUsingSigmaProbsUp = sigmaProbsUp < 1 and sigmaProbsUp[1] == 1
  128.  
  129. shortUsingProbPrime = probPrime == 0 and probPrime[1] > lowerThreshold / 100
  130. shortUsingSigmaProbsDown = sigmaProbsDown < 1 and sigmaProbsDown[1] == 1
  131.  
  132. milanIsRed = acAoColorIndex == -1
  133. milanIsGreen = acAoColorIndex == 1
  134. pricesAreMovingAwayUpFromAlligator = close > jaw and open > jaw
  135. pricesAreMovingAwayDownFromAlligator = close < jaw and open < jaw
  136.  
  137. useBWConfirmation = input(false, title="Use Bill Williams indicators for confirmation?")
  138.  
  139. bwConfirmationUp = useBWConfirmation ? milanIsGreen and pricesAreMovingAwayUpFromAlligator : true
  140. bwConfirmationDown = useBWConfirmation ? milanIsRed and pricesAreMovingAwayDownFromAlligator : true
  141.  
  142. longSignal = bwConfirmationUp and (longUsingProbPrime or longUsingSigmaProbsUp)
  143. shortSignal = bwConfirmationDown and (shortUsingProbPrime or shortUsingSigmaProbsDown)
  144.  
  145. barcolor(longSignal ? color.lime : na, title="Long Bars")
  146. barcolor(shortSignal ? color.maroon : na, title="Short Bars")
  147.  
  148. //hzl3 = hline(lowerThreshold, color=#333333, linestyle=hline.style_solid)
  149. //hzl4 = hline(0, color=#333333, linestyle=hline.style_solid)
  150. //fill(hzl3, hzl4, title="Lower Threshold", color=sideways ? color.gray : color.maroon, transp=70)
  151.  
  152. alertcondition(longSignal, title="Long!", message="Bayesian BBSMA - LONG - {{exchange}}:{{ticker}} at {{close}}")
  153. alertcondition(shortSignal, title="Short!", message="Bayesian BBSMA - SHORT - {{exchange}}:{{ticker}} at {{close}}")
  154.  
  155.  
  156. //#################### nQQE
  157.  
  158. src=input(close)
  159. length = input(14,"RSI Length", minval=1, group="═════ nQQE settings ═════")
  160. SSF=input(5, "SF RSI SMoothing Factor", minval=1)
  161. showsignals = input(title="Show Crossing Signals?", type=input.bool, defval=false)
  162. RSII=ema(rsi(src,length),SSF)
  163. TR=abs(RSII-RSII[1])
  164. wwalpha = 1/ length
  165. WWMA = 0.0
  166. WWMA := wwalpha*TR + (1-wwalpha)*nz(WWMA[1])
  167. ATRRSI=0.0
  168. ATRRSI := wwalpha*WWMA + (1-wwalpha)*nz(ATRRSI[1])
  169. QQEF=ema(rsi(src,length),SSF)
  170. QUP=QQEF+ATRRSI*4.236
  171. QDN=QQEF-ATRRSI*4.236
  172. QQES=0.0
  173. QQES:=QUP<nz(QQES[1]) ? QUP : QQEF>nz(QQES[1]) and QQEF[1]<nz(QQES[1]) ? QDN : QDN>nz(QQES[1]) ? QDN : QQEF<nz(QQES[1]) and QQEF[1]>nz(QQES[1]) ? QUP : nz(QQES[1])
  174. Colorh = QQEF-25>35 ? color.lime : QQEF-25<15 ? color.red : #E8E81A
  175. QQF=plot(QQEF-25,"FAST",color=color.maroon,linewidth=2)
  176. plot(QQEF-25,color=Colorh,linewidth=2)
  177. QQS=plot(QQES-25,"SLOW",color=color.yellow, linewidth=2)
  178. hline(35,color=color.gray,linestyle=2)
  179. hline(15,color=color.gray,linestyle=2)
  180. buySignalr = crossover(QQEF, QQES)
  181. plotshape(buySignalr and showsignals ? (QQES-25)*0.995 : na, title="Buy", text="Buy", location=location.absolute, style=shape.labelup, size=size.tiny, color=color.black, textcolor=color.white, transp=50)
  182. sellSignallr = crossunder(QQEF, QQES)
  183. plotshape(sellSignallr and showsignals ? (QQES-25)*1.005 : na, title="Sell", text="Sell", location=location.absolute, style=shape.labeldown, size=size.tiny, color=color.black, textcolor=color.white, transp=50)
  184. alertcondition(cross(QQEF, QQES), title="Cross Alert", message="QQE Crossing Signal!")
  185. alertcondition(crossover(QQEF, QQES), title="Crossover Alarm", message="QQE BUY SIGNAL!")
  186. alertcondition(crossunder(QQEF, QQES), title="Crossunder Alarm", message="QQE SELL SIGNAL!")
  187. alertcondition(crossover(QQEF, 50), title="Cross 0 Up Alert", message="QQE FAST Crossing 0 UP!")
  188. alertcondition(crossunder(QQEF, 50), title="Cross 0 Down Alert", message="QQE FAST Crossing 0 DOWN!")
  189. alertcondition(crossover(QQEF, 60), title="Cross 10 Up Alert", message="QQE Above 10 UPTREND SIGNAL!")
  190. alertcondition(crossunder(QQEF, 40), title="Cross -10 Down Alert", message="QQE Below -10 DOWNTREND SIGNAL!")
  191. alertcondition(crossunder(QQEF, 60) or crossover(QQEF, 40), title="SIDEWAYS", message="QQE Entering Sideways Market!")
  192.  
  193.  
  194. //end of this part
  195.  
  196.  
  197. //----- User inputs ---------------------
  198. Lookback1 = input(title="Lookback Left", type=input.integer, defval=56, minval=1)
  199. Lookback2 = input(title="Lookback Right", type=input.integer, defval=0, minval=0)
  200. VertLR = input(title="Show Vertical Left/Right", type=input.bool, defval=true)
  201. VertHL = input(title="Show Vertical Highest/Lowest", type=input.bool, defval=true)
  202. Count = input(title="Show Counts", type=input.bool, defval=true)
  203. FullCount = input(title="Count All Bars", type=input.bool, defval=false)
  204. Fibs = input(title="Show Fib Retrace Lines", type=input.bool, defval=false)
  205. FibsExtHigh = input(title="Show Fib Ext Highs", type=input.bool, defval=false)
  206. FibsExtLow = input(title="Show Fib Ext Lows", type=input.bool, defval=false)
  207.  
  208.  
  209. //----- Main ---------------------
  210. // Get left and right endpoints. Though user input says "left" and "right", they are interchangeable.
  211. // The larger number is left, smaller number right.
  212. left = max(Lookback1, Lookback2)
  213. right = min(Lookback1, Lookback2)
  214. // Total num bars. Must be > 0 for highest() and lowest() to work. Add 1 to left bar, if needed.
  215. left := left - right == 0 ? left + 1 : left
  216. lengthHL = left - right
  217.  
  218. // Highest price, looking back between the left/right endpoints
  219. highBack = highest(high[right], lengthHL)
  220. // Get # of bars back from present bar (offset).
  221. // NOTE: highestbars() returns a negative integer. Thus, subtract the right endpoint to get
  222. // offset from present (right-edge) bar
  223. highOffset = highestbars(high[right], lengthHL) - right
  224.  
  225. // Lowest price, looking back
  226. lowBack = lowest(low[right], lengthHL)
  227. lowOffset = lowestbars(low[right], lengthHL) - right
  228.  
  229. // Create a series of timestamps per bar. Needed to determine which bars are at the right edge,
  230. // While "n" starts at zero (left-edge bar) and counts up to the right-edge bar, this timestamp
  231. // (or tick) series counts the other way: max value at the left-edge, counting down to zero
  232. // at the right-edge.
  233. // This tick series is only valid while the indicator loads because "timenow" is the timestamp
  234. // of loading and "time" is the timestamp of a bar. The difference between the two timestamps
  235. // shrinks to zero as the righ-edge bar is processed. After loading, "timenow" and "time" are
  236. // the same value. Thus, "tick" always equals zero as new bars appear. But, for this indicator
  237. // this is sufficient behavior...
  238. tick = round((timenow - time) / change(time)) // Each bar is a tick (float) in the timeline
  239. // Make a boolean mask for bars between left and right endpoints
  240. mask = FullCount ? true : tick < left and tick >= right ? true : false
  241. // Determine the value of n at the left endpoint, used for visual counts of bars in mask
  242. nOffset = float(na)
  243. nOffset := FullCount ? 0 : tick == left ? bar_index : nz(nOffset[1])
  244.  
  245. // Note: It would be nice to count between the highest/lowest bars, instead of left/right bars,
  246. // but this isn't possible because highOffset and lowOffset are moving around as the
  247. // indicator loads. Thus, "mask" isn't accurate...
  248.  
  249. //---- Plotting ---------------------
  250. // Horizontal Lines: Highest, Lowest dynamic lines
  251. // Params trackprice and offset make the horizontal line dynamic, adjusting to new highs/lows
  252. plot(highBack, title="Highest", color=color.red, linewidth=2, trackprice=true, offset=-9999)
  253. plot(lowBack, title="Lowest", color=color.green, linewidth=2, trackprice=true, offset=-9999)
  254.  
  255. // Veritcal Lines
  256. // Use barstate to paint/re-paint vertical lines, as new bars come into the data set.
  257. // islast - True for right most bar in data set. Use this to paint vertical bar, then push it back
  258. // in time with the offset parameter.
  259. // isrealtime - False while indicator loads. True for the right most bar, after loading.
  260. // isconfirmed - False while bar is not closed. True when close price appears.
  261. // isrealtime and isconfirmed - While indicator loads, ignore isconfirmed. After loading, isconfirmed
  262. // turns off the vertical line, as the bar closes. The next (new) bar is painted. This keeps
  263. // the vertical bar moving forward, as new bars appear, erasing the old (previous) vertical bar.
  264. VertLRShow = VertLR ? barstate.isrealtime and barstate.isconfirmed ? false :
  265. barstate.islast ? true : false : false
  266. // Can't use plot() with histogram/column because histbase can't accept "series" values
  267. bgcolor(VertLRShow ? color.gray : na, title="Vertical Left", transp=60, offset=-left + 1)
  268. bgcolor(VertLRShow ? color.gray : na, title="Vertical Right", transp=60, offset=-right)
  269. // Show vertical highest/lowest lines?
  270. VertHLShow = VertHL ? barstate.isrealtime and barstate.isconfirmed ? false :
  271. barstate.islast ? true : false : false
  272. bgcolor(VertHLShow ? color.red : na, title="Vertical Highest", transp=60, offset=highOffset)
  273. bgcolor(VertHLShow ? color.green : na, title="Vertical Lowest", transp=60, offset=lowOffset)
  274.  
  275. // Fib levels extension and retracement
  276. priceRange = highBack - lowBack
  277. plot(FibsExtHigh ? lowBack + 3.618 * priceRange : na, title="3.618", color=color.lime, linewidth=2, trackprice=true, offset=-9999)
  278. plot(FibsExtHigh ? lowBack + 2.618 * priceRange : na, title="2.618", color=color.lime, linewidth=2, trackprice=true, offset=-9999)
  279. plot(FibsExtHigh ? lowBack + 1.618 * priceRange : na, title="1.618", color=color.lime, linewidth=2, trackprice=true, offset=-9999)
  280. plot(FibsExtHigh ? lowBack + 1.1 * priceRange : na, color=#88888800, trackprice=true, offset=-9999, editable=false) // invisible line to work around pine plot bug
  281. plot(Fibs ? lowBack + 1.1 * priceRange : na, color=#88888800, trackprice=true, offset=-9999, editable=false) // invisible line to work around pine plot bug
  282. plot(Fibs ? lowBack + 0.786 * priceRange : na, title="0.786", color=color.aqua, linewidth=1, trackprice=true, offset=-9999)
  283. plot(Fibs ? lowBack + 0.618 * priceRange : na, title="0.618", color=color.orange, linewidth=2, trackprice=true, offset=-9999)
  284. plot(Fibs ? lowBack + 0.50 * priceRange : na, title="0.5", color=color.yellow, linewidth=2, trackprice=true, offset=-9999)
  285. plot(Fibs ? lowBack + 0.382 * priceRange : na, title="0.382", color=color.orange, linewidth=2, trackprice=true, offset=-9999)
  286. plot(Fibs ? lowBack + 0.236 * priceRange : na, title="0.236", color=color.aqua, linewidth=1, trackprice=true, offset=-9999)
  287. plot(Fibs ? highBack - 1.1 * priceRange : na, color=#88888800, trackprice=true, offset=-9999, editable=false) // invisible line to work around pine plot bug
  288. plot(FibsExtLow ? highBack - 1.1 * priceRange : na, color=#88888800, trackprice=true, offset=-9999, editable=false) // invisible line to work around pine plot bug
  289. plot(FibsExtLow ? highBack - 1.618 * priceRange : na, title="1.618", color=color.fuchsia, linewidth=2, trackprice=true, offset=-9999)
  290. plot(FibsExtLow ? highBack - 2.618 * priceRange : na, title="2.618", color=color.fuchsia, linewidth=2, trackprice=true, offset=-9999)
  291. plot(FibsExtLow ? highBack - 3.618 * priceRange : na, title="3.618", color=color.fuchsia, linewidth=2, trackprice=true, offset=-9999)
  292.  
  293. // Lookback bar count
  294. countMod = mask ? (bar_index - nOffset) % 10 : na
  295. countInt = mask ? floor((bar_index - nOffset) / 10) % 10 : na
  296. plotshape(Count and countMod != 0 ? true : na, style=shape.circle, text="-", textcolor=color.gray, color=#88888800, location=location.bottom, size=size.auto, editable=false)
  297. plotshape(Count and countMod == 0 and countInt == 0 ? true : na, style=shape.circle, text="0", textcolor=color.gray, color=#88888800, location=location.bottom, size=size.auto, editable=false)
  298. plotshape(Count and countMod == 0 and countInt == 1 ? true : na, style=shape.circle, text="1", textcolor=color.gray, color=#88888800, location=location.bottom, size=size.auto, editable=false)
  299. plotshape(Count and countMod == 0 and countInt == 2 ? true : na, style=shape.circle, text="2", textcolor=color.gray, color=#88888800, location=location.bottom, size=size.auto, editable=false)
  300. plotshape(Count and countMod == 0 and countInt == 3 ? true : na, style=shape.circle, text="3", textcolor=color.gray, color=#88888800, location=location.bottom, size=size.auto, editable=false)
  301. plotshape(Count and countMod == 0 and countInt == 4 ? true : na, style=shape.circle, text="4", textcolor=color.gray, color=#88888800, location=location.bottom, size=size.auto, editable=false)
  302. plotshape(Count and countMod == 0 and countInt == 5 ? true : na, style=shape.circle, text="5", textcolor=color.gray, color=#88888800, location=location.bottom, size=size.auto, editable=false)
  303. plotshape(Count and countMod == 0 and countInt == 6 ? true : na, style=shape.circle, text="6", textcolor=color.gray, color=#88888800, location=location.bottom, size=size.auto, editable=false)
  304. plotshape(Count and countMod == 0 and countInt == 7 ? true : na, style=shape.circle, text="7", textcolor=color.gray, color=#88888800, location=location.bottom, size=size.auto, editable=false)
  305. plotshape(Count and countMod == 0 and countInt == 8 ? true : na, style=shape.circle, text="8", textcolor=color.gray, color=#88888800, location=location.bottom, size=size.auto, editable=false)
  306. plotshape(Count and countMod == 0 and countInt == 9 ? true : na, style=shape.circle, text="9", textcolor=color.gray, color=#88888800, location=location.bottom, size=size.auto, editable=false)
  307.  
  308.  
  309. //end of this part
Advertisement
Add Comment
Please, Sign In to add comment