gloomberb 0.20.6 → 0.20.7

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.
Files changed (67) hide show
  1. package/package.json +1 -1
  2. package/src/api-client/fund-facts.ts +20 -4
  3. package/src/api-client/socket.ts +4 -4
  4. package/src/architecture/shortcut-labels-allowlist.json +1 -0
  5. package/src/cli/commands/market.ts +33 -17
  6. package/src/cli/commands/search.ts +19 -3
  7. package/src/cli/desktop-pane-shot.ts +61 -0
  8. package/src/cli/pane-functions/dom.ts +4 -4
  9. package/src/cli/pane-functions/freshness.ts +38 -5
  10. package/src/cli/pane-functions/screenshot-assessment.ts +16 -4
  11. package/src/cli/quote-answer.ts +57 -1
  12. package/src/cli/result.ts +17 -0
  13. package/src/docs/snapshot.json +55 -16
  14. package/src/i18n/es.ts +2 -0
  15. package/src/i18n/ja.ts +2 -0
  16. package/src/i18n/ko.ts +2 -0
  17. package/src/i18n/zh-cn.ts +2 -0
  18. package/src/i18n/zh-tw.ts +2 -0
  19. package/src/market-data/market/change-basis.ts +49 -8
  20. package/src/market-data/market/dated-previous-close.ts +133 -10
  21. package/src/market-data/market/freshness.ts +18 -6
  22. package/src/market-data/market/status.ts +9 -1
  23. package/src/market-data/published-nse-sessions.ts +16 -1
  24. package/src/market-data/quotes/freshness.ts +15 -0
  25. package/src/plugins/builtin/alerts/alert-engine.ts +15 -0
  26. package/src/plugins/builtin/alerts/cli.ts +22 -9
  27. package/src/plugins/builtin/alerts/headless.ts +1 -1
  28. package/src/plugins/builtin/alerts/index.tsx +5 -1
  29. package/src/plugins/builtin/alerts/metric-command.ts +1 -1
  30. package/src/plugins/builtin/holders/fund-holders.ts +22 -1
  31. package/src/plugins/builtin/holders/headless.ts +5 -4
  32. package/src/plugins/builtin/holders/pane.tsx +7 -3
  33. package/src/plugins/builtin/holders/report-header.ts +23 -0
  34. package/src/plugins/builtin/members/client.ts +1 -1
  35. package/src/plugins/builtin/members/headless.ts +2 -0
  36. package/src/plugins/builtin/members/model.ts +10 -8
  37. package/src/plugins/builtin/members/pane.tsx +4 -1
  38. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +5 -2
  39. package/src/plugins/builtin/portfolio-list/cli/render.ts +66 -23
  40. package/src/plugins/builtin/portfolio-list/headless.ts +2 -1
  41. package/src/plugins/builtin/portfolio-list/income.ts +46 -22
  42. package/src/plugins/builtin/portfolio-list/pane/data.ts +16 -6
  43. package/src/plugins/builtin/portfolio-list/pane/index.tsx +5 -4
  44. package/src/plugins/builtin/portfolio-list/use-throttled-ticker-order.ts +40 -3
  45. package/src/plugins/builtin/sec/fund-facts.ts +25 -5
  46. package/src/plugins/builtin/shared/report-freshness.ts +15 -6
  47. package/src/plugins/builtin/supply-chain/model.ts +18 -6
  48. package/src/portfolio/column-values.ts +3 -0
  49. package/src/portfolio/valuation-basis.ts +23 -1
  50. package/src/state/hooks/quote-streaming.ts +14 -6
  51. package/src/tickers/instrument-kind.ts +22 -1
  52. package/src/tickers/search/index.ts +5 -0
  53. package/src/tickers/terminal-codes.ts +17 -5
  54. package/src/time-series/fundamentals/current-valuation.ts +244 -0
  55. package/src/time-series/fundamentals/historical-valuation.ts +99 -0
  56. package/src/time-series/fundamentals/metric-ids.ts +61 -0
  57. package/src/time-series/fundamentals/period-points.ts +104 -0
  58. package/src/time-series/fundamentals/quarterly-ttm.ts +220 -0
  59. package/src/time-series/fundamentals/series.ts +164 -0
  60. package/src/time-series/fundamentals/source-statements.ts +177 -0
  61. package/src/time-series/fundamentals/statement-fields.ts +154 -0
  62. package/src/time-series/fundamentals/statement-merge.ts +124 -0
  63. package/src/time-series/fundamentals/statement.ts +114 -0
  64. package/src/time-series/fundamentals/valuation-multiples.ts +50 -0
  65. package/src/time-series/fundamentals.ts +18 -1407
  66. package/src/types/financials.ts +9 -0
  67. package/src/utils/debug-log.ts +29 -0
@@ -6,6 +6,7 @@ import { logFailure } from "../../utils/log-failure";
6
6
  import { dailyBarDate } from "../../utils/price-history";
7
7
  import { classifyInstrumentType } from "../../tickers/instrument-kind";
8
8
  import { calendarVenue, changeBasisSessionDate, isChangeBasisDatedWithoutCloses, quoteChangeBasis } from "./change-basis";
9
+ import { latestRegularSessionClose, latestRegularSessionOpen } from "./freshness";
9
10
  import { cleanFloat32Price } from "../../utils/float32-price";
10
11
 
11
12
  /** History closes come as float32 (30.93000030517578) where the quote says 30.93: one close. */
@@ -50,7 +51,7 @@ export interface DatedCloseListing {
50
51
 
51
52
  /** A listing's recent daily closes (a month is enough), with the flags that say a bar had not closed yet. */
52
53
  export type ReadDailyCloses = (listing: DatedCloseListing) => Promise<readonly DailyClose[]>;
53
- type DailyClose = Pick<PricePoint, "date" | "close" | "partial" | "unsettled"> & { volume?: number };
54
+ type DailyClose = Pick<PricePoint, "date" | "close" | "partial" | "unsettled"> & Partial<Pick<PricePoint, "open" | "high" | "low">> & { volume?: number };
54
55
 
55
56
  export interface PreviousCloseDatesOptions {
56
57
  /** Called with the latest copy of a quote, dated, when a read lands that names its day. */
@@ -62,7 +63,7 @@ export interface PreviousCloseDatesOptions {
62
63
  indexWaitMs?: number;
63
64
  }
64
65
 
65
- type ReadingFields = Pick<Reading, "date" | "close" | "sessionClose" | "awaitsSessionClose" | "untraded">;
66
+ type ReadingFields = Pick<Reading, "date" | "close" | "sessionClose" | "awaitsSessionClose" | "untraded" | "session">;
66
67
 
67
68
  interface Reading {
68
69
  date: string | null;
@@ -81,9 +82,27 @@ interface Reading {
81
82
  * close either (ThinPreviousTrade): no day can be named for it.
82
83
  */
83
84
  untraded?: boolean;
85
+ /**
86
+ * A quote its source left behind its listing's daily bars (laggingSession):
87
+ * the later session whose close is its price, that bar's range, and the
88
+ * day the listing last traded when nothing traded in it.
89
+ */
90
+ session?: LaggingSession;
84
91
  at: number;
85
92
  }
86
93
 
94
+ interface LaggingSession {
95
+ date: string;
96
+ open?: number;
97
+ high?: number;
98
+ low?: number;
99
+ volume?: number;
100
+ nominal?: { lastTraded: string | null };
101
+ }
102
+
103
+ /** A daily bar that shows a trade: some volume. One with none, or none reported, proves nothing traded. */
104
+ const tradedBar = (point: Pick<DailyClose, "volume">): boolean => typeof point.volume === "number" && point.volume > 0;
105
+
87
106
  /**
88
107
  * Venues whose quoted previous close is the exchange's official close, not
89
108
  * the last trade its daily bar closes on, with how far apart the two can be:
@@ -132,6 +151,8 @@ function sameClose(left: number, right: number): boolean {
132
151
  */
133
152
  function readingKey(quote: Quote | null | undefined, listing: DatedCloseListing, now: number): string | null {
134
153
  if (!quote || classifyInstrumentType(quote.instrumentType) === "option") return null;
154
+ // A stale share or fund may stand at a price its venue set in a later session than its source dated (laggingSession).
155
+ if (laggingQuote(quote, now)) return `${datedCloseListingKey(listing)}|${changeBasisSessionDate(quote)}|${quote.price}|${quote.previousClose}|lagging`;
135
156
  // An index's dated close is checked against its daily close of that day as well (indexCloseOn), but for a Cboe
136
157
  // index's, which Gloom Cloud checks against Cboe's own closes.
137
158
  if (datedIndexClose(quote)) return calendarVenue(quote) === "CBOE" ? null : datedReadingKey(quote, listing);
@@ -155,6 +176,40 @@ function thinListingCalendarDate(quote: Quote): string | null {
155
176
  return basis?.kind === "close" && basis.venue ? basis.date : null;
156
177
  }
157
178
 
179
+ /**
180
+ * A share or fund whose source marked its quote stale: its venue may have set
181
+ * nominal prices in the sessions since (HKEX does for a counter nothing traded
182
+ * on), which its daily bars carry while the quote keeps the day of its last
183
+ * print. 9042.HK, the USD counter of a bitcoin fund, read on Sun 8 Nov 2026:
184
+ * Fri 6 Nov's nominal 1.172 against Thu 5 Nov's 1.244, dated Wed 4 Nov by its
185
+ * last print. While its venue's session is in progress (sessionInProgressOpen),
186
+ * only one with no print since it opened, whatever state the quote names: a
187
+ * trade today is the quote's own session. Otherwise not one its source still
188
+ * calls open.
189
+ */
190
+ function laggingQuote(quote: Quote, now: number): boolean {
191
+ const kind = classifyInstrumentType(quote.instrumentType);
192
+ if ((kind !== "equity" && kind !== "fund") || quote.stale !== true || quote.delisting) return false;
193
+ if (!(quote.price > 0 && typeof quote.previousClose === "number" && quote.previousClose > 0 && changeBasisSessionDate(quote))) return false;
194
+ const open = sessionInProgressOpen(quote, now);
195
+ if (open != null) return Number.isFinite(quote.lastUpdated) && quote.lastUpdated < open;
196
+ return quote.marketState !== "REGULAR";
197
+ }
198
+
199
+ /**
200
+ * When the regular session in progress at `now` on the quote's venue opened,
201
+ * its midday break included: HKEX's 12:00 to 13:00 is still the day's
202
+ * session, whatever state the source names then. Null between sessions and on
203
+ * a venue whose hours are unknown.
204
+ */
205
+ function sessionInProgressOpen(quote: Quote, now: number): number | null {
206
+ const venue = calendarVenue(quote);
207
+ const open = latestRegularSessionOpen(venue, now);
208
+ if (open == null) return null;
209
+ const close = latestRegularSessionClose(venue, now);
210
+ return !close || close.close < open ? open : null;
211
+ }
212
+
158
213
  function datedReadingKey(quote: Quote, listing: DatedCloseListing): string | null {
159
214
  const previousClose = quote.previousClose;
160
215
  const sessionDate = changeBasisSessionDate(quote);
@@ -171,15 +226,56 @@ function datedReadingKey(quote: Quote, listing: DatedCloseListing): string | nul
171
226
  * future's session awaiting settlement, is no close: a copy kept from the
172
227
  * session before (a US holiday) must never stand for that session's close.
173
228
  */
174
- function closedBars(points: readonly DailyClose[], quote: Quote): Array<{ date: string; close: number }> {
229
+ function closedBars(points: readonly DailyClose[], quote: Quote): Array<{ date: string; close: number; point: DailyClose }> {
175
230
  const venue = calendarVenue(quote);
176
231
  return points.flatMap((point) => {
177
232
  const time = new Date(point.date).getTime();
178
233
  if (point.partial || point.unsettled || !Number.isFinite(time) || !Number.isFinite(point.close)) return [];
179
- return [{ date: dailyBarDate(time, venue), close: point.close }];
234
+ return [{ date: dailyBarDate(time, venue), close: point.close, point }];
180
235
  });
181
236
  }
182
237
 
238
+ const positiveBarPrice = (value: number | undefined) => typeof value === "number" && Number.isFinite(value) && value > 0 ? cleanFloat32Price(value) : undefined;
239
+
240
+ /**
241
+ * The session a lagging quote's price is from (laggingQuote): the listing's
242
+ * latest daily bar, when it is later than the session the quote is dated to,
243
+ * its close is the quote's price and the bar before it closed at the quote's
244
+ * previous close; while the venue's session is in progress, the latest bar
245
+ * before today's. A bar that shows no trade (no volume, or none reported) is
246
+ * a nominal price: the reading then names the latest day the bars show a
247
+ * trade. Null when the bars do not say so, and the quote stands as its
248
+ * source dated it.
249
+ */
250
+ function laggingSession(points: readonly DailyClose[], quote: Quote, now: number): ReadingFields | null {
251
+ const quoted = changeBasisSessionDate(quote);
252
+ // While today's session is in progress, a bar of today's is not a completed session, whatever its source marks.
253
+ const sessionOpen = sessionInProgressOpen(quote, now);
254
+ const today = sessionOpen != null ? dailyBarDate(sessionOpen, calendarVenue(quote)) : null;
255
+ const bars = closedBars(points, quote)
256
+ .filter((bar) => !today || bar.date < today)
257
+ .sort((left, right) => left.date.localeCompare(right.date));
258
+ const last = bars.at(-1);
259
+ const before = bars.at(-2);
260
+ if (!quoted || !last || !before || last.date <= quoted) return null;
261
+ if (!sameClose(last.close, quote.price) || !sameClose(before.close, quote.previousClose!)) return null;
262
+ if (!tradedBar(last.point)) {
263
+ const lastTraded = bars.findLast((bar) => tradedBar(bar.point))?.date ?? null;
264
+ return { date: before.date, session: { date: last.date, ...last.point.volume === 0 ? { volume: 0 } : {}, nominal: { lastTraded } } };
265
+ }
266
+ const { open, high, low, volume } = last.point;
267
+ return {
268
+ date: before.date,
269
+ session: {
270
+ date: last.date,
271
+ ...positiveBarPrice(open) != null ? { open: positiveBarPrice(open) } : {},
272
+ ...positiveBarPrice(high) != null ? { high: positiveBarPrice(high) } : {},
273
+ ...positiveBarPrice(low) != null ? { low: positiveBarPrice(low) } : {},
274
+ ...typeof volume === "number" && Number.isFinite(volume) ? { volume } : {},
275
+ },
276
+ };
277
+ }
278
+
183
279
  /**
184
280
  * The day of the latest daily close before the move's session, when that
185
281
  * close is the quote's previous close; null otherwise, so a gap in the
@@ -257,7 +353,10 @@ function indexCloseOn(points: readonly DailyClose[], quote: Quote, date: string)
257
353
  * venue's calendar puts before the move's: the day of its latest daily close
258
354
  * before the move's session that traded, when that close is its previous
259
355
  * close. When it traded in the calendar's session the calendar stands
260
- * (date null); when its closes hold neither, the day is unknown (`untraded`).
356
+ * (date null), and so it does when the calendar's session closed at the
357
+ * previous close with nothing traded: the venue's nominal price of that day
358
+ * (83042.HK's 8.315 on Thu 5 Nov 2026, its last trade on Wed 4 Nov at
359
+ * 8.095). When its closes hold none of these, the day is unknown (`untraded`).
261
360
  */
262
361
  function thinPreviousTrade(points: readonly DailyClose[], quote: Quote, calendarDate: string): ReadingFields {
263
362
  const sessionDate = changeBasisSessionDate(quote)!;
@@ -267,12 +366,16 @@ function thinPreviousTrade(points: readonly DailyClose[], quote: Quote, calendar
267
366
  .sort((left, right) => left.date.localeCompare(right.date))
268
367
  .at(-1);
269
368
  if (!before || before.date >= calendarDate) return { date: null };
270
- return sameClose(before.close, quote.previousClose!) ? { date: before.date } : { date: null, untraded: true };
369
+ if (sameClose(before.close, quote.previousClose!)) return { date: before.date };
370
+ const nominal = closedBars(points, quote).findLast((point) => point.date === calendarDate);
371
+ return nominal && sameClose(nominal.close, quote.previousClose!) ? { date: null } : { date: null, untraded: true };
271
372
  }
272
373
 
273
- function readingOf(points: readonly DailyClose[], quote: Quote): ReadingFields {
374
+ function readingOf(points: readonly DailyClose[], quote: Quote, now: number): ReadingFields {
274
375
  const indexDate = datedIndexClose(quote);
275
376
  if (indexDate) return indexCloseOn(points, quote, indexDate);
377
+ const lagging = laggingQuote(quote, now) ? laggingSession(points, quote, now) : null;
378
+ if (lagging) return lagging;
276
379
  const calendarDate = thinListingCalendarDate(quote);
277
380
  if (calendarDate) return thinPreviousTrade(points, quote, calendarDate);
278
381
  const session = sessionCloseOf(points, quote);
@@ -288,13 +391,33 @@ function withDate<T extends Quote | null | undefined>(quote: T, date: string | n
288
391
  }
289
392
 
290
393
  /** The quote as a reading has it: dated, and for an index measured from that day's close when its own disagrees. */
291
- function withReading<T extends Quote | null | undefined>(quote: T, reading: Pick<Reading, "date" | "close" | "sessionClose" | "untraded"> | undefined): T {
394
+ function withReading<T extends Quote | null | undefined>(quote: T, reading: Pick<Reading, "date" | "close" | "sessionClose" | "untraded" | "session"> | undefined): T {
292
395
  if (!quote || !reading) return quote;
293
396
  if (reading.untraded) return { ...quote, previousCloseUndated: true };
397
+ if (reading.session && reading.date) return withDate(withLaggingSession(quote, reading.session), reading.date);
294
398
  const closed = withSessionClose(quote, reading.sessionClose);
295
399
  return closed === quote ? withDatedReading(quote, reading) : withDatedReading(closed as T, reading);
296
400
  }
297
401
 
402
+ /**
403
+ * A lagging quote as its bars date it: its move is the later session's, with
404
+ * that bar's range and volume. Its last print, and whether its source calls
405
+ * it stale, stay as they were: the bars date the price, not a trade. A
406
+ * nominal price has no range, nothing having traded, and says which
407
+ * session's it is (Quote.nominalPrice).
408
+ */
409
+ function withLaggingSession<T extends Quote>(quote: T, session: LaggingSession): T {
410
+ return {
411
+ ...quote,
412
+ changeSessionDate: session.date,
413
+ open: session.open,
414
+ high: session.high,
415
+ low: session.low,
416
+ volume: session.volume,
417
+ ...session.nominal ? { nominalPrice: { session: session.date, lastTraded: session.nominal.lastTraded } } : {},
418
+ };
419
+ }
420
+
298
421
  /** A closed quote that ended on a later print headlines its session's official close, as history and the portfolio read it. */
299
422
  function withSessionClose<T extends Quote>(quote: T, close: number | undefined): T {
300
423
  const sessionDate = close != null && quote.marketState === "CLOSED" && !(typeof quote.regularClose === "number" && quote.regularClose > 0)
@@ -411,7 +534,7 @@ export class PreviousCloseDates {
411
534
 
412
535
  private read(key: string, quote: Quote, listing: DatedCloseListing): Promise<ReadingFields> {
413
536
  const read = this.inSlot(datedIndexClose(quote) ? "index" : "dating", () => withDeadline(Promise.resolve().then(() => this.readCloses(listing)), this.readDeadlineMs, "Reading daily closes timed out"))
414
- .then((points) => readingOf(points, quote))
537
+ .then((points) => readingOf(points, quote, this.now()))
415
538
  .catch(logFailure("market-data.dated-previous-close", "Read daily closes failed", { date: null } as ReadingFields))
416
539
  .then((reading) => {
417
540
  this.pending.delete(key);
@@ -420,7 +543,7 @@ export class PreviousCloseDates {
420
543
  this.readings.set(key, { ...reading, at: this.now() });
421
544
  const latest = this.latestCopies.get(key);
422
545
  this.latestCopies.delete(key);
423
- if ((reading.date || reading.sessionClose != null || reading.untraded) && latest && this.options.onDated) {
546
+ if ((reading.date || reading.sessionClose != null || reading.untraded || reading.session) && latest && this.options.onDated) {
424
547
  try {
425
548
  this.options.onDated(latest.listing, withReading(latest.quote, reading));
426
549
  } catch (error) {
@@ -4,7 +4,7 @@ import { hasPublishedApacCalendar, isPublishedApacClosure, publishedApacEarlyClo
4
4
  import { hasPublishedCnCalendar, isPublishedCnClosure } from "../published-cn-sessions";
5
5
  import { hasPublishedFuturesCalendar, isPublishedFuturesClosure, isPublishedFuturesVenue } from "../published-futures-sessions";
6
6
  import { hasPublishedJpxCalendar, isPublishedJpxClosure } from "../published-jpx-sessions";
7
- import { hasPublishedNseCalendar, isPublishedNseClosure } from "../published-nse-sessions";
7
+ import { hasPublishedNseCalendar, isPublishedNseClosure, publishedNseSpecialSession } from "../published-nse-sessions";
8
8
  import { getPublishedUsEquityCalendarDay, getPublishedUsEquityCalendarYears, getPublishedUsEquitySession } from "../published-us-sessions";
9
9
  import { quoteFutureToleranceMs } from "../quotes/clock";
10
10
  import { zonedDateKey, zonedDateTimeParts, zonedWallClockToUtcMs } from "../../utils/zoned-date-time";
@@ -256,7 +256,8 @@ function formatExchangeLocalMinuteOfDay(timeZone: string, timestampMs: number):
256
256
 
257
257
  function isBeforeKnownRegularOpen(exchange: string, timestampMs: number): boolean {
258
258
  const canonical = canonicalExchange(exchange);
259
- const openMinute = REGULAR_OPEN_MINUTES[canonical];
259
+ const date = exchangeLocalDate(canonical, timestampMs);
260
+ const openMinute = (date ? publishedSpecialSession(canonical, date)?.open : undefined) ?? REGULAR_OPEN_MINUTES[canonical];
260
261
  const localMinute = exchangeLocalMinuteOfDay(canonical, timestampMs);
261
262
  return openMinute != null && localMinute != null && localMinute < openMinute;
262
263
  }
@@ -281,6 +282,11 @@ function isPublishedClosure(exchange: string, date: string): boolean {
281
282
  return getPublishedUsEquityCalendarDay(exchange, date) === "closed";
282
283
  }
283
284
 
285
+ /** A published special session on a day the venue is otherwise shut (NSE's and BSE's Sunday Muhurat session), with its local hours. */
286
+ function publishedSpecialSession(exchange: string, date: string): { open: number; close: number } | undefined {
287
+ return exchange === "NSE" || exchange === "BSE" ? publishedNseSpecialSession(date) : undefined;
288
+ }
289
+
284
290
  /** Whether `weekday` (0 is Sunday) is in the venue's trading week. */
285
291
  export function isTradingWeekday(exchange: string, weekday: number, weekendDays?: readonly number[]): boolean {
286
292
  return !(weekendDays ?? WEEKEND_DAYS[exchange] ?? DEFAULT_WEEKEND_DAYS).includes(weekday);
@@ -316,6 +322,7 @@ export function venueSessionOnOrBefore(exchange: string | undefined, date: strin
316
322
 
317
323
  /** `weekendDays` replaces the venue's days off (historySourceWeekendDays). */
318
324
  function isLocalTradingDay(exchange: string, date: string, weekendDays?: readonly number[]): boolean {
325
+ if (publishedSpecialSession(exchange, date)) return true;
319
326
  const weekday = localWeekday(date);
320
327
  return weekday != null && isTradingWeekday(exchange, weekday, weekendDays) && !isPublishedClosure(exchange, date);
321
328
  }
@@ -345,6 +352,8 @@ function localWeekday(date: string): number | null {
345
352
 
346
353
  /** The local close of the venue's regular session on `date`, in minutes of the day, a published half day's included. */
347
354
  function regularCloseMinutes(exchange: string, date: string): number | undefined {
355
+ const special = publishedSpecialSession(exchange, date);
356
+ if (special) return special.close;
348
357
  const early = publishedApacEarlyClose(exchange, date);
349
358
  if (early !== undefined) return early;
350
359
  const weekday = localWeekday(date);
@@ -462,8 +471,9 @@ export function latestRegularSessionOpen(
462
471
  } else if (minutes === undefined) {
463
472
  return null;
464
473
  } else if (isLocalTradingDay(canonical, date, weekendDays)) {
474
+ const opens = publishedSpecialSession(canonical, date)?.open ?? minutes;
465
475
  open = zonedWallClockToUtcMs(timeZone, Number(date.slice(0, 4)), Number(date.slice(5, 7)),
466
- Number(date.slice(8, 10)), Math.floor(minutes / 60), minutes % 60, 0);
476
+ Number(date.slice(8, 10)), Math.floor(opens / 60), opens % 60, 0);
467
477
  }
468
478
  if (open != null && open <= time) return open;
469
479
  }
@@ -496,8 +506,9 @@ export function nextRegularSessionOpen(
496
506
  } else if (minutes === undefined) {
497
507
  return null;
498
508
  } else if (isLocalTradingDay(canonical, date)) {
509
+ const opens = publishedSpecialSession(canonical, date)?.open ?? minutes;
499
510
  open = zonedWallClockToUtcMs(timeZone, Number(date.slice(0, 4)), Number(date.slice(5, 7)),
500
- Number(date.slice(8, 10)), Math.floor(minutes / 60), minutes % 60, 0);
511
+ Number(date.slice(8, 10)), Math.floor(opens / 60), opens % 60, 0);
501
512
  }
502
513
  if (open != null && open > time) return { date, open, timeZone };
503
514
  }
@@ -567,9 +578,10 @@ export function previousPublishedSession(
567
578
  for (let offset = 0; offset <= SESSION_LOOKBACK_DAYS * 2; offset++) {
568
579
  const at = new Date((day - offset) * MS_PER_DAY);
569
580
  const iso = at.toISOString().slice(0, 10);
570
- if (!isTradingWeekday(canonical, at.getUTCDay())) continue;
581
+ const special = !!publishedSpecialSession(canonical, iso);
582
+ if (!special && !isTradingWeekday(canonical, at.getUTCDay())) continue;
571
583
  if (!hasPublishedSessionCalendar(canonical, iso)) return null;
572
- const open = !isPublishedClosure(canonical, iso);
584
+ const open = special || !isPublishedClosure(canonical, iso);
573
585
  // First the session the move is from's own day, then the one before it.
574
586
  if (session == null) {
575
587
  if (open) session = offset;
@@ -67,6 +67,12 @@ export function marketStateLabel(state: MarketState): string {
67
67
 
68
68
  /** What a quote's session reads as once its last print is older than its venue's latest completed session. */
69
69
  const STALE_SESSION_LABEL = "STALE";
70
+ /**
71
+ * What a quote's session reads as when nothing traded in the session its price
72
+ * is from, nor today while its venue trades: its price is the venue's nominal
73
+ * one (Quote.nominalPrice).
74
+ */
75
+ const NO_TRADES_SESSION_LABEL = "NO TRADES";
70
76
 
71
77
  const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] as const;
72
78
  const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] as const;
@@ -139,6 +145,7 @@ function quoteMarketState(quote: Quote | null | undefined, now = Date.now()): Ma
139
145
  */
140
146
  export function quoteMarketStateLabel(quote: Quote | null | undefined, now = Date.now()): string | null {
141
147
  if (quote?.delisting) return delistingLabel(quote.delisting);
148
+ if (quote?.nominalPrice) return NO_TRADES_SESSION_LABEL;
142
149
  if (!quote?.marketState) return null;
143
150
  if (isQuoteBeforeLatestSession(quote, now)) return STALE_SESSION_LABEL;
144
151
  const awaiting = preMarketCloseAwaitingPrint(quote);
@@ -245,6 +252,7 @@ export function quoteSessionStateLabel(quote: Quote | null | undefined, now = Da
245
252
 
246
253
  function sessionLabel(quote: Quote | null | undefined, now: number, standingClose: boolean): string | null {
247
254
  if (quote?.delisting) return standingClose ? delistingLabel(quote.delisting) : delistingStateLabel(quote.delisting);
255
+ if (quote?.nominalPrice) return NO_TRADES_SESSION_LABEL;
248
256
  if (!quote?.marketState) return null;
249
257
  if (isQuoteBeforeLatestSession(quote, now)) return STALE_SESSION_LABEL;
250
258
  if (overnightSessionDisplay(quote)) return "OVERNIGHT";
@@ -259,7 +267,7 @@ function sessionLabel(quote: Quote | null | undefined, now: number, standingClos
259
267
  * pre-market still stands at.
260
268
  */
261
269
  export function quoteSessionColor(quote: Quote | null | undefined, palette: ThemeColors = colors, now = Date.now()): string {
262
- if (quote?.delisting) return palette.warning;
270
+ if (quote?.delisting || quote?.nominalPrice) return palette.warning;
263
271
  if (!quote?.marketState) return palette.textDim;
264
272
  if (isQuoteBeforeLatestSession(quote, now)) return palette.warning;
265
273
  if (overnightSessionDisplay(quote)) return marketStateColor("POST", palette);
@@ -1,7 +1,6 @@
1
1
  // Published NSE equity closures (weekend dates omitted), not a holiday-rule engine.
2
2
  // BSE closes on the same days. Source: https://www.nseindia.com/resources/exchange-communication-holidays
3
3
  // (checked 2026-10-04; past dates match the days missing from NSE bhavcopy).
4
- // The Diwali Muhurat session falls on a weekend and is not modelled.
5
4
  const NSE_CLOSURES: Record<number, readonly string[]> = {
6
5
  2026: [
7
6
  "01-15", "01-26", "03-03", "03-26", "03-31", "04-03", "04-14", "05-01",
@@ -18,3 +17,19 @@ export function isPublishedNseClosure(date: string): boolean {
18
17
  export function hasPublishedNseCalendar(year: number): boolean {
19
18
  return NSE_CLOSURES[year] !== undefined;
20
19
  }
20
+
21
+ /**
22
+ * Published special sessions on days NSE and BSE are otherwise shut (the
23
+ * Diwali Muhurat session), as local minutes: the normal market's open, and
24
+ * its close with the closing auction and post-close, as a regular day's 09:15
25
+ * and 16:00 are. 2026: Sun 8 Nov, normal market from 14:20, closing auction
26
+ * to 15:30 (NSE circular NSE/CMTR/76941 of 19 Oct 2026; BSE trades the same session).
27
+ */
28
+ const NSE_SPECIAL_SESSIONS: Record<string, { open: number; close: number }> = {
29
+ "2026-11-08": { open: 14 * 60 + 20, close: 16 * 60 },
30
+ };
31
+
32
+ /** A published special session on `date` (YYYY-MM-DD), with its local hours; undefined on every other day. */
33
+ export function publishedNseSpecialSession(date: string): { open: number; close: number } | undefined {
34
+ return NSE_SPECIAL_SESSIONS[date];
35
+ }
@@ -183,6 +183,21 @@ export function noPrintsTodayText(quote: Quote | null | undefined, now = Date.no
183
183
  return `no prints today since ${time} (${quoteAgeText(since, now)})`;
184
184
  }
185
185
 
186
+ /**
187
+ * What a quote nothing traded on says beside its price (Quote.nominalPrice):
188
+ * "no trades since Thu 29 Oct, nominal price", or "no recent trades, nominal
189
+ * price" when its bars reach back to no trade. In the regular session too,
190
+ * until it trades. Null for any other quote.
191
+ */
192
+ export function nominalPriceText(quote: Pick<Quote, "nominalPrice"> | null | undefined): string | null {
193
+ const nominal = quote?.nominalPrice;
194
+ if (!nominal) return null;
195
+ const traded = nominal.lastTraded ? new Date(`${nominal.lastTraded}T00:00:00Z`) : null;
196
+ return traded && Number.isFinite(traded.getTime())
197
+ ? `no trades since ${PRINT_WEEKDAYS[traded.getUTCDay()]} ${traded.getUTCDate()} ${PRINT_MONTHS[traded.getUTCMonth()]}, nominal price`
198
+ : "no recent trades, nominal price";
199
+ }
200
+
186
201
  export function hasFreshQuoteForCurrentSession(
187
202
  quotes: Iterable<Quote | null | undefined>,
188
203
  now = Date.now(),
@@ -93,6 +93,21 @@ export function evaluateAlert(alert: AlertRule, currentPrice: number): boolean {
93
93
  }
94
94
  }
95
95
 
96
+ /**
97
+ * Whether an above or below rule already holds at a reading. Such a rule is a
98
+ * state, not a crossing (`evaluateAlert`, `metricTrigger`), so one that holds
99
+ * when it is added goes off at its first check. `crosses`, a moving-average
100
+ * cross and an RRG quadrant wait for the next move through their level.
101
+ */
102
+ export function levelAlreadyMet(
103
+ condition: AlertCondition,
104
+ value: number | null | undefined,
105
+ level: number | null | undefined,
106
+ ): boolean {
107
+ if (value == null || level == null || !Number.isFinite(value) || !Number.isFinite(level)) return false;
108
+ return condition === "above" ? value > level : condition === "below" ? value < level : false;
109
+ }
110
+
96
111
  export function formatAlertDescription(alert: AlertRule): string {
97
112
  if (alert.metric) return metricDescription(alert);
98
113
  if (alert.move) return `${alertListing({ symbol: alert.symbol, exchange: alert.exchange })} ${moveRuleWords(alert)} from the previous close`;
@@ -45,7 +45,7 @@ import {
45
45
  type CalendarEventChoice,
46
46
  type ReleaseRename,
47
47
  } from "./calendar-events";
48
- import { createAlert, formatAlertDescription, rearmAlert, sameLevelRule } from "./alert-engine";
48
+ import { createAlert, formatAlertDescription, levelAlreadyMet, rearmAlert, sameLevelRule } from "./alert-engine";
49
49
  import { alertPriceText } from "./price-text";
50
50
  import { ALERTS_PLUGIN_ID } from "./constants";
51
51
  import { MAX_EVENT_ALERTS, eventAlertTarget, toggleEventAlert, writeEventAlertStores, type EventAlertRule } from "./events";
@@ -205,7 +205,7 @@ function releaseRequest(args: readonly string[], country: CountryFilter | null,
205
205
  }
206
206
 
207
207
  /**
208
- * Reads `alerts add` arguments: `<symbol> above 250`, `<symbol> earnings`,
208
+ * Reads `alerts add` arguments: `<symbol> above 400`, `<symbol> earnings`,
209
209
  * `<symbol> earnings results`, or a release in the economic calendar by name
210
210
  * (`CPI`, `FOMC`, `NBS PMI`, `CN PMI`), with `--days` (already taken out of
211
211
  * `args`, `null` when the flag came without a value) and `--country` for the
@@ -773,16 +773,16 @@ export const alertsCliCommand: CliCommandDef = {
773
773
  ],
774
774
  examples: [
775
775
  "alerts",
776
- "alerts add AAPL above 250",
776
+ "alerts add AAPL above 400",
777
777
  "alerts add GBPUSD=X moves 0.5%",
778
778
  "alerts add HSBA.L BARC.L down 3%",
779
779
  "alerts add --watchlist Book up 3%",
780
780
  "alerts add VOD.L below 70p",
781
781
  "alerts add AAPL pe below 25",
782
- "alerts add AAPL ps above 8",
782
+ "alerts add AAPL ps above 12",
783
783
  'alerts add NVDA "rsi(14)" under 30',
784
784
  'alerts add SPY "ma(50)" crosses above "ma(200)"',
785
- 'alerts add TSLA closes below "ma(200)"',
785
+ 'alerts add TSLA closes above "ma(200)"',
786
786
  "alerts add XLK/SPY above 0.25",
787
787
  "alerts add XLE rrg leading",
788
788
  "alerts add SMH rrg weakening --benchmark QQQ",
@@ -1110,7 +1110,7 @@ export const alertsCliCommand: CliCommandDef = {
1110
1110
  { key: "createdAt", header: "Created", format: (value) => String(value ?? "") },
1111
1111
  { key: "triggeredAt", header: "Triggered", optional: true },
1112
1112
  ],
1113
- empty: "No alerts. Add one with gloom alerts add AAPL above 250, alerts add CRWV earnings --days 3, alerts add CPI --days 1, or alerts add CN PMI.",
1113
+ empty: "No alerts. Add one with gloom alerts add AAPL above 400, alerts add CRWV earnings --days 3, alerts add CPI --days 1, or alerts add CN PMI.",
1114
1114
  });
1115
1115
  return;
1116
1116
  }
@@ -1230,12 +1230,25 @@ export const alertsCliCommand: CliCommandDef = {
1230
1230
  // A daily rule is first judged on the first close after it was set, once that close has settled.
1231
1231
  // An RRG quadrant, on the last session of that week.
1232
1232
  const weekly = alert.metric?.kind === "rrg";
1233
- const firstCheck = alert.metric && isDailyMetric(alert.metric) ? firstDailyCheck(alert.exchange, now, weekly) : null;
1233
+ const daily = !!alert.metric && isDailyMetric(alert.metric);
1234
+ const firstCheck = daily ? firstDailyCheck(alert.exchange, now, weekly) : null;
1235
+ // The price a price alert is checked on, as the far-target check measures against.
1236
+ const checkedPrice = !alert.metric && priced && Number.isFinite(priced.quote.price) && priced.quote.price !== 0 ? priced.quote.price : null;
1237
+ // An above or below rule that already holds goes off at its first check, not on the next cross: said with the reading.
1238
+ const alreadyMet = alert.metric
1239
+ ? levelAlreadyMet(alert.condition, alert.lastCheckedPrice, alert.lastCheckedTarget)
1240
+ : levelAlreadyMet(alert.condition, checkedPrice, alert.targetPrice);
1241
+ const level = alert.metric?.kind === "close_ma" ? "it" : alert.metric ? String(alert.targetPrice) : alertPriceText(alert, alert.targetPrice);
1242
+ const met = alreadyMet ? `, already ${alert.condition} ${level}${daily ? "" : ", so it goes off at the next check"}` : "";
1243
+ const goesOffThen = daily && alreadyMet ? ` It goes off then if it is still ${alert.condition}.` : "";
1234
1244
  const notes = [
1235
- alert.metric ? unread ? `Not read yet: ${unread.replace(/\.$/, "")}.` : `${metricReadingNote(alert)}.` : null,
1236
- firstCheck ? `First checked on the ${firstCheck.day} ${weekly ? "weekly close" : "close"}, from ${isoUtc(firstCheck.at).slice(11, 16)} UTC.` : null,
1245
+ alert.metric ? unread ? `Not read yet: ${unread.replace(/\.$/, "")}.` : `${metricReadingNote(alert)}${met}.`
1246
+ : checkedPrice != null ? `Last price ${alertPriceText(alert, checkedPrice)}${met}.` : null,
1247
+ firstCheck ? `First checked on the ${firstCheck.day} ${weekly ? "weekly close" : "close"}, from ${isoUtc(firstCheck.at).slice(11, 16)} UTC.${goesOffThen}`
1248
+ : goesOffThen ? `It goes off on the first close it is checked on if it is still ${alert.condition}.` : null,
1237
1249
  ].filter(Boolean).join(" ");
1238
1250
  ctx.printResult({ data: { changed: !ctx.cliOptions.dryRun, dryRun: ctx.cliOptions.dryRun, alert,
1251
+ ...alreadyMet ? { alreadyMet } : {},
1239
1252
  ...firstCheck ? { firstCheck: { close: firstCheck.day, at: isoUtc(firstCheck.at) } } : {},
1240
1253
  ...unread ? { unread } : {} }, ...(read.length > 0 ? { warnings: read } : {}) }, {
1241
1254
  // The delivery, as docs/usage.md states it, before any full stop, which after the price would read as part of it (below 81.).
@@ -141,7 +141,7 @@ function pricesResult(alerts: readonly AlertRule[], error: string | null, events
141
141
  columns: PRICE_COLUMNS,
142
142
  textColumns: PRICE_TEXT_COLUMNS,
143
143
  rows: [...active, ...triggered].map(priceRow),
144
- empty: "No level alerts. Add one with gloom alerts add AAPL above 250.",
144
+ empty: "No level alerts. Add one with gloom alerts add AAPL above 400.",
145
145
  ...(error ? { errors: [error], complete: false } : {}),
146
146
  ...(notes.length ? { notes } : {}),
147
147
  };
@@ -31,6 +31,7 @@ import {
31
31
  createAlert,
32
32
  evaluateAlert,
33
33
  formatAlertDescription,
34
+ levelAlreadyMet,
34
35
  sameLevelRule,
35
36
  } from "./alert-engine";
36
37
  import {
@@ -327,8 +328,11 @@ export const alertsPlugin: GloomPlugin = {
327
328
  recordFired(alertChangeEntry("created", alertLogRule(alert)));
328
329
  alertStream?.sync();
329
330
 
331
+ // A level the price is already past goes off at the next check, as `alerts add` says.
332
+ const met = !input.metric && levelAlreadyMet(alert.condition, quote.price, alert.targetPrice)
333
+ ? `, already ${alert.condition}, so it goes off at the next check` : "";
330
334
  ctx.notify({
331
- body: `Alert set: ${formatAlertDescription(alert)}${input.metric ? firstCheck ? `, ${firstCheck}` : "" : ` (current ${alertPriceText(alert, quote.price)})`}`,
335
+ body: `Alert set: ${formatAlertDescription(alert)}${input.metric ? firstCheck ? `, ${firstCheck}` : "" : ` (current ${alertPriceText(alert, quote.price)}${met})`}`,
332
336
  type: "success",
333
337
  });
334
338
  },
@@ -7,7 +7,7 @@ import { parsePublicTickerKey } from "../../../utils/exchanges";
7
7
 
8
8
  export interface MetricAlertInput { symbol: string; condition: AlertCondition; price: number; metric: AlertMetric }
9
9
  const direction = (s: string) => /^(above|over|>)$/i.test(s) ? "above" as const : /^(below|under|<)$/i.test(s) ? "below" as const : null;
10
- const USAGE = "Use AAPL pe below 25, AAPL ps above 8, NVDA rsi(14) under 30, SPY ma(50) crosses above ma(200), or TSLA closes below ma(200).";
10
+ const USAGE = "Use AAPL pe below 25, AAPL ps above 12, NVDA rsi(14) under 30, SPY ma(50) crosses above ma(200), or TSLA closes above ma(200).";
11
11
  function checked(input: MetricAlertInput): MetricAlertInput {
12
12
  if (!validMetricRule({ ...input, targetPrice: input.price })) throw new Error("Use a positive multiple, RSI from 0 to 100, and whole MA/RSI periods from 2 to 200 (fast MA shorter than slow MA).");
13
13
  return input;
@@ -6,6 +6,7 @@ import { isNoSourceAnswer } from "../../../sources/provider-errors";
6
6
  import { logFailure } from "../../../utils/log-failure";
7
7
  import { fetchFunds } from "../members/client";
8
8
  import { coveredFund } from "../members/model";
9
+ import { isNoHoldersAnswer, noHoldersText } from "./report-header";
9
10
 
10
11
  type FundQuote = Pick<Quote, "instrumentType" | "tradingExchangeName" | "listingExchangeName" | "exchangeName">;
11
12
 
@@ -24,7 +25,7 @@ export interface FundHoldersAnswer {
24
25
  * holds where `fn MEMB` covers it, and its fund facts (`fn ETF`). Null for a
25
26
  * listing that is not a fund, or a failure that is no answer (a timeout).
26
27
  */
27
- export async function fundHoldersAnswer(
28
+ async function fundHoldersAnswer(
28
29
  symbol: string,
29
30
  error: unknown,
30
31
  quote: FundQuote | null | undefined,
@@ -49,3 +50,23 @@ export async function fundHoldersAnswer(
49
50
  ],
50
51
  };
51
52
  }
53
+
54
+ /**
55
+ * What `holders`, `13f` and `fn HDS` say for a listing no holder source has
56
+ * holders of, in place of the source's bare NO_DATA: a fund's answer
57
+ * (`fundHoldersAnswer`), else that none are on record and, abroad, which
58
+ * filings were read (`noHoldersText`). Its venue is the quote's, else the one
59
+ * the request named. Null for a failure that is no answer (a timeout).
60
+ */
61
+ export async function noHoldersAnswer(
62
+ symbol: string,
63
+ exchange: string | undefined,
64
+ error: unknown,
65
+ quote: (FundQuote & Pick<Quote, "currency">) | null | undefined,
66
+ client: NonNullable<Parameters<typeof fetchFunds>[0]>,
67
+ ): Promise<FundHoldersAnswer | null> {
68
+ const fund = await fundHoldersAnswer(symbol, error, quote, client);
69
+ if (fund || !isNoHoldersAnswer(error)) return fund;
70
+ const venue = (quote ? quoteTradingExchange(quote) : "") || exchange || symbol.split(":")[1] || "";
71
+ return { message: noHoldersText(symbol, venue, quote?.currency), details: [] };
72
+ }
@@ -33,7 +33,7 @@ import {
33
33
  holderReportUnits,
34
34
  } from "./report-rows";
35
35
  import { REPORT_ROWS } from "../shared/headless-options";
36
- import { fundHoldersAnswer } from "./fund-holders";
36
+ import { noHoldersAnswer } from "./fund-holders";
37
37
  import { companyDataNotes } from "../../../types/company-from";
38
38
  import {
39
39
  HOLDER_ROWS_MAX,
@@ -230,15 +230,16 @@ export function createHoldersHeadless(
230
230
  dependencies.loadSnapshot(symbol, args, ctx).catch(async (error: unknown) => {
231
231
  const quote = await ctx.marketData.getQuote(symbol)
232
232
  .catch(logFailure("holders.headless", "Read the quote of a listing with no holders failed", null));
233
- const fund = await fundHoldersAnswer(symbol, error, quote, ctx.apiClient);
234
- if (fund) return fund;
233
+ const none = await noHoldersAnswer(symbol, exchange, error, quote, ctx.apiClient);
234
+ if (none) return none;
235
235
  throw error;
236
236
  }),
237
237
  indexTicker
238
238
  ? dependencies.loadIndexedHolders(indexTicker, limit, ctx).catch(logFailure("holders.headless", "Load 13F holder index failed", null))
239
239
  : null,
240
240
  ]);
241
- // A fund has no ownership breakdown: the report says so in place of rows, with what reads it, and fails as no data.
241
+ // A fund has no ownership breakdown, and a listing may have no holders on record: the report says so
242
+ // in place of rows (with what reads a fund), and fails as no data.
242
243
  if ("message" in snapshot) {
243
244
  return {
244
245
  columns: HOLDER_REPORT_COLUMNS,