问题
A question about session breaks.
I know that you can add Session Breaks to a chart by activating Session Breaks on the time scale of the chart.
It then appears as a vertical line on the chart, whenever a Session Break occurs, indicating the start of a new session.
That Session Break line can be formatted in the chart settings, under Appearance > Session Breaks.
I'm trying to detect that Session Break in Pine Script.
Is there a reliable way in Pine Script to detect the start of a new session?
Especially for futures contracts.
Typically, there's an amount of time (a pause) that passes between the stop of a session and the start of a new session.
Therefore, my idea was to check the time difference between the current bar and the previous bar.
If that time difference is greater than the "time width" of one bar, that means that there's been a "pause".
Hence, a new session has started.
That approach seems to work for most of the days.
However, when I look at futures ticker NYMEX:NG1!
, that logic does not always seem to be correct.
Some days on that ticker seem to have "pauses" mid-session.
I suspect that trading was halted on those "pause" moments.
An example can be seen by comparing 27 Oct 2020
(normal day) to 28 Oct 2020
(irregular day with mid-session pauses).
For the example, I've put the chart in Exchange timezone on a 15 minute interval.
The green background is my code detecting session breaks.
On 27 Oct 2020
(normal day)
You can see that each bar starts 15 minutes later than the previous bar, which is normal and expected.
The session starts at 18:00
and progresses per 15 minutes:
18:00 - 18:15 - 18:30 - 18:45 - 19:00 - 19:15 - 19:30 - 19:45 - 20:00 - 20:15 - etc...
On 28 Oct 2020
(irregular day with mid-session pauses)
You can see that NOT each bar starts 15
minutes later than the previous bar.
The session also starts at 18:00
and progresses per 15 minutes, but NOT consistenly:
18:00 - 18:15 - 18:30 - (gap) - 19:15 - (gap) - 20:45 - (gap) 21:00 - 21:15 - 21:30 - 21:45 - (gap) - 22:30 - (gap) - 23:00 - (gap) - 23:45 - 00:00 - (gap) - 00:45 - (gap) - 03:00 - (gap) - 03:30 - (gap) - 03:45 - 04:00 - 04:15 - (gap) - 05:15 - 05:30 - (gap) - 06:00 - 06:15 - 06:30 - 06:45 - 07:00 - 07:15 - etc... (normal from here on).
My code for detecting session breaks (green backgrounds in the screenshot above)
//@version=4
study("NewSession", overlay=true)
var bool newSession = na
var int bar_width_in_ms = timeframe.multiplier * 60 * 1000
newSession := change(time) > bar_width_in_ms
bgcolor(newSession ? color.green : na, 70)
In conclusion, my question is this:
Is there any reliable way in Pine Script to detect the start of a new session?
Especially for futures contracts.
回答1:
You can use the change(time("1D"))
to track where one daily bar ends and another begins:
//@version=4
study("NewSession", overlay=true)
newSession = change(time("1D"))
bgcolor(newSession ? color.green : na, 70)
来源:https://stackoverflow.com/questions/64892091/detecting-session-breaks