OPEN-SOURCE SCRIPT
Trend Lines [UAlgo]

Trend Lines is a pivot driven structure indicator that automatically builds, validates, extends, and monitors bullish and bearish trendlines directly on the chart. Instead of relying on manual drawing, the script searches for confirmed pivot highs and pivot lows, connects them into directional line candidates, and keeps only the lines that satisfy a strict set of structural rules.
The script is designed to solve a common problem in automated trendline tools. Many indicators can connect two points, but far fewer can judge whether that connection is meaningful. This script does more than draw a line between pivots. It checks bar separation, optional candle body integrity, touch accumulation, break violations, and active state transitions. As a result, it behaves more like a structural trendline engine than a basic line connector.
Upper trendlines are built from descending pivot highs and act as bearish pressure lines until price breaks above them. Lower trendlines are built from ascending pivot lows and act as bullish support lines until price breaks below them. Every line begins as a candidate, can become active once it collects enough touches, and is later marked as broken if price closes through it according to the selected break rule.
The indicator also supports wick based or body based pivot sourcing, ATR based touch tolerance, optional candidate line display, optional broken line display, and touch count labels on active lines. This makes it flexible enough for both stricter and more permissive trendline workflows while still keeping the core logic rules based.
In practical use, Trend Lines can help map directional structure, monitor confirmed support and resistance lines, and highlight meaningful line breaks without requiring manual chart drawing.
🔹 Features
🔸 Pivot Based Trendline Construction
The script creates trendlines from confirmed pivot highs and pivot lows. This means every line is anchored to real swing structure rather than arbitrary local movement.
🔸 Wick or Body Source Selection
Users can choose whether pivots should come from wick extremes or candle body extremes. This allows the trendline engine to behave either more aggressively or more conservatively depending on chart style.
🔸 ATR Based Touch Tolerance
Touch validation uses an ATR scaled tolerance. This helps the script adapt to different volatility conditions instead of relying on a fixed price threshold.
🔸 Minimum Bars Between Pivots
Two pivots must be separated by at least a minimum number of chart bars before they can define a candidate line. This helps reduce noisy or overly compressed line creation.
🔸 Multi Touch Validation
A line becomes active only after enough pivot touches accumulate on the same projected structure. This prevents weak two point lines from being treated as fully confirmed too early.
🔸 Optional Body Integrity Rule
The script can reject lines that cut through candle bodies between the two anchor pivots. This is useful for users who want cleaner structural lines that sit above or below the main body flow of price.
🔸 Candidate, Active, and Broken States
Every line can exist in one of several states. It may begin as a candidate, become active after enough touches, and later become broken once price violates it. Each state has its own visual styling.
🔸 Touch Count Labels
Active lines can display a compact touch count marker so the user can quickly see how many pivots supported that line.
🔸 Controlled Line Creation
The script limits how many new lines each fresh pivot can generate and also limits the total tracked lines per side. This helps reduce visual overload.
🔸 Bullish and Bearish Break Alerts
Alerts are included for bullish trendline breaks and bearish trendline breaks once they are confirmed by the selected break rule.
🔹 Calculations
1) Defining Pivot and Trendline Objects
Pine Script®
This is the structural base of the whole script.
A PivotPoint stores the time and price of one confirmed pivot.
A TrendlineState stores everything needed to manage one line:
its two anchor points,
its slope,
whether it is an upper or lower line,
how many touches it has,
whether it is active,
whether it has broken,
whether it has been disabled,
where the break occurred,
and the visual objects used to display it.
So the indicator is not simply drawing lines. It is managing full line objects with state and lifecycle logic.
2) Choosing Wick or Body Pivot Source
Pine Script®
This block determines what kind of pivots the script should use.
If the user selects Wick mode, pivot highs come from highs and pivot lows come from lows.
If the user selects Body mode, pivot highs come from the candle body top and pivot lows come from the candle body bottom.
This matters because wick based pivots are more sensitive to extreme price tests, while body based pivots focus more on where the market actually closed and opened.
So the user can tune whether the trendline engine should react to extremes or to body structure.
3) ATR Based Touch Tolerance
Pine Script®
This defines how close a pivot must be to a projected line in order to count as a valid touch.
The script multiplies ATR by the chosen tolerance multiplier. It also enforces a minimum tolerance of two ticks. This makes the detection scale naturally with volatility while still remaining usable on very quiet instruments.
So the touch system is adaptive rather than fixed.
4) Calculating the Trendline Value at Any Time
Pine Script®
This is the core projection formula.
Once the line anchors and slope are known, the script can compute the expected price of that line at any later time. This is used throughout the indicator for touch detection, break detection, candle body validation, label placement, and live extension.
So this method turns a static anchor pair into a dynamic projected structure.
5) Counting Bars Between Two Pivot Times
Pine Script®
This helper function measures how many chart bars exist between two pivot anchors.
It is used to enforce the minimum bars between pivots rule. This prevents the script from connecting pivots that are too close together and likely to generate noisy or trivial lines.
So this function helps control line quality through temporal separation.
6) Body Integrity Rule
Pine Script®
This is one of the most important quality filters in the script.
For upper lines, the projected line should stay above candle bodies between the anchor pivots.
For lower lines, the projected line should stay below candle bodies between the anchor pivots.
If the line cuts too deeply through candle bodies, it is rejected.
This filter helps eliminate visually awkward or structurally weak lines that may mathematically connect pivots but do not actually respect the shape of price movement between them.
7) Break Violation Check at a Specific Bar
Pine Script®
This method checks whether a line is violated by the current candle body.
For upper lines, a violation happens when candle body high moves above the projected line.
For lower lines, a violation happens when candle body low moves below the projected line.
If the selected break method includes tolerance, the ATR based tolerance is included in the threshold. If the user selects the no tolerance method, the break must occur directly through the line.
So this method defines exactly what a valid structural break means.
8) Scanning a Whole Time Interval for Violations
Pine Script®
This function applies the break logic across an entire span of bars.
The script uses it in two main places:
to reject candidate lines that were already violated between their anchor pivots,
and to reject future touches if price already broke the line before the new pivot arrived.
So a line is not accepted simply because its endpoints look valid. It must also remain unbroken through the relevant interval.
9) Registering a New Touch
Pine Script®
This method decides whether a fresh pivot should strengthen an existing line.
The pivot must arrive after the second anchor and after the last recorded touch. Before the script accepts the touch, it checks whether price already violated the line between the last touch and the new pivot. If a violation happened, the line is disabled. If not, the projected line price at the pivot time is calculated, and the pivot is counted as a touch if it lies within tolerance.
If the new touch count reaches the required threshold, the line becomes active.
So this is the process that transforms a simple anchor pair into a confirmed multi touch trendline.
10) Building New Candidate Lines
Pine Script®
This method is the line creation engine.
Whenever a new pivot appears, the script looks backward through stored pivots of the same type and tries to form new candidate lines.
For upper lines, the newest pivot must be lower than the older one.
For lower lines, the newest pivot must be higher than the older one.
This directional requirement ensures the script only builds descending resistance lines from highs and ascending support lines from lows.
The method also checks bar separation and respects the per pivot creation limit so one pivot does not create too many new candidates.
11) Accepting or Rejecting Candidates
Pine Script®
Once a candidate is formed, the script tests two major filters.
First, if the body rule is enabled, the candidate must respect candle bodies between the anchor pivots.
Second, the candidate must not already have been broken between those pivots.
Only if both conditions pass is the candidate stored.
So the script creates only structurally clean lines, not just any mathematically possible connection.
12) Managing Line Storage Limits
Pine Script®
This method keeps the number of tracked lines under control.
If the array exceeds the allowed maximum, the oldest line is removed and its visuals are deleted. This helps the indicator stay manageable and prevents the chart from filling with stale historical candidates.
So the script balances structure memory with chart readability.
13) Break Detection for Active Lines
Pine Script®
This is the live break engine.
Only active, valid lines are checked. The script waits for a confirmed bar after the second anchor, then tests whether the current candle body violates the line.
If an upper line breaks, the break is labeled as bullish because price broke upward through resistance.
If a lower line breaks, the break is labeled as bearish because price broke downward through support.
So the break direction is interpreted from the structural meaning of the line, not from the line type name itself.
14) Processing New Pivots Against Existing Lines
Pine Script®
Pine Script®
This is the main structural update flow.
When a new pivot high appears, the script first checks whether that pivot adds touches to existing upper lines. Then it stores the pivot in memory. After that, it tries to build new upper candidates from that fresh pivot.
The exact same sequence is used for lower pivots and lower lines.
So every new confirmed pivot serves two purposes:
it may strengthen existing structure,
and it may create new structure.
15) Refreshing Visual States
Pine Script®
The script refreshes all stored lines on every bar.
Candidate lines, active lines, and broken lines all receive different visual treatment according to the user’s settings. Active lines are stronger and more visible. Candidates are lighter and dotted. Broken lines are dashed and faded.
This means the chart always reflects the latest line state rather than treating every stored line the same way.
16) Touch Marker Logic
Pine Script®
Active lines can display a small touch count label just ahead of the current bar.
The script places the label at the projected line value on the latest bar and prints the current number of touches. This gives the user a quick measure of structural strength without needing to inspect the line history manually.
So touch markers turn active lines into easy to rank structural objects.
17) Alert Conditions
Pine Script®
This is the final event layer of the script.
The indicator scans all upper lines for bullish breaks and all lower lines for bearish breaks. If any valid active line breaks on the confirmed bar, the corresponding alert condition becomes true.
So the alert engine is tied to the same structural logic as the chart drawings, not to a simplified separate trigger.
The script is designed to solve a common problem in automated trendline tools. Many indicators can connect two points, but far fewer can judge whether that connection is meaningful. This script does more than draw a line between pivots. It checks bar separation, optional candle body integrity, touch accumulation, break violations, and active state transitions. As a result, it behaves more like a structural trendline engine than a basic line connector.
Upper trendlines are built from descending pivot highs and act as bearish pressure lines until price breaks above them. Lower trendlines are built from ascending pivot lows and act as bullish support lines until price breaks below them. Every line begins as a candidate, can become active once it collects enough touches, and is later marked as broken if price closes through it according to the selected break rule.
The indicator also supports wick based or body based pivot sourcing, ATR based touch tolerance, optional candidate line display, optional broken line display, and touch count labels on active lines. This makes it flexible enough for both stricter and more permissive trendline workflows while still keeping the core logic rules based.
In practical use, Trend Lines can help map directional structure, monitor confirmed support and resistance lines, and highlight meaningful line breaks without requiring manual chart drawing.
🔹 Features
🔸 Pivot Based Trendline Construction
The script creates trendlines from confirmed pivot highs and pivot lows. This means every line is anchored to real swing structure rather than arbitrary local movement.
🔸 Wick or Body Source Selection
Users can choose whether pivots should come from wick extremes or candle body extremes. This allows the trendline engine to behave either more aggressively or more conservatively depending on chart style.
🔸 ATR Based Touch Tolerance
Touch validation uses an ATR scaled tolerance. This helps the script adapt to different volatility conditions instead of relying on a fixed price threshold.
🔸 Minimum Bars Between Pivots
Two pivots must be separated by at least a minimum number of chart bars before they can define a candidate line. This helps reduce noisy or overly compressed line creation.
🔸 Multi Touch Validation
A line becomes active only after enough pivot touches accumulate on the same projected structure. This prevents weak two point lines from being treated as fully confirmed too early.
🔸 Optional Body Integrity Rule
The script can reject lines that cut through candle bodies between the two anchor pivots. This is useful for users who want cleaner structural lines that sit above or below the main body flow of price.
🔸 Candidate, Active, and Broken States
Every line can exist in one of several states. It may begin as a candidate, become active after enough touches, and later become broken once price violates it. Each state has its own visual styling.
🔸 Touch Count Labels
Active lines can display a compact touch count marker so the user can quickly see how many pivots supported that line.
🔸 Controlled Line Creation
The script limits how many new lines each fresh pivot can generate and also limits the total tracked lines per side. This helps reduce visual overload.
🔸 Bullish and Bearish Break Alerts
Alerts are included for bullish trendline breaks and bearish trendline breaks once they are confirmed by the selected break rule.
🔹 Calculations
1) Defining Pivot and Trendline Objects
This is the structural base of the whole script.
A PivotPoint stores the time and price of one confirmed pivot.
A TrendlineState stores everything needed to manage one line:
its two anchor points,
its slope,
whether it is an upper or lower line,
how many touches it has,
whether it is active,
whether it has broken,
whether it has been disabled,
where the break occurred,
and the visual objects used to display it.
So the indicator is not simply drawing lines. It is managing full line objects with state and lifecycle logic.
2) Choosing Wick or Body Pivot Source
This block determines what kind of pivots the script should use.
If the user selects Wick mode, pivot highs come from highs and pivot lows come from lows.
If the user selects Body mode, pivot highs come from the candle body top and pivot lows come from the candle body bottom.
This matters because wick based pivots are more sensitive to extreme price tests, while body based pivots focus more on where the market actually closed and opened.
So the user can tune whether the trendline engine should react to extremes or to body structure.
3) ATR Based Touch Tolerance
This defines how close a pivot must be to a projected line in order to count as a valid touch.
The script multiplies ATR by the chosen tolerance multiplier. It also enforces a minimum tolerance of two ticks. This makes the detection scale naturally with volatility while still remaining usable on very quiet instruments.
So the touch system is adaptive rather than fixed.
4) Calculating the Trendline Value at Any Time
This is the core projection formula.
Once the line anchors and slope are known, the script can compute the expected price of that line at any later time. This is used throughout the indicator for touch detection, break detection, candle body validation, label placement, and live extension.
So this method turns a static anchor pair into a dynamic projected structure.
5) Counting Bars Between Two Pivot Times
This helper function measures how many chart bars exist between two pivot anchors.
It is used to enforce the minimum bars between pivots rule. This prevents the script from connecting pivots that are too close together and likely to generate noisy or trivial lines.
So this function helps control line quality through temporal separation.
6) Body Integrity Rule
This is one of the most important quality filters in the script.
For upper lines, the projected line should stay above candle bodies between the anchor pivots.
For lower lines, the projected line should stay below candle bodies between the anchor pivots.
If the line cuts too deeply through candle bodies, it is rejected.
This filter helps eliminate visually awkward or structurally weak lines that may mathematically connect pivots but do not actually respect the shape of price movement between them.
7) Break Violation Check at a Specific Bar
This method checks whether a line is violated by the current candle body.
For upper lines, a violation happens when candle body high moves above the projected line.
For lower lines, a violation happens when candle body low moves below the projected line.
If the selected break method includes tolerance, the ATR based tolerance is included in the threshold. If the user selects the no tolerance method, the break must occur directly through the line.
So this method defines exactly what a valid structural break means.
8) Scanning a Whole Time Interval for Violations
This function applies the break logic across an entire span of bars.
The script uses it in two main places:
to reject candidate lines that were already violated between their anchor pivots,
and to reject future touches if price already broke the line before the new pivot arrived.
So a line is not accepted simply because its endpoints look valid. It must also remain unbroken through the relevant interval.
9) Registering a New Touch
This method decides whether a fresh pivot should strengthen an existing line.
The pivot must arrive after the second anchor and after the last recorded touch. Before the script accepts the touch, it checks whether price already violated the line between the last touch and the new pivot. If a violation happened, the line is disabled. If not, the projected line price at the pivot time is calculated, and the pivot is counted as a touch if it lies within tolerance.
If the new touch count reaches the required threshold, the line becomes active.
So this is the process that transforms a simple anchor pair into a confirmed multi touch trendline.
10) Building New Candidate Lines
This method is the line creation engine.
Whenever a new pivot appears, the script looks backward through stored pivots of the same type and tries to form new candidate lines.
For upper lines, the newest pivot must be lower than the older one.
For lower lines, the newest pivot must be higher than the older one.
This directional requirement ensures the script only builds descending resistance lines from highs and ascending support lines from lows.
The method also checks bar separation and respects the per pivot creation limit so one pivot does not create too many new candidates.
11) Accepting or Rejecting Candidates
Once a candidate is formed, the script tests two major filters.
First, if the body rule is enabled, the candidate must respect candle bodies between the anchor pivots.
Second, the candidate must not already have been broken between those pivots.
Only if both conditions pass is the candidate stored.
So the script creates only structurally clean lines, not just any mathematically possible connection.
12) Managing Line Storage Limits
This method keeps the number of tracked lines under control.
If the array exceeds the allowed maximum, the oldest line is removed and its visuals are deleted. This helps the indicator stay manageable and prevents the chart from filling with stale historical candidates.
So the script balances structure memory with chart readability.
13) Break Detection for Active Lines
This is the live break engine.
Only active, valid lines are checked. The script waits for a confirmed bar after the second anchor, then tests whether the current candle body violates the line.
If an upper line breaks, the break is labeled as bullish because price broke upward through resistance.
If a lower line breaks, the break is labeled as bearish because price broke downward through support.
So the break direction is interpreted from the structural meaning of the line, not from the line type name itself.
14) Processing New Pivots Against Existing Lines
This is the main structural update flow.
When a new pivot high appears, the script first checks whether that pivot adds touches to existing upper lines. Then it stores the pivot in memory. After that, it tries to build new upper candidates from that fresh pivot.
The exact same sequence is used for lower pivots and lower lines.
So every new confirmed pivot serves two purposes:
it may strengthen existing structure,
and it may create new structure.
15) Refreshing Visual States
The script refreshes all stored lines on every bar.
Candidate lines, active lines, and broken lines all receive different visual treatment according to the user’s settings. Active lines are stronger and more visible. Candidates are lighter and dotted. Broken lines are dashed and faded.
This means the chart always reflects the latest line state rather than treating every stored line the same way.
16) Touch Marker Logic
Active lines can display a small touch count label just ahead of the current bar.
The script places the label at the projected line value on the latest bar and prints the current number of touches. This gives the user a quick measure of structural strength without needing to inspect the line history manually.
So touch markers turn active lines into easy to rank structural objects.
17) Alert Conditions
This is the final event layer of the script.
The indicator scans all upper lines for bullish breaks and all lower lines for bearish breaks. If any valid active line breaks on the confirmed bar, the corresponding alert condition becomes true.
So the alert engine is tied to the same structural logic as the chart drawings, not to a simplified separate trigger.
Open-source Skript
Ganz im Sinne von TradingView hat dieser Autor sein/ihr Script als Open-Source veröffentlicht. Auf diese Weise können nun auch andere Trader das Script rezensieren und die Funktionalität überprüfen. Vielen Dank an den Autor! Sie können das Script kostenlos verwenden, aber eine Wiederveröffentlichung des Codes unterliegt unseren Hausregeln.
Get exclusive indicators: pinescriptmarket.com
All content provided by UAlgo is for informational & educational purposes only. Past performance does not guarantee future results.
All content provided by UAlgo is for informational & educational purposes only. Past performance does not guarantee future results.
Haftungsausschluss
Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.
Open-source Skript
Ganz im Sinne von TradingView hat dieser Autor sein/ihr Script als Open-Source veröffentlicht. Auf diese Weise können nun auch andere Trader das Script rezensieren und die Funktionalität überprüfen. Vielen Dank an den Autor! Sie können das Script kostenlos verwenden, aber eine Wiederveröffentlichung des Codes unterliegt unseren Hausregeln.
Get exclusive indicators: pinescriptmarket.com
All content provided by UAlgo is for informational & educational purposes only. Past performance does not guarantee future results.
All content provided by UAlgo is for informational & educational purposes only. Past performance does not guarantee future results.
Haftungsausschluss
Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.