Indicator · Pine Script v6 · On the chart

Trend Duration Forecast

by middlechild0· code credited to ChartPrime

Trend Duration Forecast plots Hull Moving Average on the price chart and detects trend changes using consecutive rising or falling slopes.

View on GitHub

GitHub stars2on the repository
Pine versionv6current
Lines of code181
Settings5inputs
LicenceNone statedfile: MPL-2.0
Last update5 months ago13 May 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

181 lines of Pine Script v6 from mt5/indicators/pine/trend_duration.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

trend_duration.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ChartPrime

//@version=6
indicator("Trend Duration Forecast [ChartPrime]", overlay = true)

// --------------------------------------------------------------------------------------------------------------------}
// 📌 𝙐𝙎𝙀𝙍 𝙄𝙉𝙋𝙐𝙏𝙎
// --------------------------------------------------------------------------------------------------------------------{

length = input.int(
     50,
     title = "Smoothing Length",
     tooltip = "Defines how many bars are used for the Hull Moving Average (HMA). A longer length smooths out short-term noise but increases lag."
 )

trendLength = input.int(
     3,
     title = "Trend Detection Sensitivity",
     tooltip = "Controls how many consecutive bars are checked for rising/falling HMA slope. Lower values make trends switch faster, higher values make them more stable."
 )

samples = input.int(
     10,
     title = "Trend Sample Size",
     minval = 2,
     tooltip = "Defines how many past trend durations are stored to calculate the average probable trend length. Larger samples produce smoother probability estimates."
 )

coloUP = input.color(color.rgb(18, 228, 158), "↑ Trend", inline = "col")
coloDN = input.color(color.rgb(236, 86, 16), "↓ Trend", inline = "col")

var trend = bool(na)
var TrendCount = 0

var bullishCount = array.new<int>()
var bearishCount = array.new<int>()

var TrendUP = label(na)
var TrendDN = label(na)
var LengthLine = line(na)
var LabelProbLen = label(na)



// --------------------------------------------------------------------------------------------------------------------}
// 📌 𝙄𝙉𝘿𝙄𝘾𝘼𝙏𝙊𝙍 𝘾𝘼𝙇𝘾𝙐𝙇𝘼𝙏𝙄𝙊𝙉𝙎
// --------------------------------------------------------------------------------------------------------------------{

series float hma = ta.hma(close, length)

if barstate.isconfirmed
    if ta.rising(hma, trendLength) 
        trend := true
    if ta.falling(hma, trendLength)
        trend := false

if trend or not trend 
    TrendCount += 1

if trend != trend[1]
    LengthLine.delete()
    LabelProbLen.delete()
    TrendUP.set_tooltip("")
    TrendDN.set_tooltip("")

    if trend 
        bearishCount.push(TrendCount)
        TrendUP := label.new(
             bar_index, hma,
             "Trend ↑\nProbable Length: " + str.tostring(bullishCount.avg(), "##"),
             color = color.new(coloUP, 100),
             textcolor = coloUP,
             style = label.style_label_up,
             tooltip = "New bullish trend detected.\nShows Real length of the current bullish trend."
         )
        TrendDN.set_text("Trend ↓\n" + str.tostring(TrendCount) + "\n")
        LengthLine := line.new(
             bar_index - 1, hma[1], bar_index, hma[1],
             color = chart.fg_color, style = line.style_arrow_right
         )
        LabelProbLen := label.new(
             bar_index, hma[1], "",
             style = label.style_label_up,
             textcolor = chart.fg_color,
             color = color.new(color.white, 100),
             tooltip = "Estimated extension of the current bullish trend based on average past durations."
         )
    else 
        bullishCount.push(TrendCount)
        TrendDN := label.new(
             bar_index, hma,
             "Trend ↓\nProbable Length: " + str.tostring(bearishCount.avg(), "##"),
             color = color.new(coloDN, 100),
             textcolor = coloDN,
             style = label.style_label_down,
             tooltip = "New bearish trend detected.\nShows Real length of the current bearish trend."
         )
        TrendUP.set_text("\n" + str.tostring(TrendCount) + "\nTrend ↑")
        LengthLine := line.new(
             bar_index - 1, hma[1], bar_index, hma[1],
             color = chart.fg_color, style = line.style_arrow_right
         )
        LabelProbLen := label.new(
             bar_index, hma[1], "",
             style = label.style_label_down,
             textcolor = chart.fg_color,
             color = color.new(color.white, 100),
             tooltip = "Estimated extension of the current bearish trend based on average past durations."
         )

    TrendCount := 0

// DYNAMIC LABEL UPDATES
if not trend
    TrendDN.set_text(
         "Trend ↓\nReal Length: " + str.tostring(TrendCount) + "\n")
    LengthLine.set_x2(LengthLine.get_x1() + bearishCount.avg() + 1)
    LabelProbLen.set_x(int(math.avg(LengthLine.get_x1(), LengthLine.get_x2())))
    LabelProbLen.set_text(
         "Probable Length\n" + str.tostring(bearishCount.avg(), "##")
     )
else 
    TrendUP.set_text(
         "Trend ↑\nReal Length: " + str.tostring(TrendCount)
     )
    LengthLine.set_x2(LengthLine.get_x1() + bullishCount.avg() + 1)
    LabelProbLen.set_x(int(math.avg(LengthLine.get_x1(), LengthLine.get_x2())))
    LabelProbLen.set_text(
         "Probable Length\n" + str.tostring(bullishCount.avg(), "##")
     )

if bullishCount.size() > samples
    bullishCount.shift()
if bearishCount.size() > samples
    bearishCount.shift()



// --------------------------------------------------------------------------------------------------------------------}
// 📌 𝙑𝙄𝙎𝙐𝘼𝙇𝙄𝙕𝘼𝙏𝙄𝙊𝙉
// --------------------------------------------------------------------------------------------------------------------{
// Trend Color
TColor = trend ? coloUP : coloDN

plot(hma, "HMA", TColor, linewidth = 3)

// TREND LENGTH TABLE
var tbl = table.new(position.bottom_right, 100, 100)
if barstate.islast
    for i = 0 to bullishCount.size() - 1
        // Column numbers
        tbl.cell(0, i + 1, str.tostring(i + 1), text_color = color.gray, tooltip = "Sample index (1 = most recent trend)")

        // Bullish trend lengths
        lenBull = bullishCount.get(i)
        if i == 0
            tbl.cell(1, i, "Trend ↑", text_color = coloUP, tooltip = "Bullish trend length samples — based on detected rising HMA periods")
        tbl.cell(1, i + 1, str.tostring(lenBull), text_color = chart.fg_color,
             tooltip = "Duration of bullish trend #" + str.tostring(i + 1) + " (" + str.tostring(lenBull) + " bars)")

        // Bearish trend lengths
        lenBear = bearishCount.get(i)
        if i == 0
            tbl.cell(2, i, "Trend ↓", text_color = coloDN, tooltip = "Bearish trend length samples — based on detected falling HMA periods")
        tbl.cell(2, i + 1, str.tostring(lenBear), text_color = chart.fg_color,
             tooltip = "Duration of bearish trend #" + str.tostring(i + 1) + " (" + str.tostring(lenBear) + " bars)")

    // Average row at the end
    tbl.cell(
         1, bullishCount.size() + 1,
         str.tostring(bullishCount.avg(), "##"),
         text_color = coloUP,
         tooltip = "Average duration of recent bullish trends (" + str.tostring(bullishCount.avg(), "##") + " bars)"
     )
    tbl.cell(
         2, bearishCount.size() + 1,
         str.tostring(bearishCount.avg(), "##"),
         text_color = coloDN,
         tooltip = "Average duration of recent bearish trends (" + str.tostring(bearishCount.avg(), "##") + " bars)"
     )

Overview

Trend Duration Forecast counts trend bar durations, stores bullish and bearish counts in arrays, and calculates average probable extension lengths for future trend continuation. When a trend reverses, it creates labels showing current trend direction and estimated length based on historical averages. The main settings adjust smoothing length of the HMA, trend detection sensitivity, and number of past samples used for probability estimates. It draws trend up and down labels directly on the price chart.

Details

Published by

middlechild0 on GitHub

Code credit

ChartPrime, as written in the script's header

Draws

On the price chart

Category

Trend

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
Smoothing Lengthint50length
Trend Detection Sensitivityint3trendLength
Trend Sample Sizeint10samples
↑ Trendcolorcolor.rgb(18, 228, 158)coloUP
↓ Trendcolorcolor.rgb(236, 86, 16)coloDN
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

947 stars

The Adaptive Laguerre Filter calculates a smoothed, dynamically adjusted trendline plotted directly on the main price chart. It dynamically adjusts its damping factor (alpha) based on recent price range variations and median percentile calculations over a spec

Indicator v4 TrendMoving averages
Updated 12 days ago · GPL-3.0 GitHub repository of Adaptive Laguerre Filter
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
330 stars

This script plots three moving averages on the price chart: a fast EMA or SMA with 10 periods, a slow EMA or SMA with 20 periods, and a trend EMA or SMA with 100 periods. It signals trend changes by drawing a white cross when the fast moving average crosses ab

Indicator v4 TrendMoving averages
Updated 2 months ago · None stated GitHub repository of 3 EMA/SMA + Cross [Alorse]
318 stars

This indicator calculates an ATR trailing stop line derived from the highest high minus an average true range multiple over a specified lookback period. It plots the trailing stop line directly on the price chart and colors price bars based on whether the clos

Indicator v5 TrendVolatility & bands
Updated 2 months ago · MIT GitHub repository of ATR Trailing Stoploss

All Candlestick Patterns

by shunjizhan
292 stars

All Candlestick Patterns detects and highlights a wide range of bullish, bearish, and neutral candlestick patterns directly on the price chart. It features optional trend filtering using either a 50-period simple moving average or a combination of 50-period an

Indicator v4 Candlestick patternsTrend
Updated 3 years ago · None stated GitHub repository of All Candlestick Patterns

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