Library · Pine Script v6 · Library

GapDetect

by Electrified-Trading

This library determines opening gap severity by calculating the standard deviation of overnight gaps.

View on GitHub

GitHub stars2on the repository
Pine versionv6current
Lines of code147
Settings1inputs
LicenceMPL-2.0
Last update1 year ago7 Jul 2025

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 library, select all of the template text and paste. Press Save and give it a name.
  4. 4Publish or import itA library draws nothing. Publish it from the editor, then import its functions in your own scripts.

Source Code

147 lines of Pine Script v6 from GapDetect.pine, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.

GapDetect.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Electrified (electrifiedtrading)

//@version=6

// @description Helps in determining opening gap severity by measuring the standard deviation of the open minus the previous close.
library('GapDetect', false)
import Electrified/SessionInfo/11 as Session

///////////////////////////////////////////////////
//// Gap Detection ////////////////////////////////
///////////////////////////////////////////////////


//////////////////////////////////////////////////
// @function Returns today's overnight gap value.
// @param spec session.regular (default), session.extended or other time spec.
// @param res The resolution (default = '1440').
export today(
  simple string spec = session.regular,
  simple string res = '1440') =>
    var float value = na
    var float previousClose = na

    if timeframe.isdaily
        value := open - close[1]
    else if not timeframe.isintraday
        value
    else 
        if(Session.wasLastBar(spec, res))
            previousClose := close[1]
        if(Session.isFirstBar(spec, res))
            value := open - previousClose
        value
///////////////////////////////////////////////////

//////////////////////////////////////////////////
// @function Returns today's overnight gap (% move).
// @param spec session.regular (default), session.extended or other time spec.
// @param res The resolution (default = '1440').
export todayPercent(
  simple string spec = session.regular,
  simple string res = '1440') =>
    var float value = na
    var float previousClose = na

    c1 = close[1]
    if timeframe.isdaily
        value := (open - c1) / c1
    else if not timeframe.isintraday
        value
    else 
        if(Session.wasLastBar(spec, res))
            previousClose := c1
        if(Session.isFirstBar(spec, res))
            value := (open - previousClose) / previousClose
        value
///////////////////////////////////////////////////

//////////////////////////////////////////////////
// @function Returns the normal daily standard deviation of the overnight gap value.
// @param days Number of days back to measure.
// @param maxDeviation The limit of volatility before considered an outlier.
// @param spec session.regular (default), session.extended or other time spec.
// @param res The resolution (default = '1440').
export normal(
  simple int days,
  simple float maxDeviation = 2,
  simple string spec = session.regular,
  simple string res = '1440') =>
    var delta = array.new_float()
    var result = array.new_float()

    value = today(spec, res)
    if(Session.isFirstBar(spec, res))
        array.push(delta, value)

    if(array.size(delta) > days)
        array.shift(delta)
        avg = array.avg(delta)
        stdev = array.stdev(delta)
        level = stdev * maxDeviation
        hi = avg + level
        lo = avg - level
        if lo < value or value < hi
            array.push(result, value)
        if(array.size(result) > days)
            array.shift(result)

    array.stdev(result)
///////////////////////////////////////////////////

// @function Returns the normal daily standard deviation of the overnight gap (% move).
// @param days Number of days back to measure.
// @param maxDeviation The limit of volatility before considered an outlier.
// @param spec session.regular (default), session.extended or other time spec.
// @param res The resolution (default = '1440').
export normalPercent(
  simple int days,
  simple float maxDeviation = 2,
  simple string spec = session.regular,
  simple string res = '1440') =>
    var delta = array.new_float()
    var result = array.new_float()
    
    value = todayPercent(spec, res)
    if(Session.isFirstBar(spec, res))
        array.push(delta, value)

    if(array.size(delta) > days)
        array.shift(delta)
        avg = array.avg(delta)
        stdev = array.stdev(delta)
        level = stdev * maxDeviation
        hi = avg + level
        lo = avg - level
        if lo < value or value < hi
            array.push(result, value)
        if(array.size(result) > days)
            array.shift(result)

    array.stdev(result)
///////////////////////////////////////////////////   

//////////////////////////////////////////////////
// @function Returns the severity of the overnight in ratios of the normal standard deviation.
// @param days Number of days back to measure.
// @param maxDeviation The limit of volatility before considered an outlier.
// @param spec session.regular (default), session.extended or other time spec.
// @param res The resolution (default = '1440').
export severity(
  simple int days,
  simple float maxDeviation = 2, 
  simple string spec = session.regular,
  simple string res = '1440') =>
    todayPercent(spec, res) / normalPercent(days, maxDeviation, spec, res)
///////////////////////////////////////////////////

hline(+2)
hline(+1)
hline(0, linestyle=hline.style_solid)
hline(-1)
hline(-2)

s = severity(input.int(50, 'Days to Measure', minval=3))
c = s < 0 ? color.red : color.green
plot(s, 'Gap Severity', c, style=plot.style_areabr)

Overview

GapDetect exports functions for today's gap value as open minus previous close, gap percent change, and normal daily standard deviation of the gap using a rolling window. The main setting is days to measure for the standard deviation calculation. The library relies on a session information library for accurate time-based gap detection. It provides no plots on the chart and contains no trading signals or exit rules.

Details

Published by

Electrified-Trading on GitHub

Type

Library, Pine Script v6

Draws

Library (no plots)

Category

Volatility & bands, Sessions & time

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
Days to Measureint50Days to Measure
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

Bands

by heyphat
26 stars

This library exports a Band type and functions that build a simple-moving-average basis with upper and lower envelopes from standard deviation. It classifies a source as above, below, or inside those envelopes, measures band width, and scales an imported z-sco

Library v6 Volatility & bandsMoving averages
Updated 2 months ago · AGPL-3.0 GitHub repository of Bands

AuthLib

by alboogycOdR
6 stars

AuthLib is a Pine Script v5 library that checks a caller username against a fixed list and, when authorized, prepares drawings for six killzone sessions. It stores boxes, labels, trend lines and price labels in a DrawingData type. For each window it tracks the

Library v5 Sessions & timeSMC / ICT / price action
Updated 7 months ago · None stated GitHub repository of AuthLib

Public

by wanjo-tech
6 stars

This Pine Script v5 library walks historical price, volume, time and amount series until a requested number of hours is covered, stopping at 4999 bars. TimeAligned returns the bar count, net and absolute price changes, net and absolute log-price changes, volum

Library v5 Volatility & bandsVolume
Updated 2 years ago · None stated GitHub repository of Public

VolTargeting

by Robot-Wealth
4 stars

VolTargeting is a Pine Script v5 library of functions for volatility-based position sizing. ewmaVol estimates exponentially weighted annualised volatility from squared simple returns and scales it by the square root of 365 days for crypto or 252 days otherwise

Library v5 Volatility & bands
Updated 2 years ago · None stated GitHub repository of VolTargeting

ta

by ivansoft
1 stars

Provides a collection of technical analysis calculation functions for use across Pine scripts. It exports implementations for various indicators and mathematical formulas, including oscillators like the Awesome Oscillator, Aroon, and Schaff Trend Cycle, moving

Library v5 TrendOscillators & momentum
Updated 1 year ago · None stated GitHub repository of ta

SFA FlowLiquidity v1

by genesisgrubio39
1 stars

The SFA FlowLiquidity library computes structural flow and liquidity events from price data. It detects sweep ups and downs with associated scores, identifies liquidity levels, and applies session and regime filters. Persistent arrays track liquidity prices, b

Library v6 SMC / ICT / price actionSupport & resistance
Updated 10 months ago · None stated GitHub repository of SFA FlowLiquidity v1

More libraries

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers