gloomberb 0.20.0 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/package.json +1 -1
  2. package/patches/electrobun-devkit@2.0.5.patch +268 -8
  3. package/src/api-client/crypto-markets.ts +20 -2
  4. package/src/api-client/fund-facts.ts +23 -1
  5. package/src/api-client/types/filings-and-calls.ts +6 -0
  6. package/src/app/runtime/plugin-seed.ts +119 -0
  7. package/src/app/runtime/startup.ts +45 -9
  8. package/src/app.tsx +1 -0
  9. package/src/cli/board-coins.ts +38 -5
  10. package/src/cli/commands/crypto-hints.ts +8 -1
  11. package/src/cli/commands/market.ts +29 -26
  12. package/src/cli/commands/overview.ts +13 -6
  13. package/src/cli/commands/ticker.ts +61 -14
  14. package/src/cli/company-name-hint.ts +19 -0
  15. package/src/cli/entry.ts +10 -4
  16. package/src/cli/glossary.ts +25 -0
  17. package/src/cli/helpers.ts +4 -2
  18. package/src/cli/not-a-ticker.ts +26 -1
  19. package/src/cli/pane-functions/freshness.ts +45 -29
  20. package/src/cli/pane-functions/market-session.ts +14 -5
  21. package/src/cli/restore-plugins.ts +164 -51
  22. package/src/components/chart-table/header.tsx +10 -1
  23. package/src/components/chart-table/layout.ts +14 -5
  24. package/src/components/command-bar/panel/index.tsx +13 -0
  25. package/src/components/command-bar/panel/layout.ts +7 -0
  26. package/src/components/command-bar/panel/runtime.ts +1 -0
  27. package/src/components/command-bar/panel/types.ts +2 -0
  28. package/src/i18n/es.ts +3 -0
  29. package/src/i18n/ja.ts +3 -0
  30. package/src/i18n/ko.ts +3 -0
  31. package/src/i18n/zh-cn.ts +3 -0
  32. package/src/i18n/zh-tw.ts +3 -0
  33. package/src/market-data/fund-facts.ts +7 -1
  34. package/src/market-data/market/change-basis.ts +20 -0
  35. package/src/market-data/market/format.ts +62 -2
  36. package/src/market-data/market/futures-week.ts +3 -1
  37. package/src/plugins/builtin/chart-composer/headless.ts +57 -17
  38. package/src/plugins/builtin/chart-composer/session-range.ts +82 -3
  39. package/src/plugins/builtin/correlation/compute.ts +8 -2
  40. package/src/plugins/builtin/correlation/headless.ts +10 -9
  41. package/src/plugins/builtin/correlation/history.ts +30 -0
  42. package/src/plugins/builtin/correlation/matrix/model.ts +10 -10
  43. package/src/plugins/builtin/correlation/relationship/model.ts +3 -6
  44. package/src/plugins/builtin/correlation/relationship/pane.tsx +1 -2
  45. package/src/plugins/builtin/crypto-board/client.ts +6 -1
  46. package/src/plugins/builtin/crypto-board/defi-view.tsx +12 -1
  47. package/src/plugins/builtin/crypto-board/defi.ts +44 -7
  48. package/src/plugins/builtin/crypto-board/headless.ts +83 -12
  49. package/src/plugins/builtin/crypto-board/model.ts +30 -6
  50. package/src/plugins/builtin/crypto-board/pane.tsx +13 -2
  51. package/src/plugins/builtin/perps/headless.ts +8 -2
  52. package/src/plugins/builtin/risk-factors/index.tsx +2 -28
  53. package/src/plugins/builtin/risk-factors/lock-note.ts +58 -0
  54. package/src/plugins/builtin/risk-factors/pane.tsx +10 -3
  55. package/src/plugins/builtin/scanner/hilo-model.ts +4 -3
  56. package/src/plugins/builtin/sec/fund-facts.ts +45 -11
  57. package/src/plugins/builtin/sec/headless.ts +30 -1
  58. package/src/plugins/builtin/sec/index.tsx +26 -5
  59. package/src/plugins/builtin/shared/pro-lock-note.ts +5 -1
  60. package/src/plugins/builtin/ticker-detail/overview/model.ts +14 -6
  61. package/src/plugins/builtin/time-sales/headless.ts +23 -7
  62. package/src/plugins/builtin/time-sales/index.tsx +2 -2
  63. package/src/plugins/extracted-plugins.ts +49 -24
  64. package/src/plugins/installer.ts +220 -31
  65. package/src/plugins/running-installs.ts +34 -0
  66. package/src/plugins/seed-progress.ts +72 -0
  67. package/src/renderers/electrobun/bun/desktop/backend.ts +14 -0
  68. package/src/renderers/electrobun/bun/desktop/host-requests.ts +14 -7
  69. package/src/renderers/electrobun/bun/desktop/initialization.ts +24 -14
  70. package/src/renderers/electrobun/bun/index.ts +5 -0
  71. package/src/renderers/electrobun/bun/window/context-menu-thread.ts +84 -0
  72. package/src/renderers/electrobun/bun/window/native-call-thread.ts +224 -0
  73. package/src/renderers/electrobun/bun/window/native-timing.ts +10 -0
  74. package/src/renderers/electrobun/bun/window/script-for-webview.ts +15 -0
  75. package/src/renderers/electrobun/bun/window/webview-script-thread.ts +82 -0
  76. package/src/renderers/electrobun/shared/protocol.ts +13 -2
  77. package/src/renderers/electrobun/view/backend-rpc.ts +7 -0
  78. package/src/renderers/electrobun/view/cli-pane-shot-frame.tsx +1 -1
  79. package/src/renderers/electrobun/view/main.tsx +4 -3
  80. package/src/renderers/opentui/start.tsx +3 -0
  81. package/src/telemetry/stall-reports.ts +21 -4
  82. package/src/utils/main-thread-stall.ts +21 -5
  83. package/src/utils/perf-marks.ts +88 -9
  84. package/src/utils/reported-money.ts +9 -2
  85. package/src/utils/sec.ts +34 -3
  86. package/src/plugins/seed-notice.ts +0 -20
@@ -1,5 +1,6 @@
1
1
  import { apiClient } from "../api-client";
2
2
  import type { CryptoMarketAsset } from "../api-client/crypto-markets";
3
+ import { TOP_COIN_NAMES } from "../utils/crypto-pair";
3
4
  import { logFailure } from "../utils/log-failure";
4
5
 
5
6
  /** A coin on the crypto board as a hint names it: its one symbol and its name. */
@@ -12,10 +13,37 @@ type BoardEntry = Pick<CryptoMarketAsset, "symbol" | "code" | "name" | "marketCa
12
13
 
13
14
  /** How long a hint waits for the board; a slow board leaves the plain search hint. */
14
15
  const BOARD_TIMEOUT_MS = 4_000;
15
- const BARE_NOT_A_TICKER = /Not a ticker: ([A-Za-z0-9]+)\./;
16
+ // A bare word no listing has, or one the data service could not check ("Could not check USDT: ...").
17
+ const BARE_NOT_A_TICKER = /Not a ticker: ([A-Za-z0-9]+)\.|Could not (?:check|look up) [^\s,]+(?:, [^\s,]+)*: /;
18
+
19
+ /**
20
+ * The largest stablecoins, by the code and name the board gives them, which
21
+ * the coins people type bare most often are (USDT, USDC). With the largest
22
+ * coins (TOP_COIN_NAMES) they stand in for a board that cannot be read, as in
23
+ * an outage of the data service that also left the word unchecked.
24
+ */
25
+ const STABLECOIN_NAMES: ReadonlyArray<readonly [string, string]> = [
26
+ ["USDT", "Tether USDt"],
27
+ ["USDC", "USDC"],
28
+ ["USDS", "USDS"],
29
+ ["USDE", "Ethena USDe"],
30
+ ["DAI", "Dai"],
31
+ ["USD1", "World Liberty Financial USD"],
32
+ ["PYUSD", "PayPal USD"],
33
+ ["RLUSD", "Ripple USD"],
34
+ ["FDUSD", "First Digital USD"],
35
+ ["TUSD", "TrueUSD"],
36
+ ];
37
+
38
+ const KNOWN_COINS: readonly BoardEntry[] = [
39
+ ...[...TOP_COIN_NAMES].map(([code, name]) => [code, name.replace(/\b\p{Ll}/gu, (letter) => letter.toUpperCase())] as const),
40
+ ...STABLECOIN_NAMES,
41
+ ].map(([code, name]) => ({ symbol: `${code}-USD`, code, name, marketCap: null }));
16
42
 
17
43
  let board: readonly BoardEntry[] | null = null;
18
44
  let loading: Promise<void> | null = null;
45
+ /** The board was asked for and did not come: the known coins answer instead. */
46
+ let unread = false;
19
47
 
20
48
  /**
21
49
  * Reads the crypto board once, when some text says a bare word is not a
@@ -31,7 +59,10 @@ export async function primeBoardCoins(
31
59
  loading ??= Promise.race([
32
60
  load().then((data) => { board = boardEntries(data.assets); }),
33
61
  new Promise<void>((resolve) => { timer = setTimeout(resolve, BOARD_TIMEOUT_MS); }),
34
- ]).catch(logFailure("cli.board-coins", "Read the crypto board for a coin hint failed")).finally(() => clearTimeout(timer));
62
+ ]).catch(logFailure("cli.board-coins", "Read the crypto board for a coin hint failed")).finally(() => {
63
+ clearTimeout(timer);
64
+ if (!board) unread = true;
65
+ });
35
66
  await loading;
36
67
  }
37
68
 
@@ -52,9 +83,10 @@ const compact = (text: string) => text.toUpperCase().replace(/[^\p{L}\p{N}]/gu,
52
83
  */
53
84
  export function boardCoinFor(typed: string): BoardCoin | null {
54
85
  const id = typed.trim().replace(/^\$/, "").toUpperCase();
55
- if (!board || !/^[A-Z0-9]+$/.test(id)) return null;
56
- const byCode = board.filter((coin) => coin.code.toUpperCase() === id);
57
- const byName = byCode.length ? [] : board.filter((coin) => {
86
+ const coins = board ?? (unread ? KNOWN_COINS : null);
87
+ if (!coins || !/^[A-Z0-9]+$/.test(id)) return null;
88
+ const byCode = coins.filter((coin) => coin.code.toUpperCase() === id);
89
+ const byName = byCode.length ? [] : coins.filter((coin) => {
58
90
  const name = compact(coin.name);
59
91
  const first = compact(coin.name.split(/\s+/)[0] ?? "");
60
92
  return name === id || (id.length >= 5 && first === id);
@@ -67,4 +99,5 @@ export function boardCoinFor(typed: string): BoardCoin | null {
67
99
  export function resetBoardCoins(entries: readonly BoardEntry[] | null = null): void {
68
100
  board = entries;
69
101
  loading = null;
102
+ unread = false;
70
103
  }
@@ -5,6 +5,7 @@ import { isCryptoPairSymbol, TOP_COIN_NAMES } from "../../utils/crypto-pair";
5
5
  import { isNotATickerMessage } from "../not-a-ticker";
6
6
  import { groupByCompany } from "../../tickers/company-name";
7
7
  import { DATA_SERVICE_UNREACHABLE_MESSAGE } from "../../utils/network-failure";
8
+ import { serviceDidNotAnswerMessage } from "../../sources/provider-errors";
8
9
  import type { TickerRecord } from "../../types/ticker";
9
10
 
10
11
  /** Where a crypto pair that will not load can still be read. `fn CRYP` takes no argument. */
@@ -101,6 +102,11 @@ function failureReason(message: string, symbol: string): string {
101
102
  return at > 0 ? `${line.slice(0, at)}${line.slice(at + suffix.length)}` : line;
102
103
  }
103
104
 
105
+ /** A reason that says the data service gave no answer at all, not what it found: the symbol was never checked. */
106
+ function unanswered(reason: string): boolean {
107
+ return reason === DATA_SERVICE_UNREACHABLE_MESSAGE || reason.startsWith(serviceDidNotAnswerMessage().split(".")[0]!);
108
+ }
109
+
104
110
  /**
105
111
  * Text-mode notes under a quote table: one line per distinct failure reason (with the crypto board
106
112
  * pointer when a failed symbol is a crypto pair, unless nothing could be reached), then the perpetual futures line.
@@ -118,7 +124,8 @@ export function quoteNotes(results: QuoteNoteResult[]): string[] {
118
124
  // "Not a ticker: APPLE." already names its symbol.
119
125
  isNotATickerMessage(reason)
120
126
  ? reason
121
- : `${symbols.join(", ")}: ${reason}${symbols.some(isCryptoPairSymbol) && reason !== DATA_SERVICE_UNREACHABLE_MESSAGE ? `${/[.!?]$/.test(reason) ? "" : "."} ${CRYPTO_BOARD_HINT}` : ""}`
127
+ // Nothing answered for the symbol, so it is no more a typo than a ticker: the line says it went unchecked.
128
+ : `${unanswered(reason) ? "Could not check " : ""}${symbols.join(", ")}: ${reason}${symbols.some(isCryptoPairSymbol) && reason !== DATA_SERVICE_UNREACHABLE_MESSAGE ? `${/[.!?]$/.test(reason) ? "" : "."} ${CRYPTO_BOARD_HINT}` : ""}`
122
129
  ));
123
130
  const perpetuals = results
124
131
  .filter((result) => result.quote && isCryptoVenuePerpetual(result.quote.instrumentType, result.quote.name))
@@ -16,9 +16,9 @@ import type {
16
16
  Quote,
17
17
  TickerFinancials,
18
18
  } from "../../types/financials";
19
- import { currencyPriceMinDigits, formatMarketPrice, formatMarketPriceWithCurrency, penceFigure, quoteFormatOptions, resolveAssetDisplayKind, withCurrencyMinorDigits } from "../../market-data/market/format";
19
+ import { currencyPriceMinDigits, formatMarketPrice, formatMarketPriceWithCurrency, nearParCoinPriceDigits, penceFigure, quoteFormatOptions, withCurrencyMinorDigits } from "../../market-data/market/format";
20
20
  import { INDEX_POINTS_EXPORT_UNIT, isIndexLevel, reportedQuoteVolume } from "../../market-data/market/index-level";
21
- import { changeBasisJson, changeBasisLabel, changeBasisNote, quoteChangeBasis, quotePreviousCloseDate, quoteSettleText } from "../../market-data/market/change-basis";
21
+ import { changeBasisJson, changeBasisLabel, changeBasisNote, printPredatesChangeBasis, quoteChangeBasis, quotePreviousCloseDate, quoteSettleText } from "../../market-data/market/change-basis";
22
22
  import {
23
23
  EXTENDED_SESSION_LABELS,
24
24
  getExtendedSessionDisplay,
@@ -258,6 +258,7 @@ import {
258
258
  type ListingIdentity,
259
259
  } from "../listing-arg";
260
260
  import { currencyNameMiss, currencyNameStop } from "../currency-name-hint";
261
+ import { liveCompanyQuestion } from "../company-name-hint";
261
262
  import { bareListingNote, listingFateNotes, loadNoQuoteLastTraded, noLongerTradingNote, noQuoteLastTraded, noQuoteLastTradeNote, SUCCESSOR_CHANGE_WAIT_MS, tradingListing, usVenueOf } from "../../tickers/listing-fate";
262
263
  import { isYieldIndexSymbol } from "../../tickers/index-roots";
263
264
  import {
@@ -509,6 +510,8 @@ const QUOTE_LEAD_COLUMNS = [
509
510
  header: "Chg%",
510
511
  align: "right" as const,
511
512
  format: (value: unknown, row: QuoteRow) => {
513
+ // A print older than what the move is from has no move as of now.
514
+ if (row.predatesChangeBasis) return "—";
512
515
  const move = row.yieldIndex ? yieldChangeCell(row) : formatChangePercentCell(value);
513
516
  // Keep a rolling move's short label with the value when narrow tables drop Chg Basis.
514
517
  return move && row.changeBasis === "24h" ? `${move} ${cliStyles.muted("24h")}` : move;
@@ -519,7 +522,8 @@ const QUOTE_LEAD_COLUMNS = [
519
522
  extendedColumn("POST"),
520
523
  extendedColumn("OVERNIGHT"),
521
524
  // An export keeps the market state (PRE-MKT); the table names the close a pre-market with no trade stands at (Thu close).
522
- { key: "session", header: "Session", shrink: false, format: (_value: unknown, row: QuoteRow) => row.sessionLabel },
525
+ // A print older than its move's basis has no session of its own either.
526
+ { key: "session", header: "Session", shrink: false, format: (_value: unknown, row: QuoteRow) => row.predatesChangeBasis ? "—" : row.sessionLabel },
523
527
  ];
524
528
 
525
529
  type QuoteRow = ReturnType<typeof quoteRows>[number];
@@ -617,6 +621,7 @@ function pairExportUnit(symbol: string, currency: string): string | null {
617
621
 
618
622
  function quoteExportStatus(row: QuoteRow): string {
619
623
  if (row.rawPrice == null || !Number.isFinite(row.rawPrice)) return row.error || "Last: no price";
624
+ if (row.predatesChangeBasis) return row.predatesChangeBasis;
620
625
  if (row.changePercent == null || !Number.isFinite(row.changePercent)) return "Chg%: no previous close";
621
626
  return "";
622
627
  }
@@ -697,21 +702,6 @@ function quoteFeedState(quote: QuoteCliRecord["quote"], now: number): "stale" |
697
702
  return quote.dataSource === "live" || quote.dataSource === "delayed" ? quote.dataSource : "";
698
703
  }
699
704
 
700
- /** A hundredth of a cent, one basis point of a dollar peg: the decimals CRYP prints a stablecoin to. */
701
- const STABLECOIN_PRICE_DIGITS = 4;
702
-
703
- /**
704
- * A coin trading near a dollar, a dollar stablecoin, prints to four decimals
705
- * either side of par (0.9987, 1.0003), as CRYP does, whatever digits its
706
- * source sent (0.99874, 0.99968725); below a dollar a coin otherwise keeps up to eight.
707
- */
708
- function nearParCoin(quote: QuoteCliRecord["quote"]): boolean {
709
- if (!quote || resolveAssetDisplayKind({ assetCategory: quote.instrumentType }) !== "crypto") return false;
710
- if ((quote.currency ?? "USD").trim().toUpperCase() !== "USD") return false;
711
- const reference = [quote.previousClose, quote.price].find((value) => typeof value === "number" && Number.isFinite(value) && value > 0);
712
- return reference != null && reference >= 0.9 && reference < 1.1;
713
- }
714
-
715
705
  /** What a row's move is measured from, worded as its Chg Basis cell: empty without a move. */
716
706
  function rowChangeBasis(result: Pick<QuoteCliRecord, "quote" | "futuresContract">) {
717
707
  return quoteChangeBasis(result.quote, { terms: result.futuresContract });
@@ -749,6 +739,10 @@ function quoteSessionFields(quote: Quote | null | undefined) {
749
739
  function quoteRows(results: QuoteCliRecord[], now = Date.now()) {
750
740
  return results.map((result) => {
751
741
  const quote = result.quote;
742
+ // A print older than what its move is from (a coin's last trade before 00:00 UTC) has no move as of now,
743
+ // and the session the market is in is not its own: both read "—", and the Feed cell says it is stale.
744
+ const basis = rowChangeBasis(result);
745
+ const predates = printPredatesChangeBasis(quote, basis, now);
752
746
  // Last and Chg% are the regular session, as `ticker` and the quote monitor read it; a
753
747
  // pre-market or after-hours print is its own column, measured from that session's close.
754
748
  const display = quoteSessionFields(quote);
@@ -758,10 +752,12 @@ function quoteRows(results: QuoteCliRecord[], now = Date.now()) {
758
752
  const indexPoints = isIndexLevel(quote?.instrumentType);
759
753
  // Pad to two decimals so a column lines up, but never past the currency's minor unit (JPY has none).
760
754
  // Points have no minor unit, so a yen-listed index still pads to two.
755
+ const nearParDigits = nearParCoinPriceDigits(quote);
761
756
  const options = {
762
757
  ...quoteFormatOptions(quote),
763
758
  minimumFractionDigits: indexPoints ? 2 : currencyPriceMinDigits(quote?.currency),
764
- ...nearParCoin(quote) ? { fixedFractionDigits: STABLECOIN_PRICE_DIGITS } : {},
759
+ // A coin near a dollar prints to four decimals, as `ticker`, `G` and CRYP print it.
760
+ ...nearParDigits != null ? { fixedFractionDigits: nearParDigits } : {},
765
761
  };
766
762
  const price = (value: number | null | undefined) => (
767
763
  quote && value != null
@@ -780,8 +776,10 @@ function quoteRows(results: QuoteCliRecord[], now = Date.now()) {
780
776
  rawPrice: display.price,
781
777
  priceBasis: quote?.priceBasis ?? null,
782
778
  instrumentType: quote?.instrumentType ?? null,
783
- change: display.change,
784
- changePercent: roundedPercent(display.changePercent ?? undefined),
779
+ change: predates ? null : display.change,
780
+ changePercent: predates ? null : roundedPercent(display.changePercent ?? undefined),
781
+ // Why Chg% is empty when it is for that reason, for an export's status column.
782
+ predatesChangeBasis: !predates ? "" : basis?.kind === "24h" ? "Chg%: last print over 24h old" : "Chg%: last print before 00:00 UTC",
785
783
  // A Cboe yield index is read as a yield in percent and moves in basis points.
786
784
  yieldIndex,
787
785
  changeBasisPoints: yieldIndex && display.change != null ? toBasisPoints(display.change, 1) : null,
@@ -792,8 +790,8 @@ function quoteRows(results: QuoteCliRecord[], now = Date.now()) {
792
790
  extendedChangePercent: roundedPercent(extended?.changePercent),
793
791
  // The extended price is the session's bid and ask midpoint, nothing having traded in it.
794
792
  extendedMark: extended?.mark === true,
795
- session: quoteSessionStateLabel(quote, now) ?? "",
796
- sessionLabel: quoteSessionLabel(quote, now) ?? "",
793
+ session: predates ? "" : quoteSessionStateLabel(quote, now) ?? "",
794
+ sessionLabel: predates ? "" : quoteSessionLabel(quote, now) ?? "",
797
795
  // The close the shown move is measured from: the one before the session Last is.
798
796
  previousClose: price(previousClose),
799
797
  rawPreviousClose: previousClose ?? null,
@@ -812,7 +810,7 @@ function quoteRows(results: QuoteCliRecord[], now = Date.now()) {
812
810
  updatedAt: quote?.lastUpdated ? new Date(quoteHeadlineTime(quote)).toISOString() : "",
813
811
  error: result.error ?? "",
814
812
  // Last, so a row read by position keeps every field where it was.
815
- changeBasis: basisLabel(result, now),
813
+ changeBasis: predates ? "" : basisLabel(result, now),
816
814
  changeBasisNote: changeBasisNote(rowChangeBasis(result), now) ?? "",
817
815
  };
818
816
  });
@@ -1101,6 +1099,10 @@ async function runQuote(rawArgs: string[], ctx: Parameters<CliCommandDef["execut
1101
1099
  const lastTraded = await Promise.all(answers.map(({ result, listing }) => !result.quote && !isNetworkFailure(result.error)
1102
1100
  && answers.length <= MAX_CHOICE_LOOKUPS ? loadNoQuoteLastTraded(listing.request, market.dataProvider, now) : null));
1103
1101
  const endedNotes = answers.map(({ listing }, index) => lastTraded[index] ? `${noQuoteLastTradeNote(listing.symbol, lastTraded[index]!)}.` : null);
1102
+ // A bare symbol whose listing stopped asks after the company by that name that still trades (DBS: D05 on SGX).
1103
+ const liveCompanies = await Promise.all(answers.map(({ result, listing }) => result.quote && !listing.exchange
1104
+ && answers.length <= MAX_CHOICE_LOOKUPS && noLongerTradingNote(listing.symbol, result.quote, now)
1105
+ ? liveCompanyQuestion(listing.typed ?? listing.symbol, market, now) : null));
1104
1106
  if (symbols.length === 1 && endedNotes[0]) ctx.fail(endedNotes[0], quoteChangeLine(tickerChanges[0], formerIssuers[0]) || undefined);
1105
1107
  const failed = answers[0]?.failure;
1106
1108
  if (symbols.length === 1 && failed) {
@@ -1157,10 +1159,11 @@ async function runQuote(rawArgs: string[], ctx: Parameters<CliCommandDef["execut
1157
1159
  ...answers.flatMap((answer) => answer.notes),
1158
1160
  // A row that stopped trading long ago reads as a quote that is merely stale, and one with
1159
1161
  // nothing printed in a session the calendar has open (a feed that stalled, a typhoon day) says since when.
1160
- ...data.flatMap((row) => {
1162
+ ...data.flatMap((row, index) => {
1161
1163
  if (!row.quote) return [];
1162
1164
  const label = `${row.target.symbol}${row.listing.name ? ` (${row.listing.name})` : ""}`;
1163
- const ended = noLongerTradingNote(label, row.quote, now);
1165
+ const stopped = noLongerTradingNote(label, row.quote, now);
1166
+ const ended = stopped && liveCompanies[index] ? `${stopped}. ${liveCompanies[index]}` : stopped;
1164
1167
  const quiet = ended ? null : noPrintsTodayText(row.quote, now);
1165
1168
  return [ended ?? (quiet ? `${label}: ${quiet}` : []), quoteBarNotes(label, row.quote, now)].flat();
1166
1169
  }),
@@ -58,7 +58,7 @@ import { isoDate, rejectExtraArgs, requireArg, requireOneArg, takeFlag, takeOpti
58
58
  import { buildCorrelationSeries } from "../../plugins/builtin/correlation/matrix/model";
59
59
  import { alignDailyCloses, correlateDailyCloses } from "../../plugins/builtin/correlation/compute";
60
60
  import { mixedSessionCloseNote } from "../../market-data/market/session-close-note";
61
- import { CORRELATION_RETURN_BASIS, loadCorrelationHistory } from "../../plugins/builtin/correlation/history";
61
+ import { contradictoryBarsNote, CORRELATION_RETURN_BASIS, loadCorrelationHistory, thinCorrelationNote } from "../../plugins/builtin/correlation/history";
62
62
  import { coinListingNotes, EXCHANGE_OPTION, listingIdentity, listingReadNotes, loadForListing, loadListingQuote, requireCliListing, type CliListing } from "../listing-arg";
63
63
  import { CLI_COMMAND_GROUPS } from "../help";
64
64
  import { formatChangePercentCell, formatCompactCell } from "../helpers";
@@ -886,15 +886,21 @@ async function runCorrelation(rawArgs: string[], ctx: Parameters<CliCommandDef["
886
886
  const right = rightListing!.key;
887
887
  // Same daily-return model as the CORR pane: price levels of two trending
888
888
  // assets correlate spuriously, often with the opposite sign.
889
- const loadSeries = async (listing: CliListing) => buildCorrelationSeries(
890
- listing.key,
891
- await loadForListing(
889
+ const loadSeries = async (listing: CliListing) => {
890
+ const bars = await loadForListing(
892
891
  listing, services, ctx,
893
892
  () => loadCorrelationHistory(services.dataProvider, listing.request.symbol, listing.request.exchange, "1Y"),
894
- ),
895
- );
893
+ );
894
+ return { ...buildCorrelationSeries(listing.key, bars), bars: bars.length };
895
+ };
896
896
  const [leftSeries, rightSeries] = await Promise.all([loadSeries(leftListing!), loadSeries(rightListing!)]);
897
897
  const { correlation, sampleSize } = correlateDailyCloses(leftSeries.prices, rightSeries.prices);
898
+ // The series history reads: contradictory bars are gaps, and a thin pair says which side is short.
899
+ const seriesNotes = [
900
+ ...[leftSeries, rightSeries].filter((series, index) => index === 0 || left !== right)
901
+ .map((series) => contradictoryBarsNote(series.symbol, series.integrity?.length ?? 0, series.bars)),
902
+ thinCorrelationNote({ label: left, closes: leftSeries.prices.length }, { label: right, closes: rightSeries.prices.length }, sampleSize, "1Y"),
903
+ ].filter((note) => note != null);
898
904
  // A bare symbol names no exchange; its quote says where it lists, which sets when its daily close is taken.
899
905
  const [leftQuote, rightQuote] = await Promise.all([leftListing!, rightListing!].map((listing) => loadListingQuote(services.dataProvider, listing)));
900
906
  const sessionNote = mixedSessionCloseNote(
@@ -914,6 +920,7 @@ async function runCorrelation(rawArgs: string[], ctx: Parameters<CliCommandDef["
914
920
  ...listingReadNotes(leftListing!), ...listingReadNotes(rightListing!),
915
921
  ...coinListingNotes(leftListing!, leftQuote), ...coinListingNotes(rightListing!, rightQuote),
916
922
  ...sessionNote ? [sessionNote] : [],
923
+ ...seriesNotes,
917
924
  ];
918
925
  ctx.printResult({
919
926
  data: [{ left, right, samples: sampleSize, correlation }],
@@ -1,6 +1,6 @@
1
1
  import { logFailure } from "../../utils/log-failure";
2
2
  import { formatShortDate, parseDisplayDate } from "../../utils/datetime-format";
3
- import { formatReportedMoney } from "../../utils/reported-money";
3
+ import { formatReportedMoney, REPORTING_CURRENCY_NOT_SOURCED } from "../../utils/reported-money";
4
4
  import {
5
5
  appTtmRate, computedEnterpriseValueNote, convertedPriceEarningsNote, enterpriseValueLabel, enterpriseValueReconciliationNote, epsConversionNote,
6
6
  fundamentalsCurrency, reportedEnterpriseValue, trailingEpsSourceNote, ttmAtAppRate, ttmConversionNote,
@@ -18,7 +18,7 @@ import {
18
18
  formatPercentRaw,
19
19
  MISSING_VALUE,
20
20
  } from "../../utils/format";
21
- import { formatMarketCostWithCurrency, formatMarketPriceWithCurrency, formatMarketQuantity, quoteFormatOptions, withCurrencyMinorDigits, type MarketFormatOptions } from "../../market-data/market/format";
21
+ import { formatMarketCostWithCurrency, formatMarketPriceWithCurrency, formatMarketQuantity, nearParCoinPriceDigits, quoteFormatOptions, withCurrencyMinorDigits, type MarketFormatOptions } from "../../market-data/market/format";
22
22
  import {
23
23
  cliStyles,
24
24
  cliTerminalWidth,
@@ -76,7 +76,7 @@ import {
76
76
  import { NotesFiles } from "../../plugins/builtin/notes/files";
77
77
  import { getFormDescription } from "../../plugins/builtin/sec/model";
78
78
  import { ownerNames, rowSummary, rowSummaryTarget } from "../../plugins/builtin/sec/row-summaries";
79
- import { isKnownNonUsListing, secFilingItemCodes, US_FUND_FACTS_ONLY } from "../../utils/sec";
79
+ import { fundFactsAbroadKey, hasFundFactsAbroad, isKnownNonUsListing, secFilingItemCodes, US_FUND_FACTS_ONLY } from "../../utils/sec";
80
80
  import { currentReportItemsLabel, hiddenFilingsNote, loadLatestFilings, type HiddenFilings } from "../../utils/sec-filings";
81
81
  import { canonicalExchange, exchangeLabel, isKnownExchangeCode, isUsListingExchange } from "../../utils/exchanges";
82
82
  import {
@@ -545,9 +545,36 @@ interface FundamentalsMetric {
545
545
 
546
546
  type MetricFigure = Omit<FundamentalsMetric, "label">;
547
547
 
548
- /** An amount in the currency the source reported it in; `ccy?` when it named none, as the text says. `codes`: per share too (6.54 USD). */
548
+ /**
549
+ * An amount in the currency the source reported it in. One it named none for
550
+ * is bare, with no unit, and a note under the block says so
551
+ * (unsourcedCurrencyNote). `codes`: per share too (6.54 USD).
552
+ */
549
553
  function reportedMoney(value: number | undefined, currency: string | undefined, perShare = false, codes = false): MetricFigure {
550
- return { text: formatReportedMoney(value, currency, perShare, codes), value, unit: currency?.trim() || "ccy?" };
554
+ const unit = currency?.trim();
555
+ return { text: formatReportedMoney(value, currency, perShare, codes), value, ...(unit ? { unit } : {}) };
556
+ }
557
+
558
+ /**
559
+ * What a US stock or fund line's day range from Gloom Cloud counts: its
560
+ * regular session's prints on every US venue that set a price, odd lots
561
+ * excluded, as GIP's bars and TAS's session range count them. Null for a
562
+ * future, a coin, a listing abroad or another source's quote.
563
+ */
564
+ function consolidatedRangeBasis(quote: Quote): string | null {
565
+ const venue = quote.listingExchangeName || quote.exchangeName || "";
566
+ if (quote.providerId !== "gloomberb-cloud" || !isUsListingExchange(venue) || quote.instrumentType === "FUTURE"
567
+ || isRoundTheClockCoin(quote.symbol ?? "", venue)) return null;
568
+ return "regular session, every US venue, odd lots excluded";
569
+ }
570
+
571
+ /** `Reporting currency not sourced for EPS (TTM) and Revenue (TTM).`: the trailing amounts shown bare. */
572
+ function unsourcedCurrencyNote(metrics: readonly FundamentalsMetric[]): string | undefined {
573
+ const bare = metrics.filter((metric) => TRAILING_MONEY_METRICS.has(metric.label) && metric.text !== "—" && !metric.unit)
574
+ .map((metric) => metric.label);
575
+ if (bare.length === 0) return undefined;
576
+ const list = bare.length === 1 ? bare[0]! : `${bare.slice(0, -1).join(", ")} and ${bare.at(-1)}`;
577
+ return `${REPORTING_CURRENCY_NOT_SOURCED[0]!.toUpperCase()}${REPORTING_CURRENCY_NOT_SOURCED.slice(1)} for ${list}.`;
551
578
  }
552
579
 
553
580
  /**
@@ -729,9 +756,12 @@ export async function loadReportFundFacts(
729
756
  tickerFile: TickerRecord | null = null,
730
757
  load: (symbol: string) => Promise<FundFactsPayload> = (ticker) => readFundFacts(ticker),
731
758
  ): Promise<FundFactsPayload | null> {
732
- if (resolveTickerInstrumentKind(tickerFile, financials) !== "fund" || (exchange && !isUsListingExchange(exchange))) return null;
759
+ // A fund abroad has none, but for Hong Kong's spot coin funds, which the server answers for.
760
+ if (resolveTickerInstrumentKind(tickerFile, financials) !== "fund"
761
+ || (exchange && !isUsListingExchange(exchange) && !hasFundFactsAbroad(exchange))) return null;
733
762
  try {
734
- return await load(symbol);
763
+ // Hong Kong's by its listing's key (3046:XHKG), so the server does not read a bare 3046 as a US ticker.
764
+ return await load(exchange && hasFundFactsAbroad(exchange) ? fundFactsAbroadKey(symbol, exchange) : symbol);
735
765
  } catch (error) {
736
766
  logFailure("cli.commands-ticker", "Read fund facts failed")(error);
737
767
  return null;
@@ -880,7 +910,8 @@ function fundamentalsNotes(
880
910
  : undefined;
881
911
  // A cap Gloom Cloud withheld says why, as RV and EQS do.
882
912
  const withheld = withheldMarketCap(fundamentals)?.note;
883
- return [withheld, shareBasis, enterpriseValue, conversion, eps, epsSource, priceEarnings].filter((note): note is string => !!note);
913
+ return [withheld, shareBasis, enterpriseValue, conversion, eps, epsSource, priceEarnings, unsourcedCurrencyNote(metrics)]
914
+ .filter((note): note is string => !!note);
884
915
  }
885
916
 
886
917
  // The share count is the market cap's basis: the cap is the count times the price, or a note says why not.
@@ -931,7 +962,7 @@ function fundFactsNote(
931
962
  facts: FundFactsPayload | null = null,
932
963
  ): string | null {
933
964
  if (resolveTickerInstrumentKind(tickerFile, financials) !== "fund") return null;
934
- if (exchange && !isUsListingExchange(exchange)) return US_FUND_FACTS_ONLY;
965
+ if (exchange && !isUsListingExchange(exchange) && !facts?.covered) return US_FUND_FACTS_ONLY;
935
966
  if (!facts?.covered) return null;
936
967
  const figures = [facts.expenseRatio && "fee", facts.nav && "NAV", facts.premiumDiscount && "premium", facts.netAssets && "net assets"]
937
968
  .filter((figure): figure is string => !!figure);
@@ -944,14 +975,20 @@ function fundFactsNote(
944
975
  * close's move), and a pre-market, after-hours or overnight print is a line
945
976
  * of its own, measured from that close.
946
977
  */
978
+ /** A coin near a dollar prints to four decimals, as `quote`, `G` and CRYP print it: $0.9989, not $0.99886. */
979
+ function withNearParCoinDigits(options: MarketFormatOptions, quote: Quote | null | undefined): MarketFormatOptions {
980
+ const digits = nearParCoinPriceDigits(quote);
981
+ return digits == null ? options : { ...options, fixedFractionDigits: digits };
982
+ }
983
+
947
984
  function valuationPriceMetrics(financials: FundamentalsReportData): FundamentalsMetric[] {
948
985
  const quote = financials.quote;
949
986
  const session = getRegularSessionDisplay(quote);
950
987
  if (!quote || !session) return [];
951
- const options = withCurrencyMinorDigits({
988
+ const options = withNearParCoinDigits(withCurrencyMinorDigits({
952
989
  ...quoteFormatOptions(quote, undefined, financials.quoteMetadata?.instrumentType),
953
990
  ...financials.currencyCodes ? { currencyCode: true } : {},
954
- }, quote.currency);
991
+ }, quote.currency), quote);
955
992
  const price = (value: number) => formatMarketPriceWithCurrency(value, quote.currency, options);
956
993
  const extended = getExtendedSessionDisplay(quote);
957
994
  const extendedLabel = extended ? EXTENDED_SESSION_LABELS[extended.session] : "";
@@ -1204,7 +1241,10 @@ export async function buildTickerReport({
1204
1241
  boughtAt: boughtRateCurrencies(tickerFile, quote?.currency?.trim() || tickerFile?.metadata.currency?.trim() || "", config.baseCurrency),
1205
1242
  };
1206
1243
  // Pad money prices to the currency's minor unit so a range reads £35.10 - £35.485, never past it (JPY has none).
1207
- const quoteOptions = withCurrencyMinorDigits(codes ? { ...baseQuoteOptions, currencyCode: true } : baseQuoteOptions, quote?.currency);
1244
+ const quoteOptions = withNearParCoinDigits(
1245
+ withCurrencyMinorDigits(codes ? { ...baseQuoteOptions, currencyCode: true } : baseQuoteOptions, quote?.currency),
1246
+ quote,
1247
+ );
1208
1248
  const lines: string[] = [];
1209
1249
 
1210
1250
  lines.push(`${cliStyles.accent(quote?.symbol ?? symbol)} ${cliStyles.bold(name)}`);
@@ -1312,9 +1352,10 @@ export async function buildTickerReport({
1312
1352
  // European gas beside Henry Hub: "≈ $30.832/MMBtu at EUR/USD 1.1650", a conversion that says so.
1313
1353
  ...usdPerMmbtu ? [["In USD", usdPerMmbtuText(usdPerMmbtu)] as [string, string]] : [],
1314
1354
  ["Open", quote.open != null ? formatMarketPriceWithCurrency(quote.open, quote.currency, quoteOptions) : "—"],
1315
- // A listing that no longer trades: its last session's range, never today's.
1355
+ // A listing that no longer trades: its last session's range, never today's. A US line's says what it counts,
1356
+ // the rule GIP and TAS read the session's low and high by.
1316
1357
  [quote.delisting ? "Last Session" : "Day Range", quote.low != null || quote.high != null
1317
- ? formatPriceRange(quote.low, quote.high, quote.currency, quoteOptions)
1358
+ ? `${formatPriceRange(quote.low, quote.high, quote.currency, quoteOptions)}${consolidatedRangeBasis(quote) ? ` (${consolidatedRangeBasis(quote)})` : ""}`
1318
1359
  : "—"],
1319
1360
  ["52W Range", quote.low52w != null || quote.high52w != null
1320
1361
  ? formatPriceRange(quote.low52w, quote.high52w, quote.currency, quoteOptions)
@@ -1370,15 +1411,21 @@ export async function buildTickerReport({
1370
1411
  lines.push(cliStyles.muted(`Market cap: ${describeFundamentalMarketCap(capitalization.provenance)}.`));
1371
1412
  }
1372
1413
 
1414
+ // A statement whose currency no source names reads bare, and says so once under its amounts.
1415
+ const unsourced = (row: FinancialStatement) => {
1416
+ if (!statementCurrency(row)) lines.push(cliStyles.muted(`${REPORTING_CURRENCY_NOT_SOURCED[0]!.toUpperCase()}${REPORTING_CURRENCY_NOT_SOURCED.slice(1)}.`));
1417
+ };
1373
1418
  if (latestAnnual) {
1374
1419
  appendMetricSection(lines, `Latest Annual (${statementPeriodText(latestAnnual.date, statementFilings?.latestAnnual ?? null)})`,
1375
1420
  buildStatementMetrics(latestAnnual, statementCurrency(latestAnnual), codes));
1421
+ unsourced(latestAnnual);
1376
1422
  }
1377
1423
 
1378
1424
  if (latestQuarter) {
1379
1425
  const runway = cashRunway(financials);
1380
1426
  appendMetricSection(lines, `Latest Quarter (${statementPeriodText(latestQuarter.date, statementFilings?.latestQuarter ?? null)})`,
1381
1427
  buildStatementMetrics(latestQuarter, statementCurrency(latestQuarter), codes, runway));
1428
+ unsourced(latestQuarter);
1382
1429
  // How the months are counted, and an offering since the balance sheet that the cash does not include yet.
1383
1430
  if (burnsCash(runway)) lines.push(cliStyles.muted(runwayMethod(runway.includesShortTerm)));
1384
1431
  const offering = runway ? offeringNote(offeringsAfter(offerings, runway.periodEnd), runway.periodEnd) : null;
@@ -2,6 +2,9 @@ import type { CliListing } from "./listing-arg";
2
2
  import { companyNameSuggestion, isUnsettledNoProvider, type ListingDeps } from "./listing-arg";
3
3
  import { describeSuggestion } from "./listing-suggestion";
4
4
  import { isNotATickerMessage, withListingSuggestion } from "./not-a-ticker";
5
+ import { tradingListing } from "../tickers/listing-fate";
6
+ import { parsePublicTickerKey } from "../utils/exchanges";
7
+ import { logFailure } from "../utils/log-failure";
5
8
 
6
9
  type SearchDeps = Pick<ListingDeps, "dataProvider">;
7
10
 
@@ -39,3 +42,19 @@ export async function notATickerStop(
39
42
  if (!suggestion) return notATicker ? message : null;
40
43
  return withListingSuggestion(notATicker ? message! : `Not a ticker: ${listing.symbol}.`, describeSuggestion(suggestion));
41
44
  }
45
+
46
+ /**
47
+ * "Did you mean D05:SGX (DBS Group Holdings Ltd.)?", for a bare symbol whose
48
+ * listing stopped trading (DBS, the Invesco silver fund delisted in 2023)
49
+ * when search names a company by the symbol that still trades. Null when
50
+ * search names none, names the symbol itself, or the company's line has
51
+ * stopped too. Never throws.
52
+ */
53
+ export async function liveCompanyQuestion(typed: string, deps: SearchDeps, now = Date.now()): Promise<string | null> {
54
+ const suggestion = await companyNameSuggestion(typed, deps);
55
+ if (!suggestion) return null;
56
+ const { symbol, exchange } = parsePublicTickerKey(suggestion.symbol);
57
+ const quote = await deps.dataProvider.getQuote(symbol, exchange ?? "")
58
+ .catch(logFailure("cli.company-name-hint", "Quote a company suggested for a stopped symbol failed", null));
59
+ return quote && tradingListing(quote, now) ? `Did you mean ${describeSuggestion(suggestion)}?` : null;
60
+ }
package/src/cli/entry.ts CHANGED
@@ -22,17 +22,23 @@ import {
22
22
  async function launchOpenTuiApp(cliLaunchRequest: CliLaunchRequest | null = null): Promise<void> {
23
23
  // Before anything in the app can reach for the render library, so a temp
24
24
  // folder that cannot run it is worked around (or named) first.
25
- const { restoreExtractedPlugins } = await import("./restore-plugins");
25
+ const { prepareExtractedPluginSeed } = await import("./restore-plugins");
26
26
  const { loadExternalPlugins } = await import("../plugins/loader");
27
27
  const { loadRenderLib } = await import("../renderers/opentui/render-lib");
28
28
  await measurePerfAsync("startup.opentui.render-lib", loadRenderLib);
29
29
  const { startOpenTuiApp } = await import("../renderers/opentui/start");
30
- // Before the catalog is read, so a plugin that moved out of this repository is
31
- // available in the same session rather than only after a restart.
32
- await measurePerfAsync("startup.opentui.restore-plugins", restoreExtractedPlugins);
30
+ // Plugins that moved out of this repository are planned before the config
31
+ // is read, which records the ones already settled, and installed once the
32
+ // app is drawn: cloning them first held a blank screen for seconds, or for
33
+ // good on a connection that hangs. The app brings each in as it lands.
34
+ const seed = await measurePerfAsync("startup.opentui.restore-plugins", () => prepareExtractedPluginSeed());
33
35
  const externalPlugins = await measurePerfAsync("startup.opentui.load-external-plugins", () => loadExternalPlugins("tui"));
34
36
  try {
35
37
  await startOpenTuiApp({ externalPlugins, cliLaunchRequest });
38
+ if (seed?.start) {
39
+ const { logFailure } = await import("../utils/log-failure");
40
+ void seed.start().catch(logFailure("plugin-seed", "Plugin restore failed"));
41
+ }
36
42
  } catch (error) {
37
43
  // A failed launch still prints and exits as before; the report is only
38
44
  // sent when the config was read far enough to install the reporter.
@@ -369,6 +369,31 @@ export const GLOSSARY: readonly GlossaryEntry[] = [
369
369
  definition: "How far a perpetual's price sits above or below the reference price it tracks, as a percent. "
370
370
  + "Positive means buyers are paying up for the contract; funding pulls it back toward zero.",
371
371
  },
372
+ // Stablecoins (CRYP --list stablecoin).
373
+ {
374
+ term: "Off peg", aliases: ["off-peg", "peg", "depeg", "de-peg", "peg deviation", "stablecoin peg"], functions: ["CRYP"],
375
+ definition: "How far a stablecoin trades from its peg, in basis points: (price ÷ peg − 1) × 10,000, the peg being $1 for a dollar coin "
376
+ + "and the EUR/USD rate for a euro coin (Peg EUR 1.1194). A coin whose Peg reads USD yield (yield accrues into its price) or USD bond "
377
+ + "(a bond token priced toward a dollar at maturity) has no par to be off, so it shows none.",
378
+ },
379
+ {
380
+ term: "24h low/high", aliases: ["24h low", "24h high", "24-hour low", "24-hour high", "24h range", "low utc", "high utc"], functions: ["CRYP"],
381
+ shown: ["24h low", "24h high", "Low UTC", "High UTC"],
382
+ definition: "A stablecoin's lowest and highest trade over the rolling 24 hours to the board's time, not since midnight, "
383
+ + "with when each traded in UTC (Low UTC, High UTC). A newer price outside them becomes the low or the high.",
384
+ },
385
+ {
386
+ term: "Supply", aliases: ["stablecoin supply", "total supply", "supply 7d", "supply 30d", "supply change"], functions: ["CRYP"],
387
+ shown: ["Supply", "Total supply"],
388
+ definition: "The dollar value of a stablecoin's coins in circulation, from a daily series that ends on the previous day: "
389
+ + "the line above the table gives its as-of date. Supply 7D and Supply 30D are its change over those days, in dollars and in percent; "
390
+ + "supply grows as coins are issued and shrinks as they are redeemed.",
391
+ },
392
+ {
393
+ term: "Share", aliases: ["supply share", "share of supply", "tvl share"], functions: ["CRYP"],
394
+ definition: "A stablecoin's part of all stablecoin supply, in percent, on the same previous-day series as Supply. "
395
+ + "On the DeFi chain list, a chain's part of all value locked.",
396
+ },
372
397
  // Portfolio weights and rebalancing (PF, portfolio show).
373
398
  {
374
399
  term: "Weight", aliases: ["weights", "portfolio weight", "allocation weight"], functions: ["PF"],
@@ -6,7 +6,7 @@ import {
6
6
  formatPercentRaw,
7
7
  } from "../utils/format";
8
8
  import { formatMarketChangeWithCurrency, formatMarketPriceWithCurrency, type MarketFormatOptions } from "../market-data/market/format";
9
- import { changeBasisLabel, changeBasisNote, quoteChangeBasis } from "../market-data/market/change-basis";
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";
12
12
  import type { Quote } from "../types/financials";
@@ -39,11 +39,13 @@ export function quoteChangeText(
39
39
  ): string {
40
40
  // A listing that no longer trades: its last close moves no more.
41
41
  if (quote.delisting) return "—";
42
+ const basis = quoteChangeBasis(quote, { terms });
43
+ // A print older than what its move is from (a coin's before 00:00 UTC) has no move as of now, as `quote` says.
44
+ if (printPredatesChangeBasis(quote, basis, now)) return "—";
42
45
  const move = colorBySign(
43
46
  `${formatMarketChangeWithCurrency(session.change, quote.currency ?? "USD", options, session.price)} (${formatPercentRaw(session.changePercent)})`,
44
47
  session.change,
45
48
  );
46
- const basis = quoteChangeBasis(quote, { terms });
47
49
  if (!basis) return move;
48
50
  const note = changeBasisNote(basis, now);
49
51
  return `${move} ${cliStyles.muted(changeBasisLabel(basis, now))}${note ? `\n${cliStyles.muted(note)}` : ""}`;
@@ -45,7 +45,7 @@ export type FredSeriesCheck = (seriesId: string) => boolean;
45
45
  * "APPLE" as AAPL:NASDAQ") is put back in the user's spelling too.
46
46
  */
47
47
  export function withSearchHints(text: string, args: readonly string[], isFredSeries: FredSeriesCheck = () => false): string {
48
- const named = withTypedNames(text, args);
48
+ const named = withCoinHints(withTypedNames(text, args), args);
49
49
  return named.includes("Not a ticker: ")
50
50
  ? named.replace(NOT_A_TICKER_SENTENCE, (sentence, symbol: string) => {
51
51
  const typed = typedSymbol(symbol, args);
@@ -60,6 +60,31 @@ export function withSearchHints(text: string, args: readonly string[], isFredSer
60
60
  : named;
61
61
  }
62
62
 
63
+ // "Could not check USDT, FOOBARX: ..." as `quote` says the symbols the data service did not answer for, and "Could not
64
+ // look up USDT: ..." as a command that resolves one says it; a hint already given is not given twice.
65
+ const UNCHECKED_LINE = /^((?:.*?\b)?Could not (?:check|look up) ([^\s,]+(?:, [^\s,]+)*): [^\n]*?)(?<! Did you mean [^\n]*)$/gm;
66
+
67
+ /**
68
+ * The coin a bare word the data service could not check may be, after the
69
+ * line that says so: "Did you mean USDT-USD (Tether USDt)?", "... for USDT"
70
+ * when the line names several. The coins come from the crypto board, or when
71
+ * it cannot be read either (the same service is down), the largest coins this
72
+ * build knows (`boardCoinFor`), so the hint stands in an outage.
73
+ */
74
+ function withCoinHints(text: string, args: readonly string[]): string {
75
+ if (!text.includes("Could not ")) return text;
76
+ return text.replace(UNCHECKED_LINE, (line, _whole, list: string) => {
77
+ const symbols = list.split(",").map((symbol) => symbol.trim()).filter(Boolean);
78
+ const hints = symbols.flatMap((symbol) => {
79
+ const coin = boardCoinFor(typedSymbol(symbol, args).toUpperCase());
80
+ if (!coin) return [];
81
+ const name = coin.name && coin.name.toUpperCase() !== coin.symbol ? ` (${coin.name})` : "";
82
+ return [`${coin.symbol}${name}${symbols.length > 1 ? ` for ${symbol}` : ""}`];
83
+ });
84
+ return hints.length ? `${line}${/[.!?]$/.test(line) ? "" : "."} Did you mean ${hints.join(", or ")}?` : line;
85
+ });
86
+ }
87
+
63
88
  // "Read "APPLE" as AAPL:NASDAQ (Apple Inc.)." as a list reads a one-word name, upper-cased like a symbol.
64
89
  const READ_AS_NAME = /Read "([^"\n]+)" as /g;
65
90