Indicator · Pine Script v5 · On the chart

Quartiles with Box Plot [KL]

by kevinhhl· code credited to DojiEmoji

This indicator calculates rolling quartiles and interquartile ranges (IQR) across a customizable lookback window, plotting a statistical box plot offset to the right of the chart.

View on GitHub

GitHub stars4on the repository
Pine versionv5runs as is
Lines of code114
Settings14inputs
LicenceNone statedfile: MPL-2.0
Last update3 years ago6 Oct 2023

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

114 lines of Pine Script v5 from Scripts/Rolling Quartile.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Rolling Quartile.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © DojiEmoji

//@version=5
indicator("Quartiles with Box Plot [KL]", overlay=true)

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Settings
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
float src                   = input.source(close, title="Source data")
var int n                   = input.int(20, title="Lookback", minval=1)
var int offset              = input.int(5, minval=5, maxval=150, title="Offset: Box Plot", step=5, tooltip="Relative to recenrt bar (right hand side)")

var string GROUP_1          = "Box plot"
var color color1            = input.color(color.blue, title="Box plot", group=GROUP_1)
var int ln_width            = input.int(2, title="Width", minval=1, maxval=4, group=GROUP_1)
var bool mod_boxplot        = input.bool(false, title="Use modified boxplot (Whiskers = 1.5x IQR)")
var bool show_hline_iqr     = input.bool(true, title="Show lines for rolling IQR", group=GROUP_1)
var bool show_hline_maxmin  = input.bool(false, title="Show lines for rolling Min & Max", group=GROUP_1)

var string GROUP_2          = "Historical IQR - Moving lines"
var string _tt              = "Go to 'Style' tab to modify color/width"
var bool show_bands_iqr     = input.bool(false, title="Show moving IQR", group=GROUP_2, tooltip=_tt)
var bool show_bands_mm      = input.bool(false, title="Show moving Min & Max", group=GROUP_2, tooltip=_tt)

var string GROUP_3          = "Trend Indicator"
var bool use_barcol         = input.bool(false, title="Modify bar colors according to trend:", tooltip="Based on whether price is above/within/below IQR.", group=GROUP_3)
var color color2_up         = input.color(color.blue, title="Uptrend", group=GROUP_3)
var color color3_neutral    = input.color(color.gray, title="Neutral", group=GROUP_3)
var color color4_dn         = input.color(color.red, title="Downtrend", group=GROUP_3)

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Quartiles
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

float Q1 = ta.percentile_linear_interpolation(src, n, 25)
float Q2 = ta.percentile_linear_interpolation(src, n, 50)
float Q3 = ta.percentile_linear_interpolation(src, n, 75)

float iqr_mod = (Q3 - Q1) * 1.5
float Q0 = mod_boxplot ? Q1 - iqr_mod : ta.percentile_linear_interpolation(src, n, 0)
float Q4 = mod_boxplot ? Q3 + iqr_mod : ta.percentile_linear_interpolation(src, n, 100)

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Drawing Box Plot - to represent the quartiles
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// Horizontal lines:
var line hline_q0 = na      //         ---      <- hline_q0
var line hline_q1 = na      //          |
var line hline_q2 = na      //          |
var line hline_q3 = na      //       -------    <- hline_q1
var line hline_q4 = na      //      |       | 
                            //      |       | 
// Box plot:                //      |-------|   <- hline_q2
var box box_iqr = na        //      |       | 
var line ln_q0 = na         //       -------    <- hline_q3
var line ln_q0q1 = na       //          |
var line ln_q2 = na         //          |
var line ln_q4 = na         //         ---      <- hline_q4
var line ln_q3q4 = na


// Helper functions: 
// {
var line[] dump_lns = array.new_line()

// Lines drawn with draw_line() will be temporaily stored in an array of line ("AOL")
draw_line(offset_x1, y1, offset_x2, y2, ln_color, ln_width, ln_style=line.style_solid) =>
    ln = line.new(bar_index+offset_x1, y1, bar_index+offset_x2, y2, xloc.bar_index, color=ln_color, width=ln_width, style=ln_style)
    array.push(dump_lns, ln)
    ln
// All lines in AOL will get deleted in the next bar-iteration through del_lines()
del_lines() =>
    while array.size(dump_lns) > 0
        line.delete(array.pop(dump_lns))   
// }

// Box and whisker
del_lines()
ln_q0   := draw_line(offset-1, Q0, offset+1, Q0, color1, ln_width)
ln_q0q1 := draw_line(offset+0, Q1, offset+0, Q0, color1, ln_width)
ln_q2   := draw_line(offset-2, Q2, offset+2, Q2, color1, ln_width)
ln_q3q4 := draw_line(offset+0, Q3, offset+0, Q4, color1, ln_width)
ln_q4   := draw_line(offset-1, Q4, offset+1, Q4, color1, ln_width)

box.delete(box_iqr[1])
box_iqr := box.new(bar_index+offset-2, Q3, bar_index+offset+2, Q1,
 border_color=color1, bgcolor=na, border_width=ln_width)

// Rolling quartiles
if show_hline_iqr
    hline_q1 := draw_line(-n, Q1, offset-4, Q1, color1, 1, line.style_dotted)
    hline_q2 := draw_line(-n, Q2, offset-4, Q2, color1, 1, line.style_dotted)
    hline_q3 := draw_line(-n, Q3, offset-4, Q3, color1, 1, line.style_dotted)
if show_hline_maxmin
    hline_q0 := draw_line(-n, Q0, offset-4, Q0, color1, 1, line.style_dotted)
    hline_q4 := draw_line(-n, Q4, offset-4, Q4, color1, 1, line.style_dotted)

// Moving quartiles
p1 = plot(Q1, color=show_bands_iqr ? color1 : na, title="Q1 Lower band")
plot(Q2, color=show_bands_iqr ? color1 : na, title="Q2 Center line")
p2 = plot(Q3, color=show_bands_iqr ? color1 : na, title="Q3 Upper band")
fill(p1, p2, color=color.new(color.gray,100), title="Moving IQR")

plot(Q0, color=show_bands_mm ? color1 : na, title="Q0 Min band")
plot(Q4, color=show_bands_mm ? color1 : na, title="Q4 Max band")

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Bar Color (Trend Indicator)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
barcolor(use_barcol and close > Q3 ? color2_up : na, editable=false)
barcolor(use_barcol and close < Q3 and close > Q1 ? color3_neutral : na, editable=false)
barcolor(use_barcol and close < Q1 ? color4_dn : na, editable=false)

Overview

Quartiles with Box Plot [KL] identifies the 25th, 50th (median), and 75th percentiles along with standard min/max or modified 1.5x IQR whiskers. Users can display horizontal projection levels, continuous historical IQR bands, and color price bars based on whether price action sits above, within, or below the interquartile range.

Details

Published by

kevinhhl on GitHub

Code credit

DojiEmoji, as written in the script's header

Type

Indicator, Pine Script v5

Draws

On the price chart

Category

Volatility & bands, Support & resistance, 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
Source datasourceclosesrc
Lookbackint20n
Offset: Box Plotint5offset
Box plotcolorcolor.bluecolor1
Widthint2ln_width
Use modified boxplot (Whiskers = 1.5x IQR)boolfalsemod_boxplot
Show lines for rolling IQRbooltrueshow_hline_iqr
Show lines for rolling Min & Maxboolfalseshow_hline_maxmin
Show moving IQRboolfalseshow_bands_iqr
Show moving Min & Maxboolfalseshow_bands_mm
Modify bar colors according to trend:boolfalseuse_barcol
Uptrendcolorcolor.bluecolor2_up
Show all 14 settings
SettingTypeDefaultVariable
Neutralcolorcolor.graycolor3_neutral
Downtrendcolorcolor.redcolor4_dn
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

[RS]Donchian Fans

by ricardosantos79
261 stars

This indicator plots Donchian Channel boundary lines along with dynamic fan projections directly on the price chart. It calculates the highest high, lowest low, and median price over a customizable lookback period. Whenever price establishes a new channel high

Indicator v4 Support & resistanceTrend
Updated 4 years ago · None stated GitHub repository of [RS]Donchian Fans

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

ATR Trailing Stop

by mihakralj
99 stars

Calculates an ATR-based trailing stop overlaid on the price chart to assist with trend identification and stop placement. Using a specified ATR period and multiplier, it projects upper and lower bounds around the closing price. The stop line ratchets up during

Indicator v5 TrendVolatility & bands
Updated 4 weeks ago · Apache-2.0 GitHub repository of ATR Trailing Stop

Moon Dev Lunar Sniper

by moondevonyt
92 stars

Moon Dev Lunar Sniper is a multi-indicator overlay that scores confluence across fast and slow EMAs, RSI, MACD, DMI, and BB width to fire signals only when score meets the minimum threshold. It plots buy and sell signals on the price chart, highlights cosmic b

Indicator v6 TrendOscillators & momentum Repaints
Updated 8 weeks ago · Custom licence GitHub repository of Moon Dev Lunar Sniper

SuperTrend & Pivots

by dcaoyuan
55 stars

This overlay indicator plots a SuperTrend line on the price chart using a fixed ATR length of 10 and a factor of 3. When the trend direction is up it draws a green line and a light green fill toward the candle midpoint; when down it draws a red line and a ligh

Indicator v6 TrendVolatility & bands
Updated 6 months ago · Apache-2.0 GitHub repository of SuperTrend & Pivots

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