Library · Pine Script v5 · Library

SessionInfo

by Electrified-Trading

SessionInfo is a Pine Script utility library providing functions for session-specific state tracking and calculations.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code309
Settings0inputs
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

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

SessionInfo.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=5
// @description Utility functions for session specific information like the bar index of the session.
library('SessionInfo', false)

// Note: The following are already provided by PineScript 5.
// session.ismarket     https://www.tradingview.com/pine-script-reference/v5/#var_session{dot}ismarket
// session.ispremarket  https://www.tradingview.com/pine-script-reference/v5/#var_session{dot}ispremarket
// session.ispostmarket https://www.tradingview.com/pine-script-reference/v5/#var_session{dot}ispostmarket


///////////////////////////////////////////////////
// Session Info ///////////////////////////////////
///////////////////////////////////////////////////

///////////////////////////////////////////////////
// @function Returns true if the current bar is in the session specification.
// @param spec session.regular (default), session.extended or other time spec.
// @returns True if the current is in session; otherwise false.
export isIn(
  simple string spec = session.regular,
  simple string res = timeframe.period) =>
    not na(time(res, spec))
///////////////////////////////////////////////////

///////////////////////////////////////////////////
// @function Returns true if the bar is before before the session (default = regular) opens.
// @param spec session.regular (default), session.extended or other time spec.
// @param res The resolution (default = timeframe.period).
// @returns True if before the session.
export isBefore(
  simple string spec = session.regular,
  simple string res = timeframe.period) =>
    if not timeframe.isintraday
        false
    else
        var y = year
        var m = month
        var d = dayofmonth
        var bool start = false

        if y != year or m != month or d != dayofmonth
            y := year
            m := month
            d := dayofmonth
            start := true

        if isIn(spec, res)
            start := false
            false
        else
            start
///////////////////////////////////////////////////

///////////////////////////////////////////////////
// @function Returns true if the bar is before before the session (default = regular) opens.
// @param spec session.regular (default), session.extended or other time spec.
// @param res The resolution (default = timeframe.period).
// @returns True if before the session.
export isAfter(
  simple string spec = session.regular,
  simple string res = timeframe.period) =>
    if not timeframe.isintraday
        false
    else
        var y = year
        var m = month
        var d = dayofmonth
        var int phase = na

        if y != year or m != month or d != dayofmonth
            y := year
            m := month
            d := dayofmonth
            phase := 0

        if isIn(spec, res)
            phase := 1
            false
        else
            phase == 1
///////////////////////////////////////////////////

///////////////////////////////////////////////////
// @function Converts the number of minutes to a length to be used with indicators.
// @param minutes The number of minutes.
// @param multiple The length multiplier.
// @returns math.ceil(minutes * multiple / timeframe.multiplier)
export minutesToLen(
  simple int minutes, 
  simple float multiple = 1) =>
    var minutesPerBar = timeframe.isminutes ? timeframe.multiplier : timeframe.isseconds ? timeframe.multiplier / 60 : na
    math.ceil(minutes * multiple / minutesPerBar)
///////////////////////////////////////////////////

///////////////////////////////////////////////////
// @function Returns the intraday bar index.  May not always map directly to time as a bars can be skipped.
// @param spec session.regular (default), session.extended or other time spec.
// @param res The resolution (default = '1440').
// @returns The integer index of the bar of the session.
export bar(
  simple string spec = session.regular,
  simple string res = '1440') =>
    var int notYet = na
    if timeframe.isdaily
        0
    else if not timeframe.isintraday
        notYet
    else
        var barCount = -1
        barCount += 1

        var y = year
        var m = month
        var d = dayofmonth
        var int firstBar = na
        t = time(res, spec)

        if na(t) or y != year or m != month or d != dayofmonth
            y := year
            m := month
            d := dayofmonth
            firstBar := na(t) ? na : barCount
        else if na(firstBar) and (na(t[1]) and not na(t) or t[1] < t)
            firstBar := barCount

        barCount - firstBar
///////////////////////////////////////////////////

///////////////////////////////////////////////////
// @function Returns the number bars in the past to find the first bar of the session of a given day.
// @param daysPrior The number of days in the past to count the bars.
// @param spec session.regular (default), session.extended or other time spec.
// @param res The resolution (default = '1440').
// @returns The number bars in the past to find the first bar of the session of a given day.
export firstBarOfDay(
  simple int daysPrior = 0,
  simple string spec = session.regular,
  simple string res = '1440') =>
    var int notYet = na
    if daysPrior < 0
        runtime.error('firstBarOfDay(daysPrior) must be (>=0) at least zero.')
        notYet
    else if timeframe.isdaily
        0
    else if not timeframe.isintraday
        notYet
    else
        var days = daysPrior + 1
        var dayRecord = array.new_int()
        var dayCount = 0
        var barCount = -1
        barCount += 1

        var y = year
        var m = month
        var d = dayofmonth
        var int firstBar = na
        t = time(res, spec)

        if y != year or m != month or d != dayofmonth
            y := year
            m := month
            d := dayofmonth
            if not na(t)
                array.push(dayRecord, barCount)
                dayCount += 1
                if dayCount > days
                    array.shift(dayRecord)
                    dayCount -= 1
                
        else if na(t[1]) and not na(t) or t[1] < t
            array.push(dayRecord, barCount)
            dayCount += 1
            if dayCount > days
                array.shift(dayRecord)
                dayCount -= 1

        dayCount == 0 ? notYet : barCount - array.get(dayRecord, 0)
///////////////////////////////////////////////////

///////////////////////////////////////////////////
// @function Returns true if the current bar is the first one of the session.
// @param spec session.regular (default), session.extended or other time spec.
// @param res The resolution (default = '1440').
// @returns True if the current bar is the first one of the session.
export isFirstBar(
  simple string spec = session.regular,
  simple string res = '1440') => bar(spec, res) == 0
///////////////////////////////////////////////////

///////////////////////////////////////////////////
// @function Returns Returns true if the previous bar was the last of the session.
// @param spec session.regular (default), session.extended or other time spec.
// @param res The resolution (default = '1440').
// @returns True if was the last bar of the session.
export wasLastBar(
  simple string spec = session.regular,
  simple string res = '1440') =>
    var bool notYet = na
    if timeframe.isdaily
        true
    else if not timeframe.isintraday
        notYet
    else
        var int b = na
        bb = bar(spec, res)
        wasLast = bb < b or na(bb) and not na(b)
        b := bb
        wasLast
///////////////////////////////////////////////////

//////////////////////////////////////////////////
// @function Returns maximum (usual) number of bars per day.
// @param spec session.regular (default), session.extended or other time spec.
// @param res The resolution (default = '1440').
// @returns The max (usual) number of bars per day.
export maxBars(
  simple string spec = session.regular,
  simple string res = '1440') =>
    var int notYet = na
    if timeframe.isdaily
        1
    else if not timeframe.isintraday
        notYet
    else
        var int max = na
        var int b = 0
        var int count = 0
        b += 1
        if wasLastBar(spec, res)
            count += 1
            if na(max) or b > max
                max := b
        if isFirstBar(spec, res)
            b := 0
        
        count > 3 ? max : na
///////////////////////////////////////////////////   

//////////////////////////////////////////////////
// @function Returns maximum (usual) number of minutes per day.
// @param spec session.regular (default), session.extended or other time spec.
// @param res The resolution (default = '1440').
// @returns The max (usual) number of minutes per day.
export maxMinutes(
  simple string spec = session.regular,
  simple string res = '1440') =>
    maxBars(spec, res) * timeframe.multiplier
///////////////////////////////////////////////////

//////////////////////////////////////////////////
// @function Returns the number of bars equal to the number of days based upon usual session length.
// @param spec session.regular (default), session.extended or other time spec.
// @param res The resolution (default = '1440').
// @returns The number of bars representing the number of days.
export daysToBars(
  simple int days,
  simple string spec = session.regular,
  simple string res = '1440') =>
    var int notYet = na
    if timeframe.isdaily
        days
    else if not timeframe.isintraday
        notYet
    else
        days * maxBars(spec, res)
///////////////////////////////////////////////////   

///////////////////////////////////////////////////
// @function Returns the number bars in the past to find the last bar of the session of a given day.
// @param daysPrior The number of days in the past to count the bars.
// @param spec session.regular (default), session.extended or other time spec.
// @param res The resolution (default = '1440').
// @returns The number bars in the past to find the last bar of the session of a given day.
export lastBarOfDay(
  simple int daysPrior = 1,
  simple string spec = session.regular,
  simple string res = '1440') =>
    var int notYet = na
    if daysPrior < 1
        runtime.error('lastBarOfDay(daysPrior) must be (>=1) at least one.')
        notYet
    else if timeframe.isdaily
        daysPrior
    else if not timeframe.isintraday
        notYet
    else
        var dayRecord = array.new_int()
        var dayCount = 0
        var barCount = -1
        barCount += 1

        if wasLastBar(spec, res)
            array.push(dayRecord, barCount - 1)
            dayCount += 1
            if dayCount > daysPrior
                array.shift(dayRecord)
                dayCount -= 1

        dayCount == 0 ? notYet : barCount - array.get(dayRecord, 0)
///////////////////////////////////////////////////

bos = bar()
plot(bos, 'Bar of the Standard Session', color=color.green, style=plot.style_stepline)
bose = bar(session.extended)
plot(bose, 'Bar of the Extended Session', style=plot.style_stepline)

Overview

SessionInfo exports routines to determine whether the current intraday bar falls within a specified session, before the session begins, or after it concludes. It also includes helper logic to convert elapsed minutes into bar lengths based on the current chart timeframe. Designed for use by other indicators and strategies, the library performs no independent plotting on the price chart.

Details

Published by

Electrified-Trading on GitHub

Type

Library, Pine Script v5

Draws

Library (no plots)

Category

Sessions & time

Markets

Any symbol

Timeframes

M1-M5, M15-H1

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.

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

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

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

AIActivationFunctionsBipolarSigmoid is a Pine Script library that provides mathematical implementations of the bipolar sigmoid activation function and its derivatives for machine learning algorithms. It calculates bipolar sigmoid values bounded between -1 and

Library v5 AI / machine learning
Updated 4 years ago · None stated GitHub repository of AIActivationFunctionsBipolarSigmoid

KernelFunctions

by artificial-intelligence-edge
75 stars

KernelFunctions is a Pine Script v5 library that exports kernel weight functions for Nadaraya-Watson style estimation. It calculates a Rational Quadratic kernel, a Gaussian kernel based on a radial basis function, and a periodic kernel that models repeating be

Library v5
Updated 2 days ago · MIT GitHub repository of KernelFunctions

Ta

by nersent
29 stars

This Pine Script v5 library exports thin wrappers around built-in technical analysis functions. It covers moving averages, momentum measures such as RSI and CCI, volatility tools including ATR and standard deviation, range extremes, cross detection, and runnin

Library v5
Updated 11 months ago · Custom licence GitHub repository of Ta

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

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