Reputation: 1
In Pine Script V5, how can I know if the current bar is the last bar for that trading day, as I want to exit my entire position before the end of that trading day.
ta.change(time("D"))
can know the first bar of the next trading day, but how can I know the last bar of the current trading day?
Upvotes: 0
Views: 77
Reputation: 1042
there are many ways to get what you want.
A few examples...
session.islastbar // true on last bar of session
time_close("1D") // Unix time of todays close
ta.barssince(session.isfirstbar) + 1 // closing bar of previous session
the following I would recommend when trying to exit on the last bar...
if time_close == time_close("1D")
... (your exit code)
it compares the closing time of the most right bar with the closing time of the day.
when you trying to build a strategy for backtesting,
then keep in mind this will execute your order after the bar has finished,
so you need to prepare for that.
if time_close == time_close("1D") - (timeframe.in_seconds() * 1000)
... (your exit code for previous calculated exit)
Upvotes: 0
Reputation: 1961
From Strategy library https://www.tradingview.com/v/mCOgJC67/
// @function A wrapper of the `strategy.close()` built-in which closes the position matching the `entryId` on the close of the last bar of the trading session.
// @param entryId (series string) A required parameter. The order identifier. It is possible to close an order by referencing its identifier.
// @param comment (series string) Optional. Additional notes on the order.
// @param alertMessage (series string) An optional parameter which replaces the {{strategy.order.alert_message}} placeholder when it is used in the "Create Alert" dialog box's "Message" field.
// @returns (void) Closes `entryId` on the `close` of the last bar of the trading session, instead of the `open` of the next session.
export closeAtEndOfSession(series string entryId, series string comment = na, series string alertMessage = na) =>
if session.islastbar and barstate.isconfirmed
strategy.close(entryId, comment, alert_message = alertMessage, immediately = true)
Upvotes: 0