user1051673
user1051673

Reputation: 91

How to find last bar of a day using pine script

I need to close my position at a specific time, for example, I want to close all my position at 15:15.

is there inbuilt function in pine script to check time?

Upvotes: 5

Views: 13861

Answers (7)

Arun_K_Bhaskar
Arun_K_Bhaskar

Reputation: 51

Use this built-in:

firstbar = session.isfirstbar
lastbar = session.islastbar

Upvotes: 1

Saeid Nourian
Saeid Nourian

Reputation: 1778

You can use this:

session.islastbar

Returns true if the current bar is the last bar of the day's session, false otherwise. If extended session information is used, only returns true on the last bar of the post-market bars.

As documented here: https://www.tradingview.com/pine-script-reference/v5/#var_session%7Bdot%7Dislastbar

Upvotes: 2

John Smith
John Smith

Reputation: 194

endOfDay = 1600 //session end, in exchange local time, in 24hours format: 9:30AM=930, 4pm=1600
lastBarOfDay = (hour(time_close)*60 + minute(time_close)==(60*(endOfDay/100)+endOfDay%100))?1:0

lastBarOfDay will return "1" during the bar that ends at endOfDay. Times are local to the exchange where the symbol is traded. So for a symbol trading on the Mexican exchange, which closes at 3pm Mexico City time, enter endOfDay=1500 to return 1 on the last bar of the trading session. For NYSE, which closes at 4pm EST, enter 1600. If you want to trade 15 minutes before the end of the session, you'd enter 1445 or 1545 respectively.

Upvotes: 3

trader-ap
trader-ap

Reputation: 81

Method 1 Here is a Study using a simple function which triggers TRUE on the FIRST bar of a regular session allowing you to use the reference operator to identify the Last Bar. This can be useful if you don't need it to work in realtime / intraday.

// https://uk.tradingview.com/u/trader-ap2/#published-scripts

//@version=4
study("Last Bar", overlay=true)

// Last Bar of Regular Session
f_isLastBar() =>
    t = time("1440", session.regular) // Resolution of 1440 = 60*24 minutes in a whole day
    not na(t[1]) and na(t) or t[1] < t

if f_isLastBar()
    label.new(bar_index[1], high, "Last Bar")

NOTE: This works effectively for historical data. It does not work if required for intraday / realtime because it triggers on the FIRST bar of the next day's regular session OR using a workaround of the first bar of the "Extended Hours (Intraday Only)" session of the current day if it is turned on in the chart's settings when indicator is added. Having Extended Hours enabled on the chart can have calculation implications on other indicators such as VWAP, EMA, SMA etc.

Method 2 Here is the code modified to use a input.session parameter to configure the Session Duration

// https://uk.tradingview.com/u/trader-ap2/#published-scripts

//@version=4
study("Custom Session Duration", overlay=true)

i_session = input(defval="0930-1545", title="   Session", type=input.session)

// Last Bar of Custom Session
f_isLastBar() =>
    t = time("1440", i_session) // Resolution of 1440 = 60*24 minutes in a whole day
    not na(t[1]) and na(t) or t[1] < t

if f_isLastBar()
    label.new(bar_index, high, "Last Bar")

NOTE: This works effectively for intraday/realtime and can be used to configure any custom session. It can also handle first day listings of a symbol on an exchange. It does NOT automatically handle situations of early exchange close on or ahead of particular public holidays e.g. Christmas Eve or New Years Eve. The input.session would need to be adjusted on these days.

Method 3

// https://uk.tradingview.com/u/trader-ap2/#published-scripts

//@version=4
study("Last Bar", overlay=true)

// Last Bar of Regular Session
f_isLastBar() =>

    var int sessionDuration = na
    var int sessionCalculatedLastBarTime = na

    t = time(resolution = "1440", session = session.regular) // Resolution of 1440 = 60*24 minutes in a whole day

    // Calculate regular session duration for the symbol using very first day of the Bar Set
    if na(sessionDuration) and (na(t[1]) and not na(t) or t[1] < t)
        sessionDuration := (time[1] - t[1])

    // Calculate time of the session's last bar by adding session duration to the time of the first bar of the session
    // This does not correctly handle early close of exchange on or ahead of public holiday
    // This will also not work correctly in realtime on the very first day of a new symbol listing on an Exchange
    if na(t[1]) and not na(t) or t[1] < t
        sessionCalculatedLastBarTime := t[0] + sessionDuration

    // Return true if current bar's time == session's calculated last bar time otherwise return false
    time[0] == sessionCalculatedLastBarTime

if f_isLastBar() and barstate.isconfirmed
    label.new(bar_index, high, "Last Bar")

NOTE: This works by calculating the regular session duration of the symbol using the very first day of the chart's barset but triggered on the opening bar of second day

It works effectively in realtime with the following limitations:

  1. It does NOT handle days where an Exchange closes early e.g. Christmas Eve or New Years Eve.
  2. It does NOT handle in realtime the last bar of a symbol listed for the very first day on an exchange as it gets triggered on the first bar of the second regular day OR as a workaround it can be triggered by the opening bar of the "Extended Hours (Intraday Only" if the chart setting is enabled WHEN the indicator is added to the chart.

Upvotes: 8

Anonymous
Anonymous

Reputation: 4632

First find the time difference between current and last bar and add it to current bar so you get the time of the next bar. Then check if this new candle time stamp divided by the number of milliseconds in a day has no remainder, meaning the next candle will be the daily open.

newTime = time*2 - time[1]
beforeDaily = newTime % 86400000 ==0

Edit: if you need to close at a particular time you can specify it. A more reliable time difference can be calculated using timeframe multiplier, for multiplier we will only consider seconds and minutes, hours are considered as minutes. Then we calculate the start of the day using unix time with the addition of our specified time. We will also calculate the preceding candle time, the current time should be in between the two, greater or equal then preceding but lesser than the mark time. Then run the same check with a shifted time, in case a new candle would cause a shifting to a new day.

h=23,m=30,s=0

dayTime=1000*(h*60*60+m*60+s)
diff = timeframe.multiplier*1000*(timeframe.isseconds?1:timeframe.isminutes?60:na)
div = floor(time/86400000)*86400000
mark = div + dayTime
prev = mark - diff
shifted=time-86400000
beforeDailyClose = (time<mark and time>=prev) or (shifted<mark and shifted>=prev)

Upvotes: 2

user1051673
user1051673

Reputation: 91

I was trying similar method using timeframe. However it works fine when we use bgcolor or plot function but when I am using this condition to close all my trades using close_all function. The order gets close on the opening of next day.

hour_bar = input(title="Hour", type=input.integer, defval=14, minval=0, maxval=23)
minute_bar = input(title="Minute", type=input.integer, defval=45, minval=0, maxval=59)
_h = hour(time)
_m = minute(time)
bgcolor(color=closetradetime ? color.green : na)
strategy.close_all(when = closetradetime)

As shown below the red arrow is close position on the next day opening however the black arrow indicate 15:15

enter image description here

Upvotes: 0

vitruvius
vitruvius

Reputation: 21121

There are various ways of working with Session and time information.

You can use the built-in variables hour and minute for this.

//@version=4
study("tim", overlay=true)
hour_bar = input(title="Hour", type=input.integer, defval=15, minval=0, maxval=23)
minute_bar = input(title="Minute", type=input.integer, defval=15, minval=0, maxval=59)

_h = hour(time)
_m = minute(time)
is_my_time = (_h == hour_bar) and (_m == minute_bar)

bgcolor(color=is_my_time ? color.green : na)

Note, those will return values for UTC time. So, I, for example, live in UTC+2 timezone. This means, even if I set the inputs to 15 and 15, the bar at 17:15 will be highlighted.

enter image description here

You can change the timezone to UTC or exchange from the chart settings, if you want.

enter image description here

Upvotes: 1

Related Questions