Advertisement
Techn0id

Trading view

Dec 26th, 2024
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 40.41 KB | Money | 0 0
  1. //@version=5
  2. indicator(shorttitle="Ultimate", title="Ultimate Buy and Sell Indicator", overlay=true, timeframe="", timeframe_gaps=true)
  3.  
  4. ///////////////////////////
  5. /// User Input Settings ///
  6. ///////////////////////////
  7.  
  8. // Global source for price data
  9. group1 = "Use Ultimate RSI to visualize settings"
  10. src = input(close, title="Data Source for Price", group=group1)
  11.  
  12. // Show/Hide All of the specified category
  13. group2 = "Show/Hide ALL"
  14. showAllMA = input(true, title="Moving Averages", group=group2, tooltip = "Moving average options at bottom of menu")
  15. showBasisPlot = input(true, title="Bollinger Band Basis", group=group2, tooltip = "Bollinger Band basis line")
  16. showWatchSignals = input(true, title="All Watch Signals", group=group2, tooltip = "Watch signals are prerequisite Bollinger band events used for generating buy/sell signals. Beware of watch signals when Bollinger Bands are tighter than usual (more transparent), periods of low volatility can quickly swing in the opposite direction.")
  17. showBollingerBands = input(true, title="Bollinger Bands", group=group2, tooltip = "Bollinger bands are set to have two layers with standard deviations of slightly less than 2 and 3 (Pros and cons to this). They change colors based on RSI trends (RSI itself or the RSI basis) (Red is downtrend in momentum, green is uptrend in momentum). They also become brighter with higher relative volatility and more transparent with low volatility. The calculation of relative volatility uses a lookback period to determine what the largest spread was over a period of time and then splits it up into 100 segments, also allowing for a threshold setting to filter signals (Band Width Filter) based on the tightness of the bands to potentially help eliminate early signals.")
  18. showRSICandleColors = input(true, title="RSI Colored Candles", group=group2, tooltip = "Be sure to turn off candle colors in main settings for this to work. This creates candles with colors based on zones of RSI values with red being downward momentum and green being upward momentum (Opposite of the Bollinger Bands for visibility.) Candles are also colored Orange for BUY and Fuschia for SELL. If RSI is over 80 or under 20 the candles turn white indicating a definite reversal is coming up very soon.")
  19. showDPOCandleColors = input(false, title="DPO Colored Candles", group=group2, tooltip = "Be sure to turn off candle colors in main settings for this to work. This will color the candles based on the DPO trend.", inline="DPO")
  20. fadeDPOCandles = input(false, title="DPO Candle Fading", group=group2, tooltip = "This will turn on or off the candles becoming less transparent with width of the Price Bollinger Bands.", inline="DPO")
  21. showSignals = input(true, title="Show Buy/Sell Signals", group=group2)
  22. showCircles = input(true, title="Show Buy/Sell Circles", group=group2)
  23. showSignalBackground = input(true, title="Buy/Sell Signal Warning Background", group=group2, tooltip = "Colors the background behind the bar before a buy/sell signal is officially set to act as a warning of a potential trade.")
  24. showBSBackground = input(false, title="Bought/Sold State Background", group=group2, tooltip="Colors the background to represent a previous bought or sold state (always the first in the series). The state stays in effect until the next opposite signal. This can help keep you in a trade or inform you of the direction of the trade if you come in late.")
  25.  
  26. // Watch Signal settings
  27. group3 = "Watch Signals"
  28. requireWatchSignals = input(true, title="Require the use of Watch Signals", group=group3, tooltip = "Watch signals are required within the lookback period before any buy or sell signal events are considered valid")
  29. watchSignalLookback = input.int(35, title="# of bars back to use Watch Signals", group=group3, step=1, tooltip="How many bars back to consider a Watch signal valid. Longer values tend to create more inaccurate B/S signals. The reasoning is that as volatility (range of price fluctuations) stabilizes, the bollinger bands tighten, and when price makes a sudden move, it generates a watch signal and then buy or sell signal, fails and then reverses suddenly. We don't want to count these down the road.")
  30. useSignalWaiting = input(false, title="Force a signal wait period?", group=group3, tooltip="Force a gap between signals of any type for those doing shorter-term scalping with shorter settings in place")
  31. signalWaitPeriod = input.int(5, title="# of bars before signals are allowed ", group=group3, step=1, tooltip="How many bars after a buy or sell signal to wait before allowing all watch Signals as well as buy and sell signals to be generated.")
  32.  
  33. // RSI Settings
  34. group4 = "RSI Settings"
  35. rsiSource = input(close, title="RSI Data Source", group=group4)
  36. rsiLength = input.int(32, title="RSI Length", minval=1, group=group4, tooltip="RSI is not visible, but is used for trade signals. RSI crossing various lines generates signals.")
  37. rsiMaType = input.string("RMA", title="Calculate RSI with", options=["SMA", "EMA", "WMA", "HMA", "VWMA", "RMA"], group=group4, tooltip="The moving average used to calculate the RSI. Will affect signals.")
  38. rsiMaType1 = input.string("SMA", "Rsi Basis Moving Average Type", options=["SMA", "EMA", "WMA", "HMA", "VWMA", "RMA"], group=group4, tooltip="The moving average used to calculate the RSI Bollinger Bands and basis lines. Will affect signals.")
  39. rsiBasisLength = input.int(32, title="RSI Basis Length", minval=1, group=group4)
  40. rsiMultiplier = input.float(2, minval=1, maxval=3, step=0.1, title="RSI Band Multiplier", group=group4, tooltip="This is the standard deviation, and affects Watch signals, which affect Buy and Sell signals.")
  41. useWmaSmoothing = input(true, title="Use Smoothing", group=group4, tooltip = "Uses a Weighted Moving Average to smoothe the RSI")
  42. wmaLength = input.int(5, title="Smoothing Length", minval=1, group=group4)
  43. //lookback = input.int(100, title="RSI Volatility Lookback", minval=50, step=50, group=group4)
  44. //threshold = input.float(0.25, title="RSI Volatility Threshold", minval=0.01, maxval=5, step=0.1, group=group4)
  45. //smoothingFactor = input.float(0.2, title="RSI Volatility Based Smoothing", minval=0.01, maxval=5, step=0.1, group=group4)
  46. useRsiWatchSignals = input(true, title="RSI Watch Signals", group=group4, tooltip = "If the RSI Crosses over the lower Bollinger Band it creates a buy watch signal. If it crosses under the upper band it creates a sell watch signal.")
  47. //useThresholdCrosses = input(true, title="Use RSI Volatility Threshold for Watch Signals", group=group4, tooltip = "If the RSI Volatility drops lower than the threshold it creates a buy watch signal, if it crosses over, it creates a sell watch signal.")
  48. //
  49.  
  50. // Bollinger Bands Settings
  51. group5 = "Price Bollinger Bands Settings"
  52. priceBasisLength = input.int(20, title="Price BBand Basis Length", group=group5, tooltip="Sets the length to calculate the Price Bollinger Bands and corresponding basis line.")
  53. priceMaType = input.string("SMA", title="Moving Average Type", options=["SMA", "EMA", "WMA", "HMA", "VWMA", "RMA"], group=group5, tooltip="The moving average used to calculate the Price BBands. Changes the shape and affects creation of watch signals (and therefore also B/S signals)")
  54. priceInnerMultiplier = input.float(2, minval=1, maxval=4, step=0.1, title="Price Inner BB Multiplier", group=group5, tooltip="This is the standard deviation for the inner Price Bollinger Band which does not affect signals.")
  55. priceOuterMultiplier = input.float(2.4, minval=2, maxval=6, step=0.1, title="Price Outer BB Multiplier", group=group5, tooltip="This is the standard deviation for the outer Price Bollinger Band and does affect watch signals, which affect Buy and Sell signals.")
  56. upColor = input.color(color.green, title="Bullish color", group=group5)
  57. downColor = input.color(color.red, title="Bearish color", group=group5)
  58. basisColor = input.color(color.orange, title="Basis color", group=group5)
  59. transparencyFactor = input.float(0.8, step=0.1, title="Transparency Factor", group=group5, tooltip="Adjust this to scale how transparent the bands will be based on the volatility over the past 500 bars")
  60. usePriceBandWatchSignals = input(true, title="Bollinger Band Watch Signals", group=group5, tooltip= "If price crosses the Bollinger Bands this creates a watch signal")
  61.  
  62. // Moving Average Settings
  63. group6 = "Moving Average Settings"
  64. maType = input.string("WMA", title="Moving Average Type for Chart", options=["SMA", "EMA", "WMA", "HMA", "VWMA", "RMA"], group=group6, tooltip="Select the type of moving average to be displayed on the chart.")
  65. showMA5 = input(false, inline="ma5", title="Show 5 MA", group=group6, tooltip="Toggle to show or hide the 5-period moving average on the chart.")
  66. showMA10 = input(false, inline="ma10", title="Show 10 MA", group=group6, tooltip="Toggle to show or hide the 10-period moving average on the chart.")
  67. showMA20 = input(false, inline="ma20", title="Show 20 MA", group=group6, tooltip="Toggle to show or hide the 20-period moving average on the chart.")
  68. showMA50 = input(true, inline="ma50", title="Show 50 MA", group=group6, tooltip="Toggle to show or hide the 50-period moving average on the chart.")
  69. showMA100 = input(true, inline="ma100", title="Show 100 MA", group=group6, tooltip="Toggle to show or hide the 100-period moving average on the chart.")
  70. showMA200 = input(true, inline="ma200", title="Show 200 MA", group=group6, tooltip="Toggle to show or hide the 200-period moving average on the chart.")
  71. showCustomMa = input(false, inline="customMa", title="Show Custom MA", group=group6, tooltip="A user selectable moving average")
  72. customMa = input.int(300, title="Custom Moving Average Length", group=group6)
  73. ma5Color = input.color(color.white, inline="ma5", title="Basis color", group=group6)
  74. ma10Color = input.color(color.yellow, inline="ma10", title="Basis color", group=group6)
  75. ma20Color = input.color(color.green, inline="ma20", title="Basis color", group=group6)
  76. ma50Color = input.color(color.red, inline="ma50", title="Basis color", group=group6)
  77. ma100Color = input.color(color.purple, inline="ma100", title="Basis color", group=group6)
  78. ma200Color = input.color(color.blue, inline="ma200", title="Basis color", group=group6)
  79. customMaColor = input.color(color.gray, inline="customMa", title="", group=group6)
  80.  
  81. // Buy/Sell Signal Event Options
  82. group7 = "Buy/Sell Signal Event Options"
  83. useRsiSignals = input(true, title="RSI crossing Basis", group=group7, tooltip="Uses RSI crossing RSI basis.")
  84. usePriceSignals = input(true, title="Price crossing BBand basis", group=group7, tooltip="Signals from price crossing Price Bollinger Band Basis")
  85. useMacdSignals = input(true, title="MACD Signals", group=group7, tooltip="Signals from MACD crossovers.")
  86. use75Signals = input(true, title="RSI crossing under 75", group=group7, tooltip="Sell signals from crossing under RSI 75")
  87. use50Signals = input(true, title="RSI crossing over/under 50", group=group7, tooltip="Buy and sell signals from crossing over and under RSI 50")
  88. use25Signals = input(true, title="RSI crossing over 25", group=group7, tooltip="Buy signals from crossing over RSI 25")
  89. useRsiMa = input(true, title="Rsi Crossing a Moving Average", group=group7, tooltip="Signals based on RSI crossing a custom length moving average rather than the Basis of the Bollinger Bands. This allows you to change the Bollinger Band moving average type used in the calculation (which will change the shape of the bands) and cross a different moving average without changing watch signal generation. To see these effects, use the Ultimate RSI indicator.")
  90. rsiMaLength = input.int(16, title="Length of additional RSI MA", inline="rsiMa", minval=1, group=group7, tooltip="Adds another moving average to the RSI that will not affect the Bollinger Bands. This can be used for signals without compromising the watch signals if using a WMA or other moving averages types for the Bands.")
  91. rsiMaType2 = input.string("WMA", title="Moving Average Type", inline="rsiMa", options=["SMA", "EMA", "WMA", "HMA", "VWMA", "RMA"], group=group7)
  92.  
  93. // RSI/Price Divergence
  94. group8 = "RSI/Price Divergence"
  95. showDivergence = input(true, title="Show Divergence", group=group8, tooltip="Enable or disable the RSI/Price Divergence feature.")
  96. lookbackRight = input.int(5, title="Lookback Right", minval=1, group=group8, tooltip="Number of bars to look back to the right for RSI/Price Divergence.")
  97. lookbackLeft = input.int(5, title="Lookback Left", minval=1, group=group8, tooltip="Number of bars to look back to the left for RSI/Price Divergence.")
  98. rangeUpper = input.int(60, title="Range Upper", minval=1, group=group8, tooltip="Upper threshold for RSI/Price Divergence range.")
  99. rangeLower = input.int(5, title="Range Lower", minval=1, group=group8, tooltip="Lower threshold for RSI/Price Divergence range.")
  100. bearColor = input.color(color.red, title="Bearish Divergence Color", group=group8)
  101. bullColor = input.color(color.green, title="Bullish DivergenceColor", group=group8)
  102. textColor = input.color(color.white, title="Text Color", group=group8)
  103.  
  104. // Smoothed and Averaged DPO (Detrended Price Oscillator) Ribbon
  105. group9 = "DPO Ribbon Settings"
  106. smoothDpoLength = input.int(5, minval=1, title="Smoothing length for DPO", group=group9)
  107. checkPeriod = input.int(5, minval=1, title="Bars back for DPO change", group=group9, tooltip="How many bars back to check for a change in DPO value to switch from bullish to bearish.")
  108. dpoAdjustment = input.int(0, minval=0, step=5, title="DPO value adjustment", group=group9, tooltip="This will add 1 to each of the values in the DPO ribbon. The DPO ribbon consists of 10 DPO values starting with 5 for the lowest, and going up 10 times in increments of 5. This means the ribbon defaults to 5, 10, 15, 20, 25, 30, 35, 40, 45 and 50. Increasing the value will then shift each of the values up by 1 to 6, 11, etc. ")
  109. useDpoFilter = input(true, title="Use DPO to filter buy/sell signals", group=group9, tooltip="Requires DPO to be bullish or bearish for buy or sell signals to be valid. Settings are visible in the upper Bollinger Band of Ultimate RSI indicator.")
  110.  
  111. // Rate of Change
  112. group10 = "Rate of Change"
  113. rocLength = input.int(10, title="Length for Rate of Change of price", group=group10, tooltip="If ROC is over 0 it's bullish, bearish if under. The lower Bollinger band will be colored based on this.")
  114. useRocFilter = input(true, title="Use ROC to filter buy/sell signals", group=group10)
  115.  
  116. // Alerts
  117. group11 = "Alerts"
  118. enableAdvancedAlerts = input(true, title="Advance alerts one candle", group=group11, tooltip="This will use the warning background as the signal for buy/sell alerts. On higher timeframes, this could lead to alerts for signals that end up failing and price could reverse. On sub-1minute timeframes this should be more reliable.")
  119.  
  120.  
  121. ////////////////////////////////////////////////////////
  122. // Rate of Change (ROC) (Colors lower Bollinger Band) //
  123. ////////////////////////////////////////////////////////
  124.  
  125. previous = ta.valuewhen(true, close, rocLength)
  126. roc = ((close - previous) / previous) * 100
  127. // Determine if ROC is bullish or bearish
  128. rocBullish = (roc > 0)
  129. rocBearish = (roc < 0)
  130. // Color ROC
  131. rocColor = rocBullish ? upColor : downColor
  132.  
  133.  
  134. ///////////////////////////////////////////////
  135. /// DPO Calculations (NOT VISIBLE ON CHART) ///
  136. ///////////////////////////////////////////////
  137.  
  138. // DPO ribbon moving average lengths
  139. period1 = 5 + dpoAdjustment
  140. period2 = 10 + dpoAdjustment
  141. period3 = 15 + dpoAdjustment
  142. period4 = 20 + dpoAdjustment
  143. period5 = 25 + dpoAdjustment
  144. period6 = 30 + dpoAdjustment
  145. period7 = 35 + dpoAdjustment
  146. period8 = 40 + dpoAdjustment
  147. period9 = 45 + dpoAdjustment
  148. period10 = 50 + dpoAdjustment
  149.  
  150. // Calculate individual barsback values for each period
  151. barsback1 = period1 / 2 + 1
  152. barsback2 = period2 / 2 + 1
  153. barsback3 = period3 / 2 + 1
  154. barsback4 = period4 / 2 + 1
  155. barsback5 = period5 / 2 + 1
  156. barsback6 = period6 / 2 + 1
  157. barsback7 = period7 / 2 + 1
  158. barsback8 = period8 / 2 + 1
  159. barsback9 = period9 / 2 + 1
  160. barsback10 = period10 / 2 + 1
  161.  
  162. // Calculations for DPOs
  163. // DPO ribbon moving average lengths
  164. dpoMa1 = ta.wma(close, period1)
  165. dpoMa2 = ta.wma(close, period2)
  166. dpoMa3 = ta.wma(close, period3)
  167. dpoMa4 = ta.wma(close, period4)
  168. dpoMa5 = ta.wma(close, period5)
  169. dpoMa6 = ta.wma(close, period6)
  170. dpoMa7 = ta.wma(close, period7)
  171. dpoMa8 = ta.wma(close, period8)
  172. dpoMa9 = ta.wma(close, period9)
  173. dpoMa10 = ta.wma(close, period10)
  174.  
  175. // DPO calculations with individual barsback values
  176. dpo1 = close - dpoMa1[barsback1]
  177. dpo2 = close - dpoMa2[barsback2]
  178. dpo3 = close - dpoMa3[barsback3]
  179. dpo4 = close - dpoMa4[barsback4]
  180. dpo5 = close - dpoMa5[barsback5]
  181. dpo6 = close - dpoMa6[barsback6]
  182. dpo7 = close - dpoMa7[barsback7]
  183. dpo8 = close - dpoMa8[barsback8]
  184. dpo9 = close - dpoMa9[barsback9]
  185. dpo10 = close - dpoMa10[barsback10]
  186.  
  187. // Calculate the average of the ten DPOs
  188. averageDpo = (dpo1 + dpo2 + dpo3 + dpo4 + dpo5 + dpo6 +dpo7 + dpo8 + dpo9 + dpo10) / 10
  189.  
  190. // Apply smoothing moving average
  191. smoothedAverageDpo = ta.wma(averageDpo, smoothDpoLength)
  192.  
  193. // Determine color
  194. dpoColor = smoothedAverageDpo > smoothedAverageDpo[checkPeriod] ? upColor : downColor
  195.  
  196. // Determine if bullish or bearish for signals and coloring the upper Bollinger Band
  197. dpoBullish = dpoColor == upColor
  198. dpoBearish = dpoColor == downColor
  199.  
  200. ////////////////////////////////////////////////
  201. /// MACD Calculations (NOT VISIBLE ON CHART) ///
  202. ////////////////////////////////////////////////
  203.  
  204.  
  205. // Standard MACD constants
  206. const int MACD_FAST_LENGTH = 12
  207. const int MACD_SLOW_LENGTH = 26
  208. const int MACD_SIGNAL_LENGTH = 9
  209.  
  210. // MACD Calculations with standard settings
  211. macd = ta.ema(src, 12) - ta.ema(src, 26)
  212. signal = ta.ema(macd, 9)
  213.  
  214.  
  215. ///////////////////////////////////////////////////////////////////
  216. /// Calculate RSI with Bollinger Bands [Not visible on chart] ///
  217. ///////////////////////////////////////////////////////////////////
  218.  
  219.  
  220. // RSI calculations using the selected moving average types
  221. up = switch rsiMaType
  222. "SMA" => ta.sma(math.max(ta.change(rsiSource), 0), rsiLength)
  223. "EMA" => ta.ema(math.max(ta.change(rsiSource), 0), rsiLength)
  224. "WMA" => ta.wma(math.max(ta.change(rsiSource), 0), rsiLength)
  225. "HMA" => ta.hma(math.max(ta.change(rsiSource), 0), rsiLength)
  226. "VWMA" => ta.vwma(math.max(ta.change(rsiSource), 0), rsiLength)
  227. "RMA" => ta.rma(math.max(ta.change(rsiSource), 0), rsiLength)
  228. down = switch rsiMaType
  229. "SMA" => ta.sma(-math.min(ta.change(rsiSource), 0), rsiLength)
  230. "EMA" => ta.ema(-math.min(ta.change(rsiSource), 0), rsiLength)
  231. "WMA" => ta.wma(-math.min(ta.change(rsiSource), 0), rsiLength)
  232. "HMA" => ta.hma(-math.min(ta.change(rsiSource), 0), rsiLength)
  233. "VWMA" => ta.vwma(-math.min(ta.change(rsiSource), 0), rsiLength)
  234. "RMA" => ta.rma(-math.min(ta.change(rsiSource), 0), rsiLength)
  235. rsi = down == 0 ? 100 : up == 0 ? 0 : 100 - (100 / (1 + up / down))
  236.  
  237. // Function for custom Moving Averages
  238. rsiMa(source, length, type) =>
  239. switch type
  240. "SMA" => ta.sma(source, length)
  241. "EMA" => ta.ema(source, length)
  242. "WMA" => ta.wma(source, length)
  243. "HMA" => ta.hma(source, length)
  244. "VWMA" => ta.vwma(source, length)
  245. "RMA" => ta.rma(source, length)
  246.  
  247. rsiBasis = rsiMa(rsi, rsiBasisLength, rsiMaType1)
  248. rsiDeviation = ta.stdev(rsi, rsiBasisLength)
  249.  
  250. // Inner RSI Bands
  251. upperRsi = rsiBasis + rsiMultiplier * rsiDeviation
  252. lowerRsi = rsiBasis - rsiMultiplier * rsiDeviation
  253.  
  254. // Calculate distance between upper and lower RSI bands
  255. //distance = upperRsi - lowerRsi
  256.  
  257. // Calculate the highest distance over the specified lookback period
  258. //highest = ta.highest(distance, lookback)
  259.  
  260. // Determine the volatility threshold
  261. //volatilityThreshold = highest * threshold
  262.  
  263. // Calculate RMAs of RSI with different lengths
  264. //smoothingLength = math.round(rsiBasisLength * smoothingFactor)
  265. //smoothed = ta.rma(rsi, smoothingLength)
  266.  
  267. // Calculate the WMA of RSI and switch to smoothed RSI if smoothing is enabled
  268. smoothedRsi = useWmaSmoothing ? ta.wma(rsi, wmaLength) : rsi
  269. //smoothedRsi = not useAdjustedRsi and useWmaSmoothing ? ta.wma(rsi, wmaLength) : rsi
  270.  
  271. // Select the appropriate RSI value for each bar based on current volatility
  272. //adjustedRsi = useAdjustedRsi and distance < volatilityThreshold ? smoothed : rsi
  273.  
  274. // Create an additional RSI moving average
  275. rsiMa = rsiMa(rsi, rsiMaLength, rsiMaType2)
  276.  
  277.  
  278. ////////////////
  279. // Divergence //
  280. ////////////////
  281.  
  282.  
  283. noneColor = color.new(color.white, 100)
  284. plFound = na(ta.pivotlow(smoothedRsi, lookbackLeft, lookbackRight)) ? false : true
  285. phFound = na(ta.pivothigh(smoothedRsi, lookbackLeft, lookbackRight)) ? false : true
  286. _inRange(cond) =>
  287. bars = ta.barssince(cond == true)
  288. rangeLower <= bars and bars <= rangeUpper
  289. // Regular Bullish
  290. // smoothedRsi: Higher Low
  291. rsiHL = smoothedRsi[lookbackRight] > ta.valuewhen(plFound, smoothedRsi[lookbackRight], 1) and _inRange(plFound[1])
  292. // Price: Lower Low
  293. priceLL = low[lookbackRight] < ta.valuewhen(plFound, low[lookbackRight], 1)
  294. bullCondAlert = priceLL and rsiHL and plFound
  295. bullCond = showDivergence and bullCondAlert
  296. plot(plFound ? close[lookbackRight] : na, offset=-lookbackRight, title="Bullish", linewidth=2, color=(bullCond ? bullColor : noneColor))
  297. // Regular Bearish
  298. // smoothedRsi: Lower High
  299. rsiLH = smoothedRsi[lookbackRight] < ta.valuewhen(phFound, smoothedRsi[lookbackRight], 1) and _inRange(phFound[1])
  300. // Price: Higher High
  301. priceHH = high[lookbackRight] > ta.valuewhen(phFound, high[lookbackRight], 1)
  302. bearCondAlert = priceHH and rsiLH and phFound
  303. bearCond = showDivergence and bearCondAlert
  304. plot(phFound ? close[lookbackRight] : na, offset=-lookbackRight, title="Bearish", linewidth=2, color=(bearCond ? bearColor : noneColor))
  305.  
  306. // Bullish and Bearish Divergence Alerts
  307. alertcondition(bullCondAlert, title='Bullish Divergence', message='Bullish Divergence detected')
  308. alertcondition(bearCondAlert, title='Bearish Divergence', message='Bearish Divergence detected')
  309.  
  310.  
  311. /////////////////////////////////////////////////
  312. /// Calculate 2 Bollinger Bands for the Price ///
  313. /////////////////////////////////////////////////
  314.  
  315.  
  316. // Function choosing Price moving average type
  317. priceMa(src, Length, type) =>
  318. switch type
  319. "SMA" => ta.sma(src, Length)
  320. "EMA" => ta.ema(src, Length)
  321. "WMA" => ta.wma(src, Length)
  322. "HMA" => ta.hma(src, Length)
  323. "VWMA" => ta.vwma(src, Length)
  324. "RMA" => ta.rma(src, Length)
  325. // Function to calculate Bollinger Bands with flexibility to change MA type
  326. calculateBollingerBands(src, priceBasisLength, priceInnerMultiplier, priceOuterMultiplier, priceMaType) =>
  327. priceBasis = priceMa(src, priceBasisLength, priceMaType)
  328. priceInnerDeviation = priceInnerMultiplier * ta.stdev(src, priceBasisLength)
  329. priceOuterDeviation = priceOuterMultiplier * ta.stdev(src, priceBasisLength)
  330. [priceBasis, priceBasis + priceInnerDeviation, priceBasis - priceInnerDeviation, priceBasis + priceOuterDeviation, priceBasis - priceOuterDeviation]
  331. // Using calculateBollingerBands function for the basis lines
  332. [priceBasis, upperPriceInner, lowerPriceInner, upperPriceOuter, lowerPriceOuter] = calculateBollingerBands(src, priceBasisLength, priceInnerMultiplier, priceOuterMultiplier, priceMaType)
  333.  
  334.  
  335. ////////////////////////////////////////////////////////////////////////////////
  336. /// Trend Analysis and Visualization: ///
  337. /// This section sets Bollinger Band colors based on the DPO ribbon and ROC. ///
  338. /// It also controls the transparency of the bands based on volatility. ///
  339. ////////////////////////////////////////////////////////////////////////////////
  340.  
  341.  
  342. // How many bars back to determine the largest historical width of the bollinger bands to control transparency based on the current width
  343. bbLookbackPeriod = 500
  344. // Calculate the distance between the Inner Bands of the Bollinger Bands to set transparency levels
  345. price_band_distance = upperPriceInner - lowerPriceInner
  346. price_max_distance = ta.highest(price_band_distance, bbLookbackPeriod)
  347. transparency = 100 - (100 * (price_band_distance / price_max_distance)) / transparencyFactor
  348. // Initialize and set fill color for the upper set of bands based on DPO Ribbon
  349. var color upperBandColor = na
  350. upperBandColor := showBollingerBands ? (dpoBullish ? color.new(upColor, transparency) : color.new(downColor, transparency)) : na
  351. // Initialize and set fill color for the lower set of bands based on Rate of Change
  352. var color lowerBandColor = na
  353. lowerBandColor := showBollingerBands ? (rocBullish ? color.new(upColor, transparency) : color.new(downColor, transparency)) : na
  354. // Plot invisible lines for the Upper and Lower Bollinger Bands for use in fill function
  355. U1 = plot(upperPriceInner, color=na)
  356. L1 = plot(lowerPriceInner, color=na)
  357. U2 = plot(upperPriceOuter, color=na)
  358. L2 = plot(lowerPriceOuter, color=na)
  359. // Fill the region between the Upper Bollinger Bands and Lower Bollinger Bands based on trend conditions
  360. fill(U1, U2, title="Upper Bollinger Bands DPO Based Fill", color=upperBandColor)
  361. fill(L1, L2, title="Lower Bollinger Bands ROC Based Fill", color=lowerBandColor)
  362. // Plot the Basis line, but only if the user has enabled 'showBollingerBands' and 'showBasisPlot'
  363. plot(showBasisPlot ? priceBasis : na, title="Price Basis", color=basisColor)
  364.  
  365.  
  366. ///////////////////////////////
  367. /// Popular moving averages ///
  368. ///////////////////////////////
  369.  
  370.  
  371. // Calculate Moving Averages based on user-selected type
  372. calculateMA(src, length, type) =>
  373. switch(type)
  374. "SMA" => ta.sma(src, length)
  375. "EMA" => ta.ema(src, length)
  376. "WMA" => ta.wma(src, length)
  377. "HMA" => ta.hma(src, length)
  378. "VWMA" => ta.vwma(src, length)
  379. "RMA" => ta.rma(src, length)
  380. // Calculate moving averages based on the selected type
  381. ma5 = calculateMA(close, 5, maType)
  382. ma10 = calculateMA(close, 10, maType)
  383. ma20 = calculateMA(close, 20, maType)
  384. ma50 = calculateMA(close, 50, maType)
  385. ma100 = calculateMA(close, 100, maType)
  386. ma200 = calculateMA(close, 200, maType)
  387. custom = calculateMA(close, customMa, maType)
  388.  
  389. // Plot moving averages based on user-selected type
  390. plot(showAllMA and showMA5 ? ma5 : na, "5 MA", color=color.white)
  391. plot(showAllMA and showMA10 ? ma10 : na, "10 MA", color=color.yellow)
  392. plot(showAllMA and showMA20 ? ma20 : na, "20 MA", color=color.green)
  393. plot(showAllMA and showMA50 ? ma50 : na, "50 MA", color=color.red)
  394. plot(showAllMA and showMA100 ? ma100 : na, "100 MA", color=color.purple)
  395. plot(showAllMA and showMA200 ? ma200 : na, "200 MA", color=color.blue)
  396. plot(showAllMA and showCustomMa ? custom : na, "Custom", color=customMaColor)
  397.  
  398.  
  399. /////////////////////////
  400. // TRADE SIGNAL EVENTS //
  401. /////////////////////////
  402.  
  403.  
  404. // Price band crosses
  405. priceCrossOverInner = ta.crossover(src, lowerPriceInner) // Price over outer band
  406. priceCrossUnderInner = ta.crossunder(src, upperPriceInner) // Price under outer band
  407. //RSI Band crosses
  408. rsiCrossOverLower = ta.crossover(smoothedRsi, lowerRsi) // RSI over lower band
  409. rsiCrossUnderUpper = ta.crossunder(smoothedRsi, upperRsi) // RSI under upper band
  410. // RSI Cross Basis
  411. rsiCrossOverBasis = ta.crossover(smoothedRsi, rsiBasis)
  412. rsiCrossUnderBasis = ta.crossunder(smoothedRsi, rsiBasis)
  413. // Adjusted RSI Cross basis
  414. //adjustedRsiCrossOverBasis = ta.crossover(adjustedRsi, rsiBasis)
  415. //adjustedRsiCrossUnderBasis = ta.crossunder(adjustedRsi, rsiBasis)
  416. // Adjusted Rsi Cross Additional Moving Average
  417. //adjustedRsiCrossOverMa = ta.crossover(adjustedRsi, rsiMa)
  418. //adjustedRsiCrossUnderMa =ta.crossunder(adjustedRsi, rsiMa)
  419. // RSI Cross Additional Moving Average
  420. rsiCrossOverMa = ta.crossover(smoothedRsi, rsiMa)
  421. rsiCrossUnderMa = ta.crossunder(smoothedRsi, rsiMa)
  422. // RSI Value Crosses
  423. rsiCrossUnder75 = ta.crossunder(smoothedRsi, 75) // RSI crossunder 75
  424. rsiCrossUnder70 = ta.crossunder(smoothedRsi, 70) // RSI crossunder 70
  425. rsiCrossUnder50 = ta.crossunder(smoothedRsi, 50) // RSI crossover 50
  426. rsiCrossOver50 = ta.crossover(smoothedRsi, 50) // RSI crossover 50
  427. rsiCrossOver30 = ta.crossover(smoothedRsi, 30) // RSI crossover 30
  428. rsiCrossOver25 = ta.crossover(smoothedRsi, 25) // RSI crossover 25
  429. // Price crossing Bollinger Band Basis
  430. priceCrossOverBasis = ta.crossover(close, priceBasis)
  431. priceCrossUnderBasis = ta.crossunder(close, priceBasis)
  432. // MACD crosses
  433. macdBuy = ta.crossover(macd, signal)
  434. macdSell = ta.crossunder(macd, signal)
  435.  
  436.  
  437. ///////////////////////
  438. // DPO Ribbon Filter //
  439. ///////////////////////
  440.  
  441.  
  442. dpoAllowBuy = ((not useDpoFilter) or (useDpoFilter and dpoBullish))
  443. dpoAllowSell = ((not useDpoFilter) or (useDpoFilter and dpoBearish))
  444.  
  445.  
  446. ////////////////
  447. // ROC Filter //
  448. ////////////////
  449.  
  450.  
  451. rocAllowBuy = ((not useRocFilter) or (useRocFilter and rocBullish))
  452. rocAllowSell = ((not useRocFilter) or (useRocFilter and rocBearish))
  453.  
  454.  
  455. /////////////////
  456. // Trade Logic //
  457. /////////////////
  458.  
  459.  
  460. // Initialized as true to allow for forced alternation of signals, which are dependant on a bought or sold state from the beginning.
  461. var bool bought = false
  462. var bool sold = false
  463. var bool signalsBlocked = false
  464. var int[] buyWatchArray = array.new_int(na)
  465. var int[] sellWatchArray = array.new_int(na)
  466. var int lastSignalBarIndex = na
  467. bool plotBuy = false
  468. bool plotSell = false
  469. bool plotBuyBG = false
  470. bool plotSellBG = false
  471.  
  472.  
  473. ///////////////////
  474. // Watch Signals //
  475. ///////////////////
  476.  
  477.  
  478. // Green squares
  479. buyWatch1 = (usePriceBandWatchSignals) and (priceCrossOverInner and not rsiCrossOverLower) and (barstate.isconfirmed) and (not signalsBlocked)
  480. buyWatch2 = (useRsiWatchSignals) and (rsiCrossOverLower and not priceCrossOverInner) and (barstate.isconfirmed) and (not signalsBlocked)
  481. buyWatch3 = (usePriceBandWatchSignals) and (priceCrossOverInner and rsiCrossOverLower) and (barstate.isconfirmed) and (not signalsBlocked)
  482. buyWatch4 = (usePriceBandWatchSignals) and (priceCrossOverInner) and (barstate.isconfirmed) and (not signalsBlocked)
  483. buyWatch5 = (useRsiWatchSignals) and (rsiCrossOverLower) and (barstate.isconfirmed) and (not signalsBlocked)
  484. buyWatch6 = (useRsiWatchSignals) and (rsiCrossOver25) and (barstate.isconfirmed) and (not signalsBlocked)
  485. //buyWatch8 = (useThresholdCrosses) and (ta.crossover(distance, volatilityThreshold)) and (barstate.isconfirmed) and (not signalsBlocked)
  486.  
  487. // Red squares
  488. sellWatch1 = (usePriceBandWatchSignals) and (priceCrossUnderInner and not rsiCrossUnderUpper) and (barstate.isconfirmed) and (not signalsBlocked)
  489. sellWatch2 = (useRsiWatchSignals) and (rsiCrossUnderUpper and not priceCrossUnderInner) and (barstate.isconfirmed) and (not signalsBlocked)
  490. sellWatch3 = (usePriceBandWatchSignals) and (priceCrossUnderInner and rsiCrossUnderUpper) and (barstate.isconfirmed) and (not signalsBlocked)
  491. sellWatch4 = (usePriceBandWatchSignals) and (priceCrossUnderInner) and (barstate.isconfirmed) and (not signalsBlocked)
  492. sellWatch5 = (useRsiWatchSignals) and (rsiCrossUnderUpper) and (barstate.isconfirmed) and (not signalsBlocked)
  493. sellWatch6 = (useRsiWatchSignals) and (rsiCrossUnder75) and (barstate.isconfirmed) and (not signalsBlocked)
  494. //sellWatch8 = (useThresholdCrosses) and (ta.crossunder(distance, volatilityThreshold)) and (barstate.isconfirmed) and (not signalsBlocked)
  495.  
  496. bool buyWatched = buyWatch1 or buyWatch2 or buyWatch3 or buyWatch4 or buyWatch5 or buyWatch6 // or buyWatch8
  497. bool sellWatched = sellWatch1 or sellWatch2 or sellWatch3 or sellWatch4 or sellWatch5 or sellWatch6 // or sellWatch8
  498.  
  499. // Buy signals
  500. buySignal1 = (useRsiSignals and rsiCrossOverBasis)
  501. buySignal2 = (usePriceSignals and priceCrossOverBasis)
  502. buySignal3 = (use50Signals and rsiCrossOver50)
  503. buySignal4 = (use25Signals and rsiCrossOver25)
  504. buySignal5 = (useMacdSignals and macdBuy)
  505. buySignal6 = (useRsiMa and rsiCrossOverMa)
  506. //buySignal7 = (useAdjustedRsi and adjustedRsiCrossOverBasis)
  507. //buySignal8 = (useAdjustedRsi and adjustedRsiCrossOverMa)
  508.  
  509. // Sell signals
  510. sellSignal1 = (useRsiSignals and rsiCrossUnderBasis)
  511. sellSignal2 = (use50Signals and rsiCrossUnder50)
  512. sellSignal3 = (usePriceSignals and priceCrossUnderBasis)
  513. sellSignal4 = (use75Signals and rsiCrossUnder75)
  514. sellSignal5 = (useMacdSignals and macdSell)
  515. sellSignal6 = (useRsiMa and rsiCrossUnderMa)
  516. //sellSignal7 = (useAdjustedRsi and adjustedRsiCrossUnderBasis)
  517. //sellSignal8 = (useAdjustedRsi and adjustedRsiCrossUnderMa)
  518.  
  519. /////////////////////////
  520. // Watch Signal Arrays //
  521. /////////////////////////
  522.  
  523. array.push(buyWatchArray, buyWatched ? 1 : na)
  524. array.push(sellWatchArray, sellWatched ? 1 : na)
  525.  
  526. while array.size(buyWatchArray) > watchSignalLookback
  527. array.shift(buyWatchArray)
  528. while array.size(sellWatchArray) > watchSignalLookback
  529. array.shift(sellWatchArray)
  530.  
  531. buyWatchSumMet = (array.sum(buyWatchArray) >= 1)
  532. sellWatchSumMet = (array.sum(sellWatchArray) >= 1)
  533.  
  534. buyWatchMet = (buyWatchSumMet)
  535. sellWatchMet = (sellWatchSumMet)
  536.  
  537. combinedBuySignals = buySignal1 or buySignal2 or buySignal3 or buySignal4 or buySignal5 or buySignal6 // or buySignal7 or buySignal8
  538. combinedSellSignals = sellSignal1 or sellSignal2 or sellSignal3 or sellSignal4 or sellSignal5 or sellSignal6 // or sellSignal7 or sellSignal8
  539.  
  540. // Use buyWatchRequired and sellWatchRequired here for generating buy and sell signals
  541. buySignals = ((not requireWatchSignals and combinedBuySignals) or (requireWatchSignals and buyWatchMet and combinedBuySignals))
  542. sellSignals = ((not requireWatchSignals and combinedSellSignals) or (requireWatchSignals and sellWatchMet and combinedSellSignals))
  543.  
  544. ////////////////////////
  545. // Buy and Sell logic //
  546. ////////////////////////
  547.  
  548. if (buySignals) and (not buyWatched) and (not signalsBlocked) and ((dpoAllowBuy) and (rocAllowBuy))
  549. plotBuyBG := true
  550. else if (sellSignals) and (not sellWatched) and (not signalsBlocked) and ((dpoAllowSell) and (rocAllowSell))
  551. plotSellBG := true
  552. else
  553. plotBuyBG := false
  554. plotSellBG := false
  555.  
  556. if (buySignals) and (barstate.isconfirmed) and (not signalsBlocked) and ((dpoAllowBuy) and (rocAllowBuy))
  557. bought := true
  558. sold := false
  559. plotBuy := true
  560. lastSignalBarIndex := bar_index
  561. array.clear(buyWatchArray)
  562. array.clear(sellWatchArray)
  563. else if (sellSignals) and (barstate.isconfirmed) and (not signalsBlocked) and ((dpoAllowSell) and (rocAllowSell))
  564. sold := true
  565. bought := false
  566. plotSell := true
  567. lastSignalBarIndex := bar_index
  568. array.clear(sellWatchArray)
  569. array.clear(buyWatchArray)
  570. else
  571. plotBuy := false
  572. plotSell := false
  573.  
  574. // Buy and sell signal alerts (Advanced or final)
  575. alertcondition(enableAdvancedAlerts ? plotBuyBG : plotBuy, title='Buy signal', message='Buy signal detected')
  576. alertcondition(enableAdvancedAlerts ? plotSellBG : plotSell, title='Sell signal', message='Sell signal detected')
  577.  
  578. // Check if the current bar is within the wait period after a buy or sell signal
  579. if useSignalWaiting
  580. signalsBlocked := na(lastSignalBarIndex) == false and bar_index - lastSignalBarIndex <= signalWaitPeriod
  581. else
  582. signalsBlocked := false
  583.  
  584. // Buy and Sell Signal triangles and labels
  585. plotshape(showSignals and plotBuy ? true : na, title="BUY/LONG", location=location.belowbar, color=color.new(color.orange,0), style=shape.triangleup, textcolor=color.orange, text="B", size=size.tiny)
  586. plotshape(showSignals and plotSell ? true : na, title="SELL/SHORT", location=location.abovebar, color=color.new(color.fuchsia,0), style=shape.triangledown, textcolor=color.fuchsia, text="S", size=size.tiny)
  587. // Buy Sell Warning Vertical Colored Background
  588. bgcolor(showSignalBackground and plotBuyBG ? color.new(color.orange, 80) : na)
  589. bgcolor(showSignalBackground and plotSellBG ? color.new(color.fuchsia, 80) : na)
  590. // Buy circles
  591. B1 = color.new(color.orange, 50)
  592. B2 = color.new(color.orange, 65)
  593. B3 = color.new(color.orange, 85)
  594. S1 = color.new(color.fuchsia, 50)
  595. S2 = color.new(color.fuchsia, 65)
  596. S3 = color.new(color.fuchsia, 85)
  597. plotshape(showSignals and showCircles and plotBuy ? low : na, color= B1, location=location.absolute, style=shape.circle, size=size.tiny)
  598. plotshape(showSignals and showCircles and plotBuy ? low : na, color= B2, location=location.absolute, style=shape.circle, size=size.small)
  599. plotshape(showSignals and showCircles and plotBuy ? low : na, color= B3, location=location.absolute, style=shape.circle, size=size.normal)
  600. plotshape(showSignals and showCircles and plotSell ? high : na, color= S1, location=location.absolute, style=shape.circle, size=size.tiny)
  601. plotshape(showSignals and showCircles and plotSell ? high : na, color= S2, location=location.absolute, style=shape.circle, size=size.small)
  602. plotshape(showSignals and showCircles and plotSell ? high : na, color= S3, location=location.absolute, style=shape.circle, size=size.normal)
  603. // Bought and sold state colored background
  604. bgcolor(showBSBackground and bought ? color.new(color.green, 90) : na)
  605. bgcolor(showBSBackground and sold ? color.new(color.red, 90) : na)
  606.  
  607. // Plot Buy Watch signals based on filters
  608. plotshape(showWatchSignals and buyWatched and not signalsBlocked ? true : na, title="Buy Watch Signals", location=location.belowbar, color=color.new(color.orange, 20), style=shape.square, size=size.tiny)
  609.  
  610. // Plot Sell Watch signals based on filters
  611. plotshape(showWatchSignals and sellWatched and not signalsBlocked ? true : na, title="Sell Watch Signals", location=location.abovebar, color=color.new(color.fuchsia, 20), style=shape.square, size=size.tiny)
  612.  
  613. ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  614. /// This section handles candle coloring based on RSI levels (option 1), DPO ribbon trend (option 2) ///
  615. /// as well as the color of the candles when there is a buy or sell signal (if turned on). ///
  616. /// NOTE: If DPO Candles are selected, the candles will be brighter when the Bollinger Bands are ///
  617. /// wider (higher volatility) and will darken when the Bollinger Bands are narrowing (lower volatility). ///
  618. /// I added this feature so you can still visualize the volatility without having to clutter the screen ///
  619. /// with Bollinger Bands. ///
  620. ////////////////////////////////////////////////////////////////////////////////////////////////////////////
  621.  
  622. // Ensure Mutual Exclusivity of Candle Coloring using ternary operators
  623. showRSICandleColors := showRSICandleColors ? true : showDPOCandleColors ? false : showRSICandleColors
  624. showDPOCandleColors := showDPOCandleColors ? true : showRSICandleColors ? false : showDPOCandleColors
  625.  
  626. // Define color zones
  627. oneHundredTo85 = showRSICandleColors and smoothedRsi <= 100 and smoothedRsi >= 85
  628. eightyFiveTo75 = showRSICandleColors and smoothedRsi < 85 and smoothedRsi >= 75
  629. seventyFiveTo70 = showRSICandleColors and smoothedRsi < 75 and smoothedRsi >= 70
  630. seventyTo65 = showRSICandleColors and smoothedRsi < 70 and smoothedRsi >= 65
  631. sixtyFiveTo60 = showRSICandleColors and smoothedRsi < 65 and smoothedRsi >= 60
  632. sixtyToYellowHigh = showRSICandleColors and smoothedRsi < 60 and smoothedRsi >= 55
  633. yellowHighToYellowLow = showRSICandleColors and smoothedRsi < 55 and smoothedRsi >= 45
  634. yellowLowTo40 = showRSICandleColors and smoothedRsi < 45 and smoothedRsi >= 40
  635. fourtyTo35 = showRSICandleColors and smoothedRsi < 40 and smoothedRsi >= 35
  636. thirtyFiveTo30 = showRSICandleColors and smoothedRsi < 35 and smoothedRsi >= 30
  637. thirtyTo25 = showRSICandleColors and smoothedRsi < 30 and smoothedRsi >= 25
  638. twentyFiveTo15 = showRSICandleColors and smoothedRsi < 25 and smoothedRsi >= 15
  639. fifteenTo0 = showRSICandleColors and smoothedRsi < 15 and smoothedRsi >= 0
  640.  
  641. // Assign RSI-based colors
  642. RsiCandleColor = oneHundredTo85 ? color.new(color.white, 20) : eightyFiveTo75 ? color.new(color.lime, 0) : seventyFiveTo70 ? color.new(color.lime, 15) : seventyTo65 ? color.new(color.green, 0) : sixtyFiveTo60 ? color.new(color.green, 15) : sixtyToYellowHigh ? color.new(color.green, 30) : yellowHighToYellowLow ? color.new(color.yellow, 30) : yellowLowTo40 ? color.new(color.red, 50) : fourtyTo35 ? color.new(color.red, 45) : thirtyFiveTo30 ? color.new(color.red, 30) : thirtyTo25 ? color.new(color.red, 15) : twentyFiveTo15 ? color.new(color.red, 0) : fifteenTo0 ? color.new(color.white, 20) : na
  643.  
  644. // Candle color conditions for DPO
  645. dpoCandleColor = showDPOCandleColors ? (dpoBullish ? (fadeDPOCandles ? color.new(upColor, transparency) : upColor) : (fadeDPOCandles ? color.new(downColor, transparency) : downColor)) : na
  646.  
  647. // Determine if the current candle is a buy or sell signal candle
  648. buySignalCandle = showSignals and plotBuy
  649. sellSignalCandle = showSignals and plotSell
  650.  
  651. // Determine the final candle color
  652. CandleColor = buySignalCandle ? color.new(color.orange, 0) : sellSignalCandle ? color.new(color.fuchsia, 0) : showRSICandleColors ? RsiCandleColor : showDPOCandleColors ? dpoCandleColor : na
  653.  
  654. // Plot the candles with custom color for body, wick, and border
  655. plotcandle(open, high, low, close, color=CandleColor, wickcolor=CandleColor, bordercolor=CandleColor)
  656.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement