Indicator · Pine Script v6 · On the chart

Linear Regression Channel / Curve / Slope by DGT

by theonetrade

Linear Regression Channel / Curve / Slope by DGT plots up to two linear regression channels directly on the price chart.

View on GitHub

GitHub stars34on the repository
Pine versionv6current
Lines of code420
Settings40inputs
LicenceMIT
Last update2 weeks ago8 Nov 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

420 lines of Pine Script v6 from assets/indicator/bit-exact/linear_regression_channel_curve_slope_by_dgt_ropVPOmR.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

linear_regression_channel_curve_slope_by_dgt_ropVPOmR.pine
//@version=6
// ══════════════════════════════════════════════════════════════════════════════════════════════════ //
//# * ══════════════════════════════════════════════════════════════════════════════════════════════
//# *
//# * Study       : Linear Regression Channel / Curve / Slope
//# *                - Volume / Volatility AddOns
//# * Author      : © dgtrd
//# *
//# * Revision History
//# *  Release    : Apr 19, 2021
//# *  Update     : Apr 22, 2021 : Added option to plot second Linear Regression Channel
//# *  Update     : Apr 24, 2021 : Added option to plot second Linear Regression Channel based on Higher Timeframe
//# *  Update     : May 04, 2022 : Label customization options, LRC1-Median LRC2 cross alerts, Pine v5 
//# *
//# * ══════════════════════════════════════════════════════════════════════════════════════════════
// ══════════════════════════════════════════════════════════════════════════════════════════════════ //

indicator('Linear Regression Channel / Curve / Slope by DGT', 'LɪɴRᴇɢ ☼☾', true)

// ══════════════════════════════════════════════════════════════════════════════════════════════════ //
//
// Linear Regression Channel / Curve / Slope
// ══════════════════════════════════════════════════════════════════════════════════════════════════ //

display = display.all - display.status_line

// ---------------------------------------------------------------------------------------------- //
// -Inputs -------------------------------------------------------------------------------------- //

group_linReg = 'Linear Regression — 1st Channel'

tooltip_linreg =
     'Linear Regression Channel' +
     '\nBase Line: The line that best fits price over the selected period (Count),' +
     '\ncalculated using the least-squares method.'

i_linreg       = input.bool(true, 'LinReg1 ⇨ Count', inline = 'LinReg1', group = group_linReg, tooltip = tooltip_linreg)
i_linregLength = input.int(200, '', minval = 2, maxval = 5000, inline = 'LinReg1', group = group_linReg, display = display)
i_linregSrc    = input.source(close, '       Source', inline = 'LinReg1', group = group_linReg, display = display)

i_extendLines  = input.bool(false, 'Extend Lines       ', inline = 'Lines', group = group_linReg)
i_trendColor  = input.bool(false, 'Use Trend Colors', inline = 'Lines', group = group_linReg)

i_channelLevels = input.string('Levels', 'Level Labels', options = ['Levels', 'Levels (Prices)', 'None'], inline = 'Level', group = group_linReg, display = display)
levelTextSize  = input.string('Small', '', options = ['Small', 'Normal'], inline = 'Level', group = group_linReg, display = display)
levelOffset    = input.int(0, 'Offset', minval = 0, inline = 'Level', group = group_linReg, display = display)

group_linReg2 = 'Linear Regression — 2nd Channel (HTF)'

tooltip_linreg2 =
     'Second Linear Regression Channel — User-Defined Timeframe' +
     '\n\nWhen enabled, the Linear Regression Channel extends by:' +
     '\nCount × (Selected Higher Timeframe ÷ Current Timeframe).' +
     '\n\nLimitations:' +
     '\n• May exceed the maximum allowed history limit (5000 bars),' +
     '\n  resulting in: "The study references too many candles in history (5001)".' +
     '\n  Solution: Reduce Count or select 1H / 4H.' +
     '\n\n• Lines may not be visible while labels are present.' +
     '\n  Solution: Scroll left or enable "Shorten Display when TF Extend is enabled".' +
     '\n\n• Applicable to intraday timeframes only.'

i_linreg2        = input.bool(true, 'LinReg2 ⇨ Count', inline = 'LinReg2', group = group_linReg2)
i_linregLength2 = input.int(50, '', minval = 2, maxval = 5000, inline = 'LinReg2', group = group_linReg2, display = display)
i_linregSrc2    = input.source(close, '       Source', inline = 'LinReg2', group = group_linReg2, display = display)

i_useTF   = input.bool(true, 'LinReg2 ⇨ Extend to User-Defined TF (Intraday Only)', inline = 'HTF2', group = group_linReg2, tooltip = tooltip_linreg2)
i_htf_user = input.string('4H', '', options = ['1D', '4H', '1H'], inline = 'HTF2', group = group_linReg2, display = display)

i_shorten  = input.bool(true, 'LinReg2 ⇨ Shorten Display when TF Extend Enabled', inline = 'SHORT', group = group_linReg2)
i_showLast = input.int(500, '', minval = 200, inline = 'SHORT', group = group_linReg2, display = display)

i_extendLines2  = input.bool(false, 'Extend Lines       ', inline = 'Lines', group = group_linReg2)
i_trendColor2  = input.bool(false, 'Use Trend Colors', inline = 'Lines', group = group_linReg2)
i_channelLevels2 = input.string('Levels', 'Level Labels', options = ['Levels', 'Levels (Prices)', 'None'], inline = 'Level', group = group_linReg2, display = display)
levelTextSize2  = input.string('Small', '', options = ['Small', 'Normal'], inline = 'Level', group = group_linReg2, display = display)
levelOffset2    = input.int(0, 'Offset', minval = 0, inline = 'Level', group = group_linReg2, display = display)


// ---------------------------------------------------------------------------------------------- //
// -Calculations -------------------------------------------------------------------------------- //

// ---------------------------------------------------------------------------------------------- //
// Linear Regression Channel / Curve (Bands) / Slope

f_calcSlope(_source, _length) =>
    max_bars_back(_source, 5000)

    if not barstate.islast
        [float(na), float(na)]
    else
        sumX = 0.0
        sumY = 0.0
        sumXSqr = 0.0
        sumXY = 0.0

        for i = 0 to _length - 1 by 1
            val = _source[i]
            per = i + 1.0
            sumX := sumX + per
            sumY := sumY + val
            sumXSqr := sumXSqr + per * per
            sumXY := sumXY + val * per
            sumXY

        slope = (_length * sumXY - sumX * sumY) / (_length * sumXSqr - sumX * sumX)
        intercept = sumY / _length - slope * sumX / _length + slope

        [slope, intercept]

f_calcDev(_source, _length, _slope, _intercept) =>
    stdDevAcc = 0.0
    periods = _length - 1
    val = _intercept

    for i = 0 to periods by 1
        price = _source[i]
        price := price - val
        stdDevAcc := stdDevAcc + price * price
        val := val + _slope
        val

    stdDev = math.sqrt(stdDevAcc / periods)
    stdDev

[slope, intercept] = f_calcSlope(i_linregSrc, i_linregLength)
stdDev = f_calcDev(i_linregSrc, i_linregLength, slope, intercept)
startPrice = intercept + slope * (i_linregLength - 1)
endPrice = intercept

htf_multiplier = i_htf_user == '1H' ? 60 : i_htf_user == '4H' ? 240 : i_htf_user == '1D' ? 1440 : na
linregLength2 = i_useTF and timeframe.isintraday and htf_multiplier > timeframe.multiplier ? i_linregLength2 * htf_multiplier / timeframe.multiplier : i_linregLength2

[slope2, intercept2] = f_calcSlope(i_linregSrc2, linregLength2)
stdDev2 = f_calcDev(i_linregSrc2, linregLength2, slope2, intercept2)
startPrice2 = intercept2 + slope2 * (i_shorten and i_useTF and i_showLast < linregLength2 ? i_showLast : linregLength2 - 1)
endPrice2 = intercept2

// ---------------------------------------------------------------------------------------------- //
// -Plotting ------------------------------------------------------------------------------------ //

f_crossingLevel(_current, _level) =>
    (_level > _current and _level < _current[1]) or (_level < _current and _level > _current[1])

f_drawLabel(_index, _price, _txt, _txtColor, _style, _align, _lrc, _tooltip, size, extend) =>
    var id = label.new(_index, _price, _txt, textcolor = _txtColor, style = _style, textalign = _align, color = #00000000, tooltip = _tooltip, size = size)
    label.set_xy(id, _index, _price)
    label.set_textcolor(id, _txtColor)
    label.set_text(id, extend ? _txt + '\n\n' : _txt)
    label.set_tooltip(id, _tooltip)

f_drawLine(_iStart, _pStart, _iEnd, _pEnd, _color, _width, _style, _extend) =>
    style = _style == 'Solid' ? line.style_solid : _style == 'Dotted' ? line.style_dotted : _style == 'Dashed' ? line.style_dashed : line.style_arrow_right

    var linReg = line.new(_iStart, _pStart, _iEnd, _pEnd, xloc.bar_index, _extend ? extend.right : extend.none, _color, style, _width)
    line.set_xy1(linReg, _iStart, _pStart)
    line.set_xy2(linReg, _iEnd, _pEnd)
    line.set_color(linReg, _color)

processLinRegLevel(_show, _level, _colorL, _widthL, _styleL, _linReg, _which, extend) =>
    if _show and _linReg
        pStart = _which ? startPrice : startPrice2
        pEnd = _which ? endPrice : endPrice2
        dev = _which ? stdDev : stdDev2
        trendColor = _which ? i_trendColor : i_trendColor2
        channelLevels = _which ? i_channelLevels : i_channelLevels2
        textSize = _which ? levelTextSize : levelTextSize2
        offset = _which ? levelOffset : levelOffset2


        length = _which ? i_linregLength : i_shorten and i_useTF and i_showLast < linregLength2 ? i_showLast : linregLength2
        lrColor = trendColor ? pStart > pEnd ? color.red : color.green : _colorL

        f_drawLine(bar_index - length + 1, pStart + _level * dev, bar_index, pEnd + _level * dev, lrColor, _widthL, _styleL, extend)
        f_drawLine(bar_index - length + 1, pStart - _level * dev, bar_index, pEnd - _level * dev, lrColor, _widthL, _styleL, extend)

        lbl = _which ? '1' : '2'

        if channelLevels != 'None'
            f_drawLabel(bar_index + offset, pEnd + _level * dev, 'SD ' + str.tostring(_level) + ' R' + lbl + (channelLevels == 'Levels (Prices)' ? ' (' + str.tostring(pEnd + _level * dev, format.mintick) + ')' : ''), lrColor, label.style_label_left, text.align_left, true, str.tostring(pEnd + _level * dev, format.mintick), textSize == 'Small' ? size.small : size.normal, extend)
            f_drawLabel(bar_index + offset, pEnd - _level * dev, 'SD ' + str.tostring(_level) + ' S' + lbl + (channelLevels == 'Levels (Prices)' ? ' (' + str.tostring(pEnd - _level * dev, format.mintick) + ')' : ''), lrColor, label.style_label_left, text.align_left, true, str.tostring(pEnd - _level * dev, format.mintick), textSize == 'Small' ? size.small : size.normal, extend)

            if offset > 9
                f_drawLine(bar_index + 3, pEnd + _level * dev, bar_index + offset, pEnd + _level * dev, lrColor, 1, 'Arrow', false)
                f_drawLine(bar_index + 3, pEnd - _level * dev, bar_index + offset, pEnd - _level * dev, lrColor, 1, 'Arrow', false)

        if f_crossingLevel(close, pEnd + _level * dev)
            alert('LɪɴRᴇɢ | ' + syminfo.ticker + ' — Price crossed LR' + lbl + ' Upper Band (SD ' + str.tostring(_level) + ') @ ' + str.tostring(pEnd + _level * dev, format.mintick))

        if f_crossingLevel(close, pEnd - _level * dev)
            alert('LɪɴRᴇɢ | ' + syminfo.ticker + ' — Price crossed LR' + lbl + ' Lower Band (SD ' + str.tostring(_level) + ') @ ' + str.tostring(pEnd - _level * dev, format.mintick))

i_lrcolor_m = input.color(#f44336, 'Linear Regression Line       ', inline = 'lrLine', group = group_linReg)
i_lrstyle_m = input.string('Solid', '', options = ['Dashed', 'Dotted', 'Solid'], inline = 'lrLine', group = group_linReg, display = display)
i_lrwidth_m = input.int(3, '', minval = 1, inline = 'lrLine', group = group_linReg, display = display)

if i_linreg
    f_drawLine(bar_index - i_linregLength + 1, startPrice, bar_index, endPrice, i_trendColor ? startPrice > endPrice ? color.red : color.green : i_lrcolor_m, i_lrwidth_m, i_lrstyle_m, i_extendLines)

    if i_channelLevels != 'None'
        f_drawLabel(bar_index + levelOffset, endPrice, 'LRL 1ST' + (i_channelLevels == 'Levels (Prices)' ? ' (' + str.tostring(endPrice, format.mintick) + ')' : ''), i_trendColor ? startPrice > endPrice ? color.red : color.green : i_lrcolor_m, label.style_label_left, text.align_left, true, str.tostring(endPrice, format.mintick), levelTextSize == 'Small' ? size.small : size.normal, i_extendLines)

        if levelOffset > 9
            f_drawLine(bar_index + 3, endPrice, bar_index + levelOffset, endPrice, i_lrcolor_m, 1, 'Arrow', false)

    if f_crossingLevel(close, endPrice)
        alert('LɪɴRᴇɢ | ' + syminfo.ticker + ' — Price crossed LR1 Base Line @ ' + str.tostring(endPrice, format.mintick))


i_lrshow_1 = input.bool(true, 'StdDev', inline = 'lrLevel_1', group = group_linReg)
i_lrvalue_1 = input.float(1., '', minval = 0, step = .1, inline = 'lrLevel_1', group = group_linReg, display = display)
i_lrcolor_1 = input.color(#2196f3, '', inline = 'lrLevel_1', group = group_linReg)
i_lrstyle_1 = input.string('Dashed', '', options = ['Dashed', 'Dotted', 'Solid'], inline = 'lrLevel_1', group = group_linReg, display = display)
i_lrwidth_1 = input.int(1, '', minval = 1, inline = 'lrLevel_1', group = group_linReg, display = display)
processLinRegLevel(i_lrshow_1, i_lrvalue_1, i_lrcolor_1, i_lrwidth_1, i_lrstyle_1, i_linreg, true, i_extendLines)

i_lrshow_2 = input.bool(true, 'StdDev', inline = 'lrLevel_2', group = group_linReg)
i_lrvalue_2 = input.float(2., '', minval = 1, step = .1, inline = 'lrLevel_2', group = group_linReg, display = display)
i_lrcolor_2 = input.color(#2196f3, '', inline = 'lrLevel_2', group = group_linReg)
i_lrstyle_2 = input.string('Solid', '', options = ['Dashed', 'Dotted', 'Solid'], inline = 'lrLevel_2', group = group_linReg, display = display)
i_lrwidth_2 = input.int(2, '', minval = 1, inline = 'lrLevel_2', group = group_linReg, display = display)
processLinRegLevel(i_lrshow_2, i_lrvalue_2, i_lrcolor_2, i_lrwidth_2, i_lrstyle_2, i_linreg, true, i_extendLines)

i_lrshow_3 = input.bool(true, 'StdDev', inline = 'lrLevel_3', group = group_linReg)
i_lrvalue_3 = input.float(3., '', minval = 2, step = .1, inline = 'lrLevel_3', group = group_linReg, display = display)
i_lrcolor_3 = input.color(#2196f3, '', inline = 'lrLevel_3', group = group_linReg)
i_lrstyle_3 = input.string('Dotted', '', options = ['Dashed', 'Dotted', 'Solid'], inline = 'lrLevel_3', group = group_linReg, display = display)
i_lrwidth_3 = input.int(2, '', minval = 1, inline = 'lrLevel_3', group = group_linReg, display = display)
processLinRegLevel(i_lrshow_3, i_lrvalue_3, i_lrcolor_3, i_lrwidth_3, i_lrstyle_3, i_linreg, true, i_extendLines)

i_2lrcolor_m = input.color(#ff9800, 'Linear Regression Line       ', inline = '2lrLine', group = group_linReg2)
i_2lrstyle_m = input.string('Solid', '', options = ['Dashed', 'Dotted', 'Solid'], inline = '2lrLine', group = group_linReg2, display = display)
i_2lrwidth_m = input.int(3, '', minval = 1, inline = '2lrLine', group = group_linReg2, display = display)

if i_linreg2
    f_drawLine(bar_index - (i_shorten and i_useTF and i_showLast < linregLength2 ? i_showLast : linregLength2) + 1, startPrice2, bar_index, endPrice2, i_trendColor2 ? startPrice2 > endPrice2 ? color.red : color.green : i_2lrcolor_m, i_2lrwidth_m, i_2lrstyle_m, i_extendLines2)

    if i_channelLevels2 != 'None'
        f_drawLabel(bar_index + levelOffset2, endPrice2, 'LRL 2ND' + (i_channelLevels2 == 'Levels (Prices)' ? ' (' + str.tostring(endPrice2, format.mintick) + ')' : ''), i_trendColor2 ? startPrice2 > endPrice2 ? color.red : color.green : i_2lrcolor_m, label.style_label_left, text.align_left, true, str.tostring(endPrice2, format.mintick), levelTextSize2 == 'Small' ? size.small : size.normal, i_extendLines2)

        if levelOffset2 > 9
            f_drawLine(bar_index + 3, endPrice2, bar_index + levelOffset2, endPrice2, i_2lrcolor_m, 1, 'Arrow', false)

    if f_crossingLevel(close, endPrice2)
        alert('LɪɴRᴇɢ | ' + syminfo.ticker + ' — Price crossed LR2 Base Line @ ' + str.tostring(endPrice2, format.mintick))


i_2lrshow_1 = input.bool(true, 'StdDev', inline = '2lrLevel_1', group = group_linReg2)
i_2lrvalue_1 = input.float(1., '', minval = 0, step = .1, inline = '2lrLevel_1', group = group_linReg2, display = display)
i_2lrcolor_1 = input.color(#00bcd4, '', inline = '2lrLevel_1', group = group_linReg2)
i_2lrstyle_1 = input.string('Dashed', '', options = ['Dashed', 'Dotted', 'Solid'], inline = '2lrLevel_1', group = group_linReg2, display = display)
i_2lrwidth_1 = input.int(1, '', minval = 1, inline = '2lrLevel_1', group = group_linReg2, display = display)
processLinRegLevel(i_2lrshow_1, i_2lrvalue_1, i_2lrcolor_1, i_2lrwidth_1, i_2lrstyle_1, i_linreg2, false, i_extendLines2)

i_2lrshow_2 = input.bool(true, 'StdDev', inline = '2lrLevel_2', group = group_linReg2)
i_2lrvalue_2 = input.float(2., '', minval = 1, step = .1, inline = '2lrLevel_2', group = group_linReg2, display = display)
i_2lrcolor_2 = input.color(#00bcd4, '', inline = '2lrLevel_2', group = group_linReg2)
i_2lrstyle_2 = input.string('Solid', '', options = ['Dashed', 'Dotted', 'Solid'], inline = '2lrLevel_2', group = group_linReg2, display = display)
i_2lrwidth_2 = input.int(2, '', minval = 1, inline = '2lrLevel_2', group = group_linReg2, display = display)
processLinRegLevel(i_2lrshow_2, i_2lrvalue_2, i_2lrcolor_2, i_2lrwidth_2, i_2lrstyle_2, i_linreg2, false, i_extendLines2)

i_2lrshow_3 = input.bool(true, 'StdDev', inline = '2lrLevel_3', group = group_linReg2)
i_2lrvalue_3 = input.float(3., '', minval = 2, step = .1, inline = '2lrLevel_3', group = group_linReg2, display = display)
i_2lrcolor_3 = input.color(#00bcd4, '', inline = '2lrLevel_3', group = group_linReg2)
i_2lrstyle_3 = input.string('Dotted', '', options = ['Dashed', 'Dotted', 'Solid'], inline = '2lrLevel_3', group = group_linReg2, display = display)
i_2lrwidth_3 = input.int(2, '', minval = 1, inline = '2lrLevel_3', group = group_linReg2, display = display)
processLinRegLevel(i_2lrshow_3, i_2lrvalue_3, i_2lrcolor_3, i_2lrwidth_3, i_2lrstyle_3, i_linreg2, false, i_extendLines2)


f_lrAlert(_txt, _price) =>
    alert('LɪɴRᴇɢ | ' + syminfo.ticker + ' — ' + _txt + ' @ ' + str.tostring(_price, format.mintick))


if i_linreg and i_linreg2
    if f_crossingLevel(endPrice, endPrice2)
        f_lrAlert('LR1 Base crossed LR2 Base Line', endPrice2)

    if f_crossingLevel(endPrice, endPrice2 + i_2lrvalue_1 * stdDev2)
        f_lrAlert('LR1 Base crossed LR2 Upper Band (SD ' + str.tostring(i_2lrvalue_1) + ')', endPrice2 + i_2lrvalue_1 * stdDev2)

    if f_crossingLevel(endPrice, endPrice2 + i_2lrvalue_2 * stdDev2)
        f_lrAlert('LR1 Base crossed LR2 Upper Band (SD ' + str.tostring(i_2lrvalue_2) + ')', endPrice2 + i_2lrvalue_2 * stdDev2)

    if f_crossingLevel(endPrice, endPrice2 + i_2lrvalue_3 * stdDev2)
        f_lrAlert('LR1 Base crossed LR2 Upper Band (SD ' + str.tostring(i_2lrvalue_3) + ')', endPrice2 + i_2lrvalue_3 * stdDev2)

    if f_crossingLevel(endPrice, endPrice2 - i_2lrvalue_1 * stdDev2)
        f_lrAlert('LR1 Base crossed LR2 Lower Band (SD ' + str.tostring(i_2lrvalue_1) + ')', endPrice2 - i_2lrvalue_1 * stdDev2)

    if f_crossingLevel(endPrice, endPrice2 - i_2lrvalue_2 * stdDev2)
        f_lrAlert('LR1 Base crossed LR2 Lower Band (SD ' + str.tostring(i_2lrvalue_2) + ')', endPrice2 - i_2lrvalue_2 * stdDev2)

    if f_crossingLevel(endPrice, endPrice2 - i_2lrvalue_3 * stdDev2)
        f_lrAlert('LR1 Base crossed LR2 Lower Band (SD ' + str.tostring(i_2lrvalue_3) + ')', endPrice2 - i_2lrvalue_3 * stdDev2)



group_linRegC = 'Linear Regression Curve'

i_showCurve = input.bool(true, 'Linear Regression Curve      |     Length', inline = 'Curve', group = group_linRegC)
i_linregCurveL = input.int(50, '', inline = 'Curve', group = group_linRegC, display = display)
i_lrcolorCurve = input.color(#872323, '', inline = 'Curve', group = group_linRegC)

i_showCurveBand = input.bool(false, 'Linear Regression Curve Bands           ', inline = 'Bands', group = group_linRegC)
i_lrcolorBand1 = input.color(#00897b, '1', inline = 'Bands', group = group_linRegC)
i_lrcolorBand2 = input.color(#00897b, '2', inline = 'Bands', group = group_linRegC)
i_lrcolorBand3 = input.color(#00897b, '3', inline = 'Bands', group = group_linRegC)
i_showCurveBTyp = input.string('StdDev', 'Bands', options = ['StdDev', 'ATR'], inline = 'Bands2', group = group_linRegC, display = display)
i_linregCurveBL = input.int(21, '  StdDev', inline = 'Bands2', group = group_linRegC, display = display)
i_linregCurveAL = input.int(13, ' ATR', inline = 'Bands2', group = group_linRegC, display = display)

group_linRegS = 'Linear Regression Slope'

i_showSlope = input.bool(false, 'Linear Regression Slope  |  Length', inline = 'Slope', group = group_linRegS)
i_linregSlopeL = input.int(5, '', inline = 'Slope', group = group_linRegS, display = display)
i_lrcolorSlopeU = input.color(color.new(#06bad1, 50), '', inline = 'Slope', group = group_linRegS)
i_lrcolorSlopeD = input.color(color.new(#f57f17, 50), '', inline = 'Slope', group = group_linRegS)

dev = i_showCurveBTyp == 'StdDev' ? ta.stdev(i_linregSrc, i_linregCurveBL) : ta.atr(i_linregCurveAL)
lrc = ta.linreg(i_linregSrc, i_linregCurveL, 0)

plot(i_showCurve ? lrc : na, 'LRC', i_lrcolorCurve, 3, show_last = 3 * i_linregLength, display = display)
plot(i_showCurve and i_showCurveBand ? lrc + 1 * dev : na, 'LRC Band StdDev 1', i_lrcolorBand1, 1, show_last = 3 * i_linregLength, display = display)
plot(i_showCurve and i_showCurveBand ? lrc - 1 * dev : na, 'LRC Band StdDev 1', i_lrcolorBand1, 1, show_last = 3 * i_linregLength, display = display)
plot(i_showCurve and i_showCurveBand ? lrc + 2 * dev : na, 'LRC Band StdDev 2', i_lrcolorBand2, 1, show_last = 3 * i_linregLength, display = display)
plot(i_showCurve and i_showCurveBand ? lrc - 2 * dev : na, 'LRC Band StdDev 2', i_lrcolorBand2, 1, show_last = 3 * i_linregLength, display = display)
plot(i_showCurve and i_showCurveBand ? lrc + 3 * dev : na, 'LRC Band StdDev 3', i_lrcolorBand3, 1, show_last = 3 * i_linregLength, display = display)
plot(i_showCurve and i_showCurveBand ? lrc - 3 * dev : na, 'LRC Band StdDev 3', i_lrcolorBand3, 1, show_last = 3 * i_linregLength, display = display)

plotarrow(i_showSlope ? ta.correlation(close, bar_index, i_linregSlopeL) * ta.stdev(close, i_linregSlopeL) / ta.stdev(bar_index, i_linregSlopeL) : na, 'Linear Regression Slope', i_lrcolorSlopeU, i_lrcolorSlopeD, show_last = 3 * i_linregLength, display = display)

// Linear Regression Channel / Curve (Bands) / Slope
// ══════════════════════════════════════════════════════════════════════════════════════════════════ //

// ══════════════════════════════════════════════════════════════════════════════════════════════════ //
//
// Volume / Volatility AddOns
// ══════════════════════════════════════════════════════════════════════════════════════════════════ //

// ---------------------------------------------------------------------------------------------- //
// -Inputs -------------------------------------------------------------------------------------- //

group_vol_vol = 'Volume / Volatility AddOns'

// ---------------------------------------------------------------------------------------------- //
// High Volatility ------------------------------------------------------------------------------ //

tooltip_high_volatility =
     'High Volatility\n' +
     'Detected when the current bar range exceeds ATR × Threshold over the selected period.'

i_hATRLb = input.bool(false, '⚡', inline = 'ATR', group = group_vol_vol, tooltip = tooltip_high_volatility)
i_weightedATR = ta.atr(input.int(13, 'ATR : Length', inline = 'ATR', group = group_vol_vol, display = display)) * input.float(2.718, '    Multiplier', minval = .1, step = .1, inline = 'ATR', group = group_vol_vol, display = display)

// ---------------------------------------------------------------------------------------------- //
// Volume Moving Average : Base ----------------------------------------------------------------- //

i_vSMA = ta.sma(nz(volume), input.int(89, 'Volume Moving Average Length', group = group_vol_vol, display = display))

// ---------------------------------------------------------------------------------------------- //
// Volume Spike - Sign of Exhaustion ------------------------------------------------------------ //
tooltip_volume_spike_sign_of_exhaustion =
     'Sign of Exhaustion\n' +
     'A volume spike occurs when the current volume exceeds the volume moving average multiplied by the threshold value.'

i_vSpikeLb = input.bool(false, '🚦', inline = 'SRS1', group = group_vol_vol, tooltip = tooltip_volume_spike_sign_of_exhaustion)
i_vSpikeThresh = input.float(4.669, 'Volume Spike Threshold                    ', minval = .1, step = .1, inline = 'SRS1', group = group_vol_vol, display = display)

// ---------------------------------------------------------------------------------------------- //
// Volume Weighted Colored Bars ----------------------------------------------------------------- //

tooltip_volume_weighted_colored_bars =
     'Volume-Weighted Colored Bars\n' +
     'Colors bars based on the bar’s volume relative to the volume moving average.'

i_vwcb = input.bool(true, '', inline = 'VWC', group = group_vol_vol, tooltip = tooltip_volume_weighted_colored_bars)
i_vwcbHighThresh = input.float(1.618, 'VWCB Thresholds :  High ', minval = 1., step = .1, inline = 'VWC', group = group_vol_vol, display = display)
i_vwcbLowThresh = input.float(0.618, '  Low', minval = .1, step = .1, inline = 'VWC', group = group_vol_vol, display = display)

// ---------------------------------------------------------------------------------------------- //
// -Calculations and Plotting ------------------------------------------------------------------- //

nzVolume = nz(volume)
bullCandle = close > open
bearCandle = close < open
range_1 = math.abs(high - low)

// ---------------------------------------------------------------------------------------------- //
// Volume Spike - Sign of Exhaustion ------------------------------------------------------------ //

exhaustVol = nzVolume > i_vSpikeThresh * i_vSMA
plotchar(i_vSpikeLb and bool(nzVolume) ? exhaustVol : false, 'Exhaustion Bar', '🚦', location.abovebar, size = size.tiny, show_last = 3 * i_linregLength, display = display)
alertcondition(
    ta.crossover(nzVolume, i_vSMA * i_vSpikeThresh),
    'Volume Spike — Possible Exhaustion',
    'LɪɴRᴇɢ | {{exchange}}:{{ticker}} — Unusual volume spike detected, possible exhaustion or climactic move.\nPrice : {{close}}')


// ---------------------------------------------------------------------------------------------- //
// High Volatility ------------------------------------------------------------------------------ //

highVolatility = range_1 > i_weightedATR
plotchar(i_hATRLb ? highVolatility : false, 'High Volatile Bar', '⚡', location.belowbar, size = size.tiny, show_last = 3 * i_linregLength, display = display)
alertcondition(
    ta.crossover(range_1, i_weightedATR),
    'High Volatility — Wide Bar Detected',
    'LɪɴRᴇɢ | {{exchange}}:{{ticker}} — Unusually wide bar detected, possible breakout or volatility surge.\nPrice : {{close}}')

// ---------------------------------------------------------------------------------------------- //
// Volume Weighted Colored Bars by Kıvanç Özbilgiç ---------------------------------------------- //

vwcbCol = nzVolume > i_vSMA * i_vwcbHighThresh ? bullCandle ? #006400 : #910000 : nzVolume < i_vSMA * i_vwcbLowThresh ? bearCandle ? #FF9800 : #7FFFD4 : na

barcolor(i_vwcb and bool(nzVolume) ? vwcbCol : na, title = 'Volume Weighted Colored Bars', show_last = 3 * i_linregLength)

// Volume / Volatility AddOns
// ══════════════════════════════════════════════════════════════════════════════════════════════════ //

var table logo = table.new(position.bottom_right, 1, 1)
if barstate.islast
    table.cell(logo, 0, 0, '☼☾  ', text_size = size.normal, text_color = color.teal, tooltip = 'SoleMare Analytics')

Overview

The indicator calculates a least-squares median trendline alongside customizable standard deviation upper and lower channel bands. The second channel can optionally extend to a user-defined higher timeframe on intraday timeframes. Settings allow users to adjust regression source, lookback length, line extension, label offsets, and trend-based color options. The regression lines update across the specified lookback length.

Details

Published by

theonetrade on GitHub

Draws

On the price chart

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.

Topics

algorithmic-tradingbacktestingbitcoinccxtcrypto-tradingllm-agentoffline-backtestingopen-source-tradingpine-scriptpine-to-pythonpinescriptpynecorepythonquantquantitative-financestrategy-backtestingtechnical-analysistrading-indicatorstrading-strategiestradingview

Settings

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

SettingTypeDefaultVariable
LinReg1 ⇨ Countbooltruei_linreg
i_linregLengthint200i_linregLength
       Sourcesourceclosei_linregSrc
Extend Lines       boolfalsei_extendLines
Use Trend Colorsboolfalsei_trendColor
Level LabelsstringLevelsi_channelLevels
levelTextSizestringSmalllevelTextSize
Offsetint0levelOffset
LinReg2 ⇨ Countbooltruei_linreg2
i_linregLength2int50i_linregLength2
       Sourcesourceclosei_linregSrc2
LinReg2 ⇨ Extend to User-Defined TF (Intraday Only)booltruei_useTF
Show all 40 settings
SettingTypeDefaultVariable
i_htf_userstring4Hi_htf_user
LinReg2 ⇨ Shorten Display when TF Extend Enabledbooltruei_shorten
i_showLastint500i_showLast
Extend Lines       boolfalsei_extendLines2
Use Trend Colorsboolfalsei_trendColor2
Level LabelsstringLevelsi_channelLevels2
levelTextSize2stringSmalllevelTextSize2
Offsetint0levelOffset2
Linear Regression Line       color#f44336i_lrcolor_m
i_lrstyle_mstringSolidi_lrstyle_m
i_lrwidth_mint3i_lrwidth_m
StdDevbooltruei_lrshow_1
i_lrvalue_1float1.i_lrvalue_1
i_lrcolor_1color#2196f3i_lrcolor_1
i_lrstyle_1stringDashedi_lrstyle_1
i_lrwidth_1int1i_lrwidth_1
StdDevbooltruei_lrshow_2
i_lrvalue_2float2.i_lrvalue_2
i_lrcolor_2color#2196f3i_lrcolor_2
i_lrstyle_2stringSolidi_lrstyle_2
i_lrwidth_2int2i_lrwidth_2
StdDevbooltruei_lrshow_3
i_lrvalue_3float3.i_lrvalue_3
i_lrcolor_3color#2196f3i_lrcolor_3
i_lrstyle_3stringDottedi_lrstyle_3
i_lrwidth_3int2i_lrwidth_3
Linear Regression Line       color#ff9800i_2lrcolor_m
i_2lrstyle_mstringSolidi_2lrstyle_m
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

Swing labels

by tradoor-terminal
320 stars

Calculates swing highs and swing lows on the price chart using pivot high and pivot low detection over a specified length. It places labels above pivot highs and below pivot lows to highlight key structural swing points. The indicator measures and displays the

Indicator v6 Support & resistanceTrend
Updated 3 days ago · AGPL-3.0 GitHub repository of Swing labels

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 5 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 2 months ago · None stated GitHub repository of AI Trend

Dynamic Linear Regression

by TradersPost
228 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 4 months ago · None stated GitHub repository of Dynamic Linear Regression

Ichimoku Cloud

by harryguiacorn
220 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

More Trend scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers