gloomberb 0.20.13 → 0.20.14

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 (155) hide show
  1. package/package.json +2 -1
  2. package/patches/@opentui%2Fcore@0.3.2.patch +22 -4
  3. package/src/account/auth-dialog.tsx +22 -4
  4. package/src/account/auth-form.tsx +6 -1
  5. package/src/account/checkout-handoff.tsx +7 -14
  6. package/src/account/device-signin-dialog.tsx +35 -24
  7. package/src/api-client/crypto-markets.ts +10 -0
  8. package/src/api-client/errors.ts +3 -1
  9. package/src/api-client/money-markets.ts +7 -0
  10. package/src/api-client/request.ts +12 -2
  11. package/src/architecture/floating-promise-allowlist.json +0 -1
  12. package/src/brokers/signed-in/sign-in-dialog.tsx +38 -38
  13. package/src/cli/commands/market.ts +95 -23
  14. package/src/cli/commands/overview.ts +18 -4
  15. package/src/cli/errors.ts +3 -1
  16. package/src/cli/freshness.ts +7 -2
  17. package/src/cli/glossary.ts +10 -5
  18. package/src/cli/helpers.ts +8 -16
  19. package/src/cli/history-export.ts +4 -0
  20. package/src/cli/known-gaps.ts +2 -2
  21. package/src/cli/listing-arg.ts +79 -11
  22. package/src/cli/not-a-ticker.ts +4 -0
  23. package/src/cli/pane-functions/catalog.ts +29 -8
  24. package/src/cli/pane-functions/headless.ts +5 -2
  25. package/src/cli/pane-functions/options.ts +7 -0
  26. package/src/cli/pane-functions/resolver.ts +61 -15
  27. package/src/cli/result.ts +22 -4
  28. package/src/cli/symbol-args.ts +5 -3
  29. package/src/cli/symbol-list.ts +23 -10
  30. package/src/cli/symbol-rows.ts +135 -3
  31. package/src/cli/treasury-yields.ts +15 -1
  32. package/src/components/chart/composite/format.ts +2 -1
  33. package/src/components/chart/composite/panel-surface/axis-markers.ts +133 -0
  34. package/src/components/chart/composite/panel-surface/level-labels.tsx +78 -0
  35. package/src/components/chart/composite/panel-surface/overlays.ts +108 -0
  36. package/src/components/chart/composite/panel-surface/pan-coast.ts +54 -0
  37. package/src/components/chart/composite/panel-surface/panel-cursor.tsx +138 -0
  38. package/src/components/chart/composite/panel-surface/panel-levels.ts +47 -0
  39. package/src/components/chart/composite/panel-surface/plot-gestures.ts +403 -0
  40. package/src/components/chart/composite/panel-surface/plot-pointer.ts +65 -0
  41. package/src/components/chart/composite/panel-surface/plot-wheel.ts +102 -0
  42. package/src/components/chart/composite/panel-surface/pointer.ts +12 -0
  43. package/src/components/chart/composite/panel-surface/props.ts +79 -0
  44. package/src/components/chart/composite/panel-surface/tool-readout.ts +151 -0
  45. package/src/components/chart/composite/panel-surface/value-axis-gestures.ts +152 -0
  46. package/src/components/chart/composite/panel-surface.tsx +81 -1177
  47. package/src/components/command-bar/commands/collection-list.ts +1 -0
  48. package/src/components/command-bar/routes/root/results.ts +3 -2
  49. package/src/components/command-bar/routes/root/runtime.ts +3 -2
  50. package/src/components/command-bar/routes/root/selection.ts +3 -2
  51. package/src/components/command-bar/routes/root/shortcuts.ts +15 -0
  52. package/src/components/layout/pane/title.ts +10 -4
  53. package/src/components/pane-settings-dialog/tui.tsx +6 -3
  54. package/src/components/pane-settings-dialog.tsx +2 -1
  55. package/src/components/pane-template-wizard.tsx +2 -0
  56. package/src/components/ui/choice-dialog.tsx +1 -1
  57. package/src/components/ui/confirm-dialog.tsx +3 -2
  58. package/src/components/ui/frame.tsx +7 -3
  59. package/src/components/ui/icon.tsx +4 -2
  60. package/src/components/ui/list-view.tsx +8 -0
  61. package/src/components/ui/number-prompt-dialog.tsx +2 -1
  62. package/src/components/use-pane-notice-footer.tsx +3 -1
  63. package/src/docs/snapshot.json +2 -2
  64. package/src/i18n/es.ts +1 -0
  65. package/src/i18n/ja.ts +1 -0
  66. package/src/i18n/ko.ts +1 -0
  67. package/src/i18n/zh-cn.ts +1 -0
  68. package/src/i18n/zh-tw.ts +1 -0
  69. package/src/market-data/market/format.ts +35 -1
  70. package/src/market-data/quotes/contributions.ts +13 -0
  71. package/src/market-data/quotes/export-identity.ts +36 -1
  72. package/src/market-data/quotes/resolution.ts +16 -0
  73. package/src/plugins/builtin/account-management/password-dialog.tsx +2 -2
  74. package/src/plugins/builtin/analytics/risk-client.ts +12 -2
  75. package/src/plugins/builtin/analytics/risk-headless.ts +66 -6
  76. package/src/plugins/builtin/analytics/risk-math.ts +23 -6
  77. package/src/plugins/builtin/analytics/risk-model.ts +20 -9
  78. package/src/plugins/builtin/analytics/risk-pane.tsx +2 -2
  79. package/src/plugins/builtin/chart-composer/catalog-inventory.ts +5 -2
  80. package/src/plugins/builtin/chart-composer/editor.tsx +1 -0
  81. package/src/plugins/builtin/chart-composer/pane.tsx +1 -1
  82. package/src/plugins/builtin/chart-composer/quick-add.tsx +4 -1
  83. package/src/plugins/builtin/chart-composer/series-catalog.ts +17 -1
  84. package/src/plugins/builtin/cloud/plugin.tsx +2 -0
  85. package/src/plugins/builtin/cloud/thesis/module.tsx +2 -0
  86. package/src/plugins/builtin/cloud/upgrade-status-widget.tsx +6 -2
  87. package/src/plugins/builtin/cpi/headless.ts +6 -1
  88. package/src/plugins/builtin/cpi/model.ts +17 -0
  89. package/src/plugins/builtin/cpi/pane.tsx +3 -1
  90. package/src/plugins/builtin/crypto-board/client.ts +6 -1
  91. package/src/plugins/builtin/crypto-board/headless.ts +10 -2
  92. package/src/plugins/builtin/crypto-board/model.ts +89 -11
  93. package/src/plugins/builtin/crypto-board/pane.tsx +20 -5
  94. package/src/plugins/builtin/dividend-yield/client.ts +24 -2
  95. package/src/plugins/builtin/dividend-yield/headless.ts +4 -2
  96. package/src/plugins/builtin/dividend-yield/ranking.ts +2 -1
  97. package/src/plugins/builtin/dividend-yield/view.ts +5 -1
  98. package/src/plugins/builtin/earnings/history-table.ts +8 -0
  99. package/src/plugins/builtin/earnings-ripple/index.tsx +2 -0
  100. package/src/plugins/builtin/econ/calendar-model.ts +17 -1
  101. package/src/plugins/builtin/econ/fred-catalog.ts +33 -4
  102. package/src/plugins/builtin/econ-statistics/headless.ts +21 -0
  103. package/src/plugins/builtin/macro-day/headless.ts +21 -10
  104. package/src/plugins/builtin/macro-day/model.ts +40 -3
  105. package/src/plugins/builtin/macro-day/pane.tsx +26 -8
  106. package/src/plugins/builtin/macro-day/releases.ts +24 -1
  107. package/src/plugins/builtin/money-markets/client.ts +4 -1
  108. package/src/plugins/builtin/money-markets/headless.ts +15 -4
  109. package/src/plugins/builtin/money-markets/index.tsx +1 -1
  110. package/src/plugins/builtin/money-markets/pane.tsx +7 -1
  111. package/src/plugins/builtin/portfolio-list/cli/bulk-symbols.ts +4 -2
  112. package/src/plugins/builtin/portfolio-list/cli/period-report.ts +61 -11
  113. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +11 -3
  114. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +2 -0
  115. package/src/plugins/builtin/portfolio-list/headless.ts +33 -6
  116. package/src/plugins/builtin/portfolio-list/pane/index.tsx +5 -3
  117. package/src/plugins/builtin/portfolio-list/pane/period-pnl.ts +24 -6
  118. package/src/plugins/builtin/portfolio-list/period-pnl.ts +16 -1
  119. package/src/plugins/builtin/portfolio-list/summary/index.tsx +4 -1
  120. package/src/plugins/builtin/portfolio-list/summary/totals.ts +6 -4
  121. package/src/plugins/builtin/portfolio-list/table.tsx +25 -15
  122. package/src/plugins/builtin/shared/cloud-upgrade.ts +4 -2
  123. package/src/plugins/builtin/shared/cpi-year-gap.ts +67 -0
  124. package/src/plugins/builtin/ticker-detail/adr-pair/headless.ts +45 -2
  125. package/src/plugins/builtin/ticker-detail/headless.ts +26 -1
  126. package/src/plugins/builtin/ticker-detail/overview/components.tsx +4 -5
  127. package/src/plugins/builtin/ticker-detail/overview/model.ts +4 -1
  128. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +10 -2
  129. package/src/portfolio/collection-name.ts +2 -1
  130. package/src/portfolio/column-values.ts +14 -4
  131. package/src/portfolio/listed-symbol.ts +4 -2
  132. package/src/portfolio/period-pnl.ts +51 -1
  133. package/src/renderers/dom/dialog-host.tsx +5 -5
  134. package/src/renderers/electrobun/view/remote/capability-invoker.ts +1 -1
  135. package/src/renderers/opentui/dialog-host.tsx +3 -4
  136. package/src/sources/gloomberb-cloud/normalizers.ts +5 -0
  137. package/src/sources/provider-router/history.ts +5 -2
  138. package/src/test-support/plugin-persistence.ts +12 -0
  139. package/src/tickers/company-name-listing.ts +4 -3
  140. package/src/tickers/company-name.ts +19 -1
  141. package/src/tickers/instrument-coverage.ts +27 -0
  142. package/src/tickers/search/home-listing.ts +38 -1
  143. package/src/tickers/search/index.ts +3 -2
  144. package/src/tickers/search/ranking.ts +21 -2
  145. package/src/time-series/base-series.ts +4 -0
  146. package/src/time-series/types.ts +5 -2
  147. package/src/types/financials.ts +13 -0
  148. package/src/types/headless.ts +2 -0
  149. package/src/ui/dialog-stack.ts +17 -0
  150. package/src/ui/dialog.tsx +6 -2
  151. package/src/utils/crypto-pair.ts +9 -0
  152. package/src/utils/exchanges.ts +13 -0
  153. package/src/utils/financial-statements.ts +60 -3
  154. package/src/utils/futures-generic.ts +14 -0
  155. package/src/utils/trailing-dividend.ts +13 -3
@@ -243,6 +243,7 @@ import { isPesoDollarPair, loadPesoDollarRates, pesoDollarRateLines, pesoDollarR
243
243
  import { withBalanceSheetRate } from "../../market-data/quotes/balance-sheet-rate";
244
244
  import { regularSessionValuationPrice } from "../../market-data/quotes/regular-session-valuation";
245
245
  import { atLivePriceEarnings } from "../../market-data/quotes/live-valuation";
246
+ import { quoteSourceName } from "../../market-data/quotes/export-identity";
246
247
  import { viewMarketCapitalization } from "../../utils/market-capitalization";
247
248
  import {
248
249
  barHistoryFreshness,
@@ -317,11 +318,11 @@ import { withSavedCopy, type ReportFreshness } from "../pane-functions/freshness
317
318
  import { isNotATickerMessage } from "../not-a-ticker";
318
319
  import { useKnownCoins } from "../board-coins";
319
320
  import { suggestUsTicker, type ListingSuggestion } from "../listing-suggestion";
320
- import { quotedPhrase, splitSymbolArgs, symbolInputKey, uniqueSecuritySymbols } from "../symbol-args";
321
+ import { quotedPhrase, securityInputKey, splitSymbolArgs, symbolInputKey, uniqueSecuritySymbols } from "../symbol-args";
321
322
  import { isCompanyNameInput } from "../../tickers/company-name-listing";
322
323
  import { readNameEntries, readPhraseArgument } from "../name-entries";
323
324
  import { readSymbolList, SymbolListError, type TypedForm } from "../symbol-list";
324
- import { notASymbolError } from "../symbol-cells";
325
+ import { notASymbolError, type NotASymbolError } from "../symbol-cells";
325
326
  import { cliPerpetualContract, perpetualContractStats, type PerpetualContractPayload } from "../perpetual-contract";
326
327
  import { isSubMinuteInterval, knownGapMessage, subMinuteDataMessage } from "../known-gaps";
327
328
  import { phraseSearchReport } from "./search";
@@ -542,7 +543,7 @@ async function readListedSymbols(
542
543
  market: MarketContext,
543
544
  ctx: Parameters<CliCommandDef["execute"]>[1],
544
545
  usage: string,
545
- ): Promise<{ symbols: string[]; notes: string[]; typedForms: TypedForm[] }> {
546
+ ): Promise<{ symbols: string[]; notes: string[]; typedForms: TypedForm[]; byLine: boolean }> {
546
547
  try {
547
548
  const typedForms: TypedForm[] = [];
548
549
  const list = await readSymbolList({
@@ -553,7 +554,11 @@ async function readListedSymbols(
553
554
  const where = file && file !== "-" ? file : args.includes("-") ? "standard input" : "what was given";
554
555
  ctx.fail([`No symbols in ${where}.`, ...list.notes].join(" "), usage);
555
556
  }
556
- return { symbols: uniqueEntries(list.symbols), notes: list.notes, typedForms };
557
+ // A list of one entry a line from a file or standard input has a row for each of its lines (`listRows`), however
558
+ // many entries they read as: AAPL, a blank line and AAPL again are three rows. Typed arguments, a comma list and a
559
+ // table with a header keep a row per entry.
560
+ const byLine = typedForms.filter((form) => form.ownRow).length > 1;
561
+ return { symbols: uniqueEntries(list.symbols), notes: list.notes, typedForms, byLine };
557
562
  } catch (error) {
558
563
  if (error instanceof SymbolListError) ctx.fail(error.message, usage);
559
564
  throw error;
@@ -764,7 +769,9 @@ const FEED_COLUMNS = [
764
769
  header: "Feed",
765
770
  shrink: false,
766
771
  stackPriority: 4,
767
- format: (value: unknown) => value === "stale" || value === "nominal" ? cliStyles.warning(value) : String(value ?? ""),
772
+ // A coin priced by one exchange's own trade names it on its row: `live · Coinbase`.
773
+ format: (value: unknown, row: QuoteRow) => value === "stale" || value === "nominal" ? cliStyles.warning(value)
774
+ : `${String(value ?? "")}${row.priceVenue ? ` · ${row.priceVenue}` : ""}`,
768
775
  },
769
776
  // A nominal price names the session it is from ("6 Nov close"), not the last print; JSON keeps both.
770
777
  { key: "updatedAt", header: "Updated", shrink: false, stackPriority: 5,
@@ -784,9 +791,9 @@ const CHANGE_BP_EXPORT_COLUMN = {
784
791
  * read as one listing (`USDJPY Curncy`, `USDJPY`, `usdjpy`, `USD/JPY` are all USDJPY=X), and marks a row
785
792
  * that repeats an earlier row's listing with that row's entry. After the columns an export already had.
786
793
  */
787
- const LIST_INPUT_EXPORT_COLUMNS = [
788
- { key: "input", header: "input", value: (row: QuoteRow) => row.input || null },
789
- { key: "duplicateOf", header: "duplicate_of", value: (row: QuoteRow) => row.duplicateOf || null },
794
+ const LIST_INPUT_EXPORT_COLUMNS: CliResultColumn<Record<string, unknown>>[] = [
795
+ { key: "input", header: "input", value: (row) => row.input || null },
796
+ { key: "duplicateOf", header: "duplicate_of", value: (row) => row.duplicateOf || null },
790
797
  ];
791
798
 
792
799
  /** The day's low and high as numbers, after the columns an export already had. */
@@ -979,6 +986,7 @@ function quoteRows(results: QuoteCliRecord[], now = Date.now()) {
979
986
  providerId: quote?.providerId ?? "",
980
987
  source: quote?.dataSource ?? quote?.providerId ?? "",
981
988
  feed: quoteFeedState(quote, now),
989
+ ...quote?.priceVenue ? { priceVenue: quote.priceVenue } : {},
982
990
  // When the price Last shows was observed: in a pre-market nothing has traded in, the close it stands at.
983
991
  updatedAt: quote?.lastUpdated ? new Date(quoteHeadlineTime(quote)).toISOString() : "",
984
992
  input: result.input ?? "",
@@ -1308,7 +1316,7 @@ async function runQuote(rawArgs: string[], ctx: Parameters<CliCommandDef["execut
1308
1316
  }));
1309
1317
  const tickerChanges = symbolChanges.map(({ change }) => change);
1310
1318
  // A list's rows name the entry each is for, and mark one that is the same listing as an earlier row.
1311
- const listInputs = listed && symbols.length > 1 ? quoteListInputs(asked, resolvedListings) : null;
1319
+ const listInputs = listed && (symbols.length > 1 || !!list?.byLine) ? quoteListInputs(asked, resolvedListings) : null;
1312
1320
  const formerIssuers = symbolChanges.map(({ formerIssuer }) => formerIssuer);
1313
1321
  // A symbol with no quote whose bars stopped over a month ago says when it last traded, in place of why no quote
1314
1322
  // came: no longer listed on the service's record (FLAT, a retired ETN), else no trades since. Each costs a history
@@ -1439,7 +1447,8 @@ async function runQuote(rawArgs: string[], ctx: Parameters<CliCommandDef["execut
1439
1447
  // An export of a list read from a file or standard input has a row for every line, in its order: one no listing was
1440
1448
  // read for says why in its status, as its line on stderr does. The table keeps a row per listing.
1441
1449
  const rows = listInputs && ctx.cliOptions.format !== "text"
1442
- ? listRows([...data, ...unread.map(unreadRow)], symbols, list?.typedForms ?? [])
1450
+ ? listRows([...data, ...unread.map(unreadRow), ...list?.byLine ? refused.map((error) => unlistedQuoteRow(error.input)) : []],
1451
+ symbols, list?.typedForms ?? [], unlistedQuoteRow)
1443
1452
  : data;
1444
1453
  const basisNotes = changeBasisNotes(data, now);
1445
1454
  const midNotes = extendedMidNotes(data);
@@ -1453,6 +1462,7 @@ async function runQuote(rawArgs: string[], ctx: Parameters<CliCommandDef["execut
1453
1462
  if (ctx.cliOptions.format !== "json") useKnownCoins();
1454
1463
  // Only yield indices: their change is in bp, so the text header drops the percent sign (CSV keeps the percent it holds).
1455
1464
  const yieldsOnly = data.length > 0 && data.every((row) => isYieldIndexSymbol(row.target.symbol));
1465
+ const venued = data.some((row) => row.quote?.priceVenue);
1456
1466
  ctx.printResult({
1457
1467
  data: rows,
1458
1468
  warnings: warnings.length > 0 ? warnings : undefined,
@@ -1474,6 +1484,8 @@ async function runQuote(rawArgs: string[], ctx: Parameters<CliCommandDef["execut
1474
1484
  || row.currency || (row.yieldIndex ? YIELD_INDEX_EXPORT_UNIT : isIndexLevel(row.instrumentType) ? INDEX_POINTS_EXPORT_UNIT : null),
1475
1485
  // Each row as of its own price (^TNX's 19:59 beside ^VIX's 21:15), as Updated says; a row with none is blank.
1476
1486
  asOf: row.updatedAt || null,
1487
+ // Beside a coin priced by one exchange's own trade, which is cited to that exchange, each row names its own.
1488
+ ...venued ? { source: quoteSourceName(row) } : {},
1477
1489
  }),
1478
1490
  // A row with no price or move says why in its status column, as the warnings do.
1479
1491
  exportStatus: quoteExportStatus,
@@ -1505,30 +1517,64 @@ function unreadRow({ symbol, error }: { symbol: string; error: ListingArgError }
1505
1517
  return { target: { symbol }, listing: { symbol, exchange: null, name: null }, quote: null, error: error.message, input: symbol };
1506
1518
  }
1507
1519
 
1520
+ /**
1521
+ * Why a list's line names no listing, before any lookup: "blank line", or what it is
1522
+ * (`N/A` is "not a symbol", `1.899` "a number, not a symbol").
1523
+ */
1524
+ function unlistedLineStatus(typed: string): string {
1525
+ return typed.trim() ? notASymbolError(typed)?.reason ?? "not a symbol" : "blank line";
1526
+ }
1527
+
1528
+ /** The row of a list's line that names no listing (a blank line, `N/A`), its reason in the status column. */
1529
+ function unlistedQuoteRow(typed: string): QuoteCliRecord & { listing: ReturnType<typeof listingMetadata> } {
1530
+ return { target: { symbol: typed }, listing: { symbol: typed, exchange: null, name: null }, quote: null, error: unlistedLineStatus(typed), input: typed };
1531
+ }
1532
+
1508
1533
  type ListRow = Pick<QuoteCliRecord, "input" | "duplicateOf" | "quote"> & { listing: { symbol: string; exchange: string | null } };
1509
1534
 
1510
1535
  /**
1511
1536
  * A list's rows, one for each line of its text as typed where several were read as one entry (`USDJPY` and
1512
- * `usdjpy` are both USDJPY), in the order of the lines, else of the entries; a row that is the same listing as an
1513
- * earlier row names that row's entry in `duplicateOf`.
1537
+ * `usdjpy` are both USDJPY, BRK.B and BRK-B one share class), in the order of the lines, else of the entries; a row
1538
+ * that is the same listing as an earlier row names that row's entry in `duplicateOf`. In a list of one entry a line,
1539
+ * a line no entry was read from (a blank line, `N/A`, a number) has its row too, from `unlisted`, so the rows line
1540
+ * up with the sheet's lines.
1514
1541
  */
1515
- function listRows<Row extends ListRow>(rows: readonly Row[], entries: readonly string[], forms: readonly TypedForm[]): Row[] {
1542
+ function listRows<Row extends ListRow>(
1543
+ rows: readonly Row[],
1544
+ entries: readonly string[],
1545
+ forms: readonly TypedForm[],
1546
+ unlisted: (typed: string) => Row,
1547
+ ): Row[] {
1548
+ // The entry each line reads as: its own, else the entry that is the same security spelled another way (BRK-B, BRK/B
1549
+ // for BRK.B), which the list read once.
1550
+ const keys = new Set(entries.map(symbolInputKey));
1551
+ const bySecurity = new Map<string, string>();
1552
+ for (const key of keys) if (!bySecurity.has(securityInputKey(key))) bySecurity.set(securityInputKey(key), key);
1553
+ const lineKey = (form: TypedForm) => keys.has(form.key) ? form.key : bySecurity.get(securityInputKey(form.key)) ?? form.key;
1516
1554
  // An entry read from no line of its own (a name read as its words) goes after the line before it.
1517
1555
  let last = -1;
1518
1556
  const entryAt = new Map(entries.map((entry, index) => {
1519
- const at = forms.findIndex((form) => form.key === symbolInputKey(entry));
1557
+ const at = forms.findIndex((form) => lineKey(form) === symbolInputKey(entry));
1520
1558
  if (at >= 0) last = at;
1521
1559
  return [entry, { at: at >= 0 ? at : last + 0.5, index }] as const;
1522
1560
  }));
1561
+ const used = new Set<number>();
1523
1562
  const placed = rows.flatMap((row, index) => {
1524
- const typed = forms.flatMap((form, at) => form.key === symbolInputKey(row.input ?? "") ? [{ form, at }] : []);
1563
+ const typed = forms.flatMap((form, at) => lineKey(form) === symbolInputKey(row.input ?? "") ? [{ form, at }] : []);
1564
+ typed.forEach(({ at }) => used.add(at));
1525
1565
  const place = entryAt.get(row.input ?? "") ?? { at: forms.length, index: entries.length + index };
1526
1566
  return typed.length > 1 || (typed.length === 1 && typed[0]!.form.typed !== row.input)
1527
1567
  ? typed.map(({ form, at }) => ({ row: { ...row, input: form.typed }, at, index: place.index }))
1528
1568
  : [{ row, ...place }];
1529
- }).sort((a, b) => a.at - b.at || a.index - b.index);
1569
+ });
1570
+ // A line of words read as several symbols (`AAPL MSFT`) has their rows.
1571
+ const readAsWords = (form: TypedForm) => !!form.typed && form.key.split(/\s+/).every((word) => keys.has(word) || bySecurity.has(securityInputKey(word)));
1572
+ const lines = forms.flatMap((form, at) => form.ownRow && !used.has(at) && !readAsWords(form)
1573
+ ? [{ row: unlisted(form.typed), at, index: -1 }] : []);
1530
1574
  const first = new Map<string, string>();
1531
- return placed.map(({ row }) => {
1575
+ return [...placed, ...lines].sort((a, b) => a.at - b.at || a.index - b.index).map(({ row }) => {
1576
+ // A line that names no listing is no other line's repeat.
1577
+ if (!row.input?.trim() || notASymbolError(row.input)) return row;
1532
1578
  const key = `${(row.quote?.symbol || row.listing.symbol).toUpperCase()}:${row.listing.exchange ?? ""}`;
1533
1579
  const earlier = first.get(key);
1534
1580
  if (earlier === undefined) first.set(key, row.input ?? "");
@@ -2153,7 +2199,9 @@ async function loadListingHistory(
2153
2199
  const dayToDate = fromQuote && interval === "1d" && data.at(-1)?.partial === true;
2154
2200
  // Signed out or free, the bars of a session in progress run as late as the delayed quote they end on, and say how late.
2155
2201
  const sessionTrading = quote?.marketState === "REGULAR" || quote?.marketState === "PRE" || quote?.marketState === "POST";
2156
- const delayedTail = quote?.dataSource === "delayed" && !quote.delisting && (dayToDate || (intraday && sessionTrading));
2202
+ // A coin priced by an exchange's own trade is still a reader without real-time access, whose bars stay held back.
2203
+ const barsHeldBack = quote?.dataSource === "delayed" || (quote?.priceVenue != null && intraday && await cloudRealtimeAccess() === false);
2204
+ const delayedTail = barsHeldBack && !quote?.delisting && (dayToDate || (intraday && sessionTrading));
2157
2205
  // The source that served the bars, a broker or another source when Gloom Cloud could not.
2158
2206
  const source = loaded.sourceName ? { source: loaded.sourceName } : {};
2159
2207
  // A coin's volume unit, or what an index's volume counts (a day's total, an intraday count).
@@ -2738,11 +2786,16 @@ async function runHistoryList(
2738
2786
  }
2739
2787
  const served = listed.flatMap((entry) => "history" in entry && entry.history.data.length > 0 ? [entry.history] : []);
2740
2788
  // A symbol with no bars, whether its request failed or came back empty, is one row with the reason.
2741
- const rows: HistoryListRow[] = listed.flatMap((entry) => "history" in entry
2789
+ const entryRows = (entry: ListedHistory): HistoryListRow[] => "history" in entry
2742
2790
  ? entry.history.data.length > 0
2743
2791
  ? entry.history.data.map((row) => ({ symbol: entry.history.listing.key, ...row }))
2744
2792
  : [historyFailureRow(entry.history.listing.key, emptyHistoryNote(entry.history.listing.key, ask))]
2745
- : [historyFailureRow(entry.symbol, entry.error)]);
2793
+ : [historyFailureRow(entry.symbol, entry.error)];
2794
+ // An export of a list read from a file or standard input has rows for every line, in its order, as `quote` has:
2795
+ // each bar names the line it is for and the earlier line that is the same listing, and a line that names no
2796
+ // listing (a blank line, `N/A`) is one row with why.
2797
+ const fromList = (file !== undefined || args.includes("-")) && ctx.cliOptions.format !== "text";
2798
+ const rows: HistoryListRow[] = fromList ? historyListRows(listed, entryRows, refused, list) : listed.flatMap(entryRows);
2746
2799
  const bySymbol = new Map(served.map((history) => [history.listing.key, history] as const));
2747
2800
  const notes = [
2748
2801
  ...list.notes,
@@ -2829,7 +2882,7 @@ async function runHistoryList(
2829
2882
  dateKey: "date",
2830
2883
  textColumns: [{ key: "symbol", header: "Symbol", shrink: false }, ...textColumns,
2831
2884
  { key: "currency", header: "Cur", shrink: false, format: currencyCell }, HISTORY_FLAG_TEXT_COLUMN],
2832
- columns: historyExportColumns(rows),
2885
+ columns: [...historyExportColumns(rows), ...fromList ? LIST_INPUT_EXPORT_COLUMNS : []],
2833
2886
  exportStatus: historyExportStatus,
2834
2887
  // Every row names its symbol, the currency its prices are in, its bar size and the as-of of its own symbol's bars.
2835
2888
  exportIdentity: (row) => {
@@ -2848,6 +2901,24 @@ async function runHistoryList(
2848
2901
  });
2849
2902
  }
2850
2903
 
2904
+ /** `history`'s rows of a list read from a file or standard input, for each line in its order (`listRows`). */
2905
+ function historyListRows(
2906
+ listed: readonly ListedHistory[],
2907
+ entryRows: (entry: ListedHistory) => HistoryListRow[],
2908
+ refused: readonly NotASymbolError[],
2909
+ list: { symbols: string[]; typedForms: TypedForm[]; byLine: boolean },
2910
+ ): HistoryListRow[] {
2911
+ type EntryRow = ListRow & { bars: HistoryListRow[] };
2912
+ const row = (input: string, symbol: string, bars: HistoryListRow[]): EntryRow => ({ input, quote: null, listing: { symbol, exchange: null }, bars });
2913
+ const unlisted = (typed: string) => row(typed, typed, [historyFailureRow(typed, unlistedLineStatus(typed))]);
2914
+ return listRows([
2915
+ ...listed.map((entry) => row(entry.symbol, "history" in entry ? entry.history.listing.key : entry.symbol, entryRows(entry))),
2916
+ // A cell that is no symbol (`N/A`) has a row in a list of one entry a line only, as `quote`'s export has.
2917
+ ...list.byLine ? refused.map((error) => unlisted(error.input)) : [],
2918
+ ], list.symbols, list.typedForms, unlisted)
2919
+ .flatMap(({ bars, input, duplicateOf }) => bars.map((bar) => ({ ...bar, input, ...duplicateOf ? { duplicateOf } : {} })));
2920
+ }
2921
+
2851
2922
  type FinancialsView = "statements" | "fundamentals" | "valuation";
2852
2923
 
2853
2924
  const STATEMENT_COLUMNS: CliResultColumn<ReturnType<typeof financialStatementRows>[number]>[] = [
@@ -4758,8 +4829,9 @@ export const marketDataCliCommands: BuiltinCliCommandDef[] = [
4758
4829
  }, {
4759
4830
  title: "Several symbols",
4760
4831
  lines: [
4761
- `history AAPL MSFT 000660.KS, or --file with one symbol a line (- reads standard input), writes every symbol's bars in one long table, ${HISTORY_LIST_CONCURRENCY} symbols loading at once. Each row names its symbol, its unit and the as-of of that symbol's bars in symbol_or_series, currency_or_unit and as_of.`,
4762
- "A symbol with no history is one row with its reason in status, and a warning names it; the command fails only when no symbol has any. A word typed on the command line that is no ticker fails the command, and a bar size typed in a symbol's place (1s, 30s, 1m) says where the finest bars are; a list from --file keeps a row for a line that is no ticker. --tail 5 keeps each symbol's newest five bars.",
4832
+ `history AAPL MSFT 000660.KS writes every symbol's bars in one long table, ${HISTORY_LIST_CONCURRENCY} symbols at a time; --file list.txt (- for standard input) reads one symbol a line. symbol_or_series, currency_or_unit and as_of name each row's symbol, unit and as-of.`,
4833
+ "A symbol with no bars is one row with why in status; the command fails only when none has any. A word typed on the command line that is no ticker fails it, and a bar size in a symbol's place (1s, 30s, 1m) says where the finest bars are. --tail 5 keeps each symbol's newest five bars.",
4834
+ "A --file list of one symbol a line has a row for every line, in its order: a blank line, or one that names no listing, is one row with why in status. A --file list's export adds input, the line as typed, and duplicate_of, the earlier line that is the same listing.",
4763
4835
  "--wide sets the symbols side by side instead: one row per date, one close column per symbol headed with its unit (USDJPY=X close (JPY per USD)), a blank where a symbol has no bar that day. history USDJPY=X USDCHF=X EURCHF=X --csv --wide is a spreadsheet of the three closes; --tail 5 keeps the newest five dates.",
4764
4836
  ],
4765
4837
  }, {
@@ -63,6 +63,8 @@ import {
63
63
  } from "../../plugins/builtin/econ/calendar-model";
64
64
  import { hasNoReleaseTime, hasNoStatedTime, type EconEvent } from "../../plugins/builtin/econ/types";
65
65
  import { econRowFigures, figureWithCurrency } from "../../plugins/builtin/econ/figures";
66
+ import { cpiCalendarYearGapReason } from "../../plugins/builtin/shared/cpi-year-gap";
67
+ import { fredSeriesIdForName } from "../../plugins/builtin/econ/fred-catalog";
66
68
  import { isoDate, rejectExtraArgs, requireArg, requireOneArg, takeFlag, takeOption } from "./command-utils";
67
69
  import { buildCorrelationSeries } from "../../plugins/builtin/correlation/matrix/model";
68
70
  import { alignDailyCloses, correlateDailyCloses } from "../../plugins/builtin/correlation/compute";
@@ -105,6 +107,9 @@ import {
105
107
  import { fredProvenance, fredPublicationTime, notOnFredSource } from "../../sources/gloomberb-cloud/fred-attribution";
106
108
  import { followsUsBondMarket, usBondMarketClosedNote } from "../../market-data/us-bond-market";
107
109
 
110
+ /** The Actual of a release its publisher could not compute; the notes say why. */
111
+ const NOT_PUBLISHED_TEXT = "not published";
112
+
108
113
  // Batch quotes often omit names for indices and ETFs; these baskets are fixed, so name them here.
109
114
  const BASKET_NAMES = new Map<string, string>([
110
115
  ...WORLD_INDICES.map((entry) => [entry.symbol, entry.name] as const),
@@ -664,8 +669,10 @@ async function runEcon(args: string[], ctx: Parameters<CliCommandDef["execute"]>
664
669
  forecastText: event.forecast ?? null,
665
670
  priorText: event.prior ?? null,
666
671
  // A release past its time with no figure yet: "due 07:00 UTC, awaiting figure", then "no figure from the source"
667
- // two hours on or once the release's other rows have theirs; null otherwise.
668
- actualStatus: ((gap) => gap ? figureGapText(event, gap) : null)(figureGap(event, now, inWindow)),
672
+ // two hours on or once the release's other rows have theirs; null otherwise. A US CPI y/y BLS could not publish
673
+ // (no index a year before) says so, and the notes say why.
674
+ actualStatus: cpiCalendarYearGapReason(event) ? NOT_PUBLISHED_TEXT
675
+ : ((gap) => gap ? figureGapText(event, gap) : null)(figureGap(event, now, inWindow)),
669
676
  // The publisher's own clock, for rows Gloom Cloud adds from a bank's or a statistics office's calendar.
670
677
  localTime: event.localTime ?? null,
671
678
  timeZone: event.timeZone ?? null,
@@ -696,7 +703,12 @@ async function runEcon(args: string[], ctx: Parameters<CliCommandDef["execute"]>
696
703
  // where the end is said.
697
704
  const pastRows = pastListingRows(listed);
698
705
  const listedPast = pastRows ? `No releases listed after ${listedThrough}; the rows after it are ${pastRows}` : null;
699
- const notes = [listedBefore, listedPast ?? listedAfter, ...(rows.length > 0 ? blankTimeNotes(rows) : []),
706
+ // Why a US CPI y/y row has no actual: "2026-11-10 Inflation Rate YoY: BLS published no October 2025 index, so no October 2026 y/y."
707
+ const unpublished = listed.flatMap((event) => {
708
+ const reason = cpiCalendarYearGapReason(event);
709
+ return reason ? [`${isoDate(event.date).slice(0, 10)} ${econEventName(event)}: ${reason}.`] : [];
710
+ });
711
+ const notes = [listedBefore, listedPast ?? listedAfter, ...(rows.length > 0 ? blankTimeNotes(rows) : []), ...unpublished,
700
712
  rows.length > 0 && coverage ? coverage : null,
701
713
  // A dash under Forecast on a release still to come is a consensus not in yet, not a missing figure.
702
714
  listed.some(awaitsConsensus) ? NO_CONSENSUS_NOTE : null]
@@ -832,7 +844,9 @@ async function runFred(rawArgs: string[], ctx: Parameters<CliCommandDef["execute
832
844
  if (changeGiven && !horizon) {
833
845
  ctx.fail(change ? `Unknown change "${change}".` : "--change needs 1D or 1W.", "Use 1D (from the previous observation) or 1W (from a week before).");
834
846
  }
835
- const seriesId = requireOneArg(args, FRED_USAGE, "series", ctx).toUpperCase();
847
+ const asked = requireOneArg(args, FRED_USAGE, "series", ctx);
848
+ // A series by its name (`3 month t-bill` is DTB3) when one alone fits it.
849
+ const seriesId = (/\s/.test(asked.trim()) ? fredSeriesIdForName(asked) : null) ?? asked.toUpperCase();
836
850
  await withSavedFredSeries(ctx, () => printFredSeries(ctx, { seriesId, start, startDate, sortOrder, horizon }));
837
851
  }
838
852
 
package/src/cli/errors.ts CHANGED
@@ -135,7 +135,9 @@ function cliErrorObject(error: unknown): CliErrorObject {
135
135
  }
136
136
  // A source failed (a timeout, a rate limit) where none had the data to answer: asked again it may.
137
137
  if (isSourceFailure(error) || isSourceUnavailableAnswer(error)) {
138
- return { code: SOURCE_UNAVAILABLE_CODE, message: error instanceof Error ? error.message : String(error), retryable: true };
138
+ const message = error instanceof Error ? error.message : String(error);
139
+ // It failed, it is not missing: says to ask again unless the message already says when.
140
+ return { code: SOURCE_UNAVAILABLE_CODE, message, ...(/\btry again\b/i.test(message) ? {} : { details: "Try again in a moment." }), retryable: true };
139
141
  }
140
142
  // A listing read the data service failed to answer twice: said in Gloom's words. Any other 5xx keeps the server's.
141
143
  if (wasAskedTwice(error)) {
@@ -3,6 +3,7 @@ import type { HeadlessPaneFreshness, HeadlessPaneRow } from "../types/headless";
3
3
  import { deriveHeadlessFreshness, type ReportFreshness } from "./pane-functions/freshness";
4
4
  import { quoteObservation, REPORTED_DATA } from "../plugins/builtin/shared/report-freshness";
5
5
  import { latestReportedPeriod } from "../utils/latest-financial-period";
6
+ import { quoteSourceName } from "../market-data/quotes/export-identity";
6
7
 
7
8
  /**
8
9
  * The source, as-of and status line of a plain CLI command, derived exactly as
@@ -33,8 +34,12 @@ export function quotesFreshness(
33
34
  declared?: HeadlessPaneFreshness,
34
35
  now = Date.now(),
35
36
  ): ReportFreshness | undefined {
36
- const rows = [...quotes].filter((quote): quote is Quote => quote != null).map((quote) => quoteObservation(quote, now));
37
- return rows.length > 0 ? rowsFreshness(rows, declared, undefined, now) : undefined;
37
+ const shown = [...quotes].filter((quote): quote is Quote => quote != null);
38
+ const rows = shown.map((quote) => quoteObservation(quote, now));
39
+ // A coin priced by an exchange's own trade names the exchange, as its pane footer does: `Coinbase and Kraken`.
40
+ const names = shown.some((quote) => quote.priceVenue) ? [...new Set(shown.map((quote) => quoteSourceName(quote)))] : [];
41
+ const source = !declared?.source && names.length > 0 && names.every(Boolean) ? names.join(" and ") : undefined;
42
+ return rows.length > 0 ? rowsFreshness(rows, source ? { ...declared, source } : declared, undefined, now) : undefined;
38
43
  }
39
44
 
40
45
  /**
@@ -126,7 +126,7 @@ export const GLOSSARY: readonly GlossaryEntry[] = [
126
126
  definition: "The nine-character code that identifies a US security. A reopening repeats the original issue's CUSIP.",
127
127
  },
128
128
  {
129
- term: "Bill", aliases: ["t-bill", "treasury bill", "bills"], functions: ["AUCT", "BTMM"], shown: ["Bill", "bill"],
129
+ term: "Bill", aliases: ["t-bill", "t-bills", "tbill", "tbills", "treasury bill", "bills"], functions: ["AUCT", "BTMM"], shown: ["Bill", "bill"],
130
130
  definition: "Treasury debt of a year or less, sold below face value with no coupon; the climb back to face value is the interest.",
131
131
  },
132
132
  {
@@ -870,11 +870,16 @@ export const GLOSSARY: readonly GlossaryEntry[] = [
870
870
  + "(10 bp is about ±5 points at 7 days), so CTM greys it there and Vs Spot is the figure to read.",
871
871
  },
872
872
  {
873
- term: "Crypto composite price", aliases: ["CCC", "crypto composite", "composite price", "composite crypto price"], functions: ["CTM"],
873
+ term: "Crypto composite price", aliases: ["CCC", "crypto composite", "composite price", "composite crypto price"], functions: ["CTM", "CRYP"],
874
874
  shown: ["crypto composite price"],
875
- definition: "A coin's dollar price blended from trading on several crypto exchanges rather than taken from one, quoted around the clock; "
876
- + "quotes list it under the code CCC. CTM reads CME crypto futures against it, while the futures settle to CME's own reference rate, "
877
- + "so a small gap at expiry is expected.",
875
+ definition: "A coin's dollar price blended from trading on many crypto exchanges, Binance, Coinbase, Kraken and Bitstamp among them, "
876
+ + "quoted around the clock under the code CCC. "
877
+ + "Its 5-minute low or high can be one exchange's brief wick: CRYP reads Coinbase's, Kraken's and Bitstamp's own candles "
878
+ + "around it and says Coinbase only when one alone reached it, other exchange when none of them did. "
879
+ + "An exchange's price outside the composite's 24-hour range widens it, and the extreme says so (+ Kraken). "
880
+ + "A price named after an exchange (Coinbase · 15:55 UTC) is that exchange's own price at that time, not the composite. "
881
+ + "An intraday bar's volume counts the spot venues the bar names (1 spot venue), not every exchange. "
882
+ + "CTM reads CME crypto futures against the composite, while the futures settle to CME's own reference rate, so a small gap at expiry is expected.",
878
883
  },
879
884
  {
880
885
  term: "Contango", aliases: ["contango curve", "upward curve"], functions: ["CTM", "FUT"], shown: ["contango", "Contango"],
@@ -5,7 +5,7 @@ import {
5
5
  formatNumber,
6
6
  formatPercentRaw,
7
7
  } from "../utils/format";
8
- import { formatMarketChangeWithCurrency, formatMarketPriceWithCurrency, type MarketFormatOptions } from "../market-data/market/format";
8
+ import { formatMarketChangeWithCurrency, formatMarketPriceRange, formatMarketPriceWithCurrency, type MarketFormatOptions } from "../market-data/market/format";
9
9
  import { changeBasisLabel, changeBasisNote, printPredatesChangeBasis, quoteChangeBasis } from "../market-data/market/change-basis";
10
10
  import type { FuturesContractTermsPayload } from "../api-client/futures-curve";
11
11
  import type { ActiveQuoteDisplay } from "../market-data/market/status";
@@ -100,12 +100,8 @@ export function dryRunNote(dryRun: boolean): string {
100
100
  return dryRun ? cliStyles.muted(" (dry run, nothing saved)") : "";
101
101
  }
102
102
 
103
- function fractionDigits(text: string): number {
104
- return /\.(\d+)/.exec(text)?.[1]?.length ?? 0;
105
- }
106
-
107
- /** Low and high of a range. A sub-unit quote (pence shown in pounds) varies in decimals,
108
- * so its pair shares one count: £35.1000 - £35.4871, not £35.10 - £35.4871. */
103
+ /** Low and high of a range, both to one number of decimals (formatMarketPriceRange): £35.1000 - £35.4871 for pence
104
+ * shown in pounds, not £35.10 - £35.4871, and a coin's at its price's decimals. */
109
105
  export function formatPriceRange(
110
106
  low: number | undefined,
111
107
  high: number | undefined,
@@ -113,15 +109,11 @@ export function formatPriceRange(
113
109
  options: MarketFormatOptions,
114
110
  separator = " - ",
115
111
  ): string {
116
- const format = (value: number | undefined, extra: MarketFormatOptions = {}) => (
117
- value == null ? "—" : formatMarketPriceWithCurrency(value, currency, { ...options, ...extra })
118
- );
119
- const lowText = format(low);
120
- const highText = format(high);
121
- if (!options.quotedUnitDivisor || low == null || high == null) return `${lowText}${separator}${highText}`;
122
- const digits = Math.max(fractionDigits(lowText), fractionDigits(highText));
123
- if (fractionDigits(lowText) === digits && fractionDigits(highText) === digits) return `${lowText}${separator}${highText}`;
124
- return `${format(low, { fixedFractionDigits: digits })}${separator}${format(high, { fixedFractionDigits: digits })}`;
112
+ if (low == null || high == null) {
113
+ const format = (value: number | undefined) => value == null ? "—" : formatMarketPriceWithCurrency(value, currency, options);
114
+ return `${format(low)}${separator}${format(high)}`;
115
+ }
116
+ return formatMarketPriceRange(low, high, options, currency).join(separator);
125
117
  }
126
118
 
127
119
  /** A timestamp in CLI text: UTC with the zone named, the same on every machine. */
@@ -16,6 +16,10 @@ export interface HistoryListRow extends HistoryRow {
16
16
  symbol: string;
17
17
  /** Why the symbol has no bars, as its warning says it; only on a symbol's one row with no bar. */
18
18
  status?: string;
19
+ /** In a list read from a file or standard input, the line the row is for, as typed. */
20
+ input?: string;
21
+ /** In such a list, the earlier line that is the same listing. */
22
+ duplicateOf?: string;
19
23
  }
20
24
 
21
25
  type ExportedRow = Record<string, unknown>;
@@ -5,7 +5,7 @@ import { parsePublicTickerKey } from "../utils/exchanges";
5
5
  import { commandWord } from "../utils/shell-word";
6
6
  import { listingAbroadVenue } from "../utils/sec";
7
7
  import { nimCommand } from "./bank-section";
8
- import { treasuryYieldLine, treasuryYieldTenor } from "./treasury-yields";
8
+ import { treasuryBillLine, treasuryYieldLine, treasuryYieldTenor } from "./treasury-yields";
9
9
  import { namedCurrencyPair } from "./currency-name-hint";
10
10
  import { dollarPairListing } from "../utils/currency-pair";
11
11
  import { currencyCodeTyped } from "../utils/currency-names";
@@ -589,7 +589,7 @@ export function knownGapMessage(query: string): string | null {
589
589
  const index = uncarriedIndexFor(query);
590
590
  if (index) return uncarriedIndexLine(index);
591
591
  return KNOWN_GAPS.find((gap) => namesKnownGap(gap, query))?.message
592
- ?? (tenor ? treasuryYieldLine(tenor) : null)
592
+ ?? (tenor ? treasuryBillLine(query, tenor) ?? treasuryYieldLine(tenor) : null)
593
593
  ?? topicPointer(query)?.message
594
594
  ?? macroReleaseTopic(query)?.line ?? null;
595
595
  }
@@ -24,9 +24,10 @@ import { isVenueAbroad, lineMayHaveMoved, listingChangeLine, loadListingFate, Mo
24
24
  import { quotedListingName } from "../tickers/listing-name";
25
25
  import { withdrawalLabel } from "../market-data/quotes/delisting";
26
26
  import { cliStyles } from "../utils/cli-output";
27
- import { companyNameExtraWords, groupByCompany, namesDepositaryReceipt, sameCompany, sameCompanyName, sameListedName, shortCompanyName } from "../tickers/company-name";
27
+ import { companyLinesName, companyNameExtraWords, groupByCompany, namesDepositaryReceipt, sameCompany, sameCompanyName, sameListedName, shortCompanyName } from "../tickers/company-name";
28
28
  import {
29
29
  canonicalExchange,
30
+ displayTickerKey,
30
31
  exchangeCodeVenues,
31
32
  exchangeLabel,
32
33
  exchangeName,
@@ -258,6 +259,45 @@ function tradesOn(symbol: string, venues: readonly ListingVenue[]): string {
258
259
  return venues.length > 0 ? ` ${symbol} trades on: ${venues.map((venue) => venue.exchange).join(", ")}.` : "";
259
260
  }
260
261
 
262
+ /** The companies a symbol's venues are asked about for their line on another venue: the first few, home lines first. */
263
+ const MAX_COMPANIES_ASKED = 4;
264
+
265
+ /**
266
+ * " Prudential plc trades on HKEX as 2378:HKEX." when a company that lists
267
+ * as `symbol` elsewhere has a line of its own on `exchange`: PRU on LSE is
268
+ * Prudential plc, whose Hong Kong line is 2378, and HSBC on NYSE is HSBC
269
+ * Holdings, whose is 0005. Each company is asked once, by one of its venues;
270
+ * empty when none has a line there or the service cannot say.
271
+ */
272
+ async function companyLineOn(symbol: string, exchange: string, venues: readonly ListingVenue[], deps: ListingDeps): Promise<string> {
273
+ const { getIssuerListings } = deps.dataProvider;
274
+ if (!getIssuerListings) return "";
275
+ const byCompany = new Map<string, ListingVenue>();
276
+ for (const venue of [...venues].sort((a, b) => Number(!!b.home) - Number(!!a.home))) {
277
+ const company = venue.companyId ?? venue.name;
278
+ if (!byCompany.has(company)) byCompany.set(company, venue);
279
+ }
280
+ const asked = [...byCompany.values()].slice(0, MAX_COMPANIES_ASKED);
281
+ const issuers = await Promise.all(asked.map((venue) => Promise.resolve()
282
+ .then(() => getIssuerListings.call(deps.dataProvider, venue.symbol ?? symbol, venue.exchange))
283
+ .catch(logFailure("cli.listing-arg", "Read a company's listings failed", null))));
284
+ const lines = new Map<string, string>();
285
+ issuers.forEach((issuer, index) => {
286
+ const line = issuer?.listings.find((listing) => canonicalExchange(listing.exchange) === exchange);
287
+ if (!issuer || !line) return;
288
+ const key = parsePublicTickerKey(line.symbol).exchange ? displayTickerKey(line.symbol) : `${line.symbol}:${exchange}`;
289
+ // The name search writes the line asked about under, its home line first (Prudential plc), as ADR names it.
290
+ lines.set(key, `${companyLinesName(asked[index]!.name, issuer.name)} trades on ${exchange} as ${key}.`);
291
+ });
292
+ return [...lines.values()].map((line) => ` ${line}`).join("");
293
+ }
294
+
295
+ /** "PRU does not trade on HKEX. Prudential plc trades on HKEX as 2378:HKEX. PRU trades on: LSE, NYSE." */
296
+ async function notTradedText(listing: Pick<ListingArg, "symbol" | "exchange">, venues: readonly ListingVenue[], deps: ListingDeps): Promise<string> {
297
+ const companyLine = await companyLineOn(listing.symbol, listing.exchange, venues, deps);
298
+ return `${listing.symbol} does not trade on ${listing.exchange}.${companyLine}${tradesOn(listing.symbol, venues)}`;
299
+ }
300
+
261
301
  /** "Toronto Stock Exchange (TSX) or Tokyo Stock Exchange (JPX)". */
262
302
  function venueChoices(venues: readonly string[]): string {
263
303
  const labels = venues.map(exchangeLabel);
@@ -351,7 +391,7 @@ export async function notTradedMessage(
351
391
  if (withdrawn) return withdrawnListingMessage(listing, withdrawn);
352
392
  if (venues.length === 0 || venues.some((venue) => venue.exchange === listing.exchange)) return null;
353
393
  if (await quotedOnVenue(listing, deps)) return null;
354
- return `${listing.symbol} does not trade on ${listing.exchange}.${tradesOn(listing.symbol, venues)}`;
394
+ return notTradedText(listing, venues, deps);
355
395
  }
356
396
 
357
397
  /**
@@ -1581,13 +1621,18 @@ export async function resolveCliListing(
1581
1621
  const read = await readTerminalCodeArg(deps.dataProvider, typed);
1582
1622
  // A company's name, an entry of a comma list (`WHR, Whirlpool Corporation`), is the listing search names for it.
1583
1623
  // A name before a legal form ("SAP SE", "SIEMENS AG") is looked up first: SE is also SIX Swiss's market code.
1584
- const named = !read || endsInLegalForm(typed) ? await companyNameListingArg(raw, deps) : null;
1624
+ const legalForm = !!read && endsInLegalForm(typed);
1625
+ const asName = !read || legalForm ? await companyNameListingArg(raw, deps) : null;
1626
+ // Read both ways as two companies ("ZURN SE": Zurich Insurance on SIX, Zurn Elkay by name), the code's listing wins.
1627
+ const codeWins = legalForm && asName ? await codeOverCompanyName(read!, asName.found, deps) : null;
1628
+ const named = codeWins ? null : asName?.listing ?? null;
1585
1629
  const terminal = named ? null : read;
1586
1630
  // "AAPL GP" is written as a code, with a market code no venue answers to and no company's name: one entry, never AAPL and GP.
1587
1631
  if (!terminal && !named) await refuseUnknownMarketCode(typed, deps);
1588
1632
  // `BP.` is London's code for BP: its London line where London lists it, and `GE.` a US ticker with a stray dot.
1589
1633
  const dotted = terminal || named || exchangeOption?.trim() ? null : readLondonDottedSymbol(typed);
1590
1634
  let parsed = named ?? (dotted ? await londonDottedListing(dotted, deps) : parseListingArg(raw, exchangeOption, { ...options, terminalCode: terminal }));
1635
+ if (codeWins) parsed = { ...parsed, readAs: codeWins };
1591
1636
  if (!parsed.symbol) throw new ListingArgError("Ticker symbol is required.");
1592
1637
  // $VIX is Schwab's code for ^VIX, unless a security trades as VIX: $AAPL is a cashtag.
1593
1638
  const index = named || parsed.exchange ? null : await readDollarIndexCode(raw, deps);
@@ -1645,6 +1690,33 @@ export async function resolveCliListing(
1645
1690
  };
1646
1691
  }
1647
1692
 
1693
+ /**
1694
+ * How a symbol and a market code read when the words are also a company's name
1695
+ * before its legal form, SE being both SIX Swiss's code and a European
1696
+ * company's form: "ZURN SE" is Zurich Insurance on SIX as a code and Zurn
1697
+ * Elkay Water Solutions as a name, "NOVN SE" Novartis and Novan, "SAP SE" SAP
1698
+ * either way. Two companies: the code names one listing on one venue, as a
1699
+ * desk typing a terminal's codes means it, so it wins, and the note names the
1700
+ * company the words would be ("Read "ZURN SE" as ZURN:SWX (Zurich Insurance
1701
+ * Group AG), not ZWS:NYSE (Zurn Elkay ...)"). One company, by the service's
1702
+ * company ids or by name: null, so the name reads the company's home listing
1703
+ * (SAP on Xetra, not its SIX line). Null too when the code's venue lists
1704
+ * nothing under the symbol.
1705
+ */
1706
+ async function codeOverCompanyName(code: TerminalListingCode, found: CompanyNameListing, deps: ListingDeps): Promise<string | null> {
1707
+ if (!code.exchange) return null;
1708
+ const venues = await listingVenues(code.symbol, deps).catch(logFailure("cli.listing-arg", "Read a market code's listing failed", [] as ListingVenue[]));
1709
+ const line = venues.find((venue) => venue.exchange === code.exchange && venue.name.trim());
1710
+ if (!line) return null;
1711
+ const company = found.meant ?? found;
1712
+ const companyLine = company.symbol.toUpperCase() === code.symbol.toUpperCase()
1713
+ ? venues.find((venue) => venue.exchange === company.exchange) : undefined;
1714
+ const ids = [line.companyId, companyLine?.companyId];
1715
+ if (ids[0] && ids[1] ? ids[0] === ids[1] : sameCompany(line.name, company.name)) return null;
1716
+ const key = company.exchange ? `${company.symbol}:${company.exchange}` : company.symbol;
1717
+ return `${terminalCodeReadAs(code).replace(/\.$/, "")} (${line.name.trim()}), not ${key} (${company.name.trim()}).`;
1718
+ }
1719
+
1648
1720
  /** A US share class typed with a space for its mark: `BRK B`, `brk b`. */
1649
1721
  const SPACED_SHARE_CLASS = /^([A-Za-z]{1,5})\s+([A-Za-z])$/;
1650
1722
  /** A US share class typed with no mark at all, in capitals: `BRKB`, `BFB`. */
@@ -1757,7 +1829,7 @@ async function checkTerminalCodeVenue(listing: ListingArg, market: string, deps:
1757
1829
  if (!hint && !isSearchOnlyVenue(listing.exchange)) return;
1758
1830
  const venues = await listingVenues(listing.symbol, deps).catch(logFailure("cli.listing-arg", "Read listing venues failed", []));
1759
1831
  if (venues.length === 0 || venues.some((venue) => venue.exchange === listing.exchange)) return;
1760
- throw new ListingArgError(`${listing.symbol} does not trade on ${listing.exchange}.${tradesOn(listing.symbol, venues)}`, hint ?? undefined);
1832
+ throw new ListingArgError(await notTradedText(listing, venues, deps), hint ?? undefined);
1761
1833
  }
1762
1834
 
1763
1835
  /**
@@ -1958,9 +2030,10 @@ async function japaneseNameListing(
1958
2030
  * symbol, and for a name search finds no listing for, which then fails as a
1959
2031
  * symbol would.
1960
2032
  */
1961
- async function companyNameListingArg(raw: string, deps: ListingDeps): Promise<ListingArg | null> {
2033
+ async function companyNameListingArg(raw: string, deps: ListingDeps): Promise<{ listing: ListingArg; found: CompanyNameListing } | null> {
1962
2034
  const typed = stripStrayEdges(raw).text || raw;
1963
- return isCompanyNameInput(typed) ? readCompanyName(typed, deps) : null;
2035
+ const found = isCompanyNameInput(typed) ? await findCompanyName(typed, deps) : null;
2036
+ return found ? { listing: companyListingArg(typed, found), found } : null;
1964
2037
  }
1965
2038
 
1966
2039
  /** `Read "crude oil" as CL=F (WTI Crude Oil), the benchmark future; Brent is BZ=F.` */
@@ -2104,11 +2177,6 @@ function movedWithoutQuote(change: ListingFate["change"], name: string | null):
2104
2177
  return moved && sameCompany(name, moved.issuer) ? moved : null;
2105
2178
  }
2106
2179
 
2107
- async function readCompanyName(typed: string, deps: Pick<ListingDeps, "dataProvider">, options: { oneWord?: boolean } = {}): Promise<ListingArg | null> {
2108
- const found = await findCompanyName(typed, deps, options);
2109
- return found ? companyListingArg(typed, found) : null;
2110
- }
2111
-
2112
2180
  function companyListingArg(typed: string, found: CompanyNameListing): ListingArg {
2113
2181
  const key = found.exchange ? `${found.symbol}:${found.exchange}` : found.symbol;
2114
2182
  // A fund or an index carrying the name asks about the company's stock: "Did you mean JPM (JPMorgan Chase & Co.)?".