Advertisement
sdxhex

Untitled

Jun 8th, 2023
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 26.96 KB | None | 0 0
  1. //@version=5
  2. strategy("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.  
  103. 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.
  104. 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.
  105. upper = hma(ta.rma(ema_result + (ob_dev*std_dev),3),10) // Returns the upper OB line on the chart.
  106. lower = hma(ta.rma(ema_result + (os_dev*std_dev),3),10) // Returns the upper OS line on the chart.
  107.  
  108. // ~~ Plot Upper OB and Lower OS lines on the chart {
  109. plot(obosbands?upper:na, "Upper OB", color=ema_ob_col)
  110. plot(obosbands?lower:na, "Lower OS", color=ema_os_col)
  111. plot(obosbands?upper - ta.stdev(upper,2):na, "Upper OB", color=ema_ob_col)
  112. plot(obosbands?lower + ta.stdev(lower,2):na, "Lower OS", color=ema_os_col)
  113. //~~~}
  114. //~~~~~~}
  115.  
  116. // ~~ Calculate fib 50% from OB to 50 level and OS to 50 level {
  117. fib(src)=>
  118. fib = ema_result + (src-ema_result)*0.5
  119.  
  120. // ~~ Plot the Fib lines on the chart {
  121. plot(fibbands?fib(upper):na, "Upper Fib 50%", color=ema_fib_col)
  122. plot(fibbands?fib(lower):na, "Lower Fib 50%", color=ema_fib_col)
  123. //~~~}
  124. //~~~~~~}
  125.  
  126. // ~~ Validity Checks {
  127. // ~~ Store crossover values to check Validity {
  128. // ~~ Optimal EMA Length {
  129. emavalue = 2*rsiperiod-1
  130. ema = ta.ema(close,emavalue)
  131. //~~~}
  132. var occurrence = 0
  133. var non_occurrence = 0
  134. if (ta.crossover(rsi,50) and ta.crossover(close,ema)) or (ta.crossunder(rsi,50) and ta.crossunder(close,ema))
  135. occurrence += 1
  136. if (ta.crossover(rsi,50) and not ta.crossover(close,ema)) or (ta.crossunder(rsi,50) and not ta.crossunder(close,ema))
  137. non_occurrence += 1
  138. //~~~~~~}
  139.  
  140. // ~~ Precentage Check {
  141. //The resulting value tells you how many occurrences there are relative to the total number of events, expressed as a percentage.
  142. percent = ((math.abs(occurrence)/(occurrence + non_occurrence) * 100))
  143. //~~~}
  144.  
  145. // ~~ Inputs to Table {
  146. // ~~ Trend Direction {
  147. dir = rsi>50?true:false
  148. sign = dir == true?" > 50 ":" < 50"
  149. trend = dir == true?"Bullish":"Bearish"
  150. col = dir == true?postrend:negtrend
  151. //~~~}
  152.  
  153. // ~~ Overbought & Oversold {
  154. ob_ = rsi>ob ?true:false
  155. os_ = rsi<os?true:false
  156. obos_sign = ob_? " > " + str.tostring(ob):os_? " < " + str.tostring(os):""
  157. obos_text = ob_? "Overbought":os_? "Oversold":""
  158. obos_col = ob_?ob_col:os_?os_col:color.white
  159. //~~~}
  160. //~~~~~~}
  161.  
  162. // ~~ Table {
  163. tbl = table.new(pos, 2, 11, frame_color=chart.bg_color, frame_width=2, border_width=2, border_color=chart.bg_color)
  164. if barstate.islast and showTable
  165. tbl.cell(0, 0, text="RSI Value", text_color=textcolor, bgcolor=bgcolor, text_size=TblSize)
  166. tbl.cell(0, 1, text=str.tostring(rsiperiod), text_halign=text.align_center, bgcolor=bgcolor, text_color=textcolor, text_size=TblSize)
  167. tbl.cell(1, 0, text="EMA Value", text_color=textcolor, bgcolor=bgcolor, text_size=TblSize)
  168. tbl.cell(1, 1, text=str.tostring(emavalue), text_halign=text.align_center, bgcolor=bgcolor, text_color=textcolor, text_size=TblSize)
  169. tbl.cell(0, 2, text="RSI" + sign + "", text_color=textcolor, bgcolor=bgcolor, text_size=TblSize)
  170. tbl.cell(1, 2, text=trend, text_halign=text.align_center, bgcolor=col, text_color=textcolor, text_size=TblSize)
  171. if (ob_) or (os_)
  172. tbl.cell(0, 3, text="RSI" + obos_sign + "", text_color=textcolor, bgcolor=bgcolor, text_size=TblSize)
  173. tbl.cell(1, 3, text=obos_text, text_halign=text.align_center, bgcolor=obos_col, text_color=textcolor, text_size=TblSize)
  174. if validity_check
  175. tbl.cell(0, 4, text="Validity Check", text_color=textcolor, bgcolor=bgcolor, text_size=TblSize)
  176. 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)
  177. tbl.cell(0, 5, text="RSI Stdev", text_color=textcolor, bgcolor=bgcolor, text_size=TblSize)
  178. 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)
  179.  
  180.  
  181. // ~~ Labels {
  182. labelfunc(bool_,n, line_, text_, label_col, text_col, size_)=>
  183. label l = bool_?label.new(bar_index + n,line_,text=text_,color=label_col,
  184. style=label.style_label_left,textcolor=text_col,size=size_,
  185. textalign=text.align_left):na
  186. label.delete(l[1])
  187.  
  188. labelfunc(labels,5, ema_result, "RSI 50" , color.blue, color.white, size.small)
  189. labelfunc(labels,5, upper, "RSI " + str.tostring(ob) , color.green, color.white, size.small)
  190. labelfunc(labels,5, lower, "RSI " + str.tostring(os) , color.red, color.white, size.small)
  191. labelfunc(fibbands and labels,1, fib(upper), "FIB 50 %" , color.blue, color.white, size.tiny)
  192. labelfunc(fibbands and labels,1, fib(lower), "FIB 50 %" , color.blue, color.white, size.tiny)
  193. //~~~}
  194.  
  195.  
  196.  
  197.  
  198. increment(mtx, row, col, val=1)=>matrix.set(mtx, row, col, matrix.get(mtx, row, col)+val)
  199. gettrendindex(int price, int osc, int trend)=>
  200. trendFactor = trend > 0 ? 0 : 1
  201. priceFactor = math.abs(price) > 1? 1 : 0
  202. oscFactor = math.abs(osc) > 1? 1 : 0
  203. trendFactor*4 + priceFactor*2 + oscFactor
  204.  
  205.  
  206. getSentimentDetails(pDir, oDir, sDir) =>
  207. 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)
  208. sentimentSymbol = sentiment == 4 ? '⬆' : sentiment == -4 ? '⬇' : sentiment == 3 ? '↗' : sentiment == -3 ? '↘' : sentiment == 2 ? '⤴' : sentiment == -2 ? '⤵' : sentiment == 1 ? '⤒' : sentiment == -1 ? '⤓' : '▣'
  209. 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
  210. sentimentLabel = math.abs(sentiment) == 4 ? 'C' : math.abs(sentiment) == 3 ? 'H' : math.abs(sentiment) == 2 ? 'D' : 'I'
  211. [sentimentSymbol, sentimentLabel, sentimentColor]
  212.  
  213.  
  214. getStatus(int trendIndex, int pivotDir)=>
  215. trendFactor = int(trendIndex/4)
  216. remainder = trendIndex % 4
  217. priceFactor = int(remainder/2)+1
  218. oscFactor = (remainder % 2)+1
  219. trendChar = (trendFactor == 0)? 'U' : 'D'
  220. priceChar = pivotDir > 0? (priceFactor == 2? 'HH' : 'LH') : (priceFactor == 2? 'LL' : 'HL')
  221. oscChar = pivotDir > 0? (oscFactor == 2? 'HH' : 'LH') : (oscFactor == 2? 'LL' : 'HL')
  222. trendChar + ' - ' + priceChar + '/'+oscChar
  223.  
  224. draw_zg_line(idx1, idx2, zigzaglines, zigzaglabels, valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix,
  225. barArray, trendArray, lineColor, lineWidth, lineStyle) =>
  226. if matrix.rows(valueMatrix) > 2
  227. idxLen1 = matrix.rows(valueMatrix)-idx1
  228. idxLen2 = matrix.rows(valueMatrix)-idx2
  229. lastValues = matrix.row(valueMatrix, idxLen1)
  230. llastValues = matrix.row(valueMatrix, idxLen2)
  231.  
  232. lastDirections = matrix.row(directionMatrix, idxLen1)
  233. lastRatios = matrix.row(ratioMatrix, idxLen1)
  234. lastDivergence = matrix.row(divergenceMatrix, idxLen1)
  235. lastDoubleDivergence = matrix.row(doubleDivergenceMatrix, idxLen1)
  236.  
  237. y1 = array.get(lastValues, 0)
  238. y2 = array.get(llastValues, 0)
  239. x1 = array.get(barArray, idxLen1)
  240. x2 = array.get(barArray, idxLen2)
  241. zline = line.new(x1=x1, y1=y1, x2=x2, y2=y2, color=lineColor, width=lineWidth, style=lineStyle)
  242. currentDir = y1 > y2? 1 : -1
  243.  
  244. priceDir = array.get(lastDirections, 0)
  245. oscDir = array.get(lastDirections, 1)
  246. trendDir = array.get(trendArray, idxLen1)
  247. trendIndex = gettrendindex(priceDir, oscDir, trendDir)
  248. trendLabel = getStatus(trendIndex, currentDir)
  249. [sentimentSymbol, sentimentLabel, sentimentColor] = getSentimentDetails(priceDir, oscDir, trendDir)
  250.  
  251. labelStyle = currentDir > 0? label.style_label_down : label.style_label_up
  252. zlabel = showPivotLabel ? label.new(x=x1, y=y1, yloc=yloc.price, color=sentimentColor, style=labelStyle, text=sentimentSymbol + ' ' + trendLabel,
  253. textcolor=color.black, size = size.small, tooltip=sentimentLabel) : na
  254. if array.size(zigzaglines) > 0
  255. lastLine = array.get(zigzaglines, array.size(zigzaglines)-1)
  256. if line.get_x2(lastLine) == x2 and line.get_x1(lastLine) <= x1
  257. pa.pop(zigzaglines)
  258. pa.pop(zigzaglabels)
  259.  
  260. pa.push(zigzaglines, zline, 500)
  261. pa.push(zigzaglabels, zlabel, 500)
  262.  
  263. draw(matrix<float> valueMatrix, matrix<int> directionMatrix, matrix<float> ratioMatrix, matrix<int> divergenceMatrix, matrix<int> doubleDivergenceMatrix, array<int> barArray, array<int> trendArray,
  264. bool newZG, bool doubleZG, color lineColor = color.blue, int lineWidth = 1, string lineStyle = line.style_solid)=>
  265. var zigzaglines = array.new_line(0)
  266. var zigzaglabels = array.new_label(0)
  267. if(newZG)
  268. if doubleZG
  269. draw_zg_line(2, 3, zigzaglines, zigzaglabels, valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, trendArray,
  270. lineColor, lineWidth, lineStyle)
  271.  
  272. if matrix.rows(valueMatrix) >= 2
  273. draw_zg_line(1, 2, zigzaglines, zigzaglabels, valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, trendArray,
  274. lineColor, lineWidth, lineStyle)
  275. [valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, zigzaglines, zigzaglabels]
  276.  
  277.  
  278.  
  279. indicatorHigh = array.new_float()
  280. indicatorLow = array.new_float()
  281. indicatorLabels = array.new_string()
  282.  
  283. [oscHigh, _, _] = eta.oscillator(oscillatorType, oscLength, oscLength, oscLength, high)
  284. [oscLow, _, _] = eta.oscillator(oscillatorType, oscLength, oscLength, oscLength, low)
  285. array.push(indicatorHigh, math.round(oscHigh,2))
  286. array.push(indicatorLow, math.round(oscLow,2))
  287. array.push(indicatorLabels, oscillatorType+str.tostring(oscLength))
  288.  
  289.  
  290. [valueMatrix, directionMatrix, ratioMatrix, divergenceMatrix, doubleDivergenceMatrix, barArray, trendArray, supertrendDir, supertrend, newZG, doubleZG] =
  291. zg.calculate(length, array.from(high, low), indicatorHigh, indicatorLow, supertrendLength = supertrendLength)
  292.  
  293. nextDirection = matrix.rows(directionMatrix) > 0? matrix.row(directionMatrix, matrix.rows(directionMatrix)-1) : array.new_int()
  294. lastDirection = matrix.rows(directionMatrix) > 1? matrix.row(directionMatrix, matrix.rows(directionMatrix)-2) : array.new_int()
  295. llastDirection = matrix.rows(directionMatrix) > 2? matrix.row(directionMatrix, matrix.rows(directionMatrix)-3) : array.new_int()
  296. lllastDirection = matrix.rows(directionMatrix) > 3? matrix.row(directionMatrix, matrix.rows(directionMatrix)-4) : array.new_int()
  297.  
  298. var pivotHighStats = matrix.new<int>(64, 3, 0)
  299. var pivotLowStats = matrix.new<int>(64, 3, 0)
  300.  
  301. var pivotHighRatios = matrix.new<float>(64, 3, 0)
  302. var pivotLowRatios = matrix.new<float>(64, 3, 0)
  303.  
  304. var pivotHighBars = matrix.new<float>(64, 3, 0)
  305. var pivotLowBars = matrix.new<float>(64, 3, 0)
  306.  
  307. currentTotalTrendIndex = 0
  308. nextTotalTrendIndex = 0
  309. currentDir = matrix.rows(directionMatrix) > 0? matrix.get(directionMatrix, matrix.rows(directionMatrix)-1, 0) : 0
  310.  
  311. currentPDir = lastDirection.size() > 0 ? lastDirection.first() : na
  312. changePriceDirection = ta.change(math.sign(currentPDir))
  313. if(array.size(lllastDirection) > 0)
  314. priceDirection = array.get(lastDirection, 0)
  315. priceRatio = matrix.get(ratioMatrix, matrix.rows(ratioMatrix)-2, 0)
  316.  
  317. numberOfBars = array.get(barArray, array.size(barArray)-2) - array.get(barArray, array.size(barArray)-3)
  318. currentPriceDirection = array.get(lastDirection, 0)
  319. currentOscDirection = array.get(lastDirection, 1)
  320. currentTrend = array.get(trendArray, array.size(trendArray)-2)
  321.  
  322. nextPriceDirection = array.get(nextDirection, 0)
  323. nextOscDirection = array.get(nextDirection, 1)
  324. nextTrend = array.get(trendArray, array.size(trendArray)-1)
  325.  
  326. lastPriceDirection = array.get(llastDirection, 0)
  327. lastOscDirection = array.get(llastDirection, 1)
  328. lastTrend = array.get(trendArray, array.size(trendArray)-3)
  329.  
  330. llastPriceDirection = array.get(lllastDirection, 0)
  331. llastOscDirection = array.get(lllastDirection, 1)
  332. llastTrend = array.get(trendArray, array.size(trendArray)-4)
  333.  
  334. colLast = math.abs(priceDirection) %2
  335.  
  336. nextTrendIndex = gettrendindex(nextPriceDirection, nextOscDirection, nextTrend)
  337. currentTrendIndex = gettrendindex(currentPriceDirection, currentOscDirection, currentTrend)
  338. lastTrendIndex = gettrendindex(lastPriceDirection, lastOscDirection, lastTrend)
  339. llastTrendIndex = gettrendindex(llastPriceDirection, llastOscDirection, llastTrend)
  340.  
  341. totalIndex = lastTrendIndex*8 + llastTrendIndex
  342. currentTotalTrendIndex := currentTrendIndex*8 + lastTrendIndex
  343. nextTotalTrendIndex := nextTrendIndex*8 + currentTrendIndex
  344.  
  345. matrixToSet = math.sign(priceDirection) > 0? pivotHighStats : pivotLowStats
  346. ratioMatrixToSet = math.sign(priceDirection) > 0? pivotHighRatios : pivotLowRatios
  347. barMatrixToSet = math.sign(priceDirection) > 0? pivotHighBars : pivotLowBars
  348.  
  349. if(not na(currentPDir) and changePriceDirection)
  350. increment(matrixToSet, totalIndex, colLast)
  351. increment(ratioMatrixToSet, totalIndex, colLast, priceRatio)
  352. increment(barMatrixToSet, totalIndex, colLast, numberOfBars)
  353.  
  354. increment(matrixToSet, totalIndex, 2)
  355. increment(ratioMatrixToSet, totalIndex, 2, priceRatio)
  356. increment(barMatrixToSet, totalIndex, 2, numberOfBars)
  357.  
  358.  
  359. var float hhValue = na
  360. var float lhValue = na
  361.  
  362. var float llValue = na
  363. var float hlValue = na
  364.  
  365. var float hhProbability = na
  366. var float llProbability = na
  367.  
  368. var float htRatio = na
  369. var float ltRatio = na
  370. if(array.size(barArray) > 10)
  371. currentBar = array.get(barArray, array.size(barArray)-1)
  372. lastBar = array.get(barArray, array.size(barArray)-2)
  373. currentPrice = matrix.get(valueMatrix, matrix.rows(valueMatrix)-1, 0)
  374. lastPrice = matrix.get(valueMatrix, matrix.rows(valueMatrix)-2, 0)
  375. llastPrice = matrix.get(valueMatrix, matrix.rows(valueMatrix)-3, 0)
  376. startRow = 2
  377. var statsTable = showTable ? table.new(position=position.top_right, columns=10, rows=64+startRow, border_color = color.black, border_width = 2) : na
  378.  
  379. phSortIndices = array.sort_indices(matrix.col(pivotHighStats, 2), order.descending)
  380.  
  381. phColStart = currentDir > 0 ? 0 : 5
  382.  
  383. hlr = startRow
  384. for i=0 to 63
  385. si = array.get(phSortIndices, i)
  386. lastTrendIndex = int(si/8)
  387. llastTrendIndex = si%8
  388.  
  389. lastPivotStatus = getStatus(lastTrendIndex, -1)
  390. llastPivotStatus = getStatus(llastTrendIndex, 1)
  391. hhStats = matrix.get(pivotHighStats, si, 0)
  392. lhStats = matrix.get(pivotHighStats, si, 1)
  393. tStats = matrix.get(pivotHighStats, si, 2)
  394.  
  395. hhRatio = math.round(matrix.get(pivotHighRatios, si, 0)/hhStats, 3)
  396. lhRatio = math.round(matrix.get(pivotHighRatios, si, 1)/lhStats, 3)
  397. tRatio = math.round(matrix.get(pivotHighRatios, si, 2)/tStats, 3)
  398.  
  399. hhBars = math.round(matrix.get(pivotHighBars, si, 0)/hhStats)
  400. lhBars = math.round(matrix.get(pivotHighBars, si, 1)/lhStats)
  401. tBars = math.round(matrix.get(pivotHighBars, si, 2)/tStats)
  402. highlight = math.sign(currentDir) < 0 ? nextTotalTrendIndex == si : currentTotalTrendIndex == si
  403.  
  404. hhTooltip = 'Average Ratio - '+str.tostring(hhRatio)+'\n'+'Average Bars - '+str.tostring(hhBars)
  405. lhTooltip = 'Average Ratio - '+str.tostring(lhRatio)+'\n'+'Average Bars - '+str.tostring(lhBars)
  406. tTooltip = 'Average Ratio - '+str.tostring(tRatio)+'\n'+'Average Bars - '+str.tostring(tBars)
  407.  
  408. if(highlight)
  409. var line hhLine = na
  410. var line lhLine = na
  411. var line tLine = na
  412. var label hhLabel = na
  413. var label lhLabel = na
  414. var label tLabel = na
  415.  
  416. line.delete(hhLine)
  417. line.delete(lhLine)
  418. line.delete(tLine)
  419. label.delete(hhLabel)
  420. label.delete(lhLabel)
  421. label.delete(tLabel)
  422.  
  423. x1 = math.sign(currentDir) < 0 ? currentBar : lastBar
  424. hhX2 = x1 + hhBars
  425. lhX2 = x1 + lhBars
  426. tX2 = x1 + tBars
  427.  
  428. y1 = math.sign(currentDir) < 0 ? currentPrice : lastPrice
  429. prev = math.sign(currentDir) < 0 ? lastPrice : llastPrice
  430. hhY2 = math.round_to_mintick(y1 + math.abs(y1-prev)*hhRatio)
  431. lhY2 = math.round_to_mintick(y1 + math.abs(y1-prev)*lhRatio)
  432. tY2 = math.round_to_mintick(y1 + math.abs(y1-prev)*tRatio)
  433. hhLine := line.new(x1, y1, hhX2, hhY2, xloc=xloc.bar_index, color=color.green, style=line.style_arrow_right)
  434. lhLine := line.new(x1, y1, lhX2, lhY2, xloc=xloc.bar_index, color=color.lime, style=line.style_arrow_right)
  435. tLine := line.new(x1, y1, tX2, tY2, xloc=xloc.bar_index, color=color.yellow, style=line.style_arrow_right)
  436.  
  437. hhPercent = str.tostring(hhStats*100/tStats, format.percent)
  438. lhPercent = str.tostring(lhStats*100/tStats, format.percent)
  439. hhText = 'Number of Historical References :'+str.tostring(hhStats)+'/'+str.tostring(tStats)+
  440. '\nProbability of Higher High :'+hhPercent+
  441. '\nAverage Higher High Ratio :'+str.tostring(hhRatio) +
  442. '\nAverage Higher High Bars :'+str.tostring(hhBars)
  443. lhText = 'Number of Historical References :'+str.tostring(lhStats)+'/'+str.tostring(tStats)+
  444. '\nProbability of Lower High :'+lhPercent+
  445. '\nAverage Lower High Ratio :'+str.tostring(lhRatio) +
  446. '\nAverage Lower High Bars :'+str.tostring(lhBars)
  447. tText = 'Number of Historical References :'+str.tostring(tStats)+
  448. '\nAverage Fib Ratio :'+str.tostring(tRatio)+
  449. '\nAverage Bars :'+str.tostring(tBars)
  450. 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)
  451. 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)
  452. 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)
  453. hhValue := hhY2
  454. lhValue := lhY2
  455. hhProbability := hhStats*100/tStats
  456. htRatio := tRatio
  457.  
  458.  
  459. plColStart = currentDir < 0 ? 0 : 5
  460.  
  461. llr = startRow
  462. for i=0 to 63
  463. si = array.get(plSortIndices, i)
  464. lastTrendIndex = int(si/8)
  465. llastTrendIndex = si%8
  466.  
  467. lastPivotStatus = getStatus(lastTrendIndex, 1)
  468. llastPivotStatus = getStatus(llastTrendIndex, -1)
  469. llStats = matrix.get(pivotLowStats, si, 0)
  470. hlStats = matrix.get(pivotLowStats, si, 1)
  471. tStats = matrix.get(pivotLowStats, si, 2)
  472.  
  473. llRatio = math.round(matrix.get(pivotLowRatios, si, 0)/llStats, 3)
  474. hlRatio = math.round(matrix.get(pivotLowRatios, si, 1)/hlStats, 3)
  475. tRatio = math.round(matrix.get(pivotLowRatios, si, 2)/tStats, 3)
  476.  
  477. llBars = math.round(matrix.get(pivotLowBars, si, 0)/llStats)
  478. hlBars = math.round(matrix.get(pivotLowBars, si, 1)/hlStats)
  479. tBars = math.round(matrix.get(pivotLowBars, si, 2)/tStats)
  480.  
  481. highlight = math.sign(currentDir) > 0 ? nextTotalTrendIndex== si : currentTotalTrendIndex == si
  482.  
  483. llTooltip = 'Average Ratio - '+str.tostring(llRatio)+'\n'+'Average Bars - '+str.tostring(llBars)
  484. hlTooltip = 'Average Ratio - '+str.tostring(hlRatio)+'\n'+'Average Bars - '+str.tostring(hlBars)
  485. tTooltip = 'Average Ratio - '+str.tostring(tRatio)+'\n'+'Average Bars - '+str.tostring(tBars)
  486.  
  487.  
  488.  
  489.  
  490.  
  491. fill(hhp, lhp, color=color.new(hhProbability > 50 ? color.green : hhProbability < 50? color.red : color.silver, 90))
  492. fill(llp, hlp, color=color.new(llProbability > 50 ? color.red : llProbability < 50? color.green : color.silver, 90))
  493.  
  494. longCondition = ta.crossover(hhProbability, 70) and ta.crossover(close, upper)
  495. if (longCondition)
  496. strategy.entry("Long", strategy.long)
  497.  
  498. shortCondition = ta.crossover(llProbability, 70) and ta.crossunder(close, lower)
  499. if (shortCondition)
  500. strategy.entry("Short", strategy.short)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement