@orangecharts/wrun-chart-host 0.11.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -147,6 +147,7 @@ export * from './utility/chart/local-kscript-warmup-depth.util.js';
147
147
  export * from './utility/chart/local-technical-script-live-apply-coalescer.util.js';
148
148
  export * from './utility/chart/local-technical-script-range.leaf.js';
149
149
  export * from './utility/chart/market-session-schedule.util.js';
150
+ export * from './utility/chart/market-sessions.util.js';
150
151
  export * from './utility/chart/marketKind.util.js';
151
152
  export * from './utility/chart/mixed-mode.util.js';
152
153
  export * from './utility/chart/ny-calendar.util.js';
package/dist/index.js CHANGED
@@ -150,6 +150,7 @@ export * from './utility/chart/local-kscript-warmup-depth.util.js';
150
150
  export * from './utility/chart/local-technical-script-live-apply-coalescer.util.js';
151
151
  export * from './utility/chart/local-technical-script-range.leaf.js';
152
152
  export * from './utility/chart/market-session-schedule.util.js';
153
+ export * from './utility/chart/market-sessions.util.js';
153
154
  export * from './utility/chart/marketKind.util.js';
154
155
  export * from './utility/chart/mixed-mode.util.js';
155
156
  export * from './utility/chart/ny-calendar.util.js';
@@ -1,14 +1,29 @@
1
+ import type { MarketSplitSliceId } from '../../utility/chart/market-sessions.util.js';
1
2
  export type TpoTimeRange = {
2
3
  start_time?: unknown;
3
4
  end_time?: unknown;
4
5
  timezone?: unknown;
6
+ /** Weeks and months on UTC, not the range's clock: the gateway cuts its own TradingHour sessions so. Never sent. */
7
+ periodCalendar?: 'UTC';
5
8
  };
9
+ /** A range as the table and the wire spell it: wall times and the clock they are read on. */
10
+ export interface TpoClockRange {
11
+ readonly start_time: string;
12
+ readonly end_time: string;
13
+ readonly timezone: string;
14
+ readonly periodCalendar?: 'UTC';
15
+ }
6
16
  export interface TpoSessionWindow {
7
17
  startSec: number;
8
18
  endSec: number;
9
19
  fullSession: boolean;
10
20
  }
11
- export declare const TPO_TRADING_HOUR_TIME_RANGES: Record<string, TpoTimeRange>;
21
+ /** The presets that are market sessions: hours from market-sessions.util, sent as a range, never a fixed-UTC enum. */
22
+ export declare const TPO_MARKET_SESSION_PRESETS: readonly string[];
23
+ /** Every choice's daily window: the gateway's own sessions (BuildWhereTradingHour serves these rows), the markets'. */
24
+ export declare const TPO_TRADING_HOUR_TIME_RANGES: Readonly<Record<string, TpoClockRange>>;
25
+ /** A range's wall times and clock alone, as the wire and the cache key carry it. */
26
+ export declare function tpoWireTimeRange(range: TpoTimeRange): TpoTimeRange;
12
27
  /** Settings projection every TPO time-range decision reads. */
13
28
  export interface TpoTimeRangeSettings {
14
29
  customTimeRange?: unknown;
@@ -25,12 +40,19 @@ export interface TpoTimeRangeSettings {
25
40
  * active custom sessions each keep their existing behavior.
26
41
  */
27
42
  export declare function resolveTradingDayTpoTimeRange(settings: TpoTimeRangeSettings | null | undefined): TpoTimeRange | undefined;
28
- /**
29
- * Precedence: explicit custom range, then the trading-day anchored range
30
- * (which itself yields to non-'All Hours' trading hours and custom
31
- * sessions), then the trading-hour preset table.
32
- */
33
- export declare function resolveTpoSettingsTimeRange(settings: TpoTimeRangeSettings): TpoTimeRange | undefined;
43
+ /** The trading-hour choice the settings hold: no choice is All Hours, as every TPO payload sends it. */
44
+ export declare function tpoTradingHourOf(settings: {
45
+ tradingHour?: unknown;
46
+ } | null | undefined): string;
47
+ /** A choice's window, venue day aside: a preset's table row (never the range saved beside it), else the saved range. */
48
+ export declare function tpoTradingHourTimeRange(tradingHour: string, savedRange: unknown): TpoTimeRange | undefined;
49
+ /** The one window a TPO cuts its sessions to, for every reader: a saved range beside a preset holds its old hours. */
50
+ export declare function resolveTpoSettingsTimeRange(settings: TpoTimeRangeSettings, options?: {
51
+ venueTradingDay?: boolean;
52
+ }): TpoTimeRange | undefined;
53
+ /** The IANA zone a range's clock names: 'ET' is New York, nothing is UTC. */
54
+ export declare function tpoTimeZone(value: unknown): string;
55
+ /** The daily window `timestamp` reads, on the range's own zone clock: device-independent, daylight saving included. */
34
56
  export declare function resolveTpoTimeRangeWindow(timestamp: number, customTimeRange?: TpoTimeRange): TpoSessionWindow | undefined;
35
57
  export declare function containsTpoWindowTime(timestamp: number, window: TpoSessionWindow): boolean;
36
58
  export declare function getTpoSessionStart(timestamp: number, sessionType: string, customTimeRange?: TpoTimeRange): number;
@@ -45,9 +67,9 @@ export declare function generateTpoLetters(blockIds: number[], _sessionType: str
45
67
  export type TpoSessionRole = 'day' | 'evening';
46
68
  /**
47
69
  * The clock a custom-session set is written in: UTC, or New York wall time
48
- * ('ET', daylight saving included). The gateway's custom-time-range path
49
- * serves only these two (tsdb-gateway tpo_agg.go sessionCustomTimeRange
50
- * degrades every other zone to plain UTC days), so Chicago is not offered.
70
+ * ('ET', daylight saving included). The editor offers these two; the
71
+ * gateway's custom-time-range path degrades a zone it does not serve to plain
72
+ * UTC days (tsdb-gateway tpo_agg.go sessionCustomTimeRange).
51
73
  */
52
74
  export type TpoCustomSessionsTimezone = 'UTC' | 'ET';
53
75
  export interface TpoCustomSessionSegment {
@@ -68,9 +90,10 @@ export interface TpoCustomSessionsSettings {
68
90
  /** Absent reads UTC: every set saved before the New York clock. */
69
91
  timezone?: TpoCustomSessionsTimezone;
70
92
  }
71
- /** Editable starting template (Asia / London / New York / Close, UTC) — a
72
- * default for the editor, never a hard-coded behavior. */
73
- export declare const DEFAULT_TPO_CUSTOM_SESSION_SEGMENTS: readonly TpoCustomSessionSegment[];
93
+ /** The editor's starting set: the day split's slices on its clock, named by `labelOf`; hours from the split only. */
94
+ export declare function defaultTpoCustomSessionSegments(labelOf: (id: MarketSplitSliceId) => string): TpoCustomSessionSegment[];
95
+ /** The starting set's clock, the split's own: New York, stored as 'ET'. */
96
+ export declare const DEFAULT_TPO_CUSTOM_SESSIONS_TIMEZONE: TpoCustomSessionsTimezone;
74
97
  interface NormalizedTpoSegment extends TpoCustomSessionSegment {
75
98
  startMinute: number;
76
99
  /** Minutes past the START day's midnight: above 1440 for the segment that
@@ -1,26 +1,48 @@
1
- import dayjs from 'dayjs';
2
- import isoWeek from 'dayjs/plugin/isoWeek.js';
3
- import timezone from 'dayjs/plugin/timezone.js';
4
- import utc from 'dayjs/plugin/utc.js';
5
- import { zoneWallMsAt, zoneWallToUtcMs } from '../../utility/chart/ny-calendar.util.js';
1
+ import { MARKET_SESSION_SPLIT, marketSessionInstantsOn, marketSessionNamed, sessionClockText, zoneWallEdgeToUtcMs, } from '../../utility/chart/market-sessions.util.js';
2
+ import { NY_TIME_ZONE, zoneOffsetMsAt, zoneWallMsAt } from '../../utility/chart/ny-calendar.util.js';
6
3
  import { getTradingDayAnchor, getTradingDayTpoTimeRange } from '../../utility/chart/trading-day.util.js';
7
- dayjs.extend(utc);
8
- dayjs.extend(isoWeek);
9
- dayjs.extend(timezone);
10
- export const TPO_TRADING_HOUR_TIME_RANGES = {
11
- 'Pre-Market': { start_time: '04:00', end_time: '09:30', timezone: 'ET' },
12
- Regular: { start_time: '09:30', end_time: '16:00', timezone: 'ET' },
13
- 'Post-Market': { start_time: '16:00', end_time: '20:00', timezone: 'ET' },
14
- Asia: { start_time: '00:00', end_time: '06:00', timezone: 'UTC' },
15
- 'Asia Full': { start_time: '00:00', end_time: '09:00', timezone: 'UTC' },
16
- London: { start_time: '06:00', end_time: '12:00', timezone: 'UTC' },
17
- 'London Full': { start_time: '08:00', end_time: '17:00', timezone: 'UTC' },
18
- 'New York': { start_time: '12:00', end_time: '20:00', timezone: 'UTC' },
19
- 'New York Full': { start_time: '08:00', end_time: '17:00', timezone: 'ET' },
20
- 'Pre-Close': { start_time: '20:00', end_time: '00:00', timezone: 'UTC' },
21
- 'All Hours': { start_time: '00:00', end_time: '00:00', timezone: 'UTC' },
22
- Custom: { start_time: '00:00', end_time: '00:00', timezone: 'UTC' },
23
- };
4
+ /** A gateway TradingHour session's row: its hours on the gateway's own clock, its weeks and months on UTC. */
5
+ function gatewaySessionRange(start_time, end_time, timezone) {
6
+ return Object.freeze({ start_time, end_time, timezone, periodCalendar: 'UTC' });
7
+ }
8
+ /** The presets that are market sessions: hours from market-sessions.util, sent as a range, never a fixed-UTC enum. */
9
+ export const TPO_MARKET_SESSION_PRESETS = Object.freeze([
10
+ 'Asia',
11
+ 'Asia Full',
12
+ 'London',
13
+ 'London Full',
14
+ 'New York',
15
+ 'New York Full',
16
+ ]);
17
+ /** The zone a range names on the wire: New York as 'ET' (the gateway keys it apart from 'America/New_York'). */
18
+ function tpoWireTimezone(timeZone) {
19
+ return timeZone === NY_TIME_ZONE ? 'ET' : timeZone;
20
+ }
21
+ /** A market session preset's daily window, read from the shared session table, never written here. */
22
+ function marketSessionRange(name) {
23
+ const session = marketSessionNamed(name);
24
+ if (!session)
25
+ throw new Error(`TPO preset ${name} is not a market session`);
26
+ return Object.freeze({
27
+ start_time: sessionClockText(session.openMinutes),
28
+ end_time: sessionClockText(session.closeMinutes),
29
+ timezone: tpoWireTimezone(session.timeZone),
30
+ });
31
+ }
32
+ /** Every choice's daily window: the gateway's own sessions (BuildWhereTradingHour serves these rows), the markets'. */
33
+ export const TPO_TRADING_HOUR_TIME_RANGES = Object.freeze({
34
+ 'Pre-Market': gatewaySessionRange('04:00', '09:30', 'ET'),
35
+ Regular: gatewaySessionRange('09:30', '16:00', 'ET'),
36
+ 'Post-Market': gatewaySessionRange('16:00', '20:00', 'ET'),
37
+ ...Object.fromEntries(TPO_MARKET_SESSION_PRESETS.map((name) => [name, marketSessionRange(name)])),
38
+ 'Pre-Close': gatewaySessionRange('20:00', '00:00', 'UTC'),
39
+ 'All Hours': Object.freeze({ start_time: '00:00', end_time: '00:00', timezone: 'UTC' }),
40
+ Custom: Object.freeze({ start_time: '00:00', end_time: '00:00', timezone: 'UTC' }),
41
+ });
42
+ /** A range's wall times and clock alone, as the wire and the cache key carry it. */
43
+ export function tpoWireTimeRange(range) {
44
+ return { start_time: range.start_time, end_time: range.end_time, timezone: range.timezone };
45
+ }
24
46
  function parseTpoTimeToMinutes(value) {
25
47
  const match = String(value ?? '').match(/^(\d{1,2}):(\d{2})$/);
26
48
  if (!match)
@@ -42,10 +64,11 @@ function isTpoCrossDay(customTimeRange) {
42
64
  return false;
43
65
  return startMinutes >= endMinutes;
44
66
  }
45
- function getTpoCrossDayOffset(customTimeRange) {
67
+ /** Minutes past local midnight a period's first day opens at: a range crossing midnight keeps its spill-over night. */
68
+ function getTpoCrossDayOffsetMinutes(customTimeRange) {
46
69
  if (!customTimeRange || !isTpoCrossDay(customTimeRange))
47
70
  return 0;
48
- return (parseTpoTimeToMinutes(customTimeRange.end_time) ?? 0) * 60;
71
+ return parseTpoTimeToMinutes(customTimeRange.end_time) ?? 0;
49
72
  }
50
73
  /**
51
74
  * The venue anchor these settings run on. It is venue knowledge, never
@@ -79,175 +102,173 @@ export function resolveTradingDayTpoTimeRange(settings) {
79
102
  return undefined;
80
103
  return getTradingDayTpoTimeRange(resolveTpoTradingDayAnchor(settings));
81
104
  }
82
- /**
83
- * Precedence: explicit custom range, then the trading-day anchored range
84
- * (which itself yields to non-'All Hours' trading hours and custom
85
- * sessions), then the trading-hour preset table.
86
- */
87
- export function resolveTpoSettingsTimeRange(settings) {
88
- if (settings.customTimeRange)
89
- return settings.customTimeRange;
90
- const anchored = resolveTradingDayTpoTimeRange(settings);
91
- if (anchored)
92
- return anchored;
93
- const tradingHour = typeof settings.tradingHour === 'string' ? settings.tradingHour : undefined;
94
- if (!tradingHour)
95
- return undefined;
96
- return TPO_TRADING_HOUR_TIME_RANGES[tradingHour];
97
- }
98
- function timezoneName(value) {
99
- const raw = String(value || 'UTC');
100
- if (raw.toUpperCase() === 'ET')
101
- return 'America/New_York';
102
- return raw || 'UTC';
105
+ /** The trading-hour choice the settings hold: no choice is All Hours, as every TPO payload sends it. */
106
+ export function tpoTradingHourOf(settings) {
107
+ const tradingHour = settings?.tradingHour;
108
+ return typeof tradingHour === 'string' && tradingHour ? tradingHour : 'All Hours';
103
109
  }
104
- function unixInTimeZone(timestamp, zone) {
105
- try {
106
- return dayjs.unix(timestamp).tz(zone);
107
- }
108
- catch {
109
- return dayjs.unix(timestamp).utc();
110
+ /** A choice's window, venue day aside: a preset's table row (never the range saved beside it), else the saved range. */
111
+ export function tpoTradingHourTimeRange(tradingHour, savedRange) {
112
+ if (tradingHour !== 'Custom' && Object.prototype.hasOwnProperty.call(TPO_TRADING_HOUR_TIME_RANGES, tradingHour)) {
113
+ return TPO_TRADING_HOUR_TIME_RANGES[tradingHour];
110
114
  }
115
+ return savedRange && typeof savedRange === 'object' ? savedRange : undefined;
111
116
  }
112
- const zonedDayByZone = new Map();
113
- function zonedDayFor(timestamp, zone) {
114
- const cached = zonedDayByZone.get(zone);
115
- if (cached && timestamp >= cached.startUnix && timestamp < cached.endUnix)
116
- return cached;
117
- const dayStart = unixInTimeZone(timestamp, zone).startOf('day');
118
- const fresh = { dayStart, startUnix: dayStart.unix(), endUnix: dayStart.add(1, 'day').unix() };
119
- zonedDayByZone.set(zone, fresh);
120
- return fresh;
121
- }
122
- const WALL_TIME_MEMO_CAP = 512;
123
- const wallTimeUnixMemo = new Map();
124
- /**
125
- * The instant whose wall clock in `zone` reads `minutes` past midnight on
126
- * the calendar date `dayKey` ('YYYY-MM-DD'). Parsing the wall string with
127
- * dayjs.tz is DST-exact: `startOf('day').add(minutes, 'minute')` counts REAL
128
- * minutes, which drifts by the offset delta on 23h/25h transition days. For
129
- * UTC zones both agree.
130
- */
131
- function wallTimeOnDay(dayKey, minutes, zone) {
132
- const hours = String(Math.floor(minutes / 60)).padStart(2, '0');
133
- const mins = String(minutes % 60).padStart(2, '0');
134
- const wall = `${dayKey} ${hours}:${mins}`;
135
- try {
136
- return dayjs.tz(wall, zone);
137
- }
138
- catch {
139
- return dayjs.utc(wall);
140
- }
117
+ /** The one window a TPO cuts its sessions to, for every reader: a saved range beside a preset holds its old hours. */
118
+ export function resolveTpoSettingsTimeRange(settings, options = {}) {
119
+ const tradingHour = tpoTradingHourOf(settings);
120
+ if (tradingHour !== 'All Hours')
121
+ return tpoTradingHourTimeRange(tradingHour, settings.customTimeRange);
122
+ return options.venueTradingDay === false ? undefined : resolveTradingDayTpoTimeRange(settings);
141
123
  }
142
- /** `wallTimeOnDay(...).unix()`, memoised per (day, minutes, zone): the same few wall times are asked every tick. */
143
- function wallTimeUnixOnDay(dayKey, minutes, zone) {
144
- const key = `${dayKey}|${minutes}|${zone}`;
145
- const hit = wallTimeUnixMemo.get(key);
146
- if (hit !== undefined)
147
- return hit;
148
- const value = wallTimeOnDay(dayKey, minutes, zone).unix();
149
- if (wallTimeUnixMemo.size >= WALL_TIME_MEMO_CAP)
150
- wallTimeUnixMemo.clear();
151
- wallTimeUnixMemo.set(key, value);
152
- return value;
124
+ /** The IANA zone a range's clock names: 'ET' is New York, nothing is UTC. */
125
+ export function tpoTimeZone(value) {
126
+ const raw = String(value || 'UTC');
127
+ return raw.toUpperCase() === 'ET' ? NY_TIME_ZONE : raw;
128
+ }
129
+ const servedZones = new Map();
130
+ /** The zone a range is read on: its own where the runtime's zone data knows it, else UTC (a bad saved zone). */
131
+ function servedTimeZone(value) {
132
+ const zone = tpoTimeZone(value);
133
+ let served = servedZones.get(zone);
134
+ if (served === undefined) {
135
+ try {
136
+ zoneOffsetMsAt(zone, 0);
137
+ served = zone;
138
+ }
139
+ catch {
140
+ served = 'UTC';
141
+ }
142
+ if (servedZones.size >= 64)
143
+ servedZones.clear();
144
+ servedZones.set(zone, served);
145
+ }
146
+ return served;
153
147
  }
148
+ const MINUTE_MS = 60_000;
154
149
  const DAY_MS = 86_400_000;
155
- const pad = (value, width) => String(value).padStart(width, '0');
156
- /**
157
- * The 'YYYY-MM-DD' key of the `zone` calendar date after the one holding
158
- * `timestamp` (unix seconds), as `unixInTimeZone(...).startOf('day').add(1, 'day')`
159
- * formats it, from the zone clock (ny-calendar.util: one Intl reading per UTC
160
- * day). An unknown zone reads UTC, as `unixInTimeZone` does; dayjs reads the
161
- * instants the zone clock does not serve. The day cache is left alone: its
162
- * last-day span is the one `resolveTpoTimeRangeWindow` answers from.
163
- */
164
- function nextZoneDateKey(timestamp, zone) {
150
+ /** A range's hours as a session on its own clock (open, close, zone); undefined for times that do not parse. */
151
+ function tpoRangeSession(range) {
152
+ if (!range)
153
+ return undefined;
154
+ const openMinutes = parseTpoTimeToMinutes(range.start_time);
155
+ const closeMinutes = parseTpoTimeToMinutes(range.end_time);
156
+ if (openMinutes === undefined || closeMinutes === undefined)
157
+ return undefined;
158
+ return { timeZone: servedTimeZone(range.timezone), openMinutes, closeMinutes };
159
+ }
160
+ /** `zone`'s wall clock at `ms` as a UTC-shaped epoch; the instant itself where the zone clock serves none. */
161
+ function zoneWallMsOr(zone, ms) {
162
+ if (zone === 'UTC')
163
+ return ms;
165
164
  let wallMs;
166
165
  try {
167
- wallMs = zoneWallMsAt(zone, timestamp * 1000);
166
+ wallMs = zoneWallMsAt(zone, ms);
168
167
  }
169
168
  catch {
170
- wallMs = timestamp * 1000;
169
+ wallMs = Number.NaN;
171
170
  }
172
- if (Number.isNaN(wallMs))
173
- return unixInTimeZone(timestamp, zone).startOf('day').add(1, 'day').format('YYYY-MM-DD');
174
- const next = new Date(Math.floor(wallMs / DAY_MS) * DAY_MS + DAY_MS);
175
- return `${pad(next.getUTCFullYear(), 4)}-${pad(next.getUTCMonth() + 1, 2)}-${pad(next.getUTCDate(), 2)}`;
171
+ return Number.isNaN(wallMs) ? ms : wallMs;
176
172
  }
177
- export function resolveTpoTimeRangeWindow(timestamp, customTimeRange) {
178
- if (!customTimeRange)
179
- return undefined;
180
- const startMinutes = parseTpoTimeToMinutes(customTimeRange.start_time);
181
- const endMinutes = parseTpoTimeToMinutes(customTimeRange.end_time);
182
- if (startMinutes === undefined || endMinutes === undefined)
183
- return undefined;
184
- const zone = timezoneName(customTimeRange.timezone);
185
- // Cached zoned day plus memoised wall times: the same instants as the
186
- // per-call dayjs chain, compared as unix seconds (`isBefore` on instants).
187
- const { dayStart } = zonedDayFor(timestamp, zone);
188
- const dayKey = dayStart.format('YYYY-MM-DD');
189
- const previousDay = dayStart.subtract(1, 'day');
190
- const nextDay = dayStart.add(1, 'day');
191
- const previousKey = previousDay.format('YYYY-MM-DD');
192
- const nextKey = nextDay.format('YYYY-MM-DD');
193
- const startToday = wallTimeUnixOnDay(dayKey, startMinutes, zone);
194
- const endToday = wallTimeUnixOnDay(dayKey, endMinutes, zone);
195
- if (startMinutes === endMinutes) {
196
- const crossesIntoToday = timestamp < startToday;
197
- const start = crossesIntoToday ? wallTimeUnixOnDay(previousKey, startMinutes, zone) : startToday;
198
- const end = crossesIntoToday ? startToday : wallTimeUnixOnDay(nextKey, startMinutes, zone);
199
- return { startSec: start, endSec: end, fullSession: true };
173
+ /** The session's [open, close) in unix seconds on the local day `dayWallMs`, each edge read on its own date. */
174
+ function sessionInstantsSec(session, dayWallMs) {
175
+ const [openMs, closeMs] = session.timeZone === 'UTC' ? [Number.NaN, Number.NaN] : marketSessionInstantsOn(session, dayWallMs);
176
+ if (Number.isNaN(openMs) || Number.isNaN(closeMs)) {
177
+ const closeDayMs = session.closeMinutes <= session.openMinutes ? dayWallMs + DAY_MS : dayWallMs;
178
+ return [
179
+ Math.floor((dayWallMs + session.openMinutes * MINUTE_MS) / 1000),
180
+ Math.floor((closeDayMs + session.closeMinutes * MINUTE_MS) / 1000),
181
+ ];
200
182
  }
201
- if (startMinutes < endMinutes) {
202
- return { startSec: startToday, endSec: endToday, fullSession: false };
183
+ return [Math.floor(openMs / 1000), Math.floor(closeMs / 1000)];
184
+ }
185
+ /** The local calendar day holding `timestamp` (unix seconds) on `zone`'s clock, as its midnight's UTC-shaped epoch. */
186
+ function zoneDayWallMs(zone, timestamp) {
187
+ return Math.floor(zoneWallMsOr(zone, timestamp * 1000) / DAY_MS) * DAY_MS;
188
+ }
189
+ /** The window holding `timestamp` and the local day it opened on. */
190
+ function tpoWindowOn(timestamp, session) {
191
+ const dayWallMs = zoneDayWallMs(session.timeZone, timestamp);
192
+ const [startToday, endToday] = sessionInstantsSec(session, dayWallMs);
193
+ const fullSession = session.openMinutes === session.closeMinutes;
194
+ if (session.openMinutes < session.closeMinutes) {
195
+ return { window: { startSec: startToday, endSec: endToday, fullSession }, openDayWallMs: dayWallMs };
203
196
  }
204
- const isPostMidnightContinuation = timestamp < endToday;
205
- const start = isPostMidnightContinuation ? wallTimeUnixOnDay(previousKey, startMinutes, zone) : startToday;
206
- const end = isPostMidnightContinuation ? endToday : wallTimeUnixOnDay(nextKey, endMinutes, zone);
207
- return { startSec: start, endSec: end, fullSession: false };
197
+ // Crossing midnight: before today's open, yesterday's session holds the timestamp while it is still open.
198
+ const [startYesterday, endYesterday] = sessionInstantsSec(session, dayWallMs - DAY_MS);
199
+ if (timestamp < (fullSession ? startToday : endYesterday)) {
200
+ return {
201
+ window: { startSec: startYesterday, endSec: endYesterday, fullSession },
202
+ openDayWallMs: dayWallMs - DAY_MS,
203
+ };
204
+ }
205
+ return { window: { startSec: startToday, endSec: endToday, fullSession }, openDayWallMs: dayWallMs };
206
+ }
207
+ /** The daily window `timestamp` reads, on the range's own zone clock: device-independent, daylight saving included. */
208
+ export function resolveTpoTimeRangeWindow(timestamp, customTimeRange) {
209
+ const session = tpoRangeSession(customTimeRange);
210
+ return session ? tpoWindowOn(timestamp, session).window : undefined;
208
211
  }
209
212
  export function containsTpoWindowTime(timestamp, window) {
210
213
  return timestamp >= window.startSec && timestamp < window.endSec;
211
214
  }
215
+ /** The first local day of the day, ISO week (Monday) or month holding the local day `dayWallMs`. */
216
+ function periodFirstDayWallMs(dayWallMs, sessionType) {
217
+ const day = new Date(dayWallMs);
218
+ if (sessionType === 'Weekly')
219
+ return dayWallMs - ((day.getUTCDay() + 6) % 7) * DAY_MS;
220
+ if (sessionType === 'Monthly')
221
+ return Date.UTC(day.getUTCFullYear(), day.getUTCMonth(), 1);
222
+ return dayWallMs;
223
+ }
224
+ /** The first local day of the next day, ISO week or month after the one opening on `firstDayWallMs`. */
225
+ function nextPeriodFirstDayWallMs(firstDayWallMs, sessionType) {
226
+ if (sessionType === 'Weekly')
227
+ return firstDayWallMs + 7 * DAY_MS;
228
+ if (sessionType === 'Monthly') {
229
+ const day = new Date(firstDayWallMs);
230
+ return Date.UTC(day.getUTCFullYear(), day.getUTCMonth() + 1, 1);
231
+ }
232
+ return firstDayWallMs + DAY_MS;
233
+ }
234
+ /**
235
+ * The instant (unix seconds) a window edge `wallMs` means on `zone`'s clock, by the one edge rule
236
+ * (market-sessions.util zoneWallEdgeToUtcMs): a wall time the clock skips opens at the change itself, a repeated one
237
+ * at its first occurrence. The wall time read as UTC where the zone clock serves no reading.
238
+ */
239
+ function zoneWallInstantSec(zone, wallMs) {
240
+ const ms = zoneWallEdgeToUtcMs(zone, wallMs);
241
+ return Math.floor((Number.isNaN(ms) ? wallMs : ms) / 1000);
242
+ }
243
+ /** The day, week or month holding `timestamp` on the range's own calendar, from its close if it crosses midnight. */
244
+ function tpoCalendarPeriodSec(timestamp, sessionType, range) {
245
+ const zone = !range || range.periodCalendar === 'UTC' ? 'UTC' : servedTimeZone(range.timezone);
246
+ const offsetMs = getTpoCrossDayOffsetMinutes(range) * MINUTE_MS;
247
+ const shiftedDayWallMs = Math.floor((zoneWallMsOr(zone, timestamp * 1000) - offsetMs) / DAY_MS) * DAY_MS;
248
+ const firstDayWallMs = periodFirstDayWallMs(shiftedDayWallMs, sessionType);
249
+ return [
250
+ zoneWallInstantSec(zone, firstDayWallMs + offsetMs),
251
+ zoneWallInstantSec(zone, nextPeriodFirstDayWallMs(firstDayWallMs, sessionType) + offsetMs),
252
+ ];
253
+ }
212
254
  export function getTpoSessionStart(timestamp, sessionType, customTimeRange) {
213
- const timeWindow = resolveTpoTimeRangeWindow(timestamp, customTimeRange);
214
- if (sessionType === 'Daily' && timeWindow)
215
- return timeWindow.startSec;
216
- const date = dayjs.unix(timestamp).utc();
217
- const offset = getTpoCrossDayOffset(customTimeRange);
218
- switch (sessionType) {
219
- case 'Weekly':
220
- return date.startOf('isoWeek').unix() + offset;
221
- case 'Monthly':
222
- return date.startOf('month').unix() + offset;
223
- case 'Daily':
224
- default:
225
- return date.startOf('day').unix() + offset;
255
+ if (sessionType === 'Daily' || !(sessionType === 'Weekly' || sessionType === 'Monthly')) {
256
+ const session = tpoRangeSession(customTimeRange);
257
+ if (session)
258
+ return tpoWindowOn(timestamp, session).window.startSec;
259
+ return tpoCalendarPeriodSec(timestamp, 'Daily', customTimeRange)[0];
226
260
  }
261
+ return tpoCalendarPeriodSec(timestamp, sessionType, customTimeRange)[0];
227
262
  }
228
263
  export function getNextTpoSessionStart(timestamp, sessionType, customTimeRange) {
229
- const timeWindow = resolveTpoTimeRangeWindow(timestamp, customTimeRange);
230
- if (sessionType === 'Daily' && timeWindow) {
231
- // The next session opens at the window's start wall time on the next
232
- // wall day, computed wall-exactly: a flat +24h drifts by an hour across
233
- // DST transitions (23h/25h days). The date from the zone clock and the
234
- // instant from the window's own wall-time memo: the TPO folds ask once
235
- // per period, where three dayjs conversions ran each time.
236
- const zone = timezoneName(customTimeRange?.timezone);
237
- const startMinutes = parseTpoTimeToMinutes(customTimeRange?.start_time) ?? 0;
238
- return wallTimeUnixOnDay(nextZoneDateKey(timeWindow.startSec, zone), startMinutes, zone);
239
- }
240
- const date = dayjs.unix(timestamp).utc();
241
- const offset = getTpoCrossDayOffset(customTimeRange);
242
- switch (sessionType) {
243
- case 'Weekly':
244
- return date.add(1, 'week').startOf('isoWeek').unix() + offset;
245
- case 'Monthly':
246
- return date.add(1, 'month').startOf('month').unix() + offset;
247
- case 'Daily':
248
- default:
249
- return date.add(1, 'day').startOf('day').unix() + offset;
264
+ if (sessionType === 'Daily' || !(sessionType === 'Weekly' || sessionType === 'Monthly')) {
265
+ const session = tpoRangeSession(customTimeRange);
266
+ // The next local day's open, read on that date: a flat +24h drifts an hour across a clock change.
267
+ if (session)
268
+ return sessionInstantsSec(session, tpoWindowOn(timestamp, session).openDayWallMs + DAY_MS)[0];
269
+ return tpoCalendarPeriodSec(timestamp, 'Daily', customTimeRange)[1];
250
270
  }
271
+ return tpoCalendarPeriodSec(timestamp, sessionType, customTimeRange)[1];
251
272
  }
252
273
  function formatTpoLetter(index) {
253
274
  if (!Number.isInteger(index) || index < 0) {
@@ -277,14 +298,24 @@ function formatTpoLetter(index) {
277
298
  export function generateTpoLetters(blockIds, _sessionType, _tpoBlockSizeMinutes) {
278
299
  return blockIds.map(formatTpoLetter);
279
300
  }
280
- /** Editable starting template (Asia / London / New York / Close, UTC) — a
281
- * default for the editor, never a hard-coded behavior. */
282
- export const DEFAULT_TPO_CUSTOM_SESSION_SEGMENTS = [
283
- { label: 'Asia', start: '00:00', end: '06:00', color: '#4f8cff' },
284
- { label: 'London', start: '06:00', end: '12:00', color: '#22c39b' },
285
- { label: 'New York', start: '12:00', end: '20:00', color: '#f2a33c' },
286
- { label: 'Close', start: '20:00', end: '00:00', color: '#a06bff' },
287
- ];
301
+ /** Each slice of the day split's colour (Asia, London and New York keep the colours their sessions always had). */
302
+ const SPLIT_SEGMENT_COLORS = Object.freeze({
303
+ asia: '#4f8cff',
304
+ london: '#22c39b',
305
+ newYork: '#f2a33c',
306
+ afterHours: '#a06bff',
307
+ });
308
+ /** The editor's starting set: the day split's slices on its clock, named by `labelOf`; hours from the split only. */
309
+ export function defaultTpoCustomSessionSegments(labelOf) {
310
+ return MARKET_SESSION_SPLIT.slices.map((slice) => ({
311
+ label: labelOf(slice.id),
312
+ start: sessionClockText(slice.startMinutes),
313
+ end: sessionClockText(slice.endMinutes),
314
+ color: SPLIT_SEGMENT_COLORS[slice.id],
315
+ }));
316
+ }
317
+ /** The starting set's clock, the split's own: New York, stored as 'ET'. */
318
+ export const DEFAULT_TPO_CUSTOM_SESSIONS_TIMEZONE = tpoCustomSessionsTimezoneOf(MARKET_SESSION_SPLIT.timeZone);
288
319
  const MINUTES_PER_DAY = 1440;
289
320
  const SECONDS_PER_DAY = 86_400;
290
321
  function parseTpoSegmentEndToMinutes(value) {
@@ -310,7 +341,7 @@ export function normalizeTpoCustomSessionSegments(value, timezone) {
310
341
  if (!Array.isArray(value) || value.length === 0)
311
342
  return null;
312
343
  const clock = tpoCustomSessionsTimezoneOf(timezone);
313
- const zone = timezoneName(clock);
344
+ const zone = tpoTimeZone(clock);
314
345
  const parsed = [];
315
346
  for (const raw of value) {
316
347
  if (!raw || typeof raw !== 'object')
@@ -401,60 +432,10 @@ function toTpoCustomSessionWindow(segment, startDaySec) {
401
432
  color: segment.color,
402
433
  };
403
434
  }
404
- const MS_PER_MINUTE = 60_000;
405
- /** `zone`'s wall clock at `ms` as a UTC-shaped epoch; the instant itself where the zone clock serves none. */
406
- function zoneWallMsOr(zone, ms) {
407
- let wallMs;
408
- try {
409
- wallMs = zoneWallMsAt(zone, ms);
410
- }
411
- catch {
412
- wallMs = Number.NaN;
413
- }
414
- return Number.isNaN(wallMs) ? ms : wallMs;
415
- }
416
- /**
417
- * The instant (unix seconds) `zone`'s wall clock reads `wallMs`; the wall reading itself where the clock serves none.
418
- * A wall time the clock skips (the spring-forward hour) opens at the first instant reading at or after it, the change
419
- * itself: the solver settles a skipped time on an instant reading earlier, and a session start read that way would
420
- * open before the instant asked from (a walk over starts would stall on it).
421
- */
422
- function zoneWallInstantSec(zone, wallMs) {
423
- let ms;
424
- try {
425
- ms = zoneWallToUtcMs(zone, wallMs);
426
- }
427
- catch {
428
- ms = Number.NaN;
429
- }
430
- if (Number.isNaN(ms))
431
- return Math.floor(wallMs / 1000);
432
- const readMs = zoneWallMsOr(zone, ms);
433
- return Math.floor((readMs === wallMs ? ms : firstInstantReadingAtLeast(zone, wallMs, ms, readMs)) / 1000);
434
- }
435
- /**
436
- * The first whole second whose `zone` wall reading is at least `wallMs`, for a skipped wall time: `ms` (reading
437
- * `readMs`) sits on one side of the skipped span and the instant one span away on the other, so a bisection between
438
- * them lands on the change. `ms` itself when the far side reads no later (no skipped span after all).
439
- */
440
- function firstInstantReadingAtLeast(zone, wallMs, ms, readMs) {
441
- let low = readMs < wallMs ? ms : ms - (readMs - wallMs);
442
- let high = readMs < wallMs ? ms + (wallMs - readMs) : ms;
443
- if (!(zoneWallMsOr(zone, high) >= wallMs) || zoneWallMsOr(zone, low) >= wallMs)
444
- return ms;
445
- for (let step = 0; step < 64 && high - low > 1000; step += 1) {
446
- const mid = low + Math.floor((high - low) / 2000) * 1000;
447
- if (zoneWallMsOr(zone, mid) >= wallMs)
448
- high = mid;
449
- else
450
- low = mid;
451
- }
452
- return high;
453
- }
454
435
  function zonedTpoCustomSessionWindow(segment, dayWallMs, zone) {
455
436
  return {
456
- startSec: zoneWallInstantSec(zone, dayWallMs + segment.startMinute * MS_PER_MINUTE),
457
- endSec: zoneWallInstantSec(zone, dayWallMs + segment.endMinute * MS_PER_MINUTE),
437
+ startSec: zoneWallInstantSec(zone, dayWallMs + segment.startMinute * MINUTE_MS),
438
+ endSec: zoneWallInstantSec(zone, dayWallMs + segment.endMinute * MINUTE_MS),
458
439
  index: segment.index,
459
440
  label: segment.label,
460
441
  color: segment.color,
@@ -464,10 +445,10 @@ function zonedTpoCustomSessionWindow(segment, dayWallMs, zone) {
464
445
  * date, each edge converted on its own date, so a session keeps its wall
465
446
  * hours across daylight saving (the 23 and 25 hour days included). */
466
447
  function newYorkTpoCustomSessionDay(timestamp, segments) {
467
- const zone = segments[0].zone || timezoneName('ET');
448
+ const zone = segments[0].zone || tpoTimeZone('ET');
468
449
  const wallMs = zoneWallMsOr(zone, timestamp * 1000);
469
450
  const dayWallMs = Math.floor(wallMs / DAY_MS) * DAY_MS;
470
- return { zone, dayWallMs, minuteOfDay: (wallMs - dayWallMs) / MS_PER_MINUTE };
451
+ return { zone, dayWallMs, minuteOfDay: (wallMs - dayWallMs) / MINUTE_MS };
471
452
  }
472
453
  /** The segment window containing `timestamp` (unix seconds), or null when
473
454
  * the timestamp falls in a gap between segments. Segments read on their
@@ -487,7 +468,7 @@ export function getTpoCustomSessionWindow(timestamp, segments) {
487
468
  }
488
469
  return null;
489
470
  }
490
- const dayStart = dayjs.unix(timestamp).utc().startOf('day').unix();
471
+ const dayStart = Math.floor(timestamp / SECONDS_PER_DAY) * SECONDS_PER_DAY;
491
472
  const minuteOfDay = Math.floor((timestamp - dayStart) / 60);
492
473
  // The post-midnight tail of the wrapping segment (always the last one)
493
474
  // belongs to the session that opened the previous day.
@@ -514,7 +495,7 @@ export function getNextTpoCustomSessionStart(timestamp, segments) {
514
495
  for (const segment of segments) {
515
496
  if (day === 0 && segment.startMinute <= minuteOfDay)
516
497
  continue;
517
- const startSec = zoneWallInstantSec(zone, dayWallMs + day * DAY_MS + segment.startMinute * MS_PER_MINUTE);
498
+ const startSec = zoneWallInstantSec(zone, dayWallMs + day * DAY_MS + segment.startMinute * MINUTE_MS);
518
499
  if (startSec > timestamp)
519
500
  return startSec;
520
501
  }
@@ -522,7 +503,7 @@ export function getNextTpoCustomSessionStart(timestamp, segments) {
522
503
  // Unreachable while the zone clock serves (the next day's first start lies a day ahead); still a step forward.
523
504
  return Math.floor(timestamp) + SECONDS_PER_DAY;
524
505
  }
525
- const dayStart = dayjs.unix(timestamp).utc().startOf('day').unix();
506
+ const dayStart = Math.floor(timestamp / SECONDS_PER_DAY) * SECONDS_PER_DAY;
526
507
  const minuteOfDay = (timestamp - dayStart) / 60;
527
508
  for (const segment of segments) {
528
509
  if (segment.startMinute > minuteOfDay)
@@ -0,0 +1,83 @@
1
+ /** A session's hours on its own clock. */
2
+ export interface MarketSessionWindow {
3
+ /** IANA zone the hours are written in. */
4
+ readonly timeZone: string;
5
+ /** Open, minutes after local midnight. */
6
+ readonly openMinutes: number;
7
+ /** Close, minutes after local midnight; at or below the open when the session crosses local midnight. */
8
+ readonly closeMinutes: number;
9
+ }
10
+ export type MarketSessionId = 'asia' | 'london' | 'newYork' | 'asiaFull' | 'londonFull' | 'newYorkFull';
11
+ export declare const MARKET_SESSIONS: Readonly<Record<MarketSessionId, MarketSessionWindow>>;
12
+ /** The window a stored session name means, or null for a name that is not a market session. */
13
+ export declare function marketSessionNamed(name: unknown): MarketSessionWindow | null;
14
+ /** The regions a session profile's Session dropdown stores (the Session VP family, Delta, the metric profiles). */
15
+ export declare const PROFILE_REGION_SESSION_TYPES: readonly ["US", "EU", "Asia"];
16
+ export type ProfileRegionSessionType = (typeof PROFILE_REGION_SESSION_TYPES)[number];
17
+ export declare function isProfileRegionSessionType(value: unknown): value is ProfileRegionSessionType;
18
+ /** The Session dropdown's day split (Session VP, Agg SVP): Asia, London, New York and after hours, a profile each. */
19
+ export declare const SESSION_SPLIT_TYPE = "Sessions";
20
+ export declare function isSessionSplitType(sessionType: unknown): boolean;
21
+ /** The longest chart bar the split draws on: a 1h bar straddles the 09:30 New York open. */
22
+ export declare const SESSION_SPLIT_MAX_CHART_MS: number;
23
+ export declare function isSessionSplitApplicable(chartIntervalMs: unknown): boolean;
24
+ /** A session type that brings its own hours (a region, the split): the Session start and Custom hours do not act. */
25
+ export declare function isMarketSessionType(sessionType: unknown): boolean;
26
+ /** A session profile's daily window as titan reads it (`customSessionWindow`): minutes after midnight on its zone. */
27
+ export interface SessionProfileDailyWindow {
28
+ timeZone: string;
29
+ startMinutes: number;
30
+ endMinutes: number;
31
+ }
32
+ /**
33
+ * A region's session profile keys: one profile a day inside the region's own window, which titan resolves on the
34
+ * region's clock each day. Null off the regions, and on a daily or longer chart, where a bar holds the whole session.
35
+ */
36
+ export declare function profileRegionSessionKeys(sessionType: unknown, chartIntervalMs: unknown): {
37
+ session: number;
38
+ customSessionWindow: SessionProfileDailyWindow;
39
+ } | null;
40
+ export type MarketSplitSliceId = 'asia' | 'london' | 'newYork' | 'afterHours';
41
+ export interface MarketSplitSlice {
42
+ readonly id: MarketSplitSliceId;
43
+ /** Start, minutes after midnight on the split's clock. */
44
+ readonly startMinutes: number;
45
+ /** End, minutes after midnight on the split's clock; below the start when the slice crosses midnight. */
46
+ readonly endMinutes: number;
47
+ }
48
+ export interface MarketSessionSplit {
49
+ /** The one IANA zone every slice is written in. */
50
+ readonly timeZone: string;
51
+ /** The slices in day order, each starting where the one before ends. */
52
+ readonly slices: readonly MarketSplitSlice[];
53
+ }
54
+ /**
55
+ * The day split into its sessions on ONE clock, New York, so the slices tile every day with no gap and no overlap
56
+ * whatever the clocks do: each slice ends where the next one opens. Asia opens with the CME Globex day at 18:00,
57
+ * London at 03:00 (08:00 in London, except in the weeks a year when the US and UK change clocks on different dates),
58
+ * New York at the 09:30 open, and after hours runs from the 16:00 close to the next Globex open. These are the
59
+ * America/New_York defaults of TradingView's "Three-Session Volume Profile" script. The London slice ends at the
60
+ * New York open, so it is shorter than the London session above.
61
+ */
62
+ export declare const MARKET_SESSION_SPLIT: MarketSessionSplit;
63
+ /** 'HH:MM' for minutes after local midnight: the clock text the wire and the dialogs use. */
64
+ export declare function sessionClockText(minutes: number): string;
65
+ /**
66
+ * The instant a window edge means on `timeZone`'s clock: the FIRST instant whose wall clock reads `wallMs` (a
67
+ * UTC-shaped epoch) or later. On an ordinary day that is the instant itself. A wall time that a fall-back change
68
+ * repeats is its first occurrence, and a wall time that a spring-forward change skips is the change itself: 02:30 New
69
+ * York on 2026-03-08 is 07:00Z, and 01:30 London on 2026-03-29 is 01:00Z. The gateway's local-minute filter reads a
70
+ * window the same way, so a session opens and closes where the served rows do. UTC reads as itself. NaN where the
71
+ * zone clock serves no reading.
72
+ */
73
+ export declare function zoneWallEdgeToUtcMs(timeZone: string, wallMs: number): number;
74
+ /**
75
+ * The session [open, close) as UTC instants on the local calendar day `localDayMs` (that day's midnight as a
76
+ * UTC-shaped epoch on the session's own clock). A close at or below the open lands on the next local day. Each edge
77
+ * is read on its own date with zoneWallEdgeToUtcMs, so a clock change moves the instant and keeps the wall hours, and
78
+ * an edge in a skipped or repeated hour lands where the gateway's filter puts it. NaN where the zone clock serves no
79
+ * reading.
80
+ */
81
+ export declare function marketSessionInstantsOn(session: MarketSessionWindow, localDayMs: number): readonly [number, number];
82
+ /** The [open, close) of the latest session opened at or before `tsMs` (forming or last closed); null if unreadable. */
83
+ export declare function marketSessionAtOrBefore(session: MarketSessionWindow, tsMs: number): readonly [number, number] | null;
@@ -0,0 +1,220 @@
1
+ /**
2
+ * The named trading sessions, written once. Every reader resolves a session's hours from here when it uses them and
3
+ * never keeps a copy: the Session Volume Profile family (Session VP, Aggregated Session VP, Delta, Open Interest and
4
+ * Liquidation profiles), TPO, Cumulative Returns by Session, session shading and wrun.
5
+ *
6
+ * Each session sits on its own city's clock (an IANA zone), so a name means the same hours in every indicator and
7
+ * daylight saving moves the session with its city. The mistake this ends: hours written as a fixed UTC window, or
8
+ * copied into another table or a saved setting, drift apart and ignore daylight saving. titan's fixed-UTC table put
9
+ * the US session at 08:30-15:00 New York every winter, and TPO's own table gave Asia, London and New York other
10
+ * hours again.
11
+ *
12
+ * Worker-safe: no Vue, store, i18n or dayjs imports.
13
+ */
14
+ import { zoneWallMsAt, zoneWallToUtcMs } from './ny-calendar.util.js';
15
+ const MINUTE_MS = 60_000;
16
+ const MINUTES_PER_DAY = 24 * 60;
17
+ const DAY_MS = MINUTES_PER_DAY * MINUTE_MS;
18
+ function sessionWindow(timeZone, openMinutes, closeMinutes) {
19
+ return Object.freeze({ timeZone, openMinutes, closeMinutes });
20
+ }
21
+ export const MARKET_SESSIONS = Object.freeze({
22
+ /** Asia: Tokyo hours with the pre-open, 08:00-15:00 Asia/Tokyo (23:00-06:00 UTC all year: Japan keeps no DST). */
23
+ asia: sessionWindow('Asia/Tokyo', 8 * 60, 15 * 60),
24
+ /** London: 08:00-16:00 Europe/London. */
25
+ london: sessionWindow('Europe/London', 8 * 60, 16 * 60),
26
+ /** New York: the cash session, 09:30-16:00 America/New_York. */
27
+ newYork: sessionWindow('America/New_York', 9 * 60 + 30, 16 * 60),
28
+ /** TPO's full Asia session, the forex Tokyo hours: 09:00-18:00 Asia/Tokyo. */
29
+ asiaFull: sessionWindow('Asia/Tokyo', 9 * 60, 18 * 60),
30
+ /** TPO's full London session, the forex London hours: 08:00-17:00 Europe/London. */
31
+ londonFull: sessionWindow('Europe/London', 8 * 60, 17 * 60),
32
+ /** TPO's full New York session, the forex New York hours: 08:00-17:00 America/New_York. */
33
+ newYorkFull: sessionWindow('America/New_York', 8 * 60, 17 * 60),
34
+ });
35
+ /**
36
+ * Every name a reader stores for a session, to its one window: the profiles' regions ('US', 'EU', 'Asia'),
37
+ * Cumulative Returns by Session's 'APAC', and TPO's trading-hour presets. A stored name stays as it was saved; only
38
+ * its hours come from here.
39
+ */
40
+ const SESSION_NAMES = Object.freeze({
41
+ US: 'newYork',
42
+ EU: 'london',
43
+ Asia: 'asia',
44
+ APAC: 'asia',
45
+ London: 'london',
46
+ 'New York': 'newYork',
47
+ 'Asia Full': 'asiaFull',
48
+ 'London Full': 'londonFull',
49
+ 'New York Full': 'newYorkFull',
50
+ });
51
+ /** The window a stored session name means, or null for a name that is not a market session. */
52
+ export function marketSessionNamed(name) {
53
+ if (typeof name !== 'string' || !Object.prototype.hasOwnProperty.call(SESSION_NAMES, name))
54
+ return null;
55
+ return MARKET_SESSIONS[SESSION_NAMES[name]];
56
+ }
57
+ /** The regions a session profile's Session dropdown stores (the Session VP family, Delta, the metric profiles). */
58
+ export const PROFILE_REGION_SESSION_TYPES = Object.freeze(['US', 'EU', 'Asia']);
59
+ export function isProfileRegionSessionType(value) {
60
+ return typeof value === 'string' && PROFILE_REGION_SESSION_TYPES.includes(value);
61
+ }
62
+ /** The Session dropdown's day split (Session VP, Agg SVP): Asia, London, New York and after hours, a profile each. */
63
+ export const SESSION_SPLIT_TYPE = 'Sessions';
64
+ export function isSessionSplitType(sessionType) {
65
+ return sessionType === SESSION_SPLIT_TYPE;
66
+ }
67
+ /** The longest chart bar the split draws on: a 1h bar straddles the 09:30 New York open. */
68
+ export const SESSION_SPLIT_MAX_CHART_MS = 30 * 60_000;
69
+ export function isSessionSplitApplicable(chartIntervalMs) {
70
+ return typeof chartIntervalMs === 'number' && chartIntervalMs > 0 && chartIntervalMs <= SESSION_SPLIT_MAX_CHART_MS;
71
+ }
72
+ /** A session type that brings its own hours (a region, the split): the Session start and Custom hours do not act. */
73
+ export function isMarketSessionType(sessionType) {
74
+ return isProfileRegionSessionType(sessionType) || isSessionSplitType(sessionType);
75
+ }
76
+ /**
77
+ * A region's session profile keys: one profile a day inside the region's own window, which titan resolves on the
78
+ * region's clock each day. Null off the regions, and on a daily or longer chart, where a bar holds the whole session.
79
+ */
80
+ export function profileRegionSessionKeys(sessionType, chartIntervalMs) {
81
+ if (!isProfileRegionSessionType(sessionType))
82
+ return null;
83
+ if (typeof chartIntervalMs !== 'number' || !(chartIntervalMs > 0) || chartIntervalMs >= DAY_MS)
84
+ return null;
85
+ const window = MARKET_SESSIONS[SESSION_NAMES[sessionType]];
86
+ return {
87
+ session: DAY_MS,
88
+ customSessionWindow: {
89
+ timeZone: window.timeZone,
90
+ startMinutes: window.openMinutes,
91
+ endMinutes: window.closeMinutes,
92
+ },
93
+ };
94
+ }
95
+ function splitSlice(id, startMinutes, endMinutes) {
96
+ return Object.freeze({ id, startMinutes, endMinutes });
97
+ }
98
+ /**
99
+ * The day split into its sessions on ONE clock, New York, so the slices tile every day with no gap and no overlap
100
+ * whatever the clocks do: each slice ends where the next one opens. Asia opens with the CME Globex day at 18:00,
101
+ * London at 03:00 (08:00 in London, except in the weeks a year when the US and UK change clocks on different dates),
102
+ * New York at the 09:30 open, and after hours runs from the 16:00 close to the next Globex open. These are the
103
+ * America/New_York defaults of TradingView's "Three-Session Volume Profile" script. The London slice ends at the
104
+ * New York open, so it is shorter than the London session above.
105
+ */
106
+ export const MARKET_SESSION_SPLIT = Object.freeze({
107
+ timeZone: 'America/New_York',
108
+ slices: Object.freeze([
109
+ splitSlice('asia', 18 * 60, 3 * 60),
110
+ splitSlice('london', 3 * 60, 9 * 60 + 30),
111
+ splitSlice('newYork', 9 * 60 + 30, 16 * 60),
112
+ splitSlice('afterHours', 16 * 60, 18 * 60),
113
+ ]),
114
+ });
115
+ /** 'HH:MM' for minutes after local midnight: the clock text the wire and the dialogs use. */
116
+ export function sessionClockText(minutes) {
117
+ const wrapped = ((Math.round(minutes) % MINUTES_PER_DAY) + MINUTES_PER_DAY) % MINUTES_PER_DAY;
118
+ const hours = Math.floor(wrapped / 60);
119
+ const mins = wrapped % 60;
120
+ return `${String(hours).padStart(2, '0')}:${String(mins).padStart(2, '0')}`;
121
+ }
122
+ /** How far a clock change moves the wall clock in every zone the session readers use (New York, Chicago, London). */
123
+ const CLOCK_CHANGE_MS = 60 * MINUTE_MS;
124
+ /**
125
+ * Every clock change in those zones moves the clock between 01:00 and 03:00 local (01:00 to 02:00 in London, 02:00 to
126
+ * 03:00 or back to 01:00 in New York and Chicago), so only a wall time in [01:00, 03:00) can be skipped or repeated.
127
+ * Any other edge is the solver's one reading, with no further clock reads.
128
+ */
129
+ const CHANGE_HOURS_START_MINUTES = 60;
130
+ const CHANGE_HOURS_END_MINUTES = 3 * 60;
131
+ function wallReadingAt(timeZone, ms) {
132
+ try {
133
+ return zoneWallMsAt(timeZone, ms);
134
+ }
135
+ catch {
136
+ return Number.NaN;
137
+ }
138
+ }
139
+ function solvedInstant(timeZone, wallMs) {
140
+ try {
141
+ return zoneWallToUtcMs(timeZone, wallMs);
142
+ }
143
+ catch {
144
+ return Number.NaN;
145
+ }
146
+ }
147
+ /**
148
+ * The instant a window edge means on `timeZone`'s clock: the FIRST instant whose wall clock reads `wallMs` (a
149
+ * UTC-shaped epoch) or later. On an ordinary day that is the instant itself. A wall time that a fall-back change
150
+ * repeats is its first occurrence, and a wall time that a spring-forward change skips is the change itself: 02:30 New
151
+ * York on 2026-03-08 is 07:00Z, and 01:30 London on 2026-03-29 is 01:00Z. The gateway's local-minute filter reads a
152
+ * window the same way, so a session opens and closes where the served rows do. UTC reads as itself. NaN where the
153
+ * zone clock serves no reading.
154
+ */
155
+ export function zoneWallEdgeToUtcMs(timeZone, wallMs) {
156
+ if (timeZone === 'UTC')
157
+ return wallMs;
158
+ const ms = solvedInstant(timeZone, wallMs);
159
+ if (!Number.isFinite(ms))
160
+ return Number.NaN;
161
+ const minuteOfDay = (((wallMs % DAY_MS) + DAY_MS) % DAY_MS) / MINUTE_MS;
162
+ if (minuteOfDay < CHANGE_HOURS_START_MINUTES || minuteOfDay >= CHANGE_HOURS_END_MINUTES)
163
+ return ms;
164
+ const readMs = wallReadingAt(timeZone, ms);
165
+ if (!Number.isFinite(readMs))
166
+ return Number.NaN;
167
+ if (readMs === wallMs) {
168
+ // A repeated wall time: the solver can hand back its later occurrence. One change earlier reads the same wall
169
+ // time only when the clock fell back in between, and that earlier instant is the first occurrence.
170
+ const earlier = ms - CLOCK_CHANGE_MS;
171
+ return wallReadingAt(timeZone, earlier) === wallMs ? earlier : ms;
172
+ }
173
+ // A skipped wall time: `ms` reads on one side of the jump, and one gap away the clock reads on the other. The first
174
+ // whole minute reading at or past the wall time is the change itself (changes fall on whole minutes).
175
+ let low = readMs < wallMs ? ms : ms - (readMs - wallMs);
176
+ let high = readMs < wallMs ? ms + (wallMs - readMs) : ms;
177
+ if (!(wallReadingAt(timeZone, high) >= wallMs) || wallReadingAt(timeZone, low) >= wallMs)
178
+ return ms;
179
+ while (high - low > MINUTE_MS) {
180
+ const mid = low + Math.floor((high - low) / (2 * MINUTE_MS)) * MINUTE_MS;
181
+ if (wallReadingAt(timeZone, mid) >= wallMs)
182
+ high = mid;
183
+ else
184
+ low = mid;
185
+ }
186
+ return high;
187
+ }
188
+ /**
189
+ * The session [open, close) as UTC instants on the local calendar day `localDayMs` (that day's midnight as a
190
+ * UTC-shaped epoch on the session's own clock). A close at or below the open lands on the next local day. Each edge
191
+ * is read on its own date with zoneWallEdgeToUtcMs, so a clock change moves the instant and keeps the wall hours, and
192
+ * an edge in a skipped or repeated hour lands where the gateway's filter puts it. NaN where the zone clock serves no
193
+ * reading.
194
+ */
195
+ export function marketSessionInstantsOn(session, localDayMs) {
196
+ const closeDayMs = session.closeMinutes <= session.openMinutes ? localDayMs + DAY_MS : localDayMs;
197
+ return [
198
+ zoneWallEdgeToUtcMs(session.timeZone, localDayMs + session.openMinutes * MINUTE_MS),
199
+ zoneWallEdgeToUtcMs(session.timeZone, closeDayMs + session.closeMinutes * MINUTE_MS),
200
+ ];
201
+ }
202
+ /** The [open, close) of the latest session opened at or before `tsMs` (forming or last closed); null if unreadable. */
203
+ export function marketSessionAtOrBefore(session, tsMs) {
204
+ try {
205
+ const wallMs = zoneWallMsAt(session.timeZone, tsMs);
206
+ if (!Number.isFinite(wallMs))
207
+ return null;
208
+ const localDayMs = Math.floor(wallMs / DAY_MS) * DAY_MS;
209
+ // A session that opens later in this local day than `tsMs` is the day before's; two back reaches one over midnight.
210
+ for (const back of [0, 1, 2]) {
211
+ const instants = marketSessionInstantsOn(session, localDayMs - back * DAY_MS);
212
+ if (Number.isFinite(instants[0]) && Number.isFinite(instants[1]) && instants[0] <= tsMs)
213
+ return instants;
214
+ }
215
+ }
216
+ catch {
217
+ // Intl's RangeError for a zone this runtime cannot read: no session.
218
+ }
219
+ return null;
220
+ }
@@ -1 +1,2 @@
1
- export declare function getSessionInterval(sessionType: string, chartInterval: string): number | string;
1
+ /** Always ms: a named session (a region, the day split) is a day; its hours ride its window (sessionWindowKeysFor). */
2
+ export declare function getSessionInterval(sessionType: string, chartInterval: string): number;
@@ -16,10 +16,8 @@ const SESSION_INTERVALS = {
16
16
  '3M': { Footprint: Intervals.MONTH3, Targeted: Intervals.MONTH3, Wide: Intervals.MONTH3 },
17
17
  '1Y': { Footprint: Intervals.YEAR, Targeted: Intervals.YEAR, Wide: Intervals.YEAR },
18
18
  };
19
+ /** Always ms: a named session (a region, the day split) is a day; its hours ride its window (sessionWindowKeysFor). */
19
20
  export function getSessionInterval(sessionType, chartInterval) {
20
- if (['US', 'EU', 'Asia'].includes(sessionType)) {
21
- return sessionType;
22
- }
23
21
  // A preset or an extended rung reads the row of its standard at or below
24
22
  // (10m -> 5m, 30s -> 1s, 6M -> 3M), floored at its own bar: a session never
25
23
  // splits a bar, so Footprint (one profile per chart bar) keeps the chart's
@@ -18,6 +18,7 @@ import { Intervals } from '../../constants/interval.constants.js';
18
18
  import { barEndMs, barStartMs } from '../chart/calendar-interval.util.js';
19
19
  import { intervalLabelForMs } from '../chart/interval-ladder.util.js';
20
20
  import { profileRowMultiplier } from '../chart/profile-row-height.util.js';
21
+ import { marketSessionAtOrBefore, marketSessionNamed, profileRegionSessionKeys, } from '../chart/market-sessions.util.js';
21
22
  import { getSessionInterval } from '../chart/session-interval.util.js';
22
23
  import { parseWrunThemeToken, wrunFontFamilyCss, wrunThemeTokenScaleAlpha } from './wrun-style-words.util.js';
23
24
  /** The sheet's mode words to the engine's display modes; "delta" is the
@@ -85,24 +86,27 @@ function intervalLabelOf(intervalMs) {
85
86
  }
86
87
  return best ?? '1d';
87
88
  }
88
- /** The engine's `session` setting for a session word: "auto" is the native
89
- * Targeted mapping for the chart interval, a length word its milliseconds,
90
- * a region word the engine's region name. */
91
- function sessionSettingOf(word, intervalLabel) {
92
- switch (word ?? 'auto') {
93
- case 'auto':
94
- return getSessionInterval('Targeted', intervalLabel);
95
- case 'us':
96
- return 'US';
97
- case 'eu':
98
- return 'EU';
99
- case 'asia':
100
- return 'Asia';
101
- default: {
102
- const length = Intervals.map_unit[word];
103
- return typeof length === 'number' ? length : getSessionInterval('Targeted', intervalLabel);
104
- }
89
+ /** The sheet's region words, to the region names the native session profiles store. */
90
+ const WRUN_REGION_SESSION_TYPES = {
91
+ us: 'US',
92
+ eu: 'EU',
93
+ asia: 'Asia',
94
+ };
95
+ /** The engine's session keys: "auto" the native Targeted mapping, a length word its ms, a region word its own day. */
96
+ function sessionKeysOf(word, intervalLabel, intervalMs) {
97
+ const value = word ?? 'auto';
98
+ const region = Object.prototype.hasOwnProperty.call(WRUN_REGION_SESSION_TYPES, value)
99
+ ? WRUN_REGION_SESSION_TYPES[value]
100
+ : undefined;
101
+ if (region !== undefined) {
102
+ // Never the region's name: titan reads a name off its fixed-UTC table, an hour off every winter.
103
+ const keys = profileRegionSessionKeys(region, intervalMs);
104
+ return keys ? { ...keys, region } : { session: getSessionInterval(region, intervalLabel) };
105
105
  }
106
+ if (value === 'auto')
107
+ return { session: getSessionInterval('Targeted', intervalLabel) };
108
+ const length = Intervals.map_unit[value];
109
+ return { session: typeof length === 'number' ? length : getSessionInterval('Targeted', intervalLabel) };
106
110
  }
107
111
  /** A colour word at a fraction of its own alpha: a token keeps its word
108
112
  * (`theme.text/14`), a hex colour becomes `rgba(r, g, b, a)`; any other
@@ -148,13 +152,13 @@ function newestCloseMs(ctx, rows) {
148
152
  return newest === undefined ? undefined : barEndMs(newest, ctx.intervalMs);
149
153
  }
150
154
  /** The rows of the session holding the newest bar (span "developing"): the
151
- * window of the session length (a region session reads as a day) that
152
- * contains the newest row's timestamp. A month, quarter, half-year or year
153
- * session is its calendar bar (`barStartMs` to `barEndMs`): the epoch floor
154
- * of the average length opened the March 2026 session on January 31 10:30
155
- * and handed it February's row too. */
156
- function developingRows(rows, session) {
157
- const sessionMs = typeof session === 'number' && session > 0 ? session : Intervals.DAY;
155
+ * window of the session length that contains the newest row's timestamp, or
156
+ * for a region its own session (the latest one opened by the newest row). A
157
+ * month, quarter, half-year or year session is its calendar bar (`barStartMs`
158
+ * to `barEndMs`): the epoch floor of the average length opened the March 2026
159
+ * session on January 31 10:30 and handed it February's row too. */
160
+ function developingRows(rows, keys) {
161
+ const sessionMs = keys.session > 0 ? keys.session : Intervals.DAY;
158
162
  let newest;
159
163
  for (const row of rows) {
160
164
  const ts = rowTs(row);
@@ -163,8 +167,10 @@ function developingRows(rows, session) {
163
167
  }
164
168
  if (newest === undefined)
165
169
  return [];
166
- const start = barStartMs(newest, sessionMs);
167
- const end = barEndMs(start, sessionMs);
170
+ const regionWindow = keys.region !== undefined ? marketSessionNamed(keys.region) : null;
171
+ const regionSession = regionWindow ? marketSessionAtOrBefore(regionWindow, newest) : null;
172
+ const start = regionSession ? regionSession[0] : barStartMs(newest, sessionMs);
173
+ const end = regionSession ? regionSession[1] : barEndMs(start, sessionMs);
168
174
  return rows.filter((row) => {
169
175
  const ts = rowTs(row);
170
176
  return ts !== undefined && ts >= start && ts < end;
@@ -185,7 +191,7 @@ export function wrunVolumeProfileChild(profile, cellRows, ctx) {
185
191
  return null;
186
192
  const span = profile.span ?? 'session';
187
193
  const intervalLabel = intervalLabelOf(ctx.intervalMs);
188
- const session = sessionSettingOf(profile.session, intervalLabel);
194
+ const sessionKeys = sessionKeysOf(profile.session, intervalLabel, ctx.intervalMs);
189
195
  let data;
190
196
  const anchor = {};
191
197
  switch (span) {
@@ -208,7 +214,7 @@ export function wrunVolumeProfileChild(profile, cellRows, ctx) {
208
214
  break;
209
215
  }
210
216
  case 'developing':
211
- data = developingRows(rows, session);
217
+ data = developingRows(rows, sessionKeys);
212
218
  anchor.profileWindow = 'data';
213
219
  anchor.lineBounds = 'profile';
214
220
  break;
@@ -218,7 +224,9 @@ export function wrunVolumeProfileChild(profile, cellRows, ctx) {
218
224
  default:
219
225
  data = [...rows];
220
226
  anchor.variant = 'session';
221
- anchor.session = session;
227
+ anchor.session = sessionKeys.session;
228
+ if (sessionKeys.customSessionWindow)
229
+ anchor.customSessionWindow = sessionKeys.customSessionWindow;
222
230
  }
223
231
  const bucketWidth = bucketWidthOf(rows);
224
232
  const rowHeight = profile.row_height ?? 'auto';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orangecharts/wrun-chart-host",
3
- "version": "0.11.0",
3
+ "version": "0.11.1",
4
4
  "description": "The wrun chart-host layer shared by the kiyotaka web app and the mobile app: the wrun result reader and painter model, cut from the web app (its reference implementation).",
5
5
  "type": "module",
6
6
  "files": [
@@ -22,6 +22,11 @@
22
22
  "default": "./dist/*.js"
23
23
  }
24
24
  },
25
+ "scripts": {
26
+ "build": "node scripts/generate-tool-tables.mjs && rm -rf dist && tsc -p tsconfig.build.json && node scripts/esm-dist.mjs dist",
27
+ "consumer-check": "node scripts/consumer-check.mjs",
28
+ "typecheck": "tsc -p tsconfig.json --noEmit"
29
+ },
25
30
  "peerDependencies": {
26
31
  "@orangecharts/indicator-kit": "0.106.5",
27
32
  "@orangecharts/orange-v2-pb-common": "12.79.0",
@@ -35,10 +40,5 @@
35
40
  "dayjs": "1.11.23",
36
41
  "lodash-es": "4.18.1",
37
42
  "typescript": "5.9.3"
38
- },
39
- "scripts": {
40
- "build": "node scripts/generate-tool-tables.mjs && rm -rf dist && tsc -p tsconfig.build.json && node scripts/esm-dist.mjs dist",
41
- "consumer-check": "node scripts/consumer-check.mjs",
42
- "typecheck": "tsc -p tsconfig.json --noEmit"
43
43
  }
44
- }
44
+ }