Advertisement
sdxhex

Untitled

Jun 8th, 2023
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 34.83 KB | None | 0 0
  1. //@version=5
  2. indicator("RSI Exponential Smoothing (Expo)", overlay=true)
  3.  
  4. // ~~ Inputs {
  5. import HeWhoMustNotBeNamed/mZigzag/12 as zg
  6. import HeWhoMustNotBeNamed/enhanced_ta/14 as eta
  7. import HeWhoMustNotBeNamed/arrays/1 as pa
  8. rsiperiod = input.int(14,minval=2, title="RSI Period", inline="RSI")
  9. ob = input.int(70,minval=50, maxval=100, title="Overbought", inline="obos")
  10. os = input.int(30,minval=0, maxval=50, title="Oversold", inline="obos")
  11. obosbands = input.bool(true, title="OBOS Band", inline="RSI")
  12. fibbands = input.bool(false, title="FIB Band", inline="RSI")
  13. labels = input.bool(true, title="RSI Labels", inline="RSI")
  14. // ~~ Line Colors {
  15. ema_col = input.color(color.rgb(0, 0, 255), title="EMA",inline="c")
  16. ema_ob_col = input.color(color.rgb(77, 255, 41), title="OB",inline="c")
  17. ema_os_col = input.color(color.rgb(255, 65, 47), title="OS",inline="c")
  18. ema_fib_col= input.color(color.blue, title="FIB",inline="c")
  19. //~~~}
  20. // ~~ Table Inputs {
  21. showTable = input.bool(true,title="Show Table", inline="tbl", group="Table")
  22. validity_check = input.bool(false,title="Show Validity check", inline="tbl", group="Table")
  23. TblSize = input.string(size.normal,title="",options=[size.auto,size.tiny,size.small,size.normal,size.large,size.huge],inline="tbl", group="Table")
  24. pos = input.string(position.top_right, title="",options =[position.top_right,position.top_center,
  25. position.top_left,position.bottom_right,position.bottom_center,position.bottom_left,position.middle_right,position.middle_left],inline="tbl", group="Table")
  26. textcolor = input.color(color.white, title="Text",inline="tbl_col", group="Table")
  27. bgcolor = input.color(color.new(color.blue,30), title="Bg",inline="tbl_col", group="Table")
  28. postrend = input.color(color.new(color.lime,0), title="Trend",inline="tbl_col", group="Table")
  29. negtrend = input.color(color.new(color.red,0), title="",inline="tbl_col", group="Table")
  30. ob_col = input.color(color.new(color.lime,0), title="OB/OS",inline="tbl_col", group="Table")
  31. os_col = input.color(color.new(color.red,0), title="",inline="tbl_col", group="Table")
  32.  
  33.  
  34. length = input.int(8, 'Length', group='Zigzag')
  35. oscillatorType = input.string("rsi", title="Oscillator", inline="osc", options=["cci", "cmo", "cog", "mfi", "roc", "rsi"], group='Oscillator')
  36. oscLength = input.int(14, title="", inline="osc", group='Oscillator')
  37. supertrendLength = input.int(5, 'History', inline='st', group='Supertrend')
  38. drawSupertrend = input.bool(false, "Draw Zigzag Supertrend", inline='st2', group='Supertrend')
  39.  
  40. txtSize = input.string(size.tiny, '', [size.tiny, size.small, size.normal, size.large, size.huge], inline='txt', group = 'Stats and Display')
  41. txtColor = input.color(color.white, '', inline='txt', group = 'Stats and Display')
  42.  
  43. showPivotLines = input.bool(true, 'Pivot Lines', inline='pli', group = 'Stats and Display')
  44. showPivotLabel = input.bool(false, 'Pivot Label', inline='pla', group = 'Stats and Display')
  45.  
  46. //~~~}
  47. //~~~~~~}
  48.  
  49. // ~~ EMA RSI Approx Calculation {
  50. // ~~ Exponential Smoothing Coefficient Calculation {
  51. exponential_period = 2 * rsiperiod - 1 // "exponential_period" is the length of the moving average, represented as "2 * rsiperiod - 1", where "rsiperiod" is a user-defined value.
  52. smoothing_coefficient = 2 / (exponential_period + 1) // "smoothing_coefficient" is a value used to calculate the EMA, represented as "2 / (exponential_period + 1)". This value determines the weight given to the current observation versus the previous average in the calculation.
  53. //~~~}
  54.  
  55. // ~~ Exponential Smoothing RSI Calculation {
  56. // The code calculates two running averages, "averageUp" and "averageDown", using the exponential smoothing formula with the smoothing coefficient value defined in the previous code snippet.
  57. // The "netValue" variable is then calculated as the weighted difference between the "averageUp" and "averageDown" values, with a factor determined by the user-defined "rsiperiod" value.
  58. // The "result" variable is calculated based on the sign of "netValue". If "netValue" is positive, the result is equal to the current close price plus "netValue". If "netValue" is negative, the result is equal to the close price plus a fraction of "netValue" determined by the "level" parameter
  59. emaresult(level)=>
  60. averageUp = 0.0
  61. averageDown = 0.0
  62. averageUp := close > close[1] ? smoothing_coefficient* (close - close[1]) + (1 - smoothing_coefficient) * (averageUp[1] ? averageUp[1] : 1) : (1-smoothing_coefficient) * (averageUp[1] ? averageUp[1] : 1)
  63. averageDown := close > close[1] ? (1-smoothing_coefficient) * (averageDown[1] ? averageDown[1] : 1) : smoothing_coefficient * (close[1] - close) + (1 - smoothing_coefficient) * (averageDown[1] ? averageDown[1] : 1)
  64. netValue = (rsiperiod - 1) * (averageDown * level / (100 - level) - averageUp)
  65. result = netValue >= 0 ? close + netValue : close + netValue * (100 - level) / level
  66. //~~~}
  67.  
  68. // ~~ Return EMA {
  69. ema_result = emaresult(50)
  70. // Plot the Optimal EMA based on the RSI value
  71. plot(ema_result, color=ema_col, title="Optimal EMA")
  72. //~~~}
  73. //~~~~~~}
  74.  
  75. // ~~ Calculate RSI Standard Deviation, in order to calculate the Deviation {
  76. StandardDeviation(src, period)=>
  77. mean = ta.sma(src, period)
  78. squared_diff = ((src - mean) * (src - mean))
  79. sum_squared_diff = math.sum(squared_diff, period)
  80. std_dev = math.sqrt(sum_squared_diff/period)
  81. //~~~}
  82.  
  83. // ~~ Return RSI Standard Deviation {
  84. rsi = ta.rsi(close,rsiperiod)
  85. std_dev = StandardDeviation(rsi, rsiperiod)
  86. //~~~}
  87.  
  88. // ~~ Calculate Deviation {
  89. //It calculates the difference between the RSI value of (level) and the RSI mean value, then divides that difference by the standard deviation.
  90. //This number represents how many standard deviations away the RSI Level is from its mean.
  91. dev(obos)=>
  92. deviating = (obos-ema_result)/std_dev
  93. //~~~}
  94.  
  95. // ~~ Hull Moving Average Calculation, in order to smooth the Upper OB and Lower OS lines {
  96. hma(src,len)=>
  97. wma1 = ta.wma(2 * ta.wma(src, len/2) - ta.wma(src, len), math.round(math.sqrt(0.5)))
  98. wma2 = ta.wma(2 * ta.wma(wma1, len/2) - ta.wma(wma1, len), math.round(math.sqrt(0.5)))
  99. //~~~}
  100.  
  101. // ~~ Return EMA OB/OS Lines {
  102. // Deviation refers to how far a data point is from the mean (average) of the data set. It is calculated as the difference between the data point and the mean.
  103. // Standard deviation is a measure of how much the values in a data set vary around the mean. It provides a summary of the distribution of the data.
  104. // When the deviation of a data point is multiplied by the standard deviation, it gives us a measure of how many standard deviations away from the mean the data point is.
  105. // This measure is useful in understanding the level of variation in the data set and making predictions about the data.
  106. // The deviation * stdev is used to add an offset to the EMA calculation
  107. // It returns the Upper Overbougth and Lower Oversold levels on the chart.
  108. ob_dev = dev(emaresult(ob)) // The deviation of the OB level from the mean. This number represents how many standard deviations away the OB Level is from its mean.
  109. os_dev = dev(emaresult(os)) // The deviation of the OS level from the mean. This number represents how many standard deviations away the OS Level is from its mean.
  110. upper = hma(ta.rma(ema_result + (ob_dev*std_dev),3),10) // Returns the upper OB line on the chart.
  111. lower = hma(ta.rma(ema_result + (os_dev*std_dev),3),10) // Returns the upper OS line on the chart.
  112.  
  113. // ~~ Plot Upper OB and Lower OS lines on the chart {
  114. plot(obosbands?upper:na, "Upper OB", color=ema_ob_col)
  115. plot(obosbands?lower:na, "Lower OS", color=ema_os_col)
  116. plot(obosbands?upper - ta.stdev(upper,2):na, "Upper OB", color=ema_ob_col)
  117. plot(obosbands?lower + ta.stdev(lower,2):na, "Lower OS", color=ema_os_col)
  118. //~~~}
  119. //~~~~~~}
  120.  
  121. // ~~ Calculate fib 50% from OB to 50 level and OS to 50 level {
  122. fib(src)=>
  123. fib = ema_result + (src-ema_result)*0.5
  124.  
  125. // ~~ Plot the Fib lines on the chart {
  126. plot(fibbands?fib(upper):na, "Upper Fib 50%", color=ema_fib_col)
  127. plot(fibbands?fib(lower):na, "Lower Fib 50%", color=ema_fib_col)
  128. //~~~}
  129. //~~~~~~}
  130.  
  131. // ~~ Validity Checks {
  132. // ~~ Store crossover values to check Validity {
  133. // ~~ Optimal EMA Length {
  134. emavalue = 2*rsiperiod-1
  135. ema = ta.ema(close,emavalue)
  136. //~~~}
  137. var occurrence = 0
  138. var non_occurrence = 0
  139. if (ta.crossover(rsi,50) and ta.crossover(close,ema)) or (ta.crossunder(rsi,50) and ta.crossunder(close,ema))
  140. occurrence += 1
  141. if (ta.crossover(rsi,50) and not ta.crossover(close,ema)) or (ta.crossunder(rsi,50) and not ta.crossunder(close,ema))
  142. non_occurrence += 1
  143. //~~~~~~}
  144.  
  145. // ~~ Precentage Check {
  146. //The resulting value tells you how many occurrences there are relative to the total number of events, expressed as a percentage.
  147. percent = ((math.abs(occurrence)/(occurrence + non_occurrence) * 100))
  148. //~~~}
  149.  
  150. // ~~ Inputs to Table {
  151. // ~~ Trend Direction {
  152. dir = rsi>50?true:false
  153. sign = dir == true?" > 50 ":" < 50"
  154. trend = dir == true?"Bullish":"Bearish"
  155. col = dir == true?postrend:negtrend
  156. //~~~}
  157.  
  158. // ~~ Overbought & Oversold {
  159. ob_ = rsi>ob ?true:false
  160. os_ = rsi<os?true:false
  161. obos_sign = ob_? " > " + str.tostring(ob):os_? " < " + str.tostring(os):""
  162. obos_text = ob_? "Overbought":os_? "Oversold":""
  163. obos_col = ob_?ob_col:os_?os_col:color.white
  164. //~~~}
  165. //~~~~~~}
  166.  
  167. // ~~ Table {
  168. tbl = table.new(pos, 2, 11, frame_color=chart.bg_color, frame_width=2, border_width=2, border_color=chart.bg_color)
  169. if barstate.islast and showTable
  170. tbl.cell(0, 0, text="RSI Value", text_color=textcolor, bgcolor=bgcolor, text_size=TblSize)
  171. tbl.cell(0, 1, text=str.tostring(rsiperiod), text_halign=text.align_center, bgcolor=bgcolor, text_color=textcolor, text_size=TblSize)
  172. tbl.cell(1, 0, text="EMA Value", text_color=textcolor, bgcolor=bgcolor, text_size=TblSize)
  173. tbl.cell(1, 1, text=str.tostring(emavalue), text_halign=text.align_center, bgcolor=bgcolor, text_color=textcolor, text_size=TblSize)
  174. tbl.cell(0, 2, text="RSI" + sign + "", text_color=textcolor, bgcolor=bgcolor, text_size=TblSize)
  175. tbl.cell(1, 2, text=trend, text_halign=text.align_center, bgcolor=col, text_color=textcolor, text_size=TblSize)
  176. if (ob_) or (os_)
  177. tbl.cell(0, 3, text="RSI" + obos_sign + "", text_color=textcolor, bgcolor=bgcolor, text_size=TblSize)
  178. tbl.cell(1, 3, text=obos_text, text_halign=text.align_center, bgcolor=obos_col, text_color=textcolor, text_size=TblSize)
  179. if validity_check
  180. tbl.cell(0, 4, text="Validity Check", text_color=textcolor, bgcolor=bgcolor, text_size=TblSize)
  181. tbl.cell(1, 4, text=str.tostring(percent,format.percent), text_halign=text.align_center, bgcolor=color.new(color.lime,30), text_color=textcolor, text_size=TblSize)
  182. tbl.cell(0, 5, text="RSI Stdev", text_color=textcolor, bgcolor=bgcolor, text_size=TblSize)
  183. tbl.cell(1, 5, text=str.tostring(math.round(std_dev)), text_halign=text.align_center, bgcolor=color.new(color.lime,30), text_color=textcolor, text_size=TblSize)
  184.  
  185.  
  186. // ~~ Labels {
  187. labelfunc(bool_,n, line_, text_, label_col, text_col, size_)=>
  188. label l = bool_?label.new(bar_index + n,line_,text=text_,color=label_col,
  189. style=label.style_label_left,textcolor=text_col,size=size_,
  190. textalign=text.align_left):na
  191. label.delete(l[1])
  192.  
  193. labelfunc(labels,5, ema_result, "RSI 50" , color.blue, color.white, size.small)
  194. labelfunc(labels,5, upper, "RSI " + str.tostring(ob) , color.green, color.white, size.small)
  195. labelfunc(labels,5, lower, "RSI " + str.tostring(os) , color.red, color.white, size.small)
  196. labelfunc(fibbands and labels,1, fib(upper), "FIB 50 %" , color.blue, color.white, size.tiny)
  197. labelfunc(fibbands and labels,1, fib(lower), "FIB 50 %" , color.blue, color.white, size.tiny)
  198. //~~~}
  199.  
  200.  
  201.  
  202.  
  203. increment(mtx, row, col, val=1)=>matrix.set(mtx, row, col, matrix.get(mtx, row, col)+val)
  204. gettrendindex(int price, int osc, int trend)=>
  205. trendFactor = trend > 0 ? 0 : 1
  206. priceFactor = math.abs(price) > 1? 1 : 0
  207. oscFactor = math.abs(osc) > 1? 1 : 0
  208. trendFactor*4 + priceFactor*2 + oscFactor
  209.  
  210.  
  211. getSentimentDetails(pDir, oDir, sDir) =>
  212. sentiment = pDir == oDir ? sDir == pDir or sDir * 2 == -pDir ? -sDir : sDir * 4 : sDir == pDir or sDir == -oDir ? 0 : (math.abs(oDir) > math.abs(pDir) ? sDir : -sDir) * (sDir == oDir ? 2 : 3)
  213. sentimentSymbol = sentiment == 4 ? '⬆' : sentiment == -4 ? '⬇' : sentiment == 3 ? '↗' : sentiment == -3 ? '↘' : sentiment == 2 ? '⤴' : sentiment == -2 ? '⤵' : sentiment == 1 ? '⤒' : sentiment == -1 ? '⤓' : '▣'
  214. sentimentColor = sentiment == 4 ? color.green : sentiment == -4 ? color.red : sentiment == 3 ? color.lime : sentiment == -3 ? color.orange : sentiment == 2 ? color.rgb(202, 224, 13, 0) : sentiment == -2 ? color.rgb(250, 128, 114, 0) : color.silver
  215. sentimentLabel = math.abs(sentiment) == 4 ? 'C' : math.abs(sentiment) == 3 ? 'H' : math.abs(sentiment) == 2 ? 'D' : 'I'
  216. [sentimentSymbol, sentimentLabel, sentimentColor]
  217.  
  218.  
  219. getStatus(int trendIndex, int pivotDir)=>
  220. trendFactor = int(trendIndex/4)
  221. remainder = trendIndex % 4
  222. priceFactor = int(remainder/2)+1
  223. oscFactor = (remainder % 2)+1
  224. trendChar = (trendFactor == 0)? 'U' : 'D'
  225. priceChar = pivotDir > 0? (priceFactor == 2? 'HH' : 'LH') : (priceFactor == 2? 'LL' : 'HL')
  226. oscChar = pivotDir > 0? (oscFactor == 2? 'HH' : 'LH') : (oscFactor == 2? 'LL' : 'HL')
  227. trendChar + ' - ' + priceChar + '/'+oscChar
  228.  
  229. draw_zg_line(idx1, idx2, zigzaglines, zigzaglabels, valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix,
  230. barArray, trendArray, lineColor, lineWidth, lineStyle) =>
  231. if matrix.rows(valueMatrix) > 2
  232. idxLen1 = matrix.rows(valueMatrix)-idx1
  233. idxLen2 = matrix.rows(valueMatrix)-idx2
  234. lastValues = matrix.row(valueMatrix, idxLen1)
  235. llastValues = matrix.row(valueMatrix, idxLen2)
  236.  
  237. lastDirections = matrix.row(directionMatrix, idxLen1)
  238. lastRatios = matrix.row(ratioMatrix, idxLen1)
  239. lastDivergence = matrix.row(divergenceMatrix, idxLen1)
  240. lastDoubleDivergence = matrix.row(doubleDivergenceMatrix, idxLen1)
  241.  
  242. y1 = array.get(lastValues, 0)
  243. y2 = array.get(llastValues, 0)
  244. x1 = array.get(barArray, idxLen1)
  245. x2 = array.get(barArray, idxLen2)
  246. zline = line.new(x1=x1, y1=y1, x2=x2, y2=y2, color=lineColor, width=lineWidth, style=lineStyle)
  247. currentDir = y1 > y2? 1 : -1
  248.  
  249. priceDir = array.get(lastDirections, 0)
  250. oscDir = array.get(lastDirections, 1)
  251. trendDir = array.get(trendArray, idxLen1)
  252. trendIndex = gettrendindex(priceDir, oscDir, trendDir)
  253. trendLabel = getStatus(trendIndex, currentDir)
  254. [sentimentSymbol, sentimentLabel, sentimentColor] = getSentimentDetails(priceDir, oscDir, trendDir)
  255.  
  256. labelStyle = currentDir > 0? label.style_label_down : label.style_label_up
  257. zlabel = showPivotLabel ? label.new(x=x1, y=y1, yloc=yloc.price, color=sentimentColor, style=labelStyle, text=sentimentSymbol + ' ' + trendLabel,
  258. textcolor=color.black, size = size.small, tooltip=sentimentLabel) : na
  259. if array.size(zigzaglines) > 0
  260. lastLine = array.get(zigzaglines, array.size(zigzaglines)-1)
  261. if line.get_x2(lastLine) == x2 and line.get_x1(lastLine) <= x1
  262. pa.pop(zigzaglines)
  263. pa.pop(zigzaglabels)
  264.  
  265. pa.push(zigzaglines, zline, 500)
  266. pa.push(zigzaglabels, zlabel, 500)
  267.  
  268. draw(matrix<float> valueMatrix, matrix<int> directionMatrix, matrix<float> ratioMatrix, matrix<int> divergenceMatrix, matrix<int> doubleDivergenceMatrix, array<int> barArray, array<int> trendArray,
  269. bool newZG, bool doubleZG, color lineColor = color.blue, int lineWidth = 1, string lineStyle = line.style_solid)=>
  270. var zigzaglines = array.new_line(0)
  271. var zigzaglabels = array.new_label(0)
  272. if(newZG)
  273. if doubleZG
  274. draw_zg_line(2, 3, zigzaglines, zigzaglabels, valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, trendArray,
  275. lineColor, lineWidth, lineStyle)
  276.  
  277. if matrix.rows(valueMatrix) >= 2
  278. draw_zg_line(1, 2, zigzaglines, zigzaglabels, valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, trendArray,
  279. lineColor, lineWidth, lineStyle)
  280. [valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, zigzaglines, zigzaglabels]
  281.  
  282.  
  283.  
  284. indicatorHigh = array.new_float()
  285. indicatorLow = array.new_float()
  286. indicatorLabels = array.new_string()
  287.  
  288. [oscHigh, _, _] = eta.oscillator(oscillatorType, oscLength, oscLength, oscLength, high)
  289. [oscLow, _, _] = eta.oscillator(oscillatorType, oscLength, oscLength, oscLength, low)
  290. array.push(indicatorHigh, math.round(oscHigh,2))
  291. array.push(indicatorLow, math.round(oscLow,2))
  292. array.push(indicatorLabels, oscillatorType+str.tostring(oscLength))
  293.  
  294.  
  295. [valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, trendArray, supertrendDir, supertrend, newZG, doubleZG] =
  296. zg.calculate(length, array.from(high, low), indicatorHigh, indicatorLow, supertrendLength = supertrendLength)
  297.  
  298. nextDirection = matrix.rows(directionMatrix) > 0? matrix.row(directionMatrix, matrix.rows(directionMatrix)-1) : array.new_int()
  299. lastDirection = matrix.rows(directionMatrix) > 1? matrix.row(directionMatrix, matrix.rows(directionMatrix)-2) : array.new_int()
  300. llastDirection = matrix.rows(directionMatrix) > 2? matrix.row(directionMatrix, matrix.rows(directionMatrix)-3) : array.new_int()
  301. lllastDirection = matrix.rows(directionMatrix) > 3? matrix.row(directionMatrix, matrix.rows(directionMatrix)-4) : array.new_int()
  302.  
  303. var pivotHighStats = matrix.new<int>(64, 3, 0)
  304. var pivotLowStats = matrix.new<int>(64, 3, 0)
  305.  
  306. var pivotHighRatios = matrix.new<float>(64, 3, 0)
  307. var pivotLowRatios = matrix.new<float>(64, 3, 0)
  308.  
  309. var pivotHighBars = matrix.new<float>(64, 3, 0)
  310. var pivotLowBars = matrix.new<float>(64, 3, 0)
  311.  
  312. currentTotalTrendIndex = 0
  313. nextTotalTrendIndex = 0
  314. currentDir = matrix.rows(directionMatrix) > 0? matrix.get(directionMatrix, matrix.rows(directionMatrix)-1, 0) : 0
  315.  
  316. currentPDir = lastDirection.size() > 0 ? lastDirection.first() : na
  317. changePriceDirection = ta.change(math.sign(currentPDir))
  318. if(array.size(lllastDirection) > 0)
  319. priceDirection = array.get(lastDirection, 0)
  320. priceRatio = matrix.get(ratioMatrix, matrix.rows(ratioMatrix)-2, 0)
  321.  
  322. numberOfBars = array.get(barArray, array.size(barArray)-2) - array.get(barArray, array.size(barArray)-3)
  323. currentPriceDirection = array.get(lastDirection, 0)
  324. currentOscDirection = array.get(lastDirection, 1)
  325. currentTrend = array.get(trendArray, array.size(trendArray)-2)
  326.  
  327. nextPriceDirection = array.get(nextDirection, 0)
  328. nextOscDirection = array.get(nextDirection, 1)
  329. nextTrend = array.get(trendArray, array.size(trendArray)-1)
  330.  
  331. lastPriceDirection = array.get(llastDirection, 0)
  332. lastOscDirection = array.get(llastDirection, 1)
  333. lastTrend = array.get(trendArray, array.size(trendArray)-3)
  334.  
  335. llastPriceDirection = array.get(lllastDirection, 0)
  336. llastOscDirection = array.get(lllastDirection, 1)
  337. llastTrend = array.get(trendArray, array.size(trendArray)-4)
  338.  
  339. colLast = math.abs(priceDirection) %2
  340.  
  341. nextTrendIndex = gettrendindex(nextPriceDirection, nextOscDirection, nextTrend)
  342. currentTrendIndex = gettrendindex(currentPriceDirection, currentOscDirection, currentTrend)
  343. lastTrendIndex = gettrendindex(lastPriceDirection, lastOscDirection, lastTrend)
  344. llastTrendIndex = gettrendindex(llastPriceDirection, llastOscDirection, llastTrend)
  345.  
  346. totalIndex = lastTrendIndex*8 + llastTrendIndex
  347. currentTotalTrendIndex := currentTrendIndex*8 + lastTrendIndex
  348. nextTotalTrendIndex := nextTrendIndex*8 + currentTrendIndex
  349.  
  350. matrixToSet = math.sign(priceDirection) > 0? pivotHighStats : pivotLowStats
  351. ratioMatrixToSet = math.sign(priceDirection) > 0? pivotHighRatios : pivotLowRatios
  352. barMatrixToSet = math.sign(priceDirection) > 0? pivotHighBars : pivotLowBars
  353.  
  354. if(not na(currentPDir) and changePriceDirection)
  355. increment(matrixToSet, totalIndex, colLast)
  356. increment(ratioMatrixToSet, totalIndex, colLast, priceRatio)
  357. increment(barMatrixToSet, totalIndex, colLast, numberOfBars)
  358.  
  359. increment(matrixToSet, totalIndex, 2)
  360. increment(ratioMatrixToSet, totalIndex, 2, priceRatio)
  361. increment(barMatrixToSet, totalIndex, 2, numberOfBars)
  362.  
  363.  
  364. var float hhValue = na
  365. var float lhValue = na
  366.  
  367. var float llValue = na
  368. var float hlValue = na
  369.  
  370. var float hhProbability = na
  371. var float llProbability = na
  372.  
  373. var float htRatio = na
  374. var float ltRatio = na
  375. if(array.size(barArray) > 10)
  376. currentBar = array.get(barArray, array.size(barArray)-1)
  377. lastBar = array.get(barArray, array.size(barArray)-2)
  378. currentPrice = matrix.get(valueMatrix, matrix.rows(valueMatrix)-1, 0)
  379. lastPrice = matrix.get(valueMatrix, matrix.rows(valueMatrix)-2, 0)
  380. llastPrice = matrix.get(valueMatrix, matrix.rows(valueMatrix)-3, 0)
  381. startRow = 2
  382. var statsTable = showTable ? table.new(position=position.top_right, columns=10, rows=64+startRow, border_color = color.black, border_width = 2) : na
  383.  
  384. phSortIndices = array.sort_indices(matrix.col(pivotHighStats, 2), order.descending)
  385.  
  386. phColStart = currentDir > 0 ? 0 : 5
  387.  
  388. if(showTable)
  389. table.clear(statsTable, 0, 0, 9, 64+startRow-1)
  390. table.cell(statsTable, phColStart, 0, 'Pivot High Projection', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
  391. table.cell(statsTable, phColStart, 1, 'Last Two Pivots', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
  392. table.cell(statsTable, phColStart+2, 1, 'HH', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
  393. table.cell(statsTable, phColStart+3, 1, 'LH', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
  394. table.cell(statsTable, phColStart+4, 1, 'T', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
  395. table.merge_cells(statsTable, phColStart, 0, phColStart+4, 0)
  396. table.merge_cells(statsTable, phColStart, 1, phColStart+1, 1)
  397.  
  398. hlr = startRow
  399. for i=0 to 63
  400. si = array.get(phSortIndices, i)
  401. lastTrendIndex = int(si/8)
  402. llastTrendIndex = si%8
  403.  
  404. lastPivotStatus = getStatus(lastTrendIndex, -1)
  405. llastPivotStatus = getStatus(llastTrendIndex, 1)
  406. hhStats = matrix.get(pivotHighStats, si, 0)
  407. lhStats = matrix.get(pivotHighStats, si, 1)
  408. tStats = matrix.get(pivotHighStats, si, 2)
  409.  
  410. hhRatio = math.round(matrix.get(pivotHighRatios, si, 0)/hhStats, 3)
  411. lhRatio = math.round(matrix.get(pivotHighRatios, si, 1)/lhStats, 3)
  412. tRatio = math.round(matrix.get(pivotHighRatios, si, 2)/tStats, 3)
  413.  
  414. hhBars = math.round(matrix.get(pivotHighBars, si, 0)/hhStats)
  415. lhBars = math.round(matrix.get(pivotHighBars, si, 1)/lhStats)
  416. tBars = math.round(matrix.get(pivotHighBars, si, 2)/tStats)
  417. highlight = math.sign(currentDir) < 0 ? nextTotalTrendIndex == si : currentTotalTrendIndex == si
  418.  
  419. hhTooltip = 'Average Ratio - '+str.tostring(hhRatio)+'\n'+'Average Bars - '+str.tostring(hhBars)
  420. lhTooltip = 'Average Ratio - '+str.tostring(lhRatio)+'\n'+'Average Bars - '+str.tostring(lhBars)
  421. tTooltip = 'Average Ratio - '+str.tostring(tRatio)+'\n'+'Average Bars - '+str.tostring(tBars)
  422.  
  423. if(highlight)
  424. var line hhLine = na
  425. var line lhLine = na
  426. var line tLine = na
  427. var label hhLabel = na
  428. var label lhLabel = na
  429. var label tLabel = na
  430.  
  431. line.delete(hhLine)
  432. line.delete(lhLine)
  433. line.delete(tLine)
  434. label.delete(hhLabel)
  435. label.delete(lhLabel)
  436. label.delete(tLabel)
  437.  
  438. x1 = math.sign(currentDir) < 0 ? currentBar : lastBar
  439. hhX2 = x1 + hhBars
  440. lhX2 = x1 + lhBars
  441. tX2 = x1 + tBars
  442.  
  443. y1 = math.sign(currentDir) < 0 ? currentPrice : lastPrice
  444. prev = math.sign(currentDir) < 0 ? lastPrice : llastPrice
  445. hhY2 = math.round_to_mintick(y1 + math.abs(y1-prev)*hhRatio)
  446. lhY2 = math.round_to_mintick(y1 + math.abs(y1-prev)*lhRatio)
  447. tY2 = math.round_to_mintick(y1 + math.abs(y1-prev)*tRatio)
  448. hhLine := line.new(x1, y1, hhX2, hhY2, xloc=xloc.bar_index, color=color.green, style=line.style_arrow_right)
  449. lhLine := line.new(x1, y1, lhX2, lhY2, xloc=xloc.bar_index, color=color.lime, style=line.style_arrow_right)
  450. tLine := line.new(x1, y1, tX2, tY2, xloc=xloc.bar_index, color=color.yellow, style=line.style_arrow_right)
  451.  
  452. hhPercent = str.tostring(hhStats*100/tStats, format.percent)
  453. lhPercent = str.tostring(lhStats*100/tStats, format.percent)
  454. hhText = 'Number of Historical References :'+str.tostring(hhStats)+'/'+str.tostring(tStats)+
  455. '\nProbability of Higher High :'+hhPercent+
  456. '\nAverage Higher High Ratio :'+str.tostring(hhRatio) +
  457. '\nAverage Higher High Bars :'+str.tostring(hhBars)
  458. lhText = 'Number of Historical References :'+str.tostring(lhStats)+'/'+str.tostring(tStats)+
  459. '\nProbability of Lower High :'+lhPercent+
  460. '\nAverage Lower High Ratio :'+str.tostring(lhRatio) +
  461. '\nAverage Lower High Bars :'+str.tostring(lhBars)
  462. tText = 'Number of Historical References :'+str.tostring(tStats)+
  463. '\nAverage Fib Ratio :'+str.tostring(tRatio)+
  464. '\nAverage Bars :'+str.tostring(tBars)
  465. hhLabel := label.new(hhX2, hhY2, str.tostring(hhY2)+ ' - ' +hhPercent, style=label.style_label_lower_left, color=color.new(color.green, 70), textcolor = color.white, size=size.small, tooltip=hhText)
  466. lhLabel := label.new(lhX2, lhY2, str.tostring(lhY2)+ ' - ' +lhPercent, style=label.style_label_upper_left, color=color.new(color.lime, 70), textcolor = color.white, size=size.small, tooltip=lhText)
  467. tLabel := label.new(tX2, tY2, str.tostring(tY2)+ '@'+str.tostring(tRatio), style=label.style_label_left, color=color.new(color.yellow, 70), textcolor = color.white, size=size.small, tooltip=tText)
  468. hhValue := hhY2
  469. lhValue := lhY2
  470. hhProbability := hhStats*100/tStats
  471. htRatio := tRatio
  472.  
  473. if(hhStats != 0 and lhStats != 0) and showTable
  474. table.cell(statsTable, phColStart, hlr, llastPivotStatus, text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.lime, 60))
  475. table.cell(statsTable, phColStart+1, hlr, lastPivotStatus, text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.orange, 60))
  476. table.cell(statsTable, phColStart+2, hlr, str.tostring(hhStats)+' - '+str.tostring(hhRatio), text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.green, highlight ? 50 : 90), tooltip = hhTooltip)
  477. table.cell(statsTable, phColStart+3, hlr, str.tostring(lhStats)+' - '+str.tostring(lhRatio), text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.red, highlight? 50 : 90), tooltip = lhTooltip)
  478. table.cell(statsTable, phColStart+4, hlr, str.tostring(tStats)+' - '+str.tostring(tRatio), text_color = txtColor, text_size = txtSize, bgcolor = color.from_gradient(hhStats/tStats, 0, 1, color.red, color.green), tooltip = tTooltip)
  479. hlr+=1
  480.  
  481.  
  482. plColStart = currentDir < 0 ? 0 : 5
  483. if(showTable)
  484. table.cell(statsTable, plColStart, 0, 'Pivot Low Projection', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
  485. table.cell(statsTable, plColStart, 1, 'Last Two Pivots', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
  486. table.cell(statsTable, plColStart+2, 1, 'LL', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
  487. table.cell(statsTable, plColStart+3, 1, 'HL', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
  488. table.cell(statsTable, plColStart+4, 1, 'T', text_color = txtColor, text_size = txtSize, bgcolor = color.maroon)
  489. table.merge_cells(statsTable, plColStart, 0, plColStart+4, 0)
  490. table.merge_cells(statsTable, plColStart, 1, plColStart+1, 1)
  491. plSortIndices = array.sort_indices(matrix.col(pivotLowStats, 2), order.descending)
  492.  
  493. llr = startRow
  494. for i=0 to 63
  495. si = array.get(plSortIndices, i)
  496. lastTrendIndex = int(si/8)
  497. llastTrendIndex = si%8
  498.  
  499. lastPivotStatus = getStatus(lastTrendIndex, 1)
  500. llastPivotStatus = getStatus(llastTrendIndex, -1)
  501. llStats = matrix.get(pivotLowStats, si, 0)
  502. hlStats = matrix.get(pivotLowStats, si, 1)
  503. tStats = matrix.get(pivotLowStats, si, 2)
  504.  
  505. llRatio = math.round(matrix.get(pivotLowRatios, si, 0)/llStats, 3)
  506. hlRatio = math.round(matrix.get(pivotLowRatios, si, 1)/hlStats, 3)
  507. tRatio = math.round(matrix.get(pivotLowRatios, si, 2)/tStats, 3)
  508.  
  509. llBars = math.round(matrix.get(pivotLowBars, si, 0)/llStats)
  510. hlBars = math.round(matrix.get(pivotLowBars, si, 1)/hlStats)
  511. tBars = math.round(matrix.get(pivotLowBars, si, 2)/tStats)
  512.  
  513. highlight = math.sign(currentDir) > 0 ? nextTotalTrendIndex== si : currentTotalTrendIndex == si
  514.  
  515. llTooltip = 'Average Ratio - '+str.tostring(llRatio)+'\n'+'Average Bars - '+str.tostring(llBars)
  516. hlTooltip = 'Average Ratio - '+str.tostring(hlRatio)+'\n'+'Average Bars - '+str.tostring(hlBars)
  517. tTooltip = 'Average Ratio - '+str.tostring(tRatio)+'\n'+'Average Bars - '+str.tostring(tBars)
  518.  
  519. if(highlight)
  520. var line llLine = na
  521. var line hlLine = na
  522. var line tLine = na
  523.  
  524. var label llLabel = na
  525. var label hlLabel = na
  526. var label tLabel = na
  527.  
  528. line.delete(llLine)
  529. line.delete(hlLine)
  530. line.delete(tLine)
  531.  
  532. label.delete(llLabel)
  533. label.delete(hlLabel)
  534. label.delete(tLabel)
  535.  
  536. x1 = math.sign(currentDir) > 0 ? currentBar : lastBar
  537. llX2 = x1 + llBars
  538. hlX2 = x1 + hlBars
  539. tX2 = x1 + tBars
  540.  
  541. y1 = math.sign(currentDir) > 0 ? currentPrice : lastPrice
  542. prev = math.sign(currentDir) > 0 ? lastPrice : llastPrice
  543. llY2 = math.round_to_mintick(y1 - math.abs(y1-prev)*llRatio)
  544. hlY2 = math.round_to_mintick(y1 - math.abs(y1-prev)*hlRatio)
  545. tY2 = math.round_to_mintick(y1 - math.abs(y1-prev)*tRatio)
  546. llLine := line.new(x1, y1, llX2, llY2, xloc=xloc.bar_index, color=color.red, style=line.style_arrow_right)
  547. hlLine := line.new(x1, y1, hlX2, hlY2, xloc=xloc.bar_index, color=color.orange, style=line.style_arrow_right)
  548. tLine := line.new(x1, y1, tX2, tY2, xloc=xloc.bar_index, color=color.yellow, style=line.style_arrow_right)
  549.  
  550. llPercent = str.tostring(llStats*100/tStats, format.percent)
  551. hlPercent = str.tostring(hlStats*100/tStats, format.percent)
  552. llText = 'Number of Historical References :'+str.tostring(llStats)+'/'+str.tostring(tStats)+
  553. '\nProbability of Lower Low :'+llPercent+
  554. '\nAverage Lower Low Ratio :'+str.tostring(llRatio) +
  555. '\nAverage Lower Low Bars :'+str.tostring(llBars)
  556. hlText = 'Number of Historical References :'+str.tostring(hlStats)+'/'+str.tostring(tStats)+
  557. '\nProbability of Higher Low :'+hlPercent+
  558. '\nAverage Higher Low Ratio :'+str.tostring(hlRatio) +
  559. '\nAverage Higher Low Bars :'+str.tostring(hlBars)
  560. tText = 'Number of Historical References :'+str.tostring(tStats)+
  561. '\nAverage Fib Ratio :'+str.tostring(tRatio)+
  562. '\nAverage Bars :'+str.tostring(tBars)
  563. llLabel := label.new(llX2, llY2, str.tostring(llY2)+ ' - ' +llPercent, style=label.style_label_upper_left, color=color.new(color.red, 70), textcolor = color.white, size=size.small, tooltip=llText)
  564. hlLabel := label.new(hlX2, hlY2, str.tostring(hlY2)+ ' - ' +hlPercent, style=label.style_label_lower_left, color=color.new(color.orange, 70), textcolor = color.white, size=size.small, tooltip=hlText)
  565. tLabel := label.new(tX2, tY2, str.tostring(tY2)+ '@'+str.tostring(tRatio), style=label.style_label_left, color=color.new(color.yellow, 70), textcolor = color.white, size=size.small, tooltip=tText)
  566. llValue := llY2
  567. hlValue := hlY2
  568. llProbability := llStats*100/tStats
  569. ltRatio := tRatio
  570.  
  571. if(llStats != 0 and hlStats != 0) and showTable
  572. table.cell(statsTable, plColStart, llr, llastPivotStatus, text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.orange, 60))
  573. table.cell(statsTable, plColStart+1, llr, lastPivotStatus, text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.lime, 60))
  574. table.cell(statsTable, plColStart+2, llr, str.tostring(llStats)+' - '+str.tostring(llRatio), text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.red, highlight? 50 : 90), tooltip=llTooltip)
  575. table.cell(statsTable, plColStart+3, llr, str.tostring(hlStats)+' - '+str.tostring(hlRatio), text_color = txtColor, text_size = txtSize, bgcolor = color.new(color.green, highlight? 50 : 90), tooltip = hlTooltip)
  576. table.cell(statsTable, plColStart+4, llr, str.tostring(tStats)+' - '+str.tostring(tRatio), text_color = txtColor, text_size = txtSize, bgcolor = color.from_gradient(llStats/tStats, 0, 1, color.green, color.red), tooltip = tTooltip)
  577. llr+=1
  578.  
  579.  
  580. if showPivotLines
  581. draw(valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, trendArray, newZG, doubleZG)
  582.  
  583. plot(drawSupertrend? supertrend:na, color=supertrendDir>0? color.green:color.red, style=plot.style_linebr)
  584.  
  585.  
  586. hhp = plot(hhValue, 'Higher High Range', color.new(color.green, 100), 1)
  587. lhp = plot(lhValue, 'Lower High Range', color.new(color.lime, 100), 1)
  588. llp = plot(llValue, 'Lower Low Range', color.new(color.red, 100), 1)
  589. hlp = plot(hlValue, 'Higher Low Range', color.new(color.orange, 100), 1)
  590.  
  591. fill(hhp, lhp, color=color.new(hhProbability > 50 ? color.green : hhProbability < 50? color.red : color.silver, 90))
  592. fill(llp, hlp, color=color.new(llProbability > 50 ? color.red : llProbability < 50? color.green : color.silver, 90))
  593.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement