Indicator · Pine Script v5 · Own pane

Intrabar Run Count Indicator [tbiktag]

by regalouisei· code credited to tbiktag

This indicator evaluates market non-randomness by running a Wald-Wolfowitz runs test on intrabar price movements.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code140
Settings8inputs
LicenceNone statedfile: MPL-2.0
Last update8 months ago25 Feb 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

140 lines of Pine Script v5 from pinescript/editors_picks/intrabar-run-count-indicator-tbiktag.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

intrabar-run-count-indicator-tbiktag.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tbiktag

//@version=5
indicator("Intrabar Run Count Indicator [tbiktag]", "IRCI", overlay = false)

// --- External libs ---
import PineCoders/lower_tf/4 as PCltf
//

// --- Constant variables ---
//     Titles and tooltips
string T0    = "N intrabars"
string T1    = "Confidence level"
string T2    = "Bar coloring" 
string T3    = "Background coloring" 
string T4    = "Show infobox" 
string T5    = "Signal / bar color     "
string T6    = "Test statistic color   " 
string T7    = "Lines / levels color   " 
string TT0   = "Select approximately how many intrabars will be analyzed for each chart bar. 
 To define the optimal lower timeframe in relation to the selected number of intrabars,
 the script uses the lower_ltf library published by TradingView."
string TT1   = "Select the desired confidence level that defines the critical value. 
 If the test statistic exceeds the critical value, it suggests non-randomness."
string TT2   = "The signal is triggered if \n 
 •the test statistic exceeds the critical value, and \n
 •there is sufficient number of data points in the sample (>20)." 
string TT3   = "If selected, bar coloring uses the following color scheme: \n
 •Signal color: the test statistic is greater than the critical value. \n
 •Transparent: not enough data point in the sample. \n
 •Default chart color: the test statistic is below the critical value."
string TT4   = "The infobox displays the number of intrabars used for analysis."
string GR0   = "Input"
string GR1   = "Style"
//
//     LTF distinction 
string LTF1  = "~50 intrabars per chart bar"
string LTF2  = "~100 intrabars per chart bar"
string LTF3  = "~250 intrabars per chart bar"
//
//     Minimum sample size for runs test
int    THRS  = 20
//
//     Color scheme
color  RED   = #f1363f
color  YELL  = #f1e836
color  GREY  = #CCCCCC
//
//     Confidence levels
float  ZC80  = 1.280 //alpha = 0.20
float  ZC90  = 1.645 //alpha = 0.10
float  ZC95  = 1.960 //alpha = 0.05
//

// --- Inputs ---
string ltfRes  = input.string(LTF2,  T0, [LTF1, LTF2, LTF3],    TT0, '', GR0)
string zMode   = input.string('90%', T1, ["80%", "90%", "95%"], TT1, '', GR0) 
bool   isColB  = input.bool(true,    T2,                        TT3, '', GR1)
bool   isBG    = input.bool(true,    T3,                        '',  '', GR1)
bool   isIBox  = input.bool(false,   T4,                        TT4, '', GR1)
color  CS      = input.color(YELL,   T5,                        '',  '', GR1)
color  C0      = input.color(RED,    T6,                        '',  '', GR1)
color  CL      = input.color(GREY,   T7,                        '',  '', GR1)
//

// --- Functions ---
runsTest(data) =>
    //
    // Calculate the test statistic of the Wald-Wolfowitz runs test,
    // by analyzing the signs of the input array elements.
    //
    // Input:  data,  float array  :: input data set
    // Output: zStat, float        :: test statistic
    //
    int   n        = array.size(data)
    int   nP       = 0
    int   nM       = 0
    int   R        = 1
    float lastR    = n>0?array.get(data, 0):na
    for  i = 0 to n>THRS?n-1:na
        iR = array.get(data, i)
        if iR > 0 
            nP    += 1
        else
            nM    += 1
        if   i > 0 and math.sign(iR) != math.sign(lastR)
            lastR := iR
            R     += 1 
    float mean     = 2*nP*nM/n + 1
    float sigma    = math.sqrt((mean-1)*(mean-2)/(n-1))
    float zStat    = (R - mean)/sigma
    zStat
//

// --- Calculations ---
var string   lSt        = PCltf.ltf(ltfRes, '', '', '', '', '', '', '', LTF1, LTF2, LTF3)
array<float> ltfReturns = request.security_lower_tf(syminfo.tickerid, lSt, ta.change(close))
float        zStat      = runsTest(ltfReturns)
int          nDataPts   = array.size(ltfReturns)
[nIBs, nCBs, avgIBs]    = PCltf.ltfStats(ltfReturns)
//
float  zCrit   = switch zMode
    "80%"       => ZC80
    "90%"       => ZC90
    "95%"       => ZC95
bool    isH1   = math.abs(zStat) >= zCrit
//

// --- Visuals ---
//     Define plot colors
color colZ   = isH1?color.new(C0, 30):color.new(C0, 60)
color colB   = switch
    isColB and isH1      => CS
    isColB and na(zStat) => color.new(CL, 100) 
    not (isColB or isH1) => na
//
//     Plot
plotZ  = plot(zStat,  'Test Statistic',             color=colZ,  style=plot.style_area)
plotshape(isH1,       'Signal', style=shape.circle, color=colB,  location=location.top)
plotshape(isH1,       'Signal', style=shape.circle, color=colB,  location=location.bottom)
plotC0 = hline(0.0,   'Zero',                       color=color.new(CL, 60))
plotC1 = hline( zCrit,'Critical Value',             color=color.new(CL, 60))
plotC2 = hline(-zCrit,'Critical Value',             color=color.new(CL, 60))
fill(plotC0, plotC1, 0,  zCrit, color.new(CL, 99),  color.new(CL, 80), display=isBG?display.all:display.none)
fill(plotC0, plotC2, 0, -zCrit, color.new(CL, 99),  color.new(CL, 80), display=isBG?display.all:display.none)
barcolor(colB)
//
//     Infobox
if isIBox
    var table iBox  = table.new(position.bottom_left, 1, 2, bgcolor = #FDE6E7)
    if barstate.islast 
        table.cell(iBox, 0, 0, "N intrabars used now: "+str.tostring(nIBs))
        table.cell(iBox, 0, 1, "N intrabars used on average: "+str.tostring(avgIBs,'#.##'))
//

// --- Error messages ---
if barstate.islast and avgIBs < THRS
    runtime.error('Insufficient intrabar data available at the given timeframe')
//

Overview

Using lower timeframe data requested via external libraries, it measures whether intrabar directional price sequences significantly deviate from a random distribution. The script calculates a z-score test statistic and compares it against configurable confidence levels (80%, 90%, or 95%). When non-randomness is detected with sufficient sample size, it highlights chart bars and background colors. Users can select target intrabar counts per chart bar, toggle signal colors, and display an information box in a separate indicator pane.

Details

Published by

regalouisei on GitHub

Code credit

tbiktag, as written in the script's header

Type

Indicator, Pine Script v5

Draws

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

Settings

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

SettingTypeDefaultVariable
ltfResstringLTF2ltfRes
zModestring90%zMode
isColBbooltrueisColB
isBGbooltrueisBG
isIBoxboolfalseisIBox
CScolorYELLCS
C0colorREDC0
CLcolorGREYCL
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

Asymmetrical RSI

by everget
948 stars

Asymmetrical RSI is an indicator that computes a custom relative strength index from the rate of change of a user-selected source. It plots the resulting ARSI line in a separate pane with color coding that turns green above the overbought level and red below t

Indicator v4 Oscillators & momentum
Updated 10 days ago · GPL-3.0 GitHub repository of Asymmetrical RSI

This indicator calculates momentum setups based on the Relative Strength Index (RSI) and plots in a separate pane. It offers multiple scanning modes such as Continuous Break, Continuous Retracement, Flip Break, Flip Retracement, and both regular and hidden div

Indicator v6 Oscillators & momentumDivergence Repaints
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup - RSI Directional Momentum Indicator
549 stars

Range Volume Change compares volume inside a chosen session window with the same window on the previous day and plots that change as a percentage. It accumulates volume during the window and, when enabled, volume outside it, drawing growing columns in a separa

Indicator v5 VolumeSessions & time Repaints
Updated 10 months ago · None stated GitHub repository of Range Volume Change

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

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

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