Indicator · Pine Script v4 · On the chart

Trend Lines v2

by webcrack4· code credited to LonesomeTheBlue

This indicator automatically draws trend lines on the price chart based on detected pivot points.

View on GitHub

GitHub stars1on the repository
Pine versionv4older, still runs
Lines of code121
Settings7inputs
LicenceNone statedfile: MPL-2.0
Last update9 months ago10 Jan 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

121 lines of Pine Script v4 from 17自动趋势线V2.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

17自动趋势线V2.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © LonesomeTheBlue

//@version=4
study("Trend Lines v2", overlay=true, max_bars_back = 4000)
startyear = input(defval = 2020, title = "Start Year")
startmonth = input(defval = 1, title = "Start Month")
startday = input(defval = 1, title = "Start day")
tlprd = input(defval = 20, title="Pivot Period", minval = 10, maxval = 50)
PPnum = input(defval = 3, title="Number of Pivot Points to check", minval = 2, maxval = 6)
utcol = input(defval = color.lime, title = "Colors", inline = "tcol")
dtcol = input(defval = color.red, title = "", inline = "tcol")

float tlph = pivothigh(tlprd, tlprd)
float tlpl = pivotlow(tlprd, tlprd)

var tval = array.new_float(PPnum)
var tpos = array.new_int(PPnum)
var bval = array.new_float(PPnum)
var bpos = array.new_int(PPnum)

add_to_array(apointer1, apointer2, val)=>
    array.unshift(apointer1, val)
    array.unshift(apointer2, bar_index)
    array.pop(apointer1)
    array.pop(apointer2)

if tlph
    add_to_array(tval, tpos, tlph)

if tlpl
    add_to_array(bval, bpos, tlpl)
    
// line definitions
maxline = 3
var bln = array.new_line(maxline, na)
var tln = array.new_line(maxline, na)

// loop for pivot points to check if there is possible trend line
countlinelo = 0
countlinehi = 0

starttime = timestamp(startyear, startmonth, startday, 0, 0, 0)

if time >= starttime
    for x = 0 to maxline - 1
        line.delete(array.get(bln, x))
        line.delete(array.get(tln, x))
    for p1 = 0 to PPnum - 2 
        uv1 = 0.0
        uv2 = 0.0
        up1 = 0
        up2 = 0
        if countlinelo <= maxline
            for p2 = PPnum - 1 to p1 + 1
                val1 = array.get(bval, p1)
                val2 = array.get(bval, p2)
                pos1 = array.get(bpos, p1)
                pos2 = array.get(bpos, p2)
                if val1 > val2
                    diff = (val1 - val2) / (pos1 - pos2)
                    hline = val2 + diff
                    lloc = bar_index
                    lval = low
                    valid = true
                    for x = pos2 + 1 - tlprd to bar_index
                        if close[bar_index - x] < hline
                            valid := false
                            break
                        lloc := x
                        lval := hline
                        hline := hline + diff
                    
                        
                    if valid
                        uv1 := hline - diff
                        uv2 := val2
                        up1 := lloc
                        up2 := pos2
                        break

        dv1 = 0.0
        dv2 = 0.0
        dp1 = 0
        dp2 = 0                
        if countlinehi <= maxline
            for p2 = PPnum - 1 to p1 + 1                
                val1 = array.get(tval, p1)
                val2 = array.get(tval, p2)
                pos1 = array.get(tpos, p1)
                pos2 = array.get(tpos, p2)
                if val1 < val2
                    diff = (val2 - val1) / float(pos1 - pos2)
                    hline = val2 - diff
                    lloc = bar_index
                    lval = high
                    valid = true
                    for x = pos2 + 1 - tlprd to bar_index
                        if close[bar_index - x] > hline
                            valid := false
                            break
                        lloc := x
                        lval := hline
                        hline := hline - diff
                        
                    if valid
                        dv1 := hline + diff
                        dv2 := val2
                        dp1 := lloc
                        dp2 := pos2
                        break
                         
        // if there is continues uptrend line then draw it
        if up1 != 0 and up2 != 0 and countlinelo < maxline
            countlinelo += 1
            array.set(bln, countlinelo - 1, line.new(up2 - tlprd, uv2, up1, uv1, color = utcol))
        
        // if there is continues downtrend line then draw it
        if dp1 != 0 and dp2 != 0 and countlinehi < maxline
            countlinehi += 1
            array.set(tln, countlinehi - 1, line.new(dp2 - tlprd, dv2, dp1, dv1, color = dtcol))

Overview

Trend Lines v2 identifies pivot highs and lows using a user-specified period and checks combinations of these points to determine valid trend lines that do not get violated by subsequent price action. Valid lines are maintained up to a maximum of three per side with customizable colors. The script filters data from a configurable start date and uses arrays to store recent pivot values and positions for efficient checking. It operates in Pine Script v4 and draws directly on the price chart without additional panes.

Details

Published by

webcrack4 on GitHub

Code credit

LonesomeTheBlue, as written in the script's header

Type

Indicator, Pine Script v4

Draws

On the price chart

Category

Trend, Support & resistance

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Start Yearint2020startyear
Start Monthint1startmonth
Start dayint1startday
Pivot Periodint20tlprd
Number of Pivot Points to checkint3PPnum
Colorscolorcolor.limeutcol
dtcolcolorcolor.reddtcol
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

575 stars

This indicator detects equal highs and lows by comparing prices within user-defined left and right bars using a tolerance percentage. It plots horizontal lines on the price chart for equal highs in one color and lows in another. A screener allows input of mult

Indicator v5 Support & resistanceTrend
Updated 1 year ago · MPL-2.0 GitHub repository of ICT Equal Highs and Lows with Screener

Function - Linear Regression

by ricardosantos79
261 stars

This indicator fits a linear regression through stored pivot highs and lows and draws the resulting channel on the price chart. A function returns predicted values, maximum and minimum deviations, and the average absolute deviation. Confirmed two-bar pivots up

Indicator v5 TrendSupport & resistance
Updated 4 years ago · None stated GitHub repository of Function - Linear Regression

AI Trend

by dearvn
257 stars

AI Trend is an indicator that plots pivot points, trend lines, and support and resistance levels directly on the price chart. It marks high and low pivots based on user-defined length, draws trend lines that check for violations at specified points, and identi

Indicator v5 TrendSupport & resistance
Updated 6 weeks ago · None stated GitHub repository of AI Trend

Ichimoku Cloud

by harryguiacorn
219 stars

This indicator plots Ichimoku Cloud elements on the price chart, including Tenkan-sen, Kijun-sen, Senkou Span A and B lines with optional Chikou Span. It signals trend changes via Tenkan-sen and Kijun-sen crosses and places arrows at Kijun-sen direction shifts

Indicator v5 TrendMoving averages
Updated 1 year ago · None stated GitHub repository of Ichimoku Cloud
219 stars

This indicator identifies local swing highs and swing lows to construct a Zig Zag pattern on the main price chart. It evaluates pivot points based on a customizable number of surrounding left and right bars. Using persistent variables, the script tracks previo

Indicator v4 Support & resistanceTrend Repaints
Updated 5 years ago · None stated GitHub repository of Teaching: Finding Highs and Lows 6

Dynamic Linear Regression

by TradersPost
218 stars

Dynamic Linear Regression calculates and plots linear regression trendlines and standard deviation channels directly on the price chart over a user-selected time period. Traders can configure static channels locked at the end time, dynamic channels that contin

Indicator v6 TrendSupport & resistance
Updated 3 months ago · None stated GitHub repository of Dynamic Linear Regression

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers