Indicator · Pine Script v6 · Own pane

Interquartile Range (IQR)

by mihakralj

This indicator calculates the interquartile range of a chosen price source over a lookback window.

View on GitHub

GitHub stars99on the repository
Pine versionv6current
Lines of code65
Settings2inputs
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

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

iqr.pine
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Interquartile Range (IQR)", "IQR", overlay=false, precision=4)

//@function Function to calculate percentile using linear interpolation
//@param src Source series for calculation
//@param len Lookback period for data collection
//@param p Percentile value (0-100)
//@returns Calculated percentile value
// Adapted from percentile.pine
iqr(series float src, simple int len, simple float p) =>
    if len <= 0 // Should not happen due to input minval=2
        runtime.error("Lookback Period must be greater than 0.")
        float(na)
    if p < 0 or p > 100
        runtime.error("Percentile 'p' must be between 0 and 100.")
        float(na)
    data_points = array.new_float()
    for i = 0 to len - 1
        val = src[i]
        if not na(val)
            array.push(data_points, val)
    n_valid = array.size(data_points)
    float result = na
    if n_valid == 0
        result := na
    else if n_valid == 1
        result := array.get(data_points, 0)
    else
        array.sort(data_points)
        rank = (p / 100.0) * (n_valid - 1) 
        if p == 0.0
            result := array.get(data_points, 0)
        else if p == 100.0
            result := array.get(data_points, n_valid - 1) 
        else
            k_floor_idx = math.floor(rank)
            k_ceil_idx = math.ceil(rank)
            int_k_floor = math.max(0, math.min(n_valid - 1, int(k_floor_idx)))
            int_k_ceil = math.max(0, math.min(n_valid - 1, int(k_ceil_idx)))
            if int_k_floor == int_k_ceil 
                result := array.get(data_points, int_k_floor)
            else 
                val_floor = array.get(data_points, int_k_floor)
                val_ceil = array.get(data_points, int_k_ceil)
                if val_floor == val_ceil
                    result := val_floor
                else
                    result := val_floor + (rank - k_floor_idx) * (val_ceil - val_floor)
    result

// Inputs
i_source = input.source(close, title="Source")
i_length = input.int(20, title="Lookback Period", minval=2)

// Calculate Q1 (25th percentile) and Q3 (75th percentile)
q1 = iqr(i_source, i_length, 25.0)
q3 = iqr(i_source, i_length, 75.0)

// Calculate IQR
iqr_value = q3 - q1

// Plot IQR
plot(iqr_value, title="IQR", color=color.yellow, linewidth=2)

Overview

Interquartile Range (IQR) estimates the 25th and 75th percentiles with linear interpolation, then plots their difference as a line in a separate pane. The source and lookback period are the main settings, and the lookback must be at least two bars. It does not generate entries, exits, or trade signals.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Category

Volatility & bands

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
Sourcesourceclosei_source
Lookback Periodint20i_length
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

This indicator calculates the distribution of close-to-close percentage changes using rate of change on closing prices. It bins percentage changes into intervals of 0.25 percent increments from negative to positive values and plots a normalized cumulative hist

Indicator v4 Volatility & bands
Updated 10 days ago · GPL-3.0 GitHub repository of Close-to-Close % Change Distribution

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
330 stars

This indicator plots candle range and open-to-close movement as percentages in a separate pane. Range is the high-low difference divided by the low, and change is the close-open difference divided by the open. Both series draw as columns. Teal columns show ran

Indicator v5 Volatility & bands
Updated 2 months ago · None stated GitHub repository of Percent & Volatility [Alorse]

Mojito v3 Strategy

by namuan
318 stars

The Mojito v3 Strategy indicator evaluates volatility term structure by calculating the ratio between front-month and second-month VIX futures contracts. It smooths this ratio using a configurable median filter and compares the result against user-defined uppe

Indicator v5 Volatility & bands
Updated 2 months ago · MIT GitHub repository of Mojito v3 Strategy

Function - Logistic Equation

by ricardosantos79
261 stars

Calculates dynamic modeling values by applying a mathematical logistic differential equation to price change over a specified lookback length. It measures price momentum relative to the recent high-low price range. The script plots positive and negative logist

Indicator v5 Oscillators & momentumVolatility & bands
Updated 4 years ago · None stated GitHub repository of Function - Logistic Equation

MACD-V

by harryguiacorn
219 stars

MACD-V is a volatility-normalized momentum indicator based on research by Alex Spiroglou. It calculates the standard MACD histogram and normalizes it by dividing by the Average True Range (ATR). Plotted in a separate pane as a colored histogram, it includes us

Indicator v5 Oscillators & momentumVolatility & bands
Updated 1 year ago · None stated GitHub repository of MACD-V

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