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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gloomberb",
3
- "version": "0.20.6",
3
+ "version": "0.20.7",
4
4
  "packageManager": "bun@1.3.14",
5
5
  "description": "Market research and portfolio tracker for the terminal",
6
6
  "module": "src/public/index.ts",
@@ -99,6 +99,16 @@ export interface FundFlows {
99
99
  */
100
100
  type FundFactsStatus = "covered" | "not-collected-yet" | "not-published" | "not-a-fund";
101
101
 
102
+ /**
103
+ * What a counter's computed premium is from when its own close is nominal:
104
+ * another counter's traded close (`3042:HKEX` at HK$9.18) converted at the
105
+ * rate between the two counters' NAVs, or the nominal close itself when no
106
+ * counter traded.
107
+ */
108
+ type FundPremiumPrice =
109
+ | { kind: "counter"; ticker: string; close: number; currency: string }
110
+ | { kind: "nominal" };
111
+
102
112
  /** GET /cloud/fund-facts/:ticker. Percent fields are in percent (0.03 is 0.03%). */
103
113
  export interface FundFactsPayload {
104
114
  ticker: string;
@@ -120,14 +130,20 @@ export interface FundFactsPayload {
120
130
  nav: (FundFact<number> & { period?: "day" | "month-end"; estimate?: { low: number; high: number } }) | null;
121
131
  /** Why a covered fund has no NAV, in one line. Absent when it has one, and from servers before it. */
122
132
  navReason?: string;
123
- /** Dated by its own session: a month end on a weekend is priced at the Friday before it. */
124
- closingPrice: FundFact<number> | null;
133
+ /**
134
+ * Dated by its own session: a month end on a weekend is priced at the Friday
135
+ * before it. `nominal`: nothing traded in that session (a Hong Kong fund's
136
+ * USD or RMB counter on a quiet day), so the close is the exchange's
137
+ * nominal price; absent from servers before it.
138
+ */
139
+ closingPrice: (FundFact<number> & { nominal?: true }) | null;
125
140
  /**
126
141
  * `published` by the sponsor, or `computed` from the closing price against
127
142
  * the NAV, dated by the NAV. `estimate`: computed against the midpoint of a
128
- * NAV estimate, so an estimate too; absent from servers before it.
143
+ * NAV estimate, so an estimate too; absent from servers before it. `price`:
144
+ * what a computed premium is from when not the closing price as traded.
129
145
  */
130
- premiumDiscount: (FundFact<number> & { basis: "published" | "computed"; estimate?: true }) | null;
146
+ premiumDiscount: (FundFact<number> & { basis: "published" | "computed"; estimate?: true; price?: FundPremiumPrice }) | null;
131
147
  /**
132
148
  * `period`: a `day`'s figure, or the last `month-end`'s (Vanguard and ARK
133
149
  * ETFs, N-PORT), which is not today's. `document`: the fund's N-PORT report
@@ -19,7 +19,7 @@ import {
19
19
  normalizeChatReactions,
20
20
  normalizeTeamNotification,
21
21
  } from "./normalizers";
22
- import { debugLog } from "../utils/debug-log";
22
+ import { debugLog, previewList, previewLongLists } from "../utils/debug-log";
23
23
  import { canonicalExchange, normalizeSymbol } from "../utils/exchanges";
24
24
  import { mergeQuoteSubscriptionTargets } from "../market-data/quote-subscription-target";
25
25
  import { recordServerClockSample } from "../market-data/quotes/clock";
@@ -520,7 +520,7 @@ export class CloudApiSocket {
520
520
  if (subscriptionsToSend.length > 0) {
521
521
  cloudApiLog.info("register quote listeners", {
522
522
  count: subscriptionsToSend.length,
523
- symbols: subscriptionsToSend.map((target) =>
523
+ symbols: previewList(subscriptionsToSend, (target) =>
524
524
  marketKey(target.symbol, target.exchange),
525
525
  ),
526
526
  });
@@ -562,7 +562,7 @@ export class CloudApiSocket {
562
562
  if (removedTargets.length > 0) {
563
563
  cloudApiLog.info("remove quote listeners", {
564
564
  count: removedTargets.length,
565
- symbols: removedTargets.map((target) =>
565
+ symbols: previewList(removedTargets, (target) =>
566
566
  marketKey(target.symbol, target.exchange),
567
567
  ),
568
568
  });
@@ -1062,7 +1062,7 @@ export class CloudApiSocket {
1062
1062
  type === "scanner.subscribe" ||
1063
1063
  type === "scanner.unsubscribe"
1064
1064
  ) {
1065
- cloudApiLog.info("send websocket message", payload);
1065
+ cloudApiLog.info("send websocket message", previewLongLists(payload as Record<string, unknown>));
1066
1066
  }
1067
1067
  }
1068
1068
  this.ws.send(JSON.stringify(payload));
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "src/cli/commands/keybindings.ts": "CLI errors for `config set keybindings`: example chords in the config grammar the user types.",
3
3
  "src/cli/commands/system.ts": "CLI help: example `config set keybindings` commands, written in the config grammar.",
4
+ "src/cli/pane-functions/dom.ts": "What `gloom fn` prints for a pane behind the sign-in wall: it sends the reader to the terminal app (`gloom`), where Ctrl+P opens the command bar.",
4
5
  "src/plugins/builtin/alerts/cli.ts": "`gloom alerts` output, which sends the reader to the terminal app (`gloom`), where Ctrl+P opens the command bar.",
5
6
  "src/plugins/builtin/alerts/event-rows.ts": "needsSignInNote is printed by `gloom alerts` and the headless read only: it names the terminal app's Ctrl+P.",
6
7
  "src/plugins/builtin/alerts/headless.ts": "Headless and CLI text that sends the reader to the terminal app (`gloom`), where Ctrl+P opens the command bar.",
@@ -60,7 +60,7 @@ import {
60
60
  ratingReason,
61
61
  } from "../../plugins/builtin/research/analyst-model";
62
62
  import { getPublishedUsEquityCalendarYears, getPublishedUsEquitySession } from "../../market-data/published-us-sessions";
63
- import { awaitingFirstDelayedPrint, isQuoteStaleForCurrentSession, noPrintsTodayText } from "../../market-data/quotes/freshness";
63
+ import { awaitingFirstDelayedPrint, isQuoteStaleForCurrentSession, noPrintsTodayText, nominalPriceText } from "../../market-data/quotes/freshness";
64
64
  import {
65
65
  coinOptionsAlternativesText, isCoinWithoutOptions, isOptionsUnavailableError, listedOptionsAlternative, optionsUnavailableTitle,
66
66
  } from "../../market-data/options-alternatives";
@@ -354,7 +354,7 @@ import {
354
354
  unvaluedHoldersNote,
355
355
  } from "../../plugins/builtin/holders/report-rows";
356
356
  import { fetchBeneficialOwners } from "../../plugins/builtin/holders/beneficial-client";
357
- import { fundHoldersAnswer } from "../../plugins/builtin/holders/fund-holders";
357
+ import { noHoldersAnswer } from "../../plugins/builtin/holders/fund-holders";
358
358
  import { centralBankEventsMessage } from "../central-bank-events";
359
359
  import { classSharesAsOf, classSharesToday } from "../../plugins/builtin/holders/client";
360
360
  import {
@@ -418,15 +418,20 @@ type FinancialsCliData = TickerFinancials & {
418
418
  providerId: string | null;
419
419
  };
420
420
 
421
+ /** The ranges as other tools spell them, which `--range` reads too: a week of sessions is 5d. */
422
+ const HISTORY_RANGE_ALIASES = "5d, 1mo, 3mo, 6mo, 1y, 5y and max";
423
+
421
424
  /**
422
425
  * A range as typed, in any case and as other tools spell it: `1mo`, `1m` and
423
- * `1 month` are 1M, `1wk` 1W, `5yr` 5Y, `max` ALL.
426
+ * `1 month` are 1M, `1wk` and `5d` (a week's five sessions) 1W, `5yr` 5Y,
427
+ * `max` ALL.
424
428
  */
425
429
  export function readHistoryRange(value: string): HistoryRange | null {
426
430
  const typed = value.trim().toUpperCase().replace(/\s+/g, "");
427
431
  if (typed === "MAX") return "ALL";
428
432
  const spelled = /^(\d+)(D|DAYS?|W|WKS?|WEEKS?|M|MOS?|MONTHS?|Y|YRS?|YEARS?)$/.exec(typed);
429
433
  const range = (spelled ? `${spelled[1]}${spelled[2]![0]}` : typed) as HistoryRange;
434
+ if (range === "5D" as HistoryRange || range === "7D" as HistoryRange) return "1W";
430
435
  return VALID_RANGES.has(range) ? range : null;
431
436
  }
432
437
 
@@ -442,7 +447,7 @@ function rangeTypedAsSymbol(entry: string): HistoryRange | null {
442
447
 
443
448
  function parseRange(value: string | undefined, ctx: Parameters<CliCommandDef["execute"]>[1]): HistoryRange {
444
449
  const range = readHistoryRange(value ?? "1Y");
445
- if (!range) ctx.fail(`Unknown range "${value}".`, `Use one of ${HISTORY_RANGES.join(", ")}.`);
450
+ if (!range) ctx.fail(`Unknown range "${value}".`, `Use one of ${HISTORY_RANGES.join(", ")}, or ${HISTORY_RANGE_ALIASES}.`);
446
451
  return range!;
447
452
  }
448
453
 
@@ -693,14 +698,14 @@ function quoteColumns() {
693
698
  return [
694
699
  ...QUOTE_LEAD_COLUMNS.map((column) => EXTENDED_KEYS.has(column.key) ? { ...column, stackPriority: 1 } : column),
695
700
  { key: "currency", header: "Cur", shrink: false, stackPriority: 3, format: currencyCell },
696
- // Whether the price is real-time, delayed or stale: a feed state, not where it came from. A stale
697
- // row says so here, so the closing line's "N of M stale" always points at rows the table marks.
701
+ // Whether the price is real-time, delayed, stale or nominal: a feed state, not where it came from. A stale or
702
+ // nominal row says so here, so the closing line's "N of M stale" or "N of M nominal" always points at rows the table marks.
698
703
  {
699
704
  key: "feed",
700
705
  header: "Feed",
701
706
  shrink: false,
702
707
  stackPriority: 4,
703
- format: (value: unknown) => value === "stale" ? cliStyles.warning(value) : String(value ?? ""),
708
+ format: (value: unknown) => value === "stale" || value === "nominal" ? cliStyles.warning(value) : String(value ?? ""),
704
709
  },
705
710
  { key: "updatedAt", header: "Updated", shrink: false, stackPriority: 5 },
706
711
  ...CHANGE_BASIS_EXPORT_COLUMNS,
@@ -745,9 +750,13 @@ function compareColumns() {
745
750
  ];
746
751
  }
747
752
 
748
- /** What the Feed cell says: stale wins over the feed's own live or delayed, as the closing line counts it. */
749
- function quoteFeedState(quote: QuoteCliRecord["quote"], now: number): "stale" | "live" | "delayed" | "" {
753
+ /**
754
+ * What the Feed cell says: nominal for a price nothing traded at (Quote.nominalPrice), then stale, over the feed's
755
+ * own live or delayed, as the closing line counts them.
756
+ */
757
+ function quoteFeedState(quote: QuoteCliRecord["quote"], now: number): "nominal" | "stale" | "live" | "delayed" | "" {
750
758
  if (!quote) return "";
759
+ if (quote.nominalPrice) return "nominal";
751
760
  if (isQuoteStaleForCurrentSession(quote, now)) return "stale";
752
761
  return quote.dataSource === "live" || quote.dataSource === "delayed" ? quote.dataSource : "";
753
762
  }
@@ -1245,7 +1254,7 @@ async function runQuote(rawArgs: string[], ctx: Parameters<CliCommandDef["execut
1245
1254
  const ended = stopped && liveCompanies[index] ? `${stopped}. ${liveCompanies[index]}` : stopped;
1246
1255
  // Open by its venue's calendar, before the delayed feed's first print: Last is the previous close until then.
1247
1256
  const awaiting = ended ? null : awaitingFirstDelayedPrint(row.quote, now);
1248
- const quiet = ended || awaiting ? null : noPrintsTodayText(row.quote, now);
1257
+ const quiet = ended || awaiting ? null : nominalPriceText(row.quote) ?? noPrintsTodayText(row.quote, now);
1249
1258
  const waiting = awaiting && row.quote
1250
1259
  ? `${label}: open since ${utcClock(awaiting.open)} UTC; Last is the previous close until the first delayed print, about ${utcClock(awaiting.expected)} UTC`
1251
1260
  : null;
@@ -1278,12 +1287,18 @@ async function runQuote(rawArgs: string[], ctx: Parameters<CliCommandDef["execut
1278
1287
  const columns = [...commandName === "compare" ? compareColumns() : quoteColumns(), ...holdsYield ? [CHANGE_BP_EXPORT_COLUMN] : []];
1279
1288
  const basisNotes = changeBasisNotes(data, now);
1280
1289
  const midNotes = extendedMidNotes(data);
1290
+ // Another listing a row's code names (00700 on TWSE is 700.HK on HKEX) is said under the table, not as a warning on the row.
1291
+ const listingNotes = answers.flatMap((answer) => answer.footnotes ?? []);
1292
+ const exportNotes = [...midNotes, ...listingNotes];
1293
+ const footnotes = [...basisNotes, ...listingNotes];
1294
+ // JSON has no table to put them under: they stay with its warnings.
1295
+ const warnings = [...notes, ...ctx.cliOptions.format === "json" ? listingNotes : []];
1281
1296
  if (ctx.cliOptions.format !== "json") await primeBoardCoins(notes);
1282
1297
  // Only yield indices: their change is in bp, so the text header drops the percent sign (CSV keeps the percent it holds).
1283
1298
  const yieldsOnly = data.length > 0 && data.every((row) => isYieldIndexSymbol(row.target.symbol));
1284
1299
  ctx.printResult({
1285
1300
  data,
1286
- warnings: notes.length > 0 ? notes : undefined,
1301
+ warnings: warnings.length > 0 ? warnings : undefined,
1287
1302
  // A Cboe yield index stops at its 15:00 ET close, before the Treasury's curve is taken: the line says so, so its
1288
1303
  // close does not read as a contradiction of DGS10 or GC for the same day.
1289
1304
  // Dated by the quotes as served, which say whether one is the saved copy.
@@ -1305,9 +1320,9 @@ async function runQuote(rawArgs: string[], ctx: Parameters<CliCommandDef["execut
1305
1320
  }),
1306
1321
  // A row with no price or move says why in its status column, as the warnings do.
1307
1322
  exportStatus: quoteExportStatus,
1308
- ...(midNotes.length > 0 ? { exportNotes: midNotes } : {}),
1323
+ ...(exportNotes.length > 0 ? { exportNotes } : {}),
1309
1324
  details: quoteDetailsText,
1310
- ...(basisNotes.length ? { footnote: basisNotes.join("\n") } : {}),
1325
+ ...(footnotes.length ? { footnote: footnotes.join("\n") } : {}),
1311
1326
  columns,
1312
1327
  textColumns: quoteTextColumns(yieldsOnly
1313
1328
  ? columns.map((column) => column.key === "changePercent" ? { ...column, header: "Chg" } : column)
@@ -3146,9 +3161,10 @@ async function runHolders(
3146
3161
  (found) => found.holders.length === 0,
3147
3162
  { command: commandName, noun: "holder data" },
3148
3163
  ).catch(async (error: unknown) => {
3149
- // A fund has no ownership breakdown: say so, and what reads it, rather than the source's NO_DATA.
3150
- const fund = await fundHoldersAnswer(listing.symbol, error, await quoted, apiClient);
3151
- if (fund) fail(fund.message, fund.details.join("\n") || undefined, NO_DATA_CODE);
3164
+ // A fund has no ownership breakdown, and a listing may have no holders on record: say so
3165
+ // (and what reads a fund) rather than the source's NO_DATA.
3166
+ const none = await noHoldersAnswer(listing.key, listing.request.exchange, error, await quoted, apiClient);
3167
+ if (none) fail(none.message, none.details.join("\n") || undefined, NO_DATA_CODE);
3152
3168
  throw error;
3153
3169
  }),
3154
3170
  quoted,
@@ -4101,7 +4117,7 @@ export const marketDataCliCommands: BuiltinCliCommandDef[] = [
4101
4117
  group: CLI_COMMAND_GROUPS.research,
4102
4118
  usage: [HISTORY_USAGE, "history --file <path> [--range <range> | --from <year|date> [--to <year|date>]]"],
4103
4119
  options: [
4104
- { flags: "--range <range>", description: `${HISTORY_RANGES.join(", ")} (default 1Y); ${HISTORY_YTD_RANGE}; ${HISTORY_ALL_RANGE}` },
4120
+ { flags: "--range <range>", description: `${HISTORY_RANGES.join(", ")} (default 1Y), or as other tools write them: ${HISTORY_RANGE_ALIASES}; ${HISTORY_YTD_RANGE}; ${HISTORY_ALL_RANGE}` },
4105
4121
  { flags: "--from <year|date>, --start <year|date>", description: `${PRICE_WINDOW_FROM_HELP}. Up to five years come in daily bars, up to twenty weekly, longer monthly` },
4106
4122
  { flags: "--to <year|date>, --end <year|date>", description: PRICE_WINDOW_TO_HELP },
4107
4123
  { flags: "--file <path>", description: "Read the symbols from a text or CSV file, one per line (- reads standard input), and write every symbol's bars in one table" },
@@ -424,7 +424,7 @@ function resolveSearchName(candidate: TickerSearchCandidate): string {
424
424
  function searchType(candidate: TickerSearchCandidate): string | undefined {
425
425
  return instrumentTypeLabel(candidate.result?.type
426
426
  || candidate.result?.brokerContract?.secType
427
- || candidate.ticker?.metadata.assetCategory, resolveSearchName(candidate));
427
+ || candidate.ticker?.metadata.assetCategory, resolveSearchName(candidate), { symbol: candidate.symbol });
428
428
  }
429
429
 
430
430
  /** What `--json` lists for a symbol search no longer lists: its category says so, and it keeps its last date and price. */
@@ -502,9 +502,25 @@ function catalogHint(query: string): string {
502
502
  /** What a search for a name in another script (任天堂) that found nothing says: listings are named in Latin letters. */
503
503
  const OTHER_SCRIPT_NO_MATCH = "No matches. Try the ticker or the English name.";
504
504
 
505
+ /** Words that say a query names a fund, which a fund's own name can hold anywhere ("Nippon India ETF Nifty IT"). */
506
+ const FUND_WORDS = new Set(["ETF", "ETFS", "ETN", "ETNS", "FUND", "FUNDS", "UCITS", "TRUST", "INDEX"]);
507
+
508
+ /**
509
+ * For a fund's name of three words or more that found nothing: try fewer, the
510
+ * first half of the others with the fund's word, as a fund can word its name
511
+ * in another order. Null for any other query.
512
+ */
513
+ function fundSearchHint(query: string): string | null {
514
+ const words = query.replace(/"/g, "").trim().split(/\s+/).filter(Boolean);
515
+ const fund = words.filter((word) => FUND_WORDS.has(word.toUpperCase()));
516
+ const rest = words.filter((word) => !FUND_WORDS.has(word.toUpperCase()));
517
+ if (words.length < 3 || fund.length === 0 || rest.length < 2) return null;
518
+ return `A fund's name can put its words in another order. Try fewer words: gloom search "${[...rest.slice(0, Math.ceil(rest.length / 2)), ...fund].join(" ")}"`;
519
+ }
520
+
505
521
  /** The line an empty search ends with: where else to look, or for a name in another script, what to type instead. */
506
522
  function emptySearchHint(query: string): string {
507
- return hasNonLatinLetters(query) ? OTHER_SCRIPT_NO_MATCH : catalogHint(query);
523
+ return hasNonLatinLetters(query) ? OTHER_SCRIPT_NO_MATCH : fundSearchHint(query) ?? catalogHint(query);
508
524
  }
509
525
 
510
526
  /**
@@ -589,7 +605,7 @@ export function buildSearchReport({
589
605
  if (functions.length > 0) lines.push("", renderFunctionMatches(functions));
590
606
  else if (!gap && !bank && !setting && !charted) {
591
607
  return [...lines, ...hasNonLatinLetters(query) ? [cliStyles.muted(OTHER_SCRIPT_NO_MATCH)]
592
- : [cliStyles.muted("No matches found."), cliStyles.muted(wrapToTerminal(catalogHint(query)))]].join("\n");
608
+ : [cliStyles.muted("No matches found."), cliStyles.muted(wrapToTerminal(emptySearchHint(query)))]].join("\n");
593
609
  }
594
610
  if (pointToCatalog) lines.push("", cliStyles.muted(wrapToTerminal(catalogHint(query))));
595
611
  return lines.join("\n");
@@ -165,6 +165,12 @@ export interface DesktopPaneShotRenderResult {
165
165
  * capture shows. Absent when every table is read from the viewport.
166
166
  */
167
167
  reportRows?: DesktopPaneShotRenderedRow[];
168
+ /**
169
+ * The rows each visible table holds, by `tableIndex`, drawn or not (the
170
+ * table's `rowCount`); null for a table that does not say. With `rows`, what
171
+ * a capture that cuts a list says it shows: "36 of 76 rows".
172
+ */
173
+ tableRowTotals?: Array<number | null>;
168
174
  /** `truncationReasons` without the cuts of tables whose every row is in `reportRows`. */
169
175
  reportTruncationReasons?: string[];
170
176
  /** Text of the pane footers, where a pane says whether its data is live, delayed or stale. */
@@ -596,6 +602,7 @@ async function capturePageScreenshot({
596
602
  await browser.open(url);
597
603
  await waitForShotReady(session);
598
604
  if (fitRows) await growToFitRows(session, { widthPx, heightPx, deviceScaleFactor, ...fitRows });
605
+ if (captureImage) await hideCutRows(session);
599
606
  const rendered = await readRenderedPaneState(session);
600
607
  if (captureImage && statusLine) {
601
608
  const line = await statusLine(rendered);
@@ -658,6 +665,52 @@ async function growToFitRows(session: CdpPage, size: {
658
665
  await waitForShotReady(session);
659
666
  }
660
667
 
668
+ /**
669
+ * An image ends on a whole row: a row its list's scroll box cuts at the
670
+ * bottom edge is hidden, and so is one wholly outside the box, which the
671
+ * box already clips but the row count would read. A row with no whole row
672
+ * above it stays, cut, rather than leave the list blank. The live pane keeps
673
+ * its partly visible last row, as every scrolling list reads.
674
+ */
675
+ async function hideCutRows(session: CdpPage): Promise<void> {
676
+ await session.send("Runtime.evaluate", {
677
+ expression: `(() => {
678
+ const root = document.getElementById("root") || document.body;
679
+ const rows = [...root.querySelectorAll(
680
+ '[data-gloom-role="data-table-row"], [data-gloom-role="data-table-section-header"], [data-gloom-role="desktop-list-row"], [data-gloom-row="true"]',
681
+ )];
682
+ const clips = (element) => {
683
+ const style = getComputedStyle(element);
684
+ return /(auto|scroll|hidden|clip)/.test(style.overflowY) && element.clientHeight > 0;
685
+ };
686
+ const wholeAbove = new Map();
687
+ const cut = [];
688
+ for (const row of rows) {
689
+ let box = row.parentElement;
690
+ while (box && box !== root && !clips(box)) box = box.parentElement;
691
+ if (!box || box === root) continue;
692
+ const area = box.getBoundingClientRect();
693
+ // The box's visible height: a horizontal scrollbar takes its own rows.
694
+ const bottom = area.top + box.clientTop + box.clientHeight;
695
+ const rect = row.getBoundingClientRect();
696
+ if (rect.height <= 0) continue;
697
+ if (rect.bottom <= area.top + 1 || rect.top >= bottom - 1) {
698
+ cut.push(row);
699
+ } else if (rect.top >= area.top - 1 && rect.bottom <= bottom + 1) {
700
+ wholeAbove.set(box, true);
701
+ } else if (rect.bottom > bottom + 1) {
702
+ cut.push({ row, box });
703
+ }
704
+ }
705
+ for (const entry of cut) {
706
+ if (entry instanceof Element) entry.style.visibility = "hidden";
707
+ else if (wholeAbove.get(entry.box)) entry.row.style.visibility = "hidden";
708
+ }
709
+ })()`,
710
+ returnByValue: true,
711
+ });
712
+ }
713
+
661
714
  const LOADING_STATE_PATTERNS = [
662
715
  /\bLoading(?: [^.]{0,80})?\.{3}/gi,
663
716
  /\bRendering pane\.{3}/gi,
@@ -865,6 +918,10 @@ async function readRenderedPaneState(session: CdpPage): Promise<DesktopPaneShotR
865
918
  truncated: truncationReasons.size > 0,
866
919
  truncationReasons: [...truncationReasons],
867
920
  ...(reportedTables.size > 0 ? { reportRows, reportTruncationReasons: [...reportTruncationReasons] } : {}),
921
+ tableRowTotals: visibleTables.map((_table, tableIndex) => {
922
+ const metadata = semanticTables[tableIndex] && semanticTables[tableIndex].metadata;
923
+ return metadata && typeof metadata.rowCount === "number" ? metadata.rowCount : null;
924
+ }),
868
925
  semanticUi,
869
926
  };
870
927
  })()`,
@@ -886,6 +943,7 @@ async function readRenderedPaneState(session: CdpPage): Promise<DesktopPaneShotR
886
943
  truncationReasons?: string[];
887
944
  reportRows?: DesktopPaneShotRenderedRow[];
888
945
  reportTruncationReasons?: string[];
946
+ tableRowTotals?: Array<number | null>;
889
947
  semanticUi?: RemoteUiNodeSnapshot[];
890
948
  };
891
949
  };
@@ -922,6 +980,9 @@ async function readRenderedPaneState(session: CdpPage): Promise<DesktopPaneShotR
922
980
  reportRows: value.reportRows,
923
981
  reportTruncationReasons: (value.reportTruncationReasons ?? []).filter((reason): reason is string => typeof reason === "string"),
924
982
  } : {}),
983
+ ...(Array.isArray(value?.tableRowTotals) && value.tableRowTotals.length > 0 ? {
984
+ tableRowTotals: value.tableRowTotals.map((total) => typeof total === "number" && Number.isFinite(total) ? total : null),
985
+ } : {}),
925
986
  loadingStateDetected: value?.loadingStateDetected === true || loadingStateMarkers.length > 0,
926
987
  errorStateDetected: value?.errorStateDetected === true || errorStateMarkers.length > 0,
927
988
  errorStateMarkers,
@@ -27,8 +27,8 @@ const DOM_EVERY_ROW =
27
27
  const DOM_WHOLE_PANE =
28
28
  "The pane was grown to fit the page it has open, so all of its text is returned.";
29
29
 
30
- /** The sign-in wall's buttons, which a rendered view reads as words: `Log in ↵ Sign up free`. */
31
- const SIGN_IN_WALL_BUTTONS = /\s*\b(?:Log in|Sign up free|Resend Verification Email)(?:\s*\u21B5)?(?=\s|$)/g;
30
+ /** The sign-in wall's buttons, which a rendered view reads as words, with the key that presses one: `Log in ↩ Sign up free`. */
31
+ const SIGN_IN_WALL_BUTTONS = /\s*\b(?:Log in|Sign up free|Resend Verification Email)(?:\s*[\u21A9\u21B5])?(?=\s|$)/g;
32
32
 
33
33
  /** Whether the wall asks for the account's email to be verified, not for a sign-in. */
34
34
  function asksToVerifyEmail(visibleText: string): boolean {
@@ -42,8 +42,8 @@ function asksToVerifyEmail(visibleText: string): boolean {
42
42
  function signInWallText(visibleText: string): string {
43
43
  const headline = visibleText.replace(SIGN_IN_WALL_BUTTONS, "").trim();
44
44
  const needs = asksToVerifyEmail(visibleText)
45
- ? "Requires a verified email on your Gloom account; resend the verification email in the app."
46
- : "Requires a free Gloom sign-in: log in or sign up in the app.";
45
+ ? "Requires a verified email on your Gloom account: open the app (gloom) and resend the verification email from the command bar (Ctrl+P, Resend Verification Email)."
46
+ : "Requires a free Gloom sign-in: open the app (gloom) and log in or sign up free from the command bar (Ctrl+P, Log In or Sign Up); this command then reads with that session.";
47
47
  return headline ? `${headline} ${needs}` : needs;
48
48
  }
49
49
 
@@ -66,6 +66,13 @@ export interface ReportFreshness {
66
66
  /** When only some rows are stale: how many, of the rows that say whether they are... */
67
67
  staleCount?: number;
68
68
  observationCount?: number;
69
+ /**
70
+ * How many of those rows are at a nominal price, nothing having traded
71
+ * (`nominal`): the venue's price for its latest session, counted apart
72
+ * from stale rows. The status line reads `1 of 3 nominal`, or `nominal`
73
+ * when every row is.
74
+ */
75
+ nominalCount?: number;
69
76
  /** ...and what the rest are. */
70
77
  feed?: "live" | "delayed";
71
78
  basis?: string;
@@ -195,9 +202,11 @@ interface FeedSignals {
195
202
  minDelayMinutes?: number;
196
203
  /** A record-wide stale flag (metadata), read only when no row says whether it is stale. */
197
204
  stale: boolean;
198
- /** Rows and series that carry a `stale` flag, and the times of those that are stale. */
205
+ /** Rows and series that carry a `stale` flag, and the times of those that are stale... */
199
206
  flagged: number;
200
207
  staleTimes: Array<ReportTime | null>;
208
+ /** ...and how many of them are at a nominal price instead (`nominal`). */
209
+ nominal: number;
201
210
  /** Rows that name the venue whose sessions they follow (`sessionExchange`), with their time. */
202
211
  sessions: SessionObservation[];
203
212
  }
@@ -244,7 +253,7 @@ function newestUnitRelease(observations: Observations, asOf: ReportTime): UnitRe
244
253
  }
245
254
 
246
255
  function emptySignals(): FeedSignals {
247
- return { live: false, delayed: false, stale: false, flagged: 0, staleTimes: [], sessions: [] };
256
+ return { live: false, delayed: false, stale: false, flagged: 0, staleTimes: [], nominal: 0, sessions: [] };
248
257
  }
249
258
 
250
259
  function readFeedSignals(record: Record<string, unknown>, signals: FeedSignals): void {
@@ -271,11 +280,17 @@ function readSession(record: Record<string, unknown>, time: ReportTime | null, s
271
280
  });
272
281
  }
273
282
 
274
- /** A row's or series' own stale flag; worst of across them, counted so a partly stale board says how much. */
283
+ /**
284
+ * A row's or series' own stale flag; worst of across them, counted so a partly
285
+ * stale board says how much. A row at a nominal price (`nominal`: an untraded
286
+ * counter's, whose last trade is old) is its venue's latest price, counted as
287
+ * nominal rather than stale.
288
+ */
275
289
  function readUnitStale(record: Record<string, unknown>, time: ReportTime | null, signals: FeedSignals): void {
276
290
  if (typeof record.stale !== "boolean") return;
277
291
  signals.flagged += 1;
278
- if (record.stale) signals.staleTimes.push(time);
292
+ if (record.nominal === true) signals.nominal += 1;
293
+ else if (record.stale) signals.staleTimes.push(time);
279
294
  }
280
295
 
281
296
  function observedTime(record: Record<string, unknown>, now: number, keys: readonly string[] = OBSERVATION_KEYS): ReportTime | null {
@@ -602,6 +617,7 @@ function resolveFreshness({ declared, signals, observations, now }: FreshnessInp
602
617
  ...(minDelayMinutes != null && minDelayMinutes > 0 ? { minDelayMinutes } : {}),
603
618
  ...(status === "stale" && staleAt ? { ageMinutes: Math.max(0, Math.floor((now - staleAt.time) / 60_000)) } : {}),
604
619
  ...(partial ?? {}),
620
+ ...(signals.nominal > 0 ? { nominalCount: signals.nominal, observationCount: signals.flagged } : {}),
605
621
  ...(status === "not-a-feed" && declared.basis ? { basis: declared.basis } : {}),
606
622
  ...(periodicity ? { periodicity } : {}),
607
623
  ...(periodToDate && !declaredAsOf ? { periodToDate: { period: periodToDate.period, ...(periodToDate.through ? { through: isoTime(periodToDate.through) } : {}) } } : {}),
@@ -824,8 +840,25 @@ export function staleRowsText(freshness: Pick<ReportFreshness, "staleCount" | "o
824
840
  return `${short ? freshness.staleCount : `${freshness.staleCount} of ${freshness.observationCount}`} stale`;
825
841
  }
826
842
 
827
- /** `short` counts stale rows without their total (`2 stale`), for a narrow capture. */
843
+ /**
844
+ * How many rows are at a nominal price: `nominal` when all are, `1 of 3
845
+ * nominal` (`1 nominal` when `short`) when some are. Null when none is.
846
+ */
847
+ function nominalRowsText(freshness: Pick<ReportFreshness, "nominalCount" | "observationCount">, short = false): string | null {
848
+ const { nominalCount: count, observationCount: total } = freshness;
849
+ if (!count || total == null) return null;
850
+ if (count >= total) return "nominal";
851
+ return `${short ? count : `${count} of ${total}`} nominal`;
852
+ }
853
+
854
+ /** `short` counts stale and nominal rows without their total (`2 stale`), for a narrow capture. */
828
855
  function statusText(freshness: ReportFreshness, short = false): string {
856
+ const nominal = nominalRowsText(freshness, short);
857
+ const feed = feedStatusText(freshness, short);
858
+ return nominal ? [feed, nominal].filter(Boolean).join(", ") : feed;
859
+ }
860
+
861
+ function feedStatusText(freshness: ReportFreshness, short: boolean): string {
829
862
  switch (freshness.status) {
830
863
  case "live":
831
864
  return "live";
@@ -53,20 +53,32 @@ export function shotStatusIssues(
53
53
  /**
54
54
  * For a pane that grows to fit its rows, the rows its table reports (every
55
55
  * one, `reportEveryRow`) and how many of them the image shows, by key;
56
- * section headers count in neither. Null for any other pane, or a table that
57
- * reports only what is drawn.
56
+ * section headers count in neither. For any other pane whose tables hold more
57
+ * rows than the image draws, the rows drawn of all they hold ("36 of 76").
58
+ * Null when the image holds every row, or no table says how many it holds.
58
59
  */
59
60
  export function shotTableRows(
60
61
  resolved: Pick<ResolvedPaneFunction, "pane" | "instance">,
61
- render: Pick<DesktopPaneShotRenderResult, "rows" | "reportRows">,
62
+ render: Pick<DesktopPaneShotRenderResult, "rows" | "reportRows" | "tableRowTotals">,
62
63
  ): { shown: number; total: number } | null {
63
- if (!paneFitsRows(resolved) || !render.reportRows?.length) return null;
64
+ if (!paneFitsRows(resolved) || !render.reportRows?.length) return cutTableRows(render);
64
65
  const reported = render.reportRows.filter((row) => !row.section && row.key);
65
66
  if (reported.length === 0) return null;
66
67
  const drawn = new Set(render.rows.flatMap((row) => row.key ? [`${row.tableIndex}:${row.key}`] : []));
67
68
  return { shown: reported.filter((row) => drawn.has(`${row.tableIndex}:${row.key}`)).length, total: reported.length };
68
69
  }
69
70
 
71
+ /** The rows drawn of all the visible tables hold, for the tables that say how many; null when nothing is left out. */
72
+ function cutTableRows(render: Pick<DesktopPaneShotRenderResult, "rows" | "tableRowTotals">): { shown: number; total: number } | null {
73
+ let shown = 0, total = 0;
74
+ for (const [tableIndex, rows] of (render.tableRowTotals ?? []).entries()) {
75
+ if (rows === null) continue;
76
+ total += rows;
77
+ shown += render.rows.filter((row) => row.tableIndex === tableIndex).length;
78
+ }
79
+ return total > shown ? { shown, total } : null;
80
+ }
81
+
70
82
  /** What a rendered capture shows, and whether it is fit to use. */
71
83
  export function assessPaneScreenshot(
72
84
  resolved: ResolvedPaneFunction,
@@ -66,6 +66,12 @@ export interface QuoteAnswer {
66
66
  /** Why there is no quote, when there is more to say than the source's own error. */
67
67
  failure?: { message: string; details?: string; oneLine: string };
68
68
  notes: string[];
69
+ /**
70
+ * Lines about another listing than the row's, printed under the table
71
+ * rather than as warnings on it: the HKEX listing a bare TWSE code is the
72
+ * code of too ("00700: for HKEX use 700.HK").
73
+ */
74
+ footnotes?: string[];
69
75
  }
70
76
 
71
77
  /**
@@ -108,7 +114,12 @@ export async function answerQuote(
108
114
  const venue = choice.length > 0 ? null : bareListingNote(listing, result.quote);
109
115
  // A row saved as 247540:KRX is quoted from KOSDAQ, the board it trades on.
110
116
  const board = tradingBoardNote(listing, result.quote);
111
- return { result, listing, notes: [...choice, venue ?? [], board ?? [], also(result.quote), currencyCodeNote(listing, result.quote) ?? []].flat() };
117
+ const hongKong = await hongKongCodeNote(listing, result.quote, market);
118
+ return {
119
+ result, listing,
120
+ notes: [...choice, venue ?? [], board ?? [], also(result.quote), currencyCodeNote(listing, result.quote) ?? []].flat(),
121
+ ...hongKong ? { footnotes: [hongKong] } : {},
122
+ };
112
123
  }
113
124
  // No answer from the data service: no venue lookup or other listing would get one either.
114
125
  if (isNetworkFailure(result.error)) return { result, listing, notes: [] };
@@ -147,6 +158,10 @@ export async function answerQuote(
147
158
  listing.exchange ? null : knownGapForTicker(listing.symbol),
148
159
  ].filter((line): line is string => !!line);
149
160
  if (!other && tryLines.length === 0) {
161
+ // ^GSPC typed in Windows' cmd.exe arrives as GSPC, the shell taking ^ for its escape character: said once no company
162
+ // of that name and no listing abroad answers for it, so a symbol listed abroad is still quoted. A known root (VIX) has its own line.
163
+ const caret = root ? null : await caretIndexLine(listing, result, market);
164
+ if (caret) return { result, listing, failure: { message: caret, oneLine: caret }, notes: [] };
150
165
  return await answerCompanyName(result, listing, market, request, refresh, datesChangeBasis)
151
166
  ?? { result: await withCurrencyPairHint(result, market), listing, notes: [] };
152
167
  }
@@ -276,6 +291,47 @@ export async function requireQuotedListing(
276
291
  return { listing: answer.listing, quote, notes: [...answer.notes, ...notUs ? [notUs] : []] };
277
292
  }
278
293
 
294
+ /** A bare symbol that may be an index's without its ^: letters, then letters or digits. */
295
+ const CARETLESS_INDEX = /^[A-Z][A-Z0-9]{1,9}$/;
296
+
297
+ /**
298
+ * "Not a ticker: GSPC. Did you mean ^GSPC (S&P 500)? Try "^GSPC"." for a
299
+ * bare symbol that is not a ticker while its ^ form is an index: cmd.exe
300
+ * takes ^ for its escape character and passes `gloom quote ^GSPC` on as
301
+ * GSPC, and search would offer Goldman's preferreds for it. Null for any
302
+ * other symbol, a named venue, and when the ^ form quotes no index.
303
+ */
304
+ async function caretIndexLine(listing: CliListing, result: QuoteBatchResult, market: MarketContext): Promise<string | null> {
305
+ if (listing.exchange || listing.saved || !CARETLESS_INDEX.test(listing.symbol)) return null;
306
+ const index = `^${listing.symbol}`;
307
+ const quote = await Promise.resolve().then(() => market.dataProvider.getQuote(index, ""))
308
+ .catch(logFailure("cli.quote-answer", "Quote a symbol's index form failed", null));
309
+ if (!quote || quote.instrumentType?.trim().toUpperCase() !== "INDEX") return null;
310
+ const said = notATickerSymbol(errorMessage(result.error) ?? "") ? `Not a ticker: ${listing.symbol}.` : `${listing.symbol} has no quote.`;
311
+ return `${said} Did you mean ${index}${quote.name ? ` (${quote.name})` : ""}? Try "${index}".`;
312
+ }
313
+
314
+ /** Five digits with a leading zero: a TWSE fund's code (00700), and how HKEXnews prints a Hong Kong one (00700 is 0700). */
315
+ const FIVE_DIGIT_CODE = /^0\d{4}$/;
316
+
317
+ /**
318
+ * A bare five-digit code quoted on another venue that HKEX lists too, as its
319
+ * own code without the leading zeros: 00700 is Fubon's Hang Seng China
320
+ * Enterprises ETF on TWSE and Tencent's 0700 on HKEX. The row stays the
321
+ * other venue's; the note names the HKEX listing, "00700: for HKEX use 700.HK
322
+ * (Tencent Holdings Limited)". Null for any other symbol, a named or saved
323
+ * listing, and a code HKEX does not list.
324
+ */
325
+ async function hongKongCodeNote(listing: CliListing, quote: Quote, market: MarketContext): Promise<string | null> {
326
+ if (listing.exchange || listing.saved || !FIVE_DIGIT_CODE.test(listing.symbol)) return null;
327
+ if (canonicalExchange(quote.listingExchangeName || quote.exchangeName) === "HKEX") return null;
328
+ const code = String(Number(listing.symbol));
329
+ const hongKong = await Promise.resolve().then(() => market.dataProvider.getQuote(code.padStart(4, "0"), "HKEX"))
330
+ .catch(logFailure("cli.quote-answer", "Quote a code's HKEX listing failed", null));
331
+ if (!hongKong || canonicalExchange(hongKong.listingExchangeName || hongKong.exchangeName) !== "HKEX") return null;
332
+ return `${listing.symbol}: for HKEX use ${code}.HK${hongKong.name ? ` (${hongKong.name})` : ""}`;
333
+ }
334
+
279
335
  /**
280
336
  * A symbol written like a currency pair that is not a ticker (USD_NGN, as some
281
337
  * FX feeds write a pair) names the listing `gloom search` finds nearest to