Advertisement
xmd79

Trend Lines, Supports and Resistances

Jan 3rd, 2024
652
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.50 KB | None | 0 0
  1. // This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
  2. // © ismailcarlik
  3.  
  4. //@version=5
  5. indicator("Trend Lines, Supports and Resistances", shorttitle = "TSR", overlay = true, max_bars_back = 5000)
  6.  
  7. // ╔═════════════════════════════════════════════════════════════════════════════════════════════╗
  8. // ║ * * * I N P U T S * * * ║
  9. // ╚═════════════════════════════════════════════════════════════════════════════════════════════╝
  10.  
  11. grpPivotPoints = "Pivot Points ・ Common"
  12. pvtLength = input.int(20, title = "Pivot Length", minval = 1, group = grpPivotPoints)
  13. pvtMarkPivots = input.bool(false, title = "Mark Pivots", group = grpPivotPoints)
  14.  
  15. grpTrendLines = "Trend Lines"
  16. tlEnabled = input.bool(true, title = "Enabled", group = grpTrendLines)
  17. tlPointsToCheck = input.int(3, title = "Points to Check", minval = 2, group = grpTrendLines)
  18. tlMaxViolation = input.int(0, title = "Maximum Violation", minval = 0, group = grpTrendLines)
  19. tlExceptBars = input.int(3, title = "Excepted Last Bars", minval = 0, group = grpTrendLines)
  20. tlShowViolated = input.bool(false, title = "Show Violated Trend Lines", group = grpTrendLines)
  21. tlExtension = input.string("Right", title = "Line Extension", options = ["None", "Left", "Right", "Both"], group = grpTrendLines)
  22. tlShowLabels = input.bool(true, title = "Show Labels", group = grpTrendLines)
  23. tlAlertsEnabled = input.bool(true, title = "Alerts Enabled", inline = "tlAlerts", group = grpTrendLines)
  24. tlAlertrequency = input.string("Once Per Bar", title = " ・ Frequency", options = ["Once Per Bar", "Once Per Bar Close", "All"], inline = "tlAlerts", group = grpTrendLines, display = display.none)
  25.  
  26. grpSupportResistance = "Supports & Resistances"
  27. srEnabled = input.bool(true, title = "Enabled", group = grpSupportResistance)
  28. srPointsToCheck = input.int(3, title = "Points to Check", minval = 2, group = grpSupportResistance)
  29. srMaxViolation = input.int(0, title = "Maximum Violation Allowed", minval = 0, group = grpSupportResistance)
  30. srExceptBars = input.int(3, title = "Excepted Last Bars", minval = 0, group = grpSupportResistance)
  31. srShowLabels = input.bool(true, title = "Show Labels", group = grpSupportResistance)
  32. srAlertsEnabled = input.bool(true, title = "Alerts Enabled", inline = "srAlerts", group = grpSupportResistance)
  33. srAlertrequency = input.string("Once Per Bar", title = " ・ Frequency", options = ["Once Per Bar", "Once Per Bar Close", "All"], inline = "srAlerts", group = grpSupportResistance, display = display.none)
  34.  
  35. grpVisual = "Style"
  36. stlHighColor = input.color(color.blue, title = "High Color", inline = "colors", group = grpVisual)
  37. stlLowColor = input.color(color.red, title = "Low Color", inline = "colors", group = grpVisual)
  38. lineWidth = input.int(1, title = "Line Width", minval = 1, group = grpVisual)
  39.  
  40. // ╔═════════════════════════════════════════════════════════════════════════════════════════════╗
  41. // ║ * * * T Y P E S * * * ║
  42. // ╚═════════════════════════════════════════════════════════════════════════════════════════════╝
  43.  
  44. // @type Used to represent a point pair.
  45. // @field firstPoint First point of pair.
  46. // @field secondPoint Second point of pair.
  47. type pointPair
  48. chart.point firstPoint
  49. chart.point secondPoint
  50.  
  51. // @type Used to represent a trend line.
  52. // @field mainLine Main visible line of the trend.
  53. // @field extensionLine Extension line of the trend.
  54. // @field priceLabel Price label of the trend.
  55. // @field isViolated Violation status of the trend.
  56. type trendLine
  57. line mainLine
  58. line extensionLine = na
  59. label priceLabel = na
  60. bool isViolated = false
  61.  
  62. // @type Used to represent a support or resistance level.
  63. // @field levelBox Level box for support or resistance.
  64. // @field price Price level of the support or resistance.
  65. // @field priceLabel Price label of the support or resistance.
  66. type srLevel
  67. box levelBox
  68. float price
  69. label priceLabel = na
  70.  
  71. // ╔═════════════════════════════════════════════════════════════════════════════════════════════╗
  72. // ║ * * * V A R I A B L E S * * * ║
  73. // ╚═════════════════════════════════════════════════════════════════════════════════════════════╝
  74.  
  75. tlExtendMode = str.lower(array.get(str.split(tlExtension, ""), 0))
  76. tlAlertrequencyMode = switch tlAlertrequency
  77. "Once Per Bar" => alert.freq_once_per_bar
  78. "Once Per Bar Close" => alert.freq_once_per_bar_close
  79. "All" => alert.freq_all
  80. => alert.freq_once_per_bar
  81. srAlertrequencyMode = switch srAlertrequency
  82. "Once Per Bar" => alert.freq_once_per_bar
  83. "Once Per Bar Close" => alert.freq_once_per_bar_close
  84. "All" => alert.freq_all
  85. => alert.freq_once_per_bar
  86.  
  87. var array<chart.point> highPivots = array.new<chart.point>()
  88. var array<chart.point> lowPivots = array.new<chart.point>()
  89.  
  90. var array<trendLine> uptrends = array.new<trendLine>()
  91. var array<trendLine> downtrends = array.new<trendLine>()
  92.  
  93. var array<srLevel> supports = array.new<srLevel>()
  94. var array<srLevel> resistances = array.new<srLevel>()
  95.  
  96. // ╔═════════════════════════════════════════════════════════════════════════════════════════════╗
  97. // ║ * * * M E T H O D S * * * ║
  98. // ╚═════════════════════════════════════════════════════════════════════════════════════════════╝
  99.  
  100. // @function Returns reversed version of array.
  101. // @param id (chart.point[]) Array object.
  102. // @returns (chart.point[]) Reversed version of given array.
  103. method reversed(array<chart.point> id) =>
  104. array<chart.point> reversedArray = array.new<chart.point>()
  105. for [i, v] in id
  106. reversedArray.unshift(v)
  107. reversedArray
  108.  
  109. // @function Checks for the bars if highs above trend line price.
  110. // @param id (trendLine) Trend line object.
  111. // @param exceptBars (int) Count of last bars for exception.
  112. // @returns (int) Count of the bars above trend line price.
  113. method getHighsAbovePrice(trendLine id, int exceptBars) =>
  114. historyReference = bar_index - id.mainLine.get_x1()
  115. count = 0
  116. if exceptBars < historyReference
  117. for i = historyReference to exceptBars
  118. if high[i] > line.get_price(id.mainLine, bar_index - i)
  119. count += 1
  120. count
  121.  
  122. // @function Checks for the bars if lows below trend line price.
  123. // @param id (trendLine) Trend line object.
  124. // @param exceptBars (int) Count of last bars for exception.
  125. // @returns (int) Count of the bars below trend line price.
  126. method getLowsBelowPrice(trendLine id, int exceptBars) =>
  127. historyReference = bar_index - id.mainLine.get_x1()
  128. count = 0
  129. if exceptBars < historyReference
  130. for i = historyReference to exceptBars
  131. if low[i] < line.get_price(id.mainLine, bar_index - i)
  132. count += 1
  133. count
  134.  
  135. // @function Sets the trend lines status to violated.
  136. // @param id (trendLine) Trend line object.
  137. // @param trendColor (color) Color of the trend line.
  138. // @returns (void)
  139. method setViolated(trendLine id, color trendColor) =>
  140. id.isViolated := true
  141. line.delete(id.extensionLine)
  142. label.delete(id.priceLabel)
  143. line.set_style(id.mainLine, line.style_dotted)
  144. line.set_extend(id.mainLine, extend = tlExtendMode)
  145. line.set_color(id.mainLine, tlShowViolated ? color.new(trendColor, 50) : na)
  146.  
  147. // ╔═════════════════════════════════════════════════════════════════════════════════════════════╗
  148. // ║ * * * F U N C T I O N S * * * ║
  149. // ╚═════════════════════════════════════════════════════════════════════════════════════════════╝
  150.  
  151. // @function Compares two points and returns true if first one is higher.
  152. // @param firstPoint (chart.point) First point to compare.
  153. // @param secondPoint (chart.point) Second point to compare.
  154. // @returns (bool) Whether the first point is higher than the second.
  155. f_isHigher (chart.point firstPoint, chart.point secondPoint) =>
  156. firstPoint.price > secondPoint.price
  157.  
  158. // @function Compares two points and returns true if first one is lower.
  159. // @param firstPoint (chart.point) First point to compare.
  160. // @param secondPoint (chart.point) Second point to compare.
  161. // @returns (bool) Whether the first point is lower than the second.
  162. f_isLower (chart.point firstPoint, chart.point secondPoint) =>
  163. firstPoint.price < secondPoint.price
  164.  
  165. // @function Checks for violation of support level.
  166. // @param point (chart.point) Point of support level.
  167. // @param exceptBars (int) Count of last bars for exception.
  168. // @returns (int) Count of violations.
  169. f_checkSupportViolation (chart.point point, int exceptBars) =>
  170. historyReference = bar_index - point.index
  171. violationCount = 0
  172. if exceptBars < historyReference
  173. for i = historyReference to exceptBars
  174. if low[i] < point.price
  175. violationCount += 1
  176. violationCount
  177.  
  178. // @function Checks for violation of reistance level.
  179. // @param point (chart.point) Point of resistance level.
  180. // @param exceptBars (int) Count of last bars for exception.
  181. // @returns (int) Count of violations.
  182. f_checkResistanceViolation(chart.point point, int exceptBars) =>
  183. historyReference = bar_index - point.index
  184. violationCount = 0
  185. if exceptBars < historyReference
  186. for i = historyReference to exceptBars
  187. if high[i] > point.price
  188. violationCount += 1
  189. violationCount
  190.  
  191. // @function Draws support level to chart.
  192. // @param index (int) Bar index of support level.
  193. // @returns (void)
  194. f_drawSupport(int index) =>
  195. historyReference = bar_index - index
  196. lowValue = low[historyReference]
  197. boxColor = color.new(stlHighColor, 70)
  198. textColor = color.new(stlHighColor, 50)
  199. supportBox = box.new(left = index, top = math.min(open[historyReference], close[historyReference]), right = bar_index, bottom = lowValue, bgcolor = boxColor, border_color = boxColor)
  200. supportLabel = srShowLabels ? label.new(x = bar_index - int(historyReference / 2), y = lowValue, text = "Support : " + str.tostring(lowValue, format.mintick), style = label.style_label_up, color = color.new(boxColor, 100), textcolor = textColor) : na
  201. supports.push(srLevel.new(levelBox = supportBox, price = lowValue, priceLabel = supportLabel))
  202.  
  203. // @function Draws resistance level to chart.
  204. // @param index (int) Bar index of reistance level.
  205. // @returns (void)
  206. f_drawResistance(int index) =>
  207. historyReference = bar_index - index
  208. highValue = high[historyReference]
  209. boxColor = color.new(stlLowColor, 70)
  210. textColor = color.new(stlLowColor, 50)
  211. resistanceBox = box.new(left = index, top = highValue, right = bar_index, bottom = math.max(open[historyReference], close[historyReference]), bgcolor = boxColor, border_color = boxColor)
  212. resistanceLabel = srShowLabels ? label.new(x = bar_index - int(historyReference / 2), y = highValue, text = "Resistance : " + str.tostring(highValue, format.mintick), style = label.style_label_down, color = color.new(boxColor, 100), textcolor = textColor) : na
  213. resistances.push(srLevel.new(levelBox = resistanceBox, price = highValue, priceLabel = resistanceLabel))
  214.  
  215. // @function Gets all pair combinations of given point array.
  216. // @param srcArray (chart.point[]) Source array.
  217. // @returns (pointPair[]) Array of point pairs.
  218. f_getAllPairCombinations(array<chart.point> srcArray) =>
  219. int inputLength = array.size(srcArray)
  220. array<pointPair> pairs = array.new<pointPair>()
  221. for i = 0 to inputLength - 2 by 1
  222. for j = i + 1 to inputLength - 1 by 1
  223. pairs.push(pointPair.new(firstPoint = srcArray.get(i), secondPoint = srcArray.get(j)))
  224. pairs
  225.  
  226. // @function Draws an uptrend to chart.
  227. // @param start (chart.point) Starting point of trend line.
  228. // @param end (chart.point) Ending point of trend line.
  229. // @returns (void)
  230. f_drawUptrend(chart.point start, chart.point end) =>
  231. uExtension = tlExtendMode == "n" ? na : line.new(start, end, color = color.new(stlHighColor, 50), extend = tlExtendMode, style = line.style_dashed, width = lineWidth)
  232. uMain = line.new(start, end, color = stlHighColor, style = line.style_arrow_both, width = lineWidth)
  233. uPrice = line.get_price(uMain, bar_index)
  234. uLabel = tlShowLabels ? label.new(x = bar_index, y = uPrice, text = "Uptrend : " + str.tostring(uPrice, format.mintick), style = label.style_label_left, color = color.new(stlHighColor, 80), textcolor = stlHighColor) : na
  235. uptrends.push(trendLine.new(mainLine = uMain, extensionLine = uExtension, priceLabel = uLabel))
  236.  
  237. // @function Draws a downtrend to chart.
  238. // @param start (chart.point) Starting point of trend line.
  239. // @param end (chart.point) Ending point of trend line.
  240. // @returns (void)
  241. f_drawDowntrend(chart.point start, chart.point end) =>
  242. uExtension = tlExtendMode == "n" ? na : line.new(start, end, color = color.new(stlLowColor, 50), extend = tlExtendMode, style = line.style_dashed, width = lineWidth)
  243. uMain = line.new(start, end, color = stlLowColor, style = line.style_arrow_both, width = lineWidth)
  244. uPrice = line.get_price(uMain, bar_index)
  245. uLabel = tlShowLabels ? label.new(x = bar_index, y = uPrice, text = "Downtrend : " + str.tostring(uPrice, format.mintick), style = label.style_label_left, color = color.new(stlLowColor, 80), textcolor = stlLowColor) : na
  246. downtrends.push(trendLine.new(mainLine = uMain, extensionLine = uExtension, priceLabel = uLabel))
  247.  
  248. // @function Clears all lines, boxes, labels off the chart and empties all trend line, support and resistance arrays.
  249. // @returns (void)
  250. f_clearAll() =>
  251. for [i, v] in line.all
  252. line.delete(v)
  253.  
  254. for [i, v] in box.all
  255. box.delete(v)
  256.  
  257. for [i, v] in label.all
  258. label.delete(v)
  259.  
  260. supports.clear()
  261. resistances.clear()
  262. uptrends.clear()
  263. downtrends.clear()
  264.  
  265. // ╔═════════════════════════════════════════════════════════════════════════════════════════════╗
  266. // ║ * * * C A L C U L A T I O N S * * * ║
  267. // ╚═════════════════════════════════════════════════════════════════════════════════════════════╝
  268.  
  269. ph = ta.pivothigh(pvtLength, pvtLength)
  270. pl = ta.pivotlow(pvtLength, pvtLength)
  271.  
  272. if not na(ph)
  273. highPivots.unshift(chart.point.from_index(bar_index[pvtLength], ph))
  274.  
  275. if not na(pl)
  276. lowPivots.unshift(chart.point.from_index(bar_index[pvtLength], pl))
  277.  
  278. // ╔═════════════════════════════════════════════════════════════════════════════════════════════╗
  279. // ║ * * * P L O T S * * * ║
  280. // ╚═════════════════════════════════════════════════════════════════════════════════════════════╝
  281.  
  282. if barstate.islast
  283. f_clearAll()
  284.  
  285. if tlEnabled
  286. for [i, v] in f_getAllPairCombinations(lowPivots.slice(0, tlPointsToCheck).reversed())
  287. if f_isLower(v.firstPoint, v.secondPoint)
  288. f_drawUptrend(v.firstPoint, v.secondPoint)
  289.  
  290. for [i, v] in uptrends
  291. if v.getLowsBelowPrice(exceptBars = tlExceptBars) > tlMaxViolation
  292. v.setViolated(trendColor = stlHighColor)
  293.  
  294. for [i, v] in uptrends
  295. trendPrice = line.get_price(v.mainLine, bar_index)
  296. if not v.isViolated and low <= trendPrice and tlAlertsEnabled
  297. alert(str.format("Uptrend at {0} broken with a new low price at {1} now.", str.tostring(trendPrice, format.mintick), str.tostring(low, format.mintick)), tlAlertrequencyMode)
  298.  
  299. for [i, v] in f_getAllPairCombinations(highPivots.slice(0, tlPointsToCheck).reversed())
  300. if f_isHigher(v.firstPoint, v.secondPoint)
  301. f_drawDowntrend(v.firstPoint, v.secondPoint)
  302.  
  303. for [i, v] in downtrends
  304. if v.getHighsAbovePrice(exceptBars = tlExceptBars) > tlMaxViolation
  305. v.setViolated(trendColor = stlLowColor)
  306.  
  307. for [i, v] in downtrends
  308. trendPrice = line.get_price(v.mainLine, bar_index)
  309. if not v.isViolated and high >= trendPrice and tlAlertsEnabled
  310. alert(str.format("Downtrend at {0} broken with a new high price at {1} now.", str.tostring(trendPrice, format.mintick), str.tostring(high, format.mintick)), tlAlertrequencyMode)
  311.  
  312. if srEnabled
  313. sCount = 0, lIndex = 0
  314. rCount = 0, hIndex = 0
  315.  
  316. while sCount < srPointsToCheck
  317. if f_isLower(lowPivots.get(lIndex), lowPivots.get(lIndex + 1))
  318. if f_checkSupportViolation(lowPivots.get(lIndex), exceptBars = srExceptBars) <= srMaxViolation
  319. f_drawSupport(lowPivots.get(lIndex).index)
  320. sCount += 1
  321. lIndex += 1
  322.  
  323. while rCount < srPointsToCheck
  324. if f_isHigher(highPivots.get(hIndex), highPivots.get(hIndex + 1))
  325. if f_checkResistanceViolation(highPivots.get(hIndex), exceptBars = srExceptBars) <= srMaxViolation
  326. f_drawResistance(highPivots.get(hIndex).index)
  327. rCount += 1
  328. hIndex += 1
  329.  
  330. for [i, v] in supports
  331. if low <= v.price and srAlertsEnabled
  332. alert(str.format("Support at {0} broken by new low price at {1} now.", str.tostring(v.price, format.mintick), str.tostring(low, format.mintick)), srAlertrequencyMode)
  333.  
  334. for [i, v] in resistances
  335. if high >= v.price and srAlertsEnabled
  336. alert(str.format("Resistance at {0} broken by new high price at {1} now.", str.tostring(v.price, format.mintick), str.tostring(high, format.mintick)), srAlertrequencyMode)
  337.  
  338.  
  339. plotshape(not na(ph) and pvtMarkPivots ? ph : na, title = "High Pivots", style = shape.triangleup, color = stlHighColor, location = location.abovebar, size = size.tiny, offset = -pvtLength)
  340. plotshape(not na(pl) and pvtMarkPivots ? pl : na, title = "Low Pivots", style = shape.triangledown, color = stlLowColor, location = location.belowbar, size = size.tiny, offset = -pvtLength)
Advertisement
Comments
  • # text 0.12 KB | 0 0
    1. download all types of premium tradingview indicators codes available on telegram - https://t.me/tradingview_premium_indicator
Add Comment
Please, Sign In to add comment
Advertisement