Indicator · Pine Script v5 · On the chart

FX Market Sessions

by itmakesyousick· code credited to boitoki

FX Market Sessions highlights distinct trading sessions, such as London, New York, and Tokyo, directly on the main price chart.

View on GitHub

GitHub stars7on the repository
Pine versionv5runs as is
Lines of code387
Settings40inputs
LicenceNone statedfile: MPL-2.0
Last update3 years ago25 Jan 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

387 lines of Pine Script v5 from v27.0.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

v27.0.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © boitoki

//@version=5
indicator('FX Market Sessions', overlay=true, max_boxes_count=500, max_labels_count=500, max_lines_count=500, max_bars_back=1000)

import boitoki/AwesomeColor/2 as ac

///////////////
// Groups
///////////////
g1 = '♯1 Session'
g2 = '♯2 Session'
g3 = '♯3 Session'
g4 = 'Box'
g6 = 'Labels'
g5 = 'Opening range'
g7 = 'Fibonacci levels'
YES = 'Yes'
YES_PRICE = 'Price'
YES_PIPS = 'Pips'
NO = 'No'

t_extend_option1 = 'Extend'

///////////////
// Defined
///////////////
bool show = timeframe.isintraday and timeframe.multiplier <= 60 and timeframe.multiplier >= 1
int lookback = 12 * 60
color nonecolor = color.new(color.black, 100)
float pips = syminfo.mintick * 10

///////////////
// Inputs
///////////////
// Timezone
i_tz = input.string('GMT+1', title='Timezone', tooltip='e.g. \'America/New_York\', \'Asia/Tokyo\', \'GMT-4\', \'GMT+9\'...', group='General')
i_show_history = input.string(YES, 'History', options=[YES, NO], group="General") == YES

// Oscillator mode
i_osc = input.bool(false, 'Oscillator', inline='osc', group='General')
i_osc_min = input.float(0, '', inline='osc', group='General')
i_osc_max = input.float(100, '~', inline='osc', group='General')

// Sessions
i_show_sess1 = input.bool(true, 'Session 1: ', group=g1, inline='session1_1') and show
i_sess1_label = input.string('London', ' ', group=g1, inline='session1_1')
i_sess1_color = input.color(#66D9EF, ' ', group=g1, inline='session1_1')
i_sess1 = input.session('0800-1600', 'Time', group=g1)
i_sess1_extend = input.string(NO, t_extend_option1, options=[NO, t_extend_option1], group=g1)
i_sess1_fib = input.string(NO, 'Fibonacci levels', group=g1, options=[YES, NO]) != NO
i_sess1_op = input.string(NO, 'Opening range', group=g1, options=[YES, NO]) != NO and show

i_show_sess2 = input.bool(true, 'Session 2: ', group=g2, inline='session2_1') and show
i_sess2_label = input.string('New York', ' ', group=g2, inline='session2_1')
i_sess2_color = input.color(#FD971F, ' ', group=g2, inline='session2_1')
i_sess2 = input.session('1300-2200', 'Time', group=g2)
i_sess2_extend = input.string(NO, t_extend_option1, options=[NO, t_extend_option1], group=g2)
i_sess2_fib = input.string(NO, 'Fibonacci levels', group=g2, options=[YES, NO]) != NO
i_sess2_op = input.string(NO, 'Opening range', group=g2, options=[YES, NO]) != NO and show

i_show_sess3 = input.bool(true, 'Session 3: ', group=g3, inline='session3_1') and show
i_sess3_label = input.string('Tokyo', ' ', group=g3, inline='session3_1')
i_sess3_color = input.color(#AE81FF, ' ', group=g3, inline='session3_1')
i_sess3 = input.session('0000-0900', 'Time', group=g3)
i_sess3_extend = input.string(NO, t_extend_option1, options=[NO, t_extend_option1], group=g3)
i_sess3_fib = input.string(NO, 'Fibonacci levels', group=g3, options=[YES, NO]) != NO
i_sess3_op = input.string(NO, 'Opening range', group=g3, options=[YES, NO]) != NO and show

// Show & Styles
i_sess_border_style = input.string(line.style_dashed, 'Style', options=[line.style_solid, line.style_dotted, line.style_dashed], group=g4)
i_sess_border_width = input.int(1, 'Thickness', minval=0, group=g4)
i_sess_bgopacity = input.int(94, 'Transp', minval=0, maxval=100, step=1, group=g4, tooltip='Setting the 100 is no background color')

// Labels
i_label_show = input.bool(true, 'Show labels', inline='label_show', group=g6) and show
i_label_size = str.lower(input.string('Normal', '', options=['Auto', 'Tiny', 'Small', 'Normal', 'Large', 'Huge'], inline='label_show', group=g6))
i_label_position_y = str.lower(input.string('Top', 'Position', options=['Top', 'Bottom'], inline='label_position', group=g6))
i_label_position_s = str.lower(input.string('Outside', '', options=['Inside', 'Outside'], inline='label_position', group=g6))
i_label_chg = input.string(NO, "Change value", options=[NO, YES_PRICE, YES_PIPS], group=g6)

// Fibonacci levels
i_f_linestyle = input.string(line.style_solid, title="Style", options=[line.style_solid, line.style_dotted, line.style_dashed], group=g7)
i_f_linewidth = input.int(1, title="Thickness", minval=1, group=g7)

// Opening range
i_o_minutes = input.int(15, title='Periods (minutes)', minval=1, step=1, group=g5)
i_o_transp = input.int(88, title='Transp', minval=0, maxval=100, step=1, group=g5)


// Alerts
i_alert1_show = input.bool(false, 'Alerts - Sessions stard/end', group='Alerts visualized')
i_alert2_show = input.bool(false, 'Alerts - Opening range breakouts', group='Alerts visualized')
i_alert3_show = input.bool(false, 'Alerts - Price crossed session\'s High/Low after session closed', group='Alerts visualized')


// Variables
icon_closed = '⚀'
icon_separator = ' • '

f_price = '{0,number,#.#####}'
f_pip = '{0,number,#.#}'

///////////////
// Functions
///////////////
get_time_by_bar(bar_count) => timeframe.multiplier * bar_count * 60 * 1000

get_period (_session, _start, _lookback) =>
    result = math.max(_start, 1)
    for i = result to _lookback
        if na(_session[i+1]) and _session[i]
            result := i
            break
    result

is_start (_session) => na(_session[1]) and _session

is_end (_session) => na(_session) and _session[1]


// ------------------------
// Drawing progress
// ------------------------
// [├, ┤, ∅, •]
draw_progress (_show, _session, _is_started, _is_ended, _color, _top, _bottom, _delete_history) =>
    var label my_label = na

    if _show
        if _is_started
            my_label := label.new(time, _bottom, '', textcolor=color.new(_color, 10), style=label.style_label_lower_right, color=nonecolor, xloc=xloc.bar_time, size=size.small)
            
            if _delete_history
                label.delete(my_label[1])

        if _session
            label.set_y(my_label, _bottom)
            label.set_x(my_label, time)
        
        if _is_ended
            label.set_text(my_label, icon_closed)
            label.set_x(my_label, time)

// ------------------------
// Drawing labels
// ------------------------
draw_label (_show, _session, _is_started, _color, _top, _bottom, _text, _delete_history) =>
    var label my_label = na
    label_text = array.new_string()
    label_y = i_label_position_y == 'top' ? _top : _bottom
    label_style = i_label_position_y == 'top'
      ? i_label_position_s == 'outside' ? label.style_label_lower_left : label.style_label_upper_left
      : i_label_position_s == 'outside' ? label.style_label_upper_left : label.style_label_lower_left
    
    if not na(_text)
        array.push(label_text, _text)

    chg = _top - _bottom
    chg_text = i_label_chg == YES_PRICE 
      ? str.format(f_price, chg)
      : str.format(f_pip, chg / pips) + ' pips'

    if i_label_chg != NO
        array.push(label_text, chg_text)

    if _show
        if _is_started
            my_label := label.new(time, label_y, array.join(label_text, icon_separator), textcolor=_color, color=nonecolor, size=i_label_size, style=label_style, xloc=xloc.bar_time)
            
            if _delete_history
                label.delete(my_label[1])

        if _session
            label.set_y(my_label, label_y)
            label.set_text(my_label, array.join(label_text, icon_separator))

// ------------------------
// Drawing Fibonacci levels
// ------------------------
draw_fib (_show, _session, _is_started, _x1, _x2, _color, _top, _bottom, _level, _width, _style, _is_extend, _delete_history) =>
    var line my_line = na

    if _show
        y = (_top - _bottom) * _level + _bottom

        if _is_started
            my_line := line.new(_x1, y, _x2, y, width=_width, color=color.new(_color, 30), style=_style)

            if _is_extend
                line.set_extend(my_line, extend.right)

            if _delete_history
                line.delete(my_line[1])

        if _session
            line.set_y1(my_line, y)
            line.set_y2(my_line, y)


// ------------------------
// Drawing Opening range
// ------------------------
draw_op (_show, _session, _is_started, _x1, _x2, _color, _max, _is_extend, _delete_history) =>
    var int start_time = na
    var box my_box = na
    top = ta.highest(high, _max)
    bottom = ta.lowest(low, _max)
    is_crossover = ta.crossover(close, box.get_top(my_box))
    is_crossunder = ta.crossunder(close, box.get_bottom(my_box))
    
    if _show
        if _is_started
            start_time := time
            my_box := na

            if _delete_history
                box.delete(my_box[1])

        if _session
            time_op = start_time + (i_o_minutes * 60 * 1000)
            
            if time >= time_op and time < time_op + get_time_by_bar(1)
                my_box := box.new(_x1, top, _x2, bottom, border_width=0, bgcolor=color.new(_color, i_o_transp))

                if _is_extend
                    box.set_extend(my_box, extend.right)
                    my_box

            else
                //box.set_right(my_box, bar_index + 1)

                if is_crossover
                    alert('Price crossed over the opening range', alert.freq_once_per_bar)

                    if i_alert2_show
                        label.new(bar_index, box.get_top(my_box), "×", color=color.blue, textcolor=ac.tradingview('blue'), style=label.style_none, size=size.large)

                if is_crossunder
                    alert('Price crossed under the opening range', alert.freq_once_per_bar)

                    if i_alert2_show
                        label.new(bar_index, box.get_bottom(my_box), "×", color=color.red, textcolor=ac.tradingview('red'), style=label.style_none, size=size.large)

                my_box

// ------------------------
// Drawing market
// ------------------------
draw_market (_show, _session, _is_started, _is_ended, _color, _top, _bottom, _extend, _is_extend, _delete_history) =>
    var box my_box = na

    x0_1 = ta.valuewhen(na(_session[1]) and _session, bar_index, 1)
    x0_2 = ta.valuewhen(na(_session) and _session[1], bar_index, 0)
    var x1 = 0
    var x2 = 0
    var v_session_high = 0.0
    var v_session_low = 0.0

    if _show
        if _is_started
            x1 := bar_index
            x2 := bar_index + math.abs(x0_2 - x0_1)
            my_box := box.new(x1, _top, x2, _bottom)
            box.set_border_style(my_box, i_sess_border_style)
            box.set_border_width(my_box, i_sess_border_width)
            box.set_border_color(my_box, _color)
            box.set_bgcolor(my_box, color.new(_color, i_sess_bgopacity))
            
            v_session_high := _top
            v_session_low := _bottom

            if _is_extend
                box.set_extend(my_box, extend.right)
                

            if _delete_history
                box.delete(my_box[1])
    
        // Proccesing
        else if _session
            box.set_top(my_box, _top)
            box.set_bottom(my_box, _bottom)

            v_session_high := _top
            v_session_low  := _bottom
        
        else if _is_ended
            box.set_right(my_box, bar_index)

    [x1, x2, v_session_high, v_session_low]

// ------------------------
// Drawing
// ------------------------

draw (_show, _session, _color, _label, _extend, _show_fib, _show_op, _lookback) =>
    max = get_period(_session, 1, _lookback)
    top = ta.highest(high, max)
    bottom = ta.lowest(low, max)
    
    if i_osc
        top := i_osc_max
        bottom := i_osc_min
    
    is_started = is_start(_session)
    is_ended = is_end(_session)
    is_extend = _extend != NO

    delete_history = (not i_show_history) or is_extend

    [x1, x2, _high, _low] = draw_market(_show, _session, is_started, is_ended, _color, top, bottom, _extend, is_extend, delete_history)
    
    if i_label_show
        draw_label(_show, _session, is_started, _color, top, bottom, _label, delete_history)

    if _show_op
        draw_op(_show, _session, is_started, x1, x2, _color, max, is_extend, delete_history)

    if _show_fib
        draw_fib(_show, _session, is_started, x1, x2, _color, top, bottom, 0.500, 2, line.style_solid, is_extend, delete_history)
        draw_fib(_show, _session, is_started, x1, x2, _color, top, bottom, 0.628, i_f_linewidth, i_f_linestyle, is_extend, delete_history)
        draw_fib(_show, _session, is_started, x1, x2, _color, top, bottom, 0.382, i_f_linewidth, i_f_linestyle, is_extend, delete_history)

    [_session, _high, _low]

///////////////////
// Calculating
///////////////////
string tz = (i_tz == NO or i_tz == '') ? na : i_tz
int sess1 = time(timeframe.period, i_sess1, tz)
int sess2 = time(timeframe.period, i_sess2, tz)
int sess3 = time(timeframe.period, i_sess3, tz)

///////////////////
// Plotting
///////////////////
[is_sess1, sess1_high, sess1_low] = draw(i_show_sess1, sess1, i_sess1_color, i_sess1_label, i_sess1_extend, i_sess1_fib, i_sess1_op, lookback)
[is_sess2, sess2_high, sess2_low] = draw(i_show_sess2, sess2, i_sess2_color, i_sess2_label, i_sess2_extend, i_sess2_fib, i_sess2_op, lookback)
[is_sess3, sess3_high, sess3_low] = draw(i_show_sess3, sess3, i_sess3_color, i_sess3_label, i_sess3_extend, i_sess3_fib, i_sess3_op, lookback)


////////////////////
// Alerts
////////////////////
// Session alerts
bool sess1_started = is_sess1 and not is_sess1[1]
bool sess1_ended = not is_sess1 and is_sess1[1]
bool sess2_started = is_sess2 and not is_sess2[1]
bool sess2_ended = not is_sess2 and is_sess2[1]
bool sess3_started = is_sess3 and not is_sess3[1]
bool sess3_ended = not is_sess3 and is_sess3[1]

alertcondition(sess1_started,   'Session #1 started')
alertcondition(sess1_ended,     'Session #1 ended')
alertcondition(sess2_started,   'Session #2 started')
alertcondition(sess2_ended,     'Session #2 ended')
alertcondition(sess3_started,   'Session #3 started')
alertcondition(sess3_ended,     'Session #3 ended')

alertcondition((not is_sess1) and ta.crossover(close, sess1_high), 'Session #1 High crossed (after session closed)')
alertcondition((not is_sess1) and ta.crossunder(close, sess1_low), 'Session #1 Low crossed (after session closed)')
alertcondition((not is_sess2) and ta.crossover(close, sess2_high), 'Session #2 High crossed (after session closed)')
alertcondition((not is_sess2) and ta.crossunder(close, sess2_low), 'Session #2 Low crossed (after session closed)')
alertcondition((not is_sess3) and ta.crossover(close, sess3_high), 'Session #3 High crossed (after session closed)')
alertcondition((not is_sess3) and ta.crossunder(close, sess3_low), 'Session #3 Low crossed (after session closed)')

plotshape(i_alert1_show and sess1_started, color=i_sess1_color, text='Start', style=shape.labeldown, location=location.bottom, size=size.small, textcolor=color.new(color.white, 0))
plotshape(i_alert1_show and sess1_ended, color=i_sess1_color, text='End', style=shape.labeldown, location=location.bottom, size=size.small, textcolor=color.new(color.white, 0))
plotshape(i_alert1_show and sess2_started, color=i_sess2_color, text='Start', style=shape.labeldown, location=location.bottom, size=size.small, textcolor=color.new(color.white, 0))
plotshape(i_alert1_show and sess2_ended, color=i_sess2_color, text='End', style=shape.labeldown, location=location.bottom, size=size.small, textcolor=color.new(color.white, 0))
plotshape(i_alert1_show and sess3_started, color=i_sess3_color, text='Start', style=shape.labeldown, location=location.bottom, size=size.small, textcolor=color.new(color.white, 0))
plotshape(i_alert1_show and sess3_ended, color=i_sess3_color, text='End', style=shape.labeldown, location=location.bottom, size=size.small, textcolor=color.new(color.white, 0))

plot(i_alert3_show ? sess1_high : na, style=plot.style_linebr, color=i_sess1_color)
plot(i_alert3_show ? sess1_low : na, style=plot.style_linebr, linewidth=2, color=i_sess1_color)
plot(i_alert3_show ? sess2_high : na, style=plot.style_linebr, color=i_sess2_color)
plot(i_alert3_show ? sess2_low : na, style=plot.style_linebr, linewidth=2, color=i_sess2_color)
plot(i_alert3_show ? sess3_high : na, style=plot.style_linebr, color=i_sess3_color)
plot(i_alert3_show ? sess3_low : na, style=plot.style_linebr, linewidth=2, color=i_sess3_color)

plotshape(i_alert3_show and (not is_sess1) and ta.crossover(close, sess1_high), color=i_sess1_color, title="", style=shape.triangleup, location=location.bottom, size=size.tiny)
plotshape(i_alert3_show and (not is_sess1) and ta.crossunder(close, sess1_low), color=i_sess1_color, title="", style=shape.triangledown, location=location.bottom, size=size.tiny)
plotshape(i_alert3_show and (not is_sess2) and ta.crossover(close, sess2_high), color=i_sess2_color, title="", style=shape.triangleup, location=location.bottom, size=size.tiny)
plotshape(i_alert3_show and (not is_sess2) and ta.crossunder(close, sess2_low), color=i_sess2_color, title="", style=shape.triangledown, location=location.bottom, size=size.tiny)
plotshape(i_alert3_show and (not is_sess3) and ta.crossover(close, sess3_high), color=i_sess3_color, title="", style=shape.triangleup, location=location.bottom, size=size.tiny)
plotshape(i_alert3_show and (not is_sess3) and ta.crossunder(close, sess3_low), color=i_sess3_color, title="", style=shape.triangledown, location=location.bottom, size=size.tiny)

Overview

FX Market Sessions draws background boxes for each active session and optionally plots opening ranges, Fibonacci retracement levels, and session extensions. The indicator supports custom timezone settings, customizable colors, and alerts when post-session price breaks above or below a session high or low. It operates on intraday timeframes between 1-minute and 60-minute charts.

Details

Published by

itmakesyousick on GitHub

Code credit

boitoki, as written in the script's header

Type

Indicator, Pine Script v5

Draws

On the price chart

Category

Sessions & time, Support & resistance, Breakout

Markets

Forex

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.

Topics

pinescript

Settings

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

SettingTypeDefaultVariable
TimezonestringGMT+1i_tz
HistorystringYESi_show_history
Oscillatorboolfalsei_osc
i_osc_minfloat0i_osc_min
~float100i_osc_max
Session 1: booltruei_show_sess1
stringLondoni_sess1_label
color#66D9EFi_sess1_color
Timesession0800-1600i_sess1
i_sess1_extendstringNOi_sess1_extend
Fibonacci levelsstringNOi_sess1_fib
Opening rangestringNOi_sess1_op
Show all 40 settings
SettingTypeDefaultVariable
Session 2: booltruei_show_sess2
stringNew Yorki_sess2_label
color#FD971Fi_sess2_color
Timesession1300-2200i_sess2
i_sess2_extendstringNOi_sess2_extend
Fibonacci levelsstringNOi_sess2_fib
Opening rangestringNOi_sess2_op
Session 3: booltruei_show_sess3
stringTokyoi_sess3_label
color#AE81FFi_sess3_color
Timesession0000-0900i_sess3
i_sess3_extendstringNOi_sess3_extend
Fibonacci levelsstringNOi_sess3_fib
Opening rangestringNOi_sess3_op
Stylestringline.style_dashedi_sess_border_style
Thicknessint1i_sess_border_width
Transpint94i_sess_bgopacity
Show labelsbooltruei_label_show
stringNormal
PositionstringTopPosition
stringOutside
Change valuestringNOi_label_chg
Stylestringline.style_solidi_f_linestyle
Thicknessint1i_f_linewidth
Periods (minutes)int15i_o_minutes
Transpint88i_o_transp
Alerts - Sessions stard/endboolfalsei_alert1_show
Alerts - Opening range breakoutsboolfalsei_alert2_show
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

IB / ORB Live Stats

by TamaraKGreen
46 stars

This overlay indicator marks the New York initial balance and a configurable opening range on the price chart and reports live range statistics in two tables. It builds an IB box for a default 09:30–10:30 ET window, an ORB box from 09:30 for a set number of mi

Indicator v6 Sessions & timeBreakout
Updated 7 weeks ago · None stated GitHub repository of IB / ORB Live Stats

Zen-DAX GX

by Zen-Tim
29 stars

This indicator calculates and plots session ranges and key breakout levels for DAX futures directly on the price chart. It defines the overnight Globex session, the Frankfurt pre-market range, and the regular trading hours open using European timezone settings

Indicator v5 Sessions & timeBreakout
Updated 2 weeks ago · MIT GitHub repository of Zen-DAX GX

ORB Pro - Research-Based ORB

by Mrshahidali420
16 stars

The ORB Pro indicator calculates and plots Opening Range Breakout levels, stop-loss and take-profit zones, signal labels, and an status dashboard on the price chart. Built on academic research, it evaluates trades using an opening-candle direction filter, open

Indicator v6 BreakoutSessions & time Repaints
Updated 3 months ago · None stated GitHub repository of ORB Pro - Research-Based ORB

Nexural ORB

by JasonTeixeira
9 stars

This indicator plots opening range breakout levels across multiple timeframes, including five, fifteen, thirty, and sixty minutes, directly on the price chart. It also displays the session open and overnight high and low levels. The script calculates an openin

Indicator v6 BreakoutSessions & time
Updated 12 days ago · Custom licence GitHub repository of Nexural ORB

Gold Breakout Trader

by eddiebelaval
7 stars

Plots timed breakout ranges directly on the price chart, designed for gold trading using dollar-based spacing. At scheduled trigger times or recurring two-hour intervals, it creates a central reference box flanked by upper and lower breakout stop lines, follow

Indicator v6 BreakoutSupport & resistance
Updated 3 months ago · None stated GitHub repository of Gold Breakout Trader

LunarTick ORB

by lunarticktrading
7 stars

This indicator calculates and plots Opening Range Breakout (ORB) levels directly on the price chart. It defines the high, low, and midpoint of an opening range based on a configurable duration and session time, with an optional Anchored VWAP (AVWAP) and extens

Indicator v6 Sessions & timeBreakout Repaints
Updated 2 weeks ago · None stated GitHub repository of LunarTick ORB

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