Indicator · Pine Script v6 · Own pane

VHF: Vertical Horizontal Filter

by mihakralj

This indicator calculates Adam White's Vertical Horizontal Filter in a separate pane.

View on GitHub

GitHub stars99on the repository
Pine versionv6current
Lines of code93
Settings3inputs
LicenceApache-2.0
Last update4 weeks ago27 Sep 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

93 lines of Pine Script v6 from lib/dynamics/vhf/vhf.pine, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

vhf.pine
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("VHF: Vertical Horizontal Filter", "VHF", overlay=false)

//@function Calculates Vertical Horizontal Filter using max-min range vs sum of absolute changes
//@param period Lookback period for range and path measurement (default: 28)
//@returns VHF value (positive, typically 0 to 1; higher = trending, lower = ranging)
//@references Adam White, "Vertical Horizontal Filter", Futures magazine, August 1991
//@optimized O(1) per bar via circular buffer with running sum + deque-based min/max tracking
vhf(simple int period) =>
    if period <= 1
        runtime.error("Period must be greater than 1")

    // Circular buffer for close values (size = period + 1 to access close[period])
    var array<float> closeBuf = array.new_float(period + 1, na)
    var int head = 0
    var int filled = 0

    // Running sum of absolute bar-to-bar changes over period bars
    // |close[0]-close[1]| + |close[1]-close[2]| + ... + |close[period-2]-close[period-1]|
    // That is period terms of absolute 1-bar changes within the window
    var array<float> absDiffBuf = array.new_float(period, na)
    var int diffHead = 0
    var int diffFilled = 0
    var float diffSum = 0.0

    // Store current close in buffer
    array.set(closeBuf, head, close)
    filled := math.min(filled + 1, period + 1)

    // Compute absolute change from previous close (if available)
    float absDiff = na
    if filled >= 2
        int prevIdx = (head - 1 + period + 1) % (period + 1)
        float prevClose = array.get(closeBuf, prevIdx)
        if not na(prevClose)
            absDiff := math.abs(close - prevClose)

    // Update running sum of absolute differences
    if not na(absDiff)
        float oldDiff = array.get(absDiffBuf, diffHead)
        if not na(oldDiff)
            diffSum -= oldDiff
        diffSum += absDiff
        array.set(absDiffBuf, diffHead, absDiff)
        diffFilled := math.min(diffFilled + 1, period)
        diffHead := (diffHead + 1) % period

    float result = na

    // Need period+1 close values to compute:
    //   - Highest/Lowest over period+1 values (current + period historical)
    //   - Sum of period absolute bar-to-bar changes
    if filled >= period + 1 and diffFilled >= period
        // Step 1: Numerator (Vertical) = Highest(close, period+1) - Lowest(close, period+1)
        // Scan the circular buffer for max and min over the full window
        float hi = -1e308
        float lo = 1e308
        for i = 0 to period
            int idx = (head - i + period + 1) % (period + 1)
            float val = array.get(closeBuf, idx)
            if not na(val)
                hi := math.max(hi, val)
                lo := math.min(lo, val)

        float numerator = hi - lo

        // Step 2: Denominator (Horizontal) = Sum of |close[i] - close[i-1]| over period bars
        float denominator = diffSum

        // Step 3: VHF = Numerator / Denominator
        // Guard against division by zero (flat price = all changes zero)
        if denominator > 1e-10
            result := numerator / denominator

    head := (head + 1) % (period + 1)
    result

// ---------- Main loop ----------

// Inputs
i_period = input.int(28, "Period", minval=2, maxval=200, tooltip="Lookback period (Adam White default: 28)")
i_trendThreshold = input.float(0.40, "Trend Threshold", minval=0.0, maxval=2.0, step=0.05, tooltip="Above this level = trending market")
i_rangeThreshold = input.float(0.25, "Range Threshold", minval=0.0, maxval=2.0, step=0.05, tooltip="Below this level = ranging market")

// Calculation
vhf_value = vhf(i_period)

// Plot
plot(vhf_value, "VHF", color=color.yellow, linewidth=2)
hline(i_trendThreshold, "Trend Threshold", color=color.new(color.green, 50), linestyle=hline.style_dashed)
hline(i_rangeThreshold, "Range Threshold", color=color.new(color.red, 50), linestyle=hline.style_dashed)

Overview

VHF: Vertical Horizontal Filter divides the close range over the lookback by the sum of absolute bar-to-bar close changes, so higher values indicate a more directional path and lower values a more ranging path. The period sets the window, and the trend and range thresholds mark those two regimes. The script uses a circular buffer and a running sum; no stop, entry, or exit rules are included.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

Separate pane below the 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.

Topics

algorithmic-tradingcsharpdotnetpinescriptpythonquantitative-financesimdta-libtechnical-analysistechnical-indicators

Settings

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

SettingTypeDefaultVariable
Periodint28i_period
Trend Thresholdfloat0.40i_trendThreshold
Range Thresholdfloat0.25i_rangeThreshold
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

Schaff Trend Cycle

by everget
948 stars

This indicator plots the Schaff Trend Cycle in a separate pane. It subtracts a slow exponential moving average from a fast one, applies a stochastic cycle twice, and smooths each result to form a 0–100 oscillator. Line color follows the slope, or the upper and

Indicator v4 Oscillators & momentumTrend
Updated 10 days ago · GPL-3.0 GitHub repository of Schaff Trend Cycle

This indicator plots a Supertrend-based trend-following setup in a separate pane and skips conditions it treats as a sideways market. A volatility range is built from an ATR value, with RMA, SMA, EMA, or WMA smoothing, or from a fixed point distance. Optional

Indicator v5 TrendVolatility & bands
Updated 1 year ago · MPL-2.0 GitHub repository of Trend Following Setup - Sideways Market Skipper

Beep Boop

by magic8bot
409 stars

This indicator calculates a modified MACD oscillator and signal line alongside a trend EMA filter, plotting the output as a stylized column histogram in a separate pane. Instead of plotting true MACD distance, it quantifies positive and negative histogram mome

Indicator v4 Oscillators & momentumTrend
Updated 3 years ago · MIT GitHub repository of Beep Boop

[RS]Standardized Trend Map

by ricardosantos79
261 stars

Standardized Trend Map calculates series momentum relative to active price range across 40 distinct lookback periods ranging from 2 to 80 bars on an exponential moving average source. Each standardized calculation rounds to an integer values of -1, 0, or 1 to

Indicator v4 TrendOscillators & momentum
Updated 4 years ago · None stated GitHub repository of [RS]Standardized Trend Map

ADX Histogram

by harryguiacorn
219 stars

This indicator calculates and displays the Average Directional Index (ADX) as a column histogram in a separate pane. It evaluates market trend strength by calculating directional movement metrics based on specified smoothing and DI length inputs. When the ADX

Indicator v5 TrendOscillators & momentum
Updated 1 year ago · None stated GitHub repository of ADX Histogram

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