@gloom-sh/terminal 0.20.22 → 0.20.23

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 (195) hide show
  1. package/package.json +1 -1
  2. package/src/account/heard-from-question.tsx +6 -4
  3. package/src/account/heard-from.ts +3 -4
  4. package/src/api-client/exchange-announcements.ts +2 -2
  5. package/src/api-client/heard-from.ts +5 -7
  6. package/src/api-client/ownership-disclosures.ts +38 -5
  7. package/src/api-client/types/ticker-data.ts +3 -1
  8. package/src/architecture/dom-cell-metrics-allowlist.json +2 -2
  9. package/src/cli/commands/market.ts +5 -3
  10. package/src/cli/commands/overview.ts +7 -9
  11. package/src/cli/listing-arg.ts +45 -18
  12. package/src/cli/pane-functions/catalog-snapshot.json +2 -2
  13. package/src/cli/pane-functions/data.ts +3 -1
  14. package/src/cli/pane-functions/freshness.ts +6 -1
  15. package/src/cli/pane-functions/function-help.ts +0 -2
  16. package/src/cli/pane-functions/market-session.ts +12 -2
  17. package/src/cli/pane-functions/screenshot-payload.ts +3 -1
  18. package/src/cli/symbol-list.ts +52 -14
  19. package/src/cli/ticker-resolution.ts +133 -38
  20. package/src/components/chart/composite/composite-chart.tsx +12 -0
  21. package/src/components/chart/composite/types.ts +18 -0
  22. package/src/components/chart/composite/use-composite-chart-keyboard.ts +38 -15
  23. package/src/components/chart-table/header.tsx +11 -5
  24. package/src/components/chart-table/selection.ts +20 -1
  25. package/src/components/data-table/view.tsx +2 -0
  26. package/src/components/feed-data-table/stack-view.tsx +85 -5
  27. package/src/components/layout/pane/header.tsx +12 -30
  28. package/src/components/ticker/badge/index.tsx +9 -4
  29. package/src/components/ticker/badge/list.tsx +3 -1
  30. package/src/components/ui/data-table/index.tsx +7 -1
  31. package/src/components/ui/data-table/muted-row.tsx +47 -0
  32. package/src/components/ui/data-table/opentui/index.tsx +42 -11
  33. package/src/components/ui/data-table/spill.ts +36 -0
  34. package/src/components/ui/data-table/types.ts +17 -1
  35. package/src/components/ui/data-table/use-column-order.ts +11 -0
  36. package/src/components/ui/icon.tsx +50 -3
  37. package/src/components/ui/list-view.tsx +2 -2
  38. package/src/components/ui/table-layout.ts +32 -0
  39. package/src/components/ui/terminal-hover-label.tsx +49 -0
  40. package/src/components/use-pinned-moment.ts +222 -13
  41. package/src/core/state/app/state.ts +11 -2
  42. package/src/core/state/app/types.ts +2 -1
  43. package/src/data/sqlite/access.ts +14 -1
  44. package/src/data/sqlite/checkpointer.ts +2 -2
  45. package/src/data/sqlite/database.ts +4 -0
  46. package/src/docs/snapshot.json +180 -26
  47. package/src/i18n/es.ts +1 -0
  48. package/src/i18n/ja.ts +1 -0
  49. package/src/i18n/ko.ts +1 -0
  50. package/src/i18n/zh-cn.ts +1 -0
  51. package/src/i18n/zh-tw.ts +1 -0
  52. package/src/market-data/market/freshness.ts +2 -2
  53. package/src/market-data/market/globex-day.ts +14 -0
  54. package/src/market-data/published-us-sessions.ts +3 -2
  55. package/src/market-data/quotes/live-valuation.ts +4 -2
  56. package/src/market-data/quotes/metadata.ts +48 -5
  57. package/src/market-data/quotes/regular-session-valuation.ts +12 -1
  58. package/src/plugins/builtin/alerts/history-pane.tsx +19 -3
  59. package/src/plugins/builtin/broker-trading/orders.tsx +4 -2
  60. package/src/plugins/builtin/chat/attachments/desktop.tsx +46 -12
  61. package/src/plugins/builtin/chat/channels.ts +5 -2
  62. package/src/plugins/builtin/chat/content/composer-runtime.ts +64 -65
  63. package/src/plugins/builtin/chat/content/footer.tsx +17 -7
  64. package/src/plugins/builtin/chat/content/index.tsx +108 -36
  65. package/src/plugins/builtin/chat/content/new-dm-dialog.tsx +21 -8
  66. package/src/plugins/builtin/chat/content/selection-runtime.ts +16 -0
  67. package/src/plugins/builtin/chat/content/shortcuts.ts +3 -0
  68. package/src/plugins/builtin/chat/content/snapshot.ts +37 -13
  69. package/src/plugins/builtin/chat/content/transcript.tsx +12 -0
  70. package/src/plugins/builtin/chat/content/types.ts +2 -0
  71. package/src/plugins/builtin/chat/controller/channels.ts +15 -15
  72. package/src/plugins/builtin/chat/controller/index.ts +140 -34
  73. package/src/plugins/builtin/chat/controller/lifecycle.ts +8 -12
  74. package/src/plugins/builtin/chat/controller/persistence.ts +32 -4
  75. package/src/plugins/builtin/chat/controller/send.ts +41 -17
  76. package/src/plugins/builtin/chat/controller/session-runtime.ts +28 -27
  77. package/src/plugins/builtin/chat/controller/state.ts +17 -8
  78. package/src/plugins/builtin/chat/controller/storage.ts +41 -4
  79. package/src/plugins/builtin/chat/controller/view.ts +6 -3
  80. package/src/plugins/builtin/chat/index.tsx +1 -1
  81. package/src/plugins/builtin/chat/layout.ts +8 -1
  82. package/src/plugins/builtin/chat/message/desktop.tsx +15 -11
  83. package/src/plugins/builtin/chat/message/header.tsx +112 -30
  84. package/src/plugins/builtin/chat/message/reactions.tsx +10 -11
  85. package/src/plugins/builtin/chat/message/render-state.ts +4 -2
  86. package/src/plugins/builtin/chat/message/terminal.tsx +13 -15
  87. package/src/plugins/builtin/chat/message/types.ts +5 -0
  88. package/src/plugins/builtin/cloud-tweets/table.tsx +25 -2
  89. package/src/plugins/builtin/company-kpis/model.ts +11 -3
  90. package/src/plugins/builtin/correlation/compute.ts +6 -1
  91. package/src/plugins/builtin/custom-view/loader.ts +95 -34
  92. package/src/plugins/builtin/custom-view/pane.tsx +31 -41
  93. package/src/plugins/builtin/custom-view/table.ts +201 -0
  94. package/src/plugins/builtin/dividend-yield/client.ts +14 -17
  95. package/src/plugins/builtin/dividend-yield/headless.ts +0 -1
  96. package/src/plugins/builtin/dividend-yield/model.ts +45 -6
  97. package/src/plugins/builtin/dividend-yield/pane.tsx +70 -7
  98. package/src/plugins/builtin/dividend-yield/types.ts +2 -3
  99. package/src/plugins/builtin/dividend-yield/view.ts +22 -2
  100. package/src/plugins/builtin/econ/calendar-model.ts +135 -0
  101. package/src/plugins/builtin/econ/columns.ts +132 -0
  102. package/src/plugins/builtin/econ/index.tsx +25 -65
  103. package/src/plugins/builtin/holders/disclosures-view.tsx +9 -6
  104. package/src/plugins/builtin/holders/disclosures.ts +20 -6
  105. package/src/plugins/builtin/holders/headless.ts +2 -2
  106. package/src/plugins/builtin/ipo-calendar/model.ts +30 -1
  107. package/src/plugins/builtin/ipo-calendar/pane.tsx +7 -3
  108. package/src/plugins/builtin/kelly-sizer/headless.ts +9 -4
  109. package/src/plugins/builtin/kelly-sizer/pane.tsx +19 -9
  110. package/src/plugins/builtin/kelly-sizer/units.ts +26 -0
  111. package/src/plugins/builtin/market-halts/pane.tsx +14 -2
  112. package/src/plugins/builtin/news/wire/news/row.ts +5 -12
  113. package/src/plugins/builtin/news/wire/news/table.tsx +32 -41
  114. package/src/plugins/builtin/pe-band/headless.ts +1 -1
  115. package/src/plugins/builtin/pe-band/model.ts +41 -18
  116. package/src/plugins/builtin/pe-band/pane.tsx +6 -5
  117. package/src/plugins/builtin/perps/equity-row.tsx +4 -6
  118. package/src/plugins/builtin/perps/markets-section.tsx +19 -15
  119. package/src/plugins/builtin/perps/model.ts +10 -2
  120. package/src/plugins/builtin/portfolio-list/cli/import-positions.ts +6 -18
  121. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +1 -1
  122. package/src/plugins/builtin/portfolio-list/pane/purchase-date-fx.ts +1 -1
  123. package/src/plugins/builtin/portfolio-list/positions-import/index.tsx +1 -1
  124. package/src/plugins/builtin/portfolio-list/positions-import/lookup.ts +28 -57
  125. package/src/plugins/builtin/research/event-data.ts +3 -1
  126. package/src/plugins/builtin/research/event-model.ts +17 -15
  127. package/src/plugins/builtin/research/relative-valuation-columns.ts +19 -6
  128. package/src/plugins/builtin/research/relative-valuation-headless.ts +1 -1
  129. package/src/plugins/builtin/scanner/flow-pane.tsx +10 -0
  130. package/src/plugins/builtin/sec/exchange-filings.ts +32 -7
  131. package/src/plugins/builtin/sec/headless.ts +8 -8
  132. package/src/plugins/builtin/sec/index.tsx +69 -29
  133. package/src/plugins/builtin/shared/report-freshness.ts +4 -1
  134. package/src/plugins/builtin/ticker-detail/financials/aggregation.ts +1 -2
  135. package/src/plugins/builtin/ticker-detail/financials/exchange-table.tsx +61 -0
  136. package/src/plugins/builtin/ticker-detail/financials/model.ts +38 -4
  137. package/src/plugins/builtin/ticker-detail/financials/ratio-table.tsx +9 -2
  138. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +68 -39
  139. package/src/plugins/builtin/ticker-detail/headless.ts +4 -1
  140. package/src/plugins/builtin/ticker-detail/overview/model.ts +61 -15
  141. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +5 -0
  142. package/src/plugins/builtin/time-sales/model.ts +16 -9
  143. package/src/plugins/builtin/time-sales/pane.tsx +27 -24
  144. package/src/plugins/builtin/treasury-daily/client.ts +43 -9
  145. package/src/plugins/builtin/treasury-daily/pane.tsx +48 -27
  146. package/src/plugins/builtin/treasury-daily/resource.ts +33 -0
  147. package/src/portfolio/positions-import/parse.ts +14 -6
  148. package/src/portfolio/positions-import/plan.ts +3 -2
  149. package/src/react/async-resource.ts +3 -1
  150. package/src/renderers/dom/data-table/index.tsx +40 -0
  151. package/src/renderers/dom/data-table/row.tsx +39 -3
  152. package/src/renderers/dom/desktop/icons.tsx +147 -3
  153. package/src/renderers/dom/desktop/popover.tsx +2 -2
  154. package/src/renderers/dom/host/media-surface.tsx +204 -45
  155. package/src/renderers/dom/host/tabs.tsx +1 -0
  156. package/src/renderers/dom/styles.css +14 -2
  157. package/src/renderers/electrobun/bun/desktop/backend.ts +2 -0
  158. package/src/renderers/electrobun/bun/desktop/rpc-timing.ts +9 -3
  159. package/src/renderers/electrobun/shared/protocol.ts +2 -0
  160. package/src/renderers/electrobun/view/backend-rpc.ts +5 -2
  161. package/src/renderers/electrobun/view/rpc-timeout.ts +44 -3
  162. package/src/sources/gloomberb-cloud/index.ts +8 -7
  163. package/src/sources/gloomberb-cloud/normalizers.ts +7 -2
  164. package/src/sources/listing-symbols.ts +7 -1
  165. package/src/sources/provider-router/cache.ts +5 -4
  166. package/src/sources/provider-router/financials.ts +40 -18
  167. package/src/state/app/tab-cursor.ts +47 -6
  168. package/src/telemetry/stall-clocks.ts +3 -0
  169. package/src/telemetry/stall-reports.ts +12 -3
  170. package/src/telemetry/windows-process-activity.ts +41 -0
  171. package/src/telemetry/windows-time.ts +32 -0
  172. package/src/test-support/scoped-earnings.ts +24 -0
  173. package/src/tickers/terminal-codes.ts +1 -6
  174. package/src/time-series/daily-valuation.ts +13 -6
  175. package/src/time-series/filed-trailing-eps.ts +16 -3
  176. package/src/time-series/fundamentals/current-valuation.ts +8 -0
  177. package/src/time-series/fundamentals/historical-valuation.ts +20 -0
  178. package/src/time-series/fundamentals/series.ts +13 -1
  179. package/src/time-series/valuation-currency.ts +2 -0
  180. package/src/types/financials.ts +46 -10
  181. package/src/ui/dialog-context.ts +8 -0
  182. package/src/utils/datetime-format.ts +23 -1
  183. package/src/utils/declared-dividends.ts +12 -2
  184. package/src/utils/exchange-announcements.ts +4 -1
  185. package/src/utils/exchange-notation.generated.ts +3 -1
  186. package/src/utils/exchanges.ts +2 -1
  187. package/src/utils/fundamentals.ts +1 -0
  188. package/src/utils/main-thread-stall.ts +9 -1
  189. package/src/utils/rpc-timeout-error.ts +36 -11
  190. package/src/utils/sec.ts +3 -1
  191. package/src/utils/share-multiples.ts +1 -1
  192. package/src/utils/stall-process-activity.ts +70 -0
  193. package/src/utils/statement-scope.ts +103 -0
  194. package/src/utils/trailing-eps.ts +1 -1
  195. package/src/utils/zoned-date-time.ts +1 -0
@@ -62,6 +62,7 @@ export async function loadBrokerMarkedHolding(context: MarketContext, symbol: st
62
62
  export async function fetchTickerFinancials(
63
63
  context: MarketContext,
64
64
  symbol: string,
65
+ datesChangeBasis = false,
65
66
  ): Promise<{
66
67
  tickerFile: TickerRecord | null;
67
68
  financials: TickerFinancials;
@@ -71,7 +72,8 @@ export async function fetchTickerFinancials(
71
72
  const instrument = parsePublicTickerKey(normalized);
72
73
  const tickerFile = await loadStoredShotTicker(context, symbol);
73
74
  const exchange = instrument.exchange ?? tickerFile?.metadata.exchange ?? "";
74
- const financials = await context.dataProvider.getTickerFinancials(instrument.symbol, exchange);
75
+ const financials = await context.dataProvider.getTickerFinancials(instrument.symbol, exchange,
76
+ datesChangeBasis ? { datesChangeBasis } : undefined);
75
77
  return { tickerFile, financials, instrument: { symbol: instrument.symbol, ...(exchange ? { exchange } : {}) } };
76
78
  }
77
79
 
@@ -89,6 +89,7 @@ export interface ReportFreshness {
89
89
  periodToDate?: { period: "week" | "month"; through?: string };
90
90
  /** The local date of the session close `asOf` is, when the newest observation is its venue's latest close. */
91
91
  asOfClose?: string;
92
+ asOfTradeDate?: string;
92
93
  /** A session list of a part of `asOfClose`'s session (declared `sessionList.part`), named in its place: `pre-market`. */
93
94
  asOfSessionPart?: "pre-market" | "after-hours";
94
95
  /**
@@ -314,6 +315,7 @@ function readSession(record: Record<string, unknown>, time: ReportTime | null, s
314
315
  ...(calendar ? { calendar } : {}),
315
316
  // A row at its venue's nominal price is that session's price, however old its last trade.
316
317
  ...(record.nominal === true ? { nominal: true as const } : {}),
318
+ ...(record.futuresPriceKind === "settlement" ? { settlement: true as const } : {}),
317
319
  });
318
320
  }
319
321
 
@@ -683,6 +685,8 @@ function resolveReadFreshness({ declared, signals, observations, now }: Freshnes
683
685
  ...(periodicity ? { periodicity } : {}),
684
686
  ...(periodToDate && !declaredAsOf ? { periodToDate: { period: periodToDate.period, ...(periodToDate.through ? { through: isoTime(periodToDate.through) } : {}) } } : {}),
685
687
  ...(asOfClose ? { asOfClose } : {}),
688
+ ...(!declaredAsOf && !listed && rowsSession.tradeDate && asOf?.time === rowsSession.tradeDate.time
689
+ ? { asOfTradeDate: rowsSession.tradeDate.date } : {}),
686
690
  ...(asOfClose && listed?.part ? { asOfSessionPart: listed.part } : {}),
687
691
  ...(asOfLastPrint ? { asOfLastPrint: true as const } : {}),
688
692
  ...(tradingDayMarket ? { tradingDayMarket } : {}),
@@ -1036,7 +1040,8 @@ function asOfText(freshness: ReportFreshness, short: boolean, local: boolean, un
1036
1040
  const oldestPeriod = freshness.oldestPeriodicity !== undefined ? freshness.oldestPeriodicity : period;
1037
1041
  const oldest = freshness.oldest && (oldestPeriod ? periodText(freshness.oldest, oldestPeriod) : dayText(freshness.oldest));
1038
1042
  // A list dated by its newest entry names it, so the time is not read as when the list was read.
1039
- const dated = freshness.asOfLabel ? `${freshness.asOfLabel} ${asOf}` : asOf;
1043
+ const observed = freshness.asOfLabel ? `${freshness.asOfLabel} ${asOf}` : asOf;
1044
+ const dated = freshness.asOfTradeDate ? `${observed} · ${dayText(freshness.asOfTradeDate)} trade date` : observed;
1040
1045
  return oldest && !short && freshness.oldestAgeMinutes == null ? `${dated} (oldest ${oldest})` : dated;
1041
1046
  }
1042
1047
 
@@ -1138,7 +1138,6 @@ export const FUNCTION_HELP: Readonly<Record<string, FunctionHelp>> = {
1138
1138
  keys: [TABS, OPEN],
1139
1139
  data: same("Daily HKEX settlement custody; historical archive from 2007"),
1140
1140
  bloomberg: [],
1141
- docs: "HDS",
1142
1141
  },
1143
1142
  DILU: {
1144
1143
  summary: "Global equity dilution, active SEC S-3/S-3ASR/F-3 shelves with Rule 415 3-year expiry, Form S-3 I.B.6 baby-shelf 1/3 cap, 424B5/424B7 ATM and equity offerings, Form 144 proposed insider sales with 10b5-1 dates, IPO lock-ups, and HKEX CCASS pre-placement physical deposits.",
@@ -1146,7 +1145,6 @@ export const FUNCTION_HELP: Readonly<Record<string, FunctionHelp>> = {
1146
1145
  keys: [TABS, OPEN, OPEN_SOURCE],
1147
1146
  data: same("SEC EDGAR S-3/F-3/424B5/Form 144 filings as filed; HKEX CCASS daily deposits"),
1148
1147
  bloomberg: [],
1149
- docs: "HDS",
1150
1148
  },
1151
1149
  CBBC: {
1152
1150
  summary: "Hong Kong HKEX Callable Bull/Bear Contract (CBBC) knock-out call-level street map, bull/bear ratios, equivalent HSI futures delta, heavy kill zones, and top individual contracts for HSI, HSTECH and HKEX equities.",
@@ -10,6 +10,8 @@ import {
10
10
  nextRegularSessionOpen,
11
11
  } from "../../market-data/market/freshness";
12
12
  import { futuresWeekendClosure } from "../../market-data/market/futures-week";
13
+ import { publishedGlobexPrintTradeDate } from "../../market-data/market/globex-day";
14
+ import { futuresListingVenue } from "../../utils/futures-generic";
13
15
  import { shownSessionDay } from "../../market-data/market/venue-session";
14
16
  import { currentFxClosureStart, isFxWeekClosePrint, nextFxWeekOpen } from "../../utils/fx-market-hours";
15
17
  import { zonedDateKey } from "../../utils/zoned-date-time";
@@ -43,6 +45,7 @@ export interface SessionObservation {
43
45
  calendar?: QuoteIndexSession;
44
46
  /** The row is at its venue's nominal price: that session's price, however old its last trade. */
45
47
  nominal?: true;
48
+ settlement?: true;
46
49
  }
47
50
 
48
51
  interface VenueSession {
@@ -186,6 +189,7 @@ function isPreClosePrint(observation: SessionObservation, session: VenueSession)
186
189
  function closeDateOf(observation: SessionObservation, session: VenueSession, now: number): string | null {
187
190
  const time = observation.time;
188
191
  if (!time || time.dateOnly) return null;
192
+ if (futuresListingVenue("", observation.exchange)) return null;
189
193
  // FX closes once a week, Friday 17:00 New York time: a print in its last
190
194
  // minute is that Friday's close. An earlier print of the day (20:39Z) is no
191
195
  // close, and a tick after it, over the weekend, is no price of the week:
@@ -321,7 +325,7 @@ export function reportVenueMarkets(observations: readonly SessionObservation[],
321
325
  export function reportMarketSession(
322
326
  observations: readonly SessionObservation[],
323
327
  now: number,
324
- ): { market: ReportMarket | null; closeDate: string | null; closeMarket: string | null; lastPrint?: true } {
328
+ ): { market: ReportMarket | null; closeDate: string | null; closeMarket: string | null; lastPrint?: true; tradeDate?: { date: string; time: number } } {
325
329
  const sessions = new Map<string, VenueSession>();
326
330
  let newest: { observation: SessionObservation; session: VenueSession; exchange: string } | null = null;
327
331
  for (const observation of observations) {
@@ -345,9 +349,15 @@ export function reportMarketSession(
345
349
  : null;
346
350
  const reopen = reopening?.next ?? null;
347
351
  const closeDate = (state === "closed" || state === "pre-market") && newest ? closeDateOf(newest.observation, newest.session, now) : null;
348
- const lastPrint = !closeDate && (state === "closed" || state === "pre-market") && newest && isPreClosePrint(newest.observation, newest.session);
352
+ const futuresTime = newest && !newest.observation.settlement && !newest.observation.time?.dateOnly
353
+ && futuresListingVenue("", newest.exchange) ? newest.observation.time : null;
354
+ const tradeDate = futuresTime && newest ? publishedGlobexPrintTradeDate(newest.exchange, futuresTime.time) : null;
355
+ const lastPrint = !closeDate && (state === "closed" || state === "pre-market") && newest
356
+ && (futuresTime || isPreClosePrint(newest.observation, newest.session));
349
357
  return {
350
358
  ...(lastPrint ? { lastPrint: true as const } : {}),
359
+ ...(tradeDate && futuresTime && tradeDate !== new Date(futuresTime.time).toISOString().slice(0, 10)
360
+ ? { tradeDate: { date: tradeDate, time: futuresTime.time } } : {}),
351
361
  market: {
352
362
  state,
353
363
  ...(reopen ? {
@@ -308,11 +308,13 @@ export async function buildDesktopShotPayload(
308
308
  collectShotStatSeries(resolved),
309
309
  ]);
310
310
  const includeOptionsChains = resolved.pane.id === OPTIONS_PANE_ID || resolved.template?.paneId === OPTIONS_PANE_ID;
311
+ const datesChangeBasis = resolved.pane.id === TICKER_RESEARCH_PANE_ID
312
+ && (!resolved.options.tab || resolved.options.tab === "overview");
311
313
  /** One row's data, or null for an argument the report reads as words rather than a ticker. */
312
314
  const captureShotSymbol = async (symbol: string): Promise<ShotSymbolCapture | null> => {
313
315
  let entry: Awaited<ReturnType<typeof fetchTickerFinancials>>;
314
316
  try {
315
- entry = await fetchTickerFinancials(context, symbol);
317
+ entry = await fetchTickerFinancials(context, symbol, datesChangeBasis);
316
318
  } catch (error) {
317
319
  // A report that reads its own argument (CDS's issuer name) renders it with no ticker data, as `fn` does.
318
320
  if (resolved.headless?.argument.kind === "free-text" && isNotATickerMessage(error instanceof Error ? error.message : null)) return null;
@@ -248,6 +248,8 @@ interface SymbolText {
248
248
  * Group`), or symbols written on one line (`AAPL MSFT`).
249
249
  */
250
250
  entries?: true;
251
+ /** Every populated cell is a list entry, rather than a column in a table. */
252
+ tokens?: true;
251
253
  /** A first row read as a header in words no header list knows (`Hisse,Adet,Maliyet`), skipped and named. */
252
254
  header?: string[];
253
255
  /** Each symbol is a line of the text, whole: a list of one entry a line, as a sheet's column pastes. */
@@ -339,14 +341,14 @@ export function parseSymbolText(text: string): SymbolText {
339
341
  // A file of lines split by commas or spaces reads as the same list typed would (`lmt, NOC ,` then `^HSI, 0700.hk 9988.HK`):
340
342
  // a cell of words is read as a typed entry is, so its symbols split.
341
343
  const spaced = cleaned.some((cells) => cells.some((cell) => !isTerminalCodeCell(cell) && isSymbolWords(cell)));
342
- if (grid) return { symbols: records.flat().filter(Boolean), ignored: [], ...spaced ? { entries: true as const } : {} };
344
+ if (grid) return { symbols: records.flat().filter(Boolean), ignored: [], tokens: true, ...spaced ? { entries: true as const } : {} };
343
345
  // A ragged list (lines of symbols beside a line holding a company's name) is a list, read as typed entries are.
344
- if (isRaggedList(cleaned)) return { symbols: records.flat().filter(Boolean), ignored: [], entries: true };
346
+ if (isRaggedList(cleaned)) return { symbols: records.flat().filter(Boolean), ignored: [], entries: true, tokens: true };
345
347
  // Names split by semicolons or commas, with no figures: one pasted line, or one name a line with a separator left
346
348
  // on it, is a list. A name beside a sector or any other text is a table, read by its first column below.
347
349
  const names = cleaned.some((cells) => /\s/.test(cells[0] ?? ""));
348
350
  if (!figures && (records.length === 1 || (names && cleaned.every((cells) => cells.filter(Boolean).length <= 1)))) {
349
- return { symbols: records.flat().filter(Boolean), ignored: [], entries: true };
351
+ return { symbols: records.flat().filter(Boolean), ignored: [], entries: true, tokens: true };
350
352
  }
351
353
  return {
352
354
  symbols: records.map((cells) => cells[0] ?? "").filter(Boolean),
@@ -455,6 +457,8 @@ export interface SymbolListSource {
455
457
  * words, each a symbol.
456
458
  */
457
459
  readEntries?: (entries: string[]) => Promise<string[]>;
460
+ /** Like `readEntries`, keeping the resolver's reading of each entry for occurrence-preserving output. */
461
+ readEntryGroups?: (entries: string[]) => Promise<string[][]>;
458
462
  /** Given, gets each line of the file and standard input as typed (`TypedForm`), for a command whose rows name them. */
459
463
  typedForms?: TypedForm[];
460
464
  }
@@ -486,15 +490,18 @@ export async function readSymbolList(source: SymbolListSource): Promise<{ symbol
486
490
  const typedArgs = source.args.filter((arg) => arg !== "-");
487
491
  const figures: string[] = [];
488
492
  const entries = typedEntries(typedArgs, figures);
489
- const readEntries = (read: string[]) => source.readEntries ? source.readEntries(read) : Promise.resolve(splitSymbolWords(read));
490
- const typed = source.readEntries ? await source.readEntries(entries) : splitSymbolWords(entries);
493
+ const readGroups = source.readEntryGroups;
494
+ const readEntries = async (read: string[]) => readGroups ? (await readGroups(read)).flat()
495
+ : source.readEntries ? source.readEntries(read) : splitSymbolWords(read);
496
+ const typed = await readEntries(entries);
491
497
  const collected = [...typed];
492
498
  // A separator left on the end of what was typed: `UPST;`, or a list that ends in a comma.
493
499
  const strays = new Set<string>(stripStrayEdges(typedArgs.join(" ")).notes);
494
500
  const ignored: string[] = [];
495
501
  const headers: string[] = [];
496
502
  const typedForms = source.typedForms ?? [];
497
- const addCells = async ({ symbols, ignored: beside, entries: whole, header }: SymbolText) => {
503
+ const lineEntry = (line: string) => stripStrayEdges(foldTypedText(line)).text.replace(/\s+/g, " ");
504
+ const addCells = async ({ symbols, ignored: beside, entries: whole, header, lines }: SymbolText) => {
498
505
  if (header) headers.push(`Skipped the first row as a header: ${listCells(header)}.`);
499
506
  const cells = symbols.map((cell) => {
500
507
  const cleaned = stripStrayEdges(cell);
@@ -502,8 +509,44 @@ export async function readSymbolList(source: SymbolListSource): Promise<{ symbol
502
509
  return cleaned.text;
503
510
  }).filter(Boolean);
504
511
  // A list's lines and names are read as typed entries are: `Altria Group` stays one company.
505
- collected.push(...whole ? await readEntries(cells) : cells);
512
+ const groups = whole && lines && readGroups ? await readGroups(cells) : null;
513
+ collected.push(...groups ? groups.flat() : whole ? await readEntries(cells) : cells);
506
514
  ignored.push(...beside);
515
+ return groups && new Map(cells.map((cell, index) => [lineEntry(cell), groups[index]]));
516
+ };
517
+ const addText = async (text: string) => {
518
+ const folded = foldTypedText(text);
519
+ const parsed = parseSymbolText(folded);
520
+ const before = collected.length;
521
+ const readings = await addCells(parsed);
522
+ if (!parsed.tokens) {
523
+ for (const form of typedLines(text, !!parsed.lines)) {
524
+ const entries = readings?.get(lineEntry(form.typed));
525
+ if (!entries || entries.length < 2) {
526
+ typedForms.push(form);
527
+ continue;
528
+ }
529
+ const words = splitSymbolWords([form.typed]);
530
+ entries.forEach((entry, index) => typedForms.push({
531
+ typed: words.length === entries.length ? words[index]! : entry,
532
+ key: symbolInputKey(entry), ownRow: true,
533
+ }));
534
+ }
535
+ return;
536
+ }
537
+ const raw = text === folded ? parsed : parseSymbolText(text);
538
+ const typed = raw.tokens && raw.symbols.length === parsed.symbols.length ? raw.symbols : parsed.symbols;
539
+ const keys = new Set(collected.slice(before).map(symbolInputKey));
540
+ for (const cell of typed) {
541
+ const input = stripStrayEdges(cell).text;
542
+ const key = symbolInputKey(foldTypedText(input).replace(/\s+/g, " "));
543
+ const words = input.split(/\s+/);
544
+ if (!keys.has(key) && words.length > 1 && words.every((word) => keys.has(symbolInputKey(foldTypedText(word))))) {
545
+ for (const word of words) typedForms.push({ typed: word, key: symbolInputKey(foldTypedText(word)), ownRow: true });
546
+ } else if (input) {
547
+ typedForms.push({ typed: input, key, ownRow: true });
548
+ }
549
+ }
507
550
  };
508
551
  if (source.file != null && source.file !== "-") {
509
552
  if (!source.file.trim() || source.file.startsWith("--")) throw new SymbolListError("--file needs a path, such as --file symbols.csv.");
@@ -514,15 +557,10 @@ export async function readSymbolList(source: SymbolListSource): Promise<{ symbol
514
557
  const code = (error as NodeJS.ErrnoException).code;
515
558
  throw new SymbolListError(code === "ENOENT" ? `No file at ${source.file}.` : `Could not read ${source.file}: ${error instanceof Error ? error.message : String(error)}`);
516
559
  }
517
- const parsed = parseSymbolText(foldTypedText(text));
518
- typedForms.push(...typedLines(text, !!parsed.lines));
519
- await addCells(parsed);
560
+ await addText(text);
520
561
  }
521
562
  if (wantsStdin || (typed.length === 0 && source.file == null && (source.stdinPiped ?? stdinIsPiped()))) {
522
- const text = await readStdin();
523
- const parsed = parseSymbolText(foldTypedText(text));
524
- typedForms.push(...typedLines(text, !!parsed.lines));
525
- await addCells(parsed);
563
+ await addText(await readStdin());
526
564
  }
527
565
  // A number where a symbol goes (a line of prices, a typed 1.899) is left out with those typed beside a symbol.
528
566
  const numbers = [...figures, ...collected.filter(isNumberCell)];
@@ -11,10 +11,13 @@ import { mapWithConcurrency } from "../utils/concurrency";
11
11
  import {
12
12
  AmbiguousContractError,
13
13
  AmbiguousTickerError,
14
+ listingExchange,
14
15
  resolveTickerSearch,
15
16
  upsertTickerFromSearchResult,
16
17
  type ResolvedTickerSearch,
17
18
  } from "../tickers/search";
19
+ import { getSearchResultSymbol, isLowQualityTickerName } from "../tickers/search/result";
20
+ import { sameCompanyName } from "../tickers/company-name";
18
21
  import { canonicalExchange, isUsListingExchange, parsePublicTickerKey } from "../utils/exchanges";
19
22
  import {
20
23
  chosenListingNote,
@@ -33,13 +36,16 @@ import {
33
36
  quoteBareListing,
34
37
  resolveCliListing,
35
38
  savedListingName,
39
+ snapshotListingKey,
36
40
  UNLISTED_TYPES,
37
41
  type CliListing,
38
42
  type ListingChoice,
39
43
  type ListingDeps,
44
+ type ListingIdentity,
40
45
  } from "./listing-arg";
41
46
  import { listingChangeLine, loadListingFate, noLongerTradingNote, tradingListing } from "../tickers/listing-fate";
42
- import { delistingLabel } from "../market-data/quotes/delisting";
47
+ import { delistingLabel, parseListingDelisting, parseListingWithdrawal, withdrawalLabel } from "../market-data/quotes/delisting";
48
+ import { securityInputKey } from "./symbol-args";
43
49
  import {
44
50
  describeFormerIssuer,
45
51
  describeTickerChange,
@@ -59,7 +65,7 @@ import { providerSearchQueries } from "../tickers/search";
59
65
  import { coinElsewhereNote, savedListingCoinNote } from "./commands/crypto-hints";
60
66
  import { NotASymbolError, notASymbolError } from "./symbol-cells";
61
67
  import { kindFromListingSyntax } from "../tickers/instrument-kind";
62
- import { classifyInstrumentKind, normalizeTickerSymbol } from "../tickers/search/ranking";
68
+ import { classifyInstrumentKind, normalizeSearchText, normalizeTickerSymbol } from "../tickers/search/ranking";
63
69
  import { companyNameQueries, findFormerIssuerOfName, isCompanyNameInput, settledTerminalCode } from "../tickers/company-name-listing";
64
70
  import { unreadBloombergCode } from "../tickers/terminal-codes";
65
71
 
@@ -82,6 +88,8 @@ export interface CliTicker {
82
88
  notes: string[];
83
89
  /** Of those, the one saying the listing stopped trading; null while it trades. */
84
90
  ended: string | null;
91
+ /** Structured lifecycle evidence for the resolved listing, never an inference from quote age. */
92
+ listingEnd?: string;
85
93
  /** How the input was read, when not as typed: a company's name as the listing it names (`listingReadNotes`). */
86
94
  readAs: string | null;
87
95
  /** The symbol changed (FB became META); when its company left it, the line leads `notes`. */
@@ -152,6 +160,32 @@ export interface CliTickerOptions {
152
160
  * that asks which listing is meant (the command bar's single add does).
153
161
  */
154
162
  askWhenAmbiguous?: boolean;
163
+ /** An import row is a listing symbol, never a request to find a company or its successor. */
164
+ currentSnapshot?: boolean;
165
+ }
166
+
167
+ function recordedListingEnd(delisting: unknown, withdrawal?: unknown): string | undefined {
168
+ const withdrawn = parseListingWithdrawal(withdrawal);
169
+ if (withdrawn) return withdrawalLabel(withdrawn);
170
+ const recorded = parseListingDelisting(delisting);
171
+ return recorded ? `Listing no longer trades (last traded ${recorded.lastTradeDate}).` : undefined;
172
+ }
173
+
174
+ type SnapshotListing = Pick<ListingIdentity, "symbol"> & { exchange?: string };
175
+
176
+ function matchesSnapshotListing(left: SnapshotListing, right: SnapshotListing, allowBareRequest = false): boolean {
177
+ const requested = snapshotListingKey(left);
178
+ const candidate = snapshotListingKey(right);
179
+ return !!requested && !!candidate && securityInputKey(requested.symbol) === securityInputKey(candidate.symbol)
180
+ && (requested.exchange === candidate.exchange || (allowBareRequest && !requested.exchange));
181
+ }
182
+
183
+ function searchListingIdentity(row: InstrumentSearchResult): ListingIdentity {
184
+ return { symbol: getSearchResultSymbol(row), exchange: listingExchange(row), name: row.name };
185
+ }
186
+
187
+ function matchesIssuer(name: string | null, other: string | null): boolean {
188
+ return name === other || sameCompanyName(name, other);
155
189
  }
156
190
 
157
191
  /**
@@ -235,37 +269,85 @@ export async function resolveCliTicker(
235
269
  const deps: ListingDeps = { store, dataProvider };
236
270
  // A vendor's suffix is the venue it names (GARAN.IS is GARAN:BIST), so the listing is saved under one key. A word that
237
271
  // names a company is read below, once the lookup says no listing trades as it (`oneWordCompanyName`).
238
- const listing = await resolveCliListing(symbol, exchange, deps, { ownExchangeWins: options.ownExchangeWins, listingSuffix: true, companyWord: false, listingAbroad: false });
272
+ const listing = await resolveCliListing(symbol, exchange, deps, {
273
+ ownExchangeWins: options.ownExchangeWins, currentSnapshot: options.currentSnapshot, listingSuffix: true, companyWord: false, listingAbroad: false,
274
+ });
239
275
  const read = listingReadNotes(listing);
240
276
  // Looked up beside the search, so saying FB is now META costs no wait.
241
277
  const changes = options.changes === false ? null : startTickerChangeLookup(dataProvider, listing.symbol, listing.exchange);
242
- const withChange = (resolved: ResolvedListing, current: CurrentListing | null | undefined) =>
243
- describeResolution(listing, changes, resolved, current, options.changeGraceMs);
244
- // A listing already saved says, as one search found does, when its quote stopped long ago.
245
- const withEnded = (named: { ticker: TickerRecord; quote: Quote | null }, notes: string[]): ResolvedListing => {
278
+ const withChange = async (resolved: ResolvedListing, current: CurrentListing | null | undefined) => {
279
+ const result = await describeResolution(listing, changes, resolved, current, options.changeGraceMs);
280
+ if (options.currentSnapshot && !matchesSnapshotListing(listing, savedListingName(result.ticker), true)) {
281
+ throw new ListingArgError(`No exact listing match for "${symbol}".`, tickerChangeLine(result.change) ?? undefined);
282
+ }
283
+ return result;
284
+ };
285
+ const snapshotListing = async (identity: ListingIdentity, selected?: InstrumentSearchResult) => {
286
+ const catalog = await dataProvider.search(listing.symbol).catch(logFailure("cli.ticker-resolution", "Listing lifecycle search failed", []));
287
+ const target = snapshotListingKey(identity) ?? identity;
288
+ const exact = (selected ? [selected, ...catalog] : catalog).filter((row) => matchesSnapshotListing(identity, searchListingIdentity(row)))
289
+ .map((row) => ({ row, end: recordedListingEnd(row.delisting, row.withdrawal) }));
290
+ const live = exact.filter(({ row, end }) => !end && !isLowQualityTickerName(row.name, target.symbol));
291
+ const current = live[0]?.row;
292
+ const issuer = current?.name ?? identity.name;
293
+ const companyId = live.find(({ row }) => row.companyId && matchesIssuer(issuer, row.name))?.row.companyId;
294
+ const sameIssuer = (row: InstrumentSearchResult) => companyId && row.companyId ? companyId === row.companyId
295
+ : !issuer || matchesIssuer(issuer, row.name);
296
+ if (live.some(({ row }) => !sameIssuer(row))) {
297
+ const key = target.exchange ? `${target.symbol}:${target.exchange}` : target.symbol;
298
+ throw new ListingArgError(`Multiple current issuers for "${key}".`, [...new Set(live.map(({ row }) => row.name))].join("; "));
299
+ }
300
+ const acceptsIssuer = (name: string | null): boolean => {
301
+ if (!name) return exact.every(({ row }) => sameIssuer(row));
302
+ const normalized = normalizeSearchText(name);
303
+ const literal = exact.filter(({ row }) => normalizeSearchText(row.name) === normalized);
304
+ const matches = literal.length ? literal : exact.filter(({ row }) => matchesIssuer(name, row.name));
305
+ return matches.length ? matches.every(({ row }) => sameIssuer(row)) : !issuer || matchesIssuer(issuer, name);
306
+ };
307
+ const listingEnd = exact.find(({ row, end }) => end && sameIssuer(row))?.end;
308
+ return { current, acceptsIssuer, listingEnd };
309
+ };
310
+ const requireCurrentIssuer = (ticker: TickerRecord, snapshot?: Awaited<ReturnType<typeof snapshotListing>>) => {
311
+ if (snapshot?.current) {
312
+ const identity = savedListingName(ticker);
313
+ if (!snapshot.acceptsIssuer(identity.name)) {
314
+ throw new ListingArgError(`Saved listing ${identity.label} does not match the current issuer (${snapshot.current.name}).`);
315
+ }
316
+ }
317
+ };
318
+ const resolveSaved = async (ticker: TickerRecord, quote: Quote | null, notes: string[], otherVenues?: string[]) => {
319
+ const snapshot = options.currentSnapshot ? await snapshotListing(savedListingName(ticker)) : undefined;
320
+ requireCurrentIssuer(ticker, snapshot);
321
+ const named = options.refreshName === false ? { ticker, quote: null }
322
+ : await nameFromListingQuote(ticker, store, dataProvider, quote, snapshot?.acceptsIssuer);
246
323
  const ended = named.quote ? noLongerTradingNote(savedListingName(named.ticker).label, named.quote) : null;
247
- return { ticker: named.ticker, notes: [...notes, ...ended ? [ended] : []], ended };
324
+ const listingEnd = snapshot?.listingEnd ?? recordedListingEnd(named.quote?.delisting);
325
+ return withChange({ ticker: named.ticker, notes: [...notes, ...ended ? [ended] : []], ended, otherVenues,
326
+ ...(listingEnd ? { listingEnd } : {}), ...uncheckedIf(listing, named, ended) },
327
+ named.quote ? tradingListing(named.quote) : { name: named.ticker.metadata.name });
248
328
  };
249
329
  // A saved listing names what lists there; the issuer that left, if it is that one, is its old line.
250
- if (listing.saved) {
251
- const saved = options.refreshName === false ? { ticker: listing.saved, quote: null } : await nameFromListingQuote(listing.saved, store, dataProvider, null);
252
- // A saved line that stopped trading is the old line, not something listed under the symbol now.
253
- const ended = withEnded(saved, read);
254
- return withChange({ ...ended, ...uncheckedIf(listing, saved, ended.ended) }, saved.quote ? tradingListing(saved.quote) : { name: saved.ticker.metadata.name });
255
- }
330
+ if (listing.saved) return resolveSaved(listing.saved, null, read);
256
331
  // A listing its own quote names is found as `quote` finds it, the quote cache first, so a busy search never
257
332
  // blocks a listing the quote knows. Search is asked after, for the venues a note names, and may fail.
258
- const known = await listingOfOwnQuote(listing, dataProvider);
333
+ const known = await listingOfOwnQuote(listing, dataProvider, options.currentSnapshot);
259
334
  if (known) {
260
- const { ticker, created } = await upsertTickerFromSearchResult(store, known.result);
261
- const named = created ? await nameFromListingQuote(ticker, store, dataProvider, known.quote) : { ticker, quote: known.quote };
335
+ const snapshot = options.currentSnapshot ? await snapshotListing(searchListingIdentity(known.result)) : undefined;
336
+ const result = snapshot?.current && !snapshot.acceptsIssuer(known.result.name) ? snapshot.current : known.result;
337
+ const { ticker, created } = await upsertTickerFromSearchResult(store, result);
338
+ if (!created) requireCurrentIssuer(ticker, snapshot);
339
+ const named = options.currentSnapshot || created
340
+ ? await nameFromListingQuote(ticker, store, dataProvider, known.quote, snapshot?.acceptsIssuer)
341
+ : { ticker, quote: known.quote };
262
342
  const saved = savedListingName(named.ticker);
263
343
  const venues = listing.exchange ? [] : await listingVenues(listing.symbol, deps).catch(logFailure("cli.ticker-resolution", "Read quoted listing venues failed", []));
264
344
  const others = venues.map((venue) => venue.exchange).filter((venue) => venue !== saved.exchange);
265
345
  const venueNote = others.length > 0 && saved.exchange
266
346
  ? listingChoiceNote(listing.symbol, saved, venues) ?? chosenListingNote(listing.symbol, saved.exchange, others)
267
347
  : null;
268
- return withChange({ ticker: named.ticker, notes: [...read, ...venueNote ? [venueNote] : []], ended: null, otherVenues: others }, tradingListing(known.quote));
348
+ const listingEnd = snapshot?.listingEnd;
349
+ return withChange({ ticker: named.ticker, notes: [...read, ...venueNote ? [venueNote] : []], ended: null, otherVenues: others,
350
+ ...(listingEnd ? { listingEnd } : {}) }, options.currentSnapshot && !named.quote ? { name: saved.name } : tradingListing(known.quote));
269
351
  }
270
352
 
271
353
  const localTickers = new Map(
@@ -316,23 +398,27 @@ export async function resolveCliTicker(
316
398
  throw new TickerNotFoundError(line ? `${message} ${line}.` : message, successor);
317
399
  }
318
400
  if (resolved.kind === "local") {
319
- const local = options.refreshName === false ? { ticker: resolved.ticker, quote: null } : await nameFromListingQuote(resolved.ticker, store, dataProvider, bareQuote);
320
- const ended = withEnded(local, [...read, ...bareNote ? [bareNote] : []]);
321
- return withChange({ ...ended, otherVenues: bareNote ? bareVenues : null, ...uncheckedIf(listing, local, ended.ended) }, local.quote ? tradingListing(local.quote) : { name: local.ticker.metadata.name });
401
+ return resolveSaved(resolved.ticker, bareQuote, [...read, ...bareNote ? [bareNote] : []], bareNote ? bareVenues : undefined);
322
402
  }
323
403
 
324
404
  // A bare word no quote of its own placed, which search read on a listing abroad, is the company the service marks
325
405
  // with the word, as `quote` reads it: VISA is V:NYSE (Visa Inc.), not a receipt on Toronto; SHELL is SHEL:LSE.
326
406
  const abroad = !listing.exchange && !!listing.typed && !isUsListingExchange(canonicalExchange(resolved.result.exchange));
327
- const marked = abroad ? await serviceNamedCompany(listing.typed!, deps)
407
+ const marked = abroad && !options.currentSnapshot ? await serviceNamedCompany(listing.typed!, deps)
328
408
  .catch(logFailure("cli.ticker-resolution", "Read a word the service marks as a name failed", null)) : null;
329
409
  if (marked) {
330
410
  const found = await resolveCliTicker(marked.key, store, dataProvider, undefined, options);
331
411
  return { ...found, readAs: marked.readAs ?? found.readAs };
332
412
  }
333
- const { ticker, created } = await upsertTickerFromSearchResult(store, resolved.result);
413
+ const snapshot = options.currentSnapshot
414
+ ? await snapshotListing(searchListingIdentity(resolved.result), resolved.quote ? undefined : resolved.result) : undefined;
415
+ const result = snapshot?.current ?? resolved.result;
416
+ const { ticker, created } = await upsertTickerFromSearchResult(store, result);
417
+ if (!created) requireCurrentIssuer(ticker, snapshot);
334
418
  // A listing saved before (by an earlier look at a list) is read again too: its quote says whether it still trades.
335
- const named = created || !bareQuote ? await nameFromListingQuote(ticker, store, dataProvider, bareQuote) : { ticker, quote: bareQuote };
419
+ const named = options.currentSnapshot || created || !bareQuote
420
+ ? await nameFromListingQuote(ticker, store, dataProvider, bareQuote, snapshot?.acceptsIssuer)
421
+ : { ticker, quote: bareQuote };
336
422
  const saved = savedListingName(named.ticker);
337
423
  const others = resolved.otherListings?.map((key) => parsePublicTickerKey(key).exchange ?? key) ?? [];
338
424
  // Several companies' listings name the company it went to and theirs; one company's name its other venues.
@@ -341,7 +427,8 @@ export async function resolveCliTicker(
341
427
  ?? chosenListingNote(listing.symbol, saved.exchange, others)
342
428
  : null);
343
429
  // A row search marks as delisted (UBSH, no venue, no quote) says so when its quote cannot.
344
- const listed = resolved.result.delisting;
430
+ const listed = result.delisting;
431
+ const listingEnd = snapshot?.listingEnd ?? recordedListingEnd(named.quote?.delisting) ?? recordedListingEnd(listed, result.withdrawal);
345
432
  const ended = (named.quote ? noLongerTradingNote(saved.label, named.quote) : listed ? `${saved.label}: ${delistingLabel(listed)}` : null)
346
433
  ?? (listing.exchange ? null : await ownLineEnded(listing, saved.exchange, dataProvider));
347
434
  // Search listed it, so something trades there; its quote says whether that is the issuer that left.
@@ -350,6 +437,7 @@ export async function resolveCliTicker(
350
437
  ticker: named.ticker,
351
438
  notes: [...read, venueNote, ended].filter((note): note is string => !!note),
352
439
  ended,
440
+ ...(listingEnd ? { listingEnd } : {}),
353
441
  otherVenues: bareNote ? bareVenues : others,
354
442
  ...uncheckedIf(listing, named, ended),
355
443
  }, current);
@@ -382,7 +470,7 @@ function uncheckedIf(
382
470
  * for on any of them answers as that venue (AAPL:NYSE), where search says
383
471
  * AAPL trades on NASDAQ, unless search named that venue for a company's name.
384
472
  */
385
- async function listingOfOwnQuote(listing: CliListing, dataProvider: DataProvider): Promise<{ result: InstrumentSearchResult; quote: Quote } | null> {
473
+ async function listingOfOwnQuote(listing: CliListing, dataProvider: DataProvider, currentSnapshot = false): Promise<{ result: InstrumentSearchResult; quote: Quote } | null> {
386
474
  if (listing.sharedCode || kindFromListingSyntax(listing.key, listing.exchange)) return null;
387
475
  if (listing.exchange && isUsSymbolVenue(listing.exchange) && !listing.venueFromSearch) return null;
388
476
  let quote: Quote;
@@ -393,10 +481,11 @@ async function listingOfOwnQuote(listing: CliListing, dataProvider: DataProvider
393
481
  if (!isNoProviderError(error)) logFailure("cli.ticker-resolution", "Quote listing before search failed")(error);
394
482
  return null;
395
483
  }
396
- const exchange = canonicalExchange(quote.listingExchangeName || quote.exchangeName);
397
- const answered = normalizeTickerSymbol(quote.symbol ?? "");
398
- if (!exchange || (answered !== listing.symbol && answered !== listing.key)) return null;
399
- if (listing.exchange && exchange !== listing.exchange) return null;
484
+ const quoted = { symbol: quote.symbol ?? "", exchange: canonicalExchange(quote.listingExchangeName || quote.exchangeName) };
485
+ const exchange = currentSnapshot ? snapshotListingKey(quoted)?.exchange : quoted.exchange;
486
+ if (!exchange) return null;
487
+ if (currentSnapshot ? !matchesSnapshotListing(listing, quoted, true)
488
+ : (listing.exchange && exchange !== listing.exchange) || ![listing.symbol, listing.key].includes(normalizeTickerSymbol(quoted.symbol))) return null;
400
489
  if (!Number.isFinite(quote.price) || quote.price === 0 || !(quote.lastUpdated > 0)) return null;
401
490
  if (quote.delisting || noLongerTradingNote(listing.key, quote)) return null;
402
491
  if (UNLISTED_TYPES.has(quote.instrumentType?.trim().toUpperCase() ?? "")) return null;
@@ -482,6 +571,7 @@ async function nameFromListingQuote(
482
571
  store: AppTickerRepositoryPort,
483
572
  dataProvider: DataProvider,
484
573
  known: Quote | null,
574
+ acceptsSnapshotIssuer?: (name: string | null) => boolean,
485
575
  ): Promise<{ ticker: TickerRecord; quote: Quote | null; failed?: true; missing?: true }> {
486
576
  const { metadata } = ticker;
487
577
  try {
@@ -491,7 +581,11 @@ async function nameFromListingQuote(
491
581
  // venue) is asked with none, and its own quote names none when the line stopped trading.
492
582
  const quoteExchange = canonicalExchange(quote.listingExchangeName || quote.exchangeName);
493
583
  const ownExchange = canonicalExchange(metadata.exchange);
494
- if (quoteExchange !== ownExchange || (!quoteExchange && !quote.delisting)) return { ticker, quote: null };
584
+ if (acceptsSnapshotIssuer) {
585
+ const quoted = { symbol: quote.symbol ?? "", exchange: quoteExchange };
586
+ if ((!snapshotListingKey(quoted)?.exchange && !quote.delisting) || !matchesSnapshotListing(savedListingName(ticker), quoted)
587
+ || !acceptsSnapshotIssuer(name || null)) return { ticker, quote: null };
588
+ } else if (quoteExchange !== ownExchange || (!quoteExchange && !quote.delisting)) return { ticker, quote: null };
495
589
  if (!name || name === metadata.name) return { ticker, quote };
496
590
  const named: TickerRecord = { ...ticker, metadata: { ...metadata, name } };
497
591
  await store.saveTicker(named);
@@ -611,7 +705,7 @@ function lookAgain(entry: CliTickerResolution): boolean {
611
705
  * spellings (`providerSearchQueries`); one with a venue, or read another way,
612
706
  * is searched as it always is.
613
707
  */
614
- function listLookupPlan(input: string, exchange: string | undefined): ListLookupPlan {
708
+ function listLookupPlan(input: string, exchange: string | undefined, currentSnapshot?: boolean): ListLookupPlan {
615
709
  // What cannot be a symbol is refused without a request.
616
710
  if (notASymbolError(input)) return { searches: [], changes: null };
617
711
  // A terminal's code abroad (`VOD LN`) is its listing as written: it asks only for its quote.
@@ -621,7 +715,7 @@ function listLookupPlan(input: string, exchange: string | undefined): ListLookup
621
715
  if (isCompanyNameInput(input)) return { searches: companyNameQueries(input), changes: null };
622
716
  try {
623
717
  // GARAN.IS names its venue, as GARAN:BIST does: it is looked up as a named listing is.
624
- const listing = parseListingArg(input, exchange, { ownExchangeWins: true, listingSuffix: true });
718
+ const listing = parseListingArg(input, exchange, { ownExchangeWins: true, listingSuffix: true, currentSnapshot });
625
719
  const searchable = !listing.exchange && /^[A-Z0-9][A-Z0-9.-]{0,11}$/.test(listing.symbol);
626
720
  // A named US venue (ZION:NASDAQ, as a company's name reads) is looked up by search (`listingOfOwnQuote`).
627
721
  const usVenue = !!listing.exchange && !listing.sharedCode && isUsSymbolVenue(listing.exchange);
@@ -656,10 +750,11 @@ export async function resolveTickersForCli(
656
750
  {
657
751
  retry,
658
752
  askWhenAmbiguous,
753
+ currentSnapshot,
659
754
  onRetry,
660
755
  onProgress,
661
756
  retryWaitsMs = RETRY_WAITS_MS,
662
- }: Pick<CliTickerOptions, "retry" | "askWhenAmbiguous"> & {
757
+ }: Pick<CliTickerOptions, "retry" | "askWhenAmbiguous" | "currentSnapshot"> & {
663
758
  /** Told before each new look, with how many symbols and how long it waits first. */
664
759
  onRetry?: (count: number, waitMs: number) => void;
665
760
  /** Told (0, total) as the first look starts, then as each of its symbols is settled, with how many are and how many there are. */
@@ -667,7 +762,7 @@ export async function resolveTickersForCli(
667
762
  retryWaitsMs?: readonly number[];
668
763
  } = {},
669
764
  ): Promise<CliTickerResolution[]> {
670
- const plans = new Map(symbols.map((input) => [input, listLookupPlan(input, exchange)] as const));
765
+ const plans = new Map(symbols.map((input) => [input, listLookupPlan(input, exchange, currentSnapshot)] as const));
671
766
  let settled = 0;
672
767
  const progress = onProgress ? () => onProgress(++settled, symbols.length) : undefined;
673
768
  // Told before any answer, so a slow first answer is said to be awaited.
@@ -681,7 +776,7 @@ export async function resolveTickersForCli(
681
776
  const batched = await batchedListLookups(dataProvider, inputs.map((input) => plans.get(input)!));
682
777
  for (const input of inputs) if (batched.settled(plans.get(input)!)) told.add(input);
683
778
  const resolve = (symbol: string) => resolveCliTicker(symbol, store, batched.dataProvider, exchange, {
684
- retry, askWhenAmbiguous, ownExchangeWins: true, changeGraceMs: LOOKUP_TIMEOUT_MS,
779
+ retry, askWhenAmbiguous, currentSnapshot, ownExchangeWins: true, changeGraceMs: LOOKUP_TIMEOUT_MS,
685
780
  });
686
781
  // Symbols whose searches were answered ask only for quotes, which go out together; the rest ask as before.
687
782
  const answered = (input: string) => batched.answered(plans.get(input)!);
@@ -707,9 +802,9 @@ export async function resolveTickersForCli(
707
802
  failing = failedRequests.count() > before || [...again.values()].some(busyLookup);
708
803
  }
709
804
  // A company's name typed as one word (Canon, ADVANTEST) that no listing trades as is read as `quote` reads it.
710
- lookups = await withOneWordNames(lookups, store, dataProvider, { retry, askWhenAmbiguous });
805
+ if (!currentSnapshot) lookups = await withOneWordNames(lookups, store, dataProvider, { retry, askWhenAmbiguous });
711
806
  // One written as a name (Aeon) that went to another company's ticker is the company of that name.
712
- lookups = await withTitleCaseNames(lookups, store, dataProvider, { retry, askWhenAmbiguous });
807
+ if (!currentSnapshot) lookups = await withTitleCaseNames(lookups, store, dataProvider, { retry, askWhenAmbiguous });
713
808
  if (!failing) return lookups;
714
809
  // Still refused after the last wait: a failure may only be the refusal, so none is called not found,
715
810
  // and a match whose quote was refused is not taken as trading.
@@ -112,6 +112,7 @@ const NO_EVENTS: readonly CompositeChartEvent[] = [];
112
112
  const NO_PROJECTED_EVENTS: readonly { event: CompositeChartEvent; guide: CompositeEventGuide }[] = [];
113
113
  const subscribeToNothing = () => () => {};
114
114
  const holdsNothing = () => false;
115
+ const pinsNothing = () => null;
115
116
 
116
117
  function finiteTimestampOrNull(date: Date | null | undefined): number | null {
117
118
  const timestamp = date?.getTime() ?? null;
@@ -235,6 +236,8 @@ function ThemedCompositeChart({
235
236
  emptyDetail,
236
237
  formatValue,
237
238
  onCursorDateChange,
239
+ pinKeys = false,
240
+ onPinnedMomentChange,
238
241
  onViewportChange,
239
242
  onActivate,
240
243
  onPress,
@@ -581,6 +584,14 @@ function ThemedCompositeChart({
581
584
  const showsSharedCursor = useSyncExternalStore(subscribeToLink, useCallback(() => sharedTime?.() != null, [sharedTime]));
582
585
  const holdsSharedCursor = useSyncExternalStore(subscribeToLink, link?.held ?? holdsNothing);
583
586
  const pinnedCursor = useSyncExternalStore(subscribeToLink, link?.pinned ?? holdsNothing);
587
+ // An owner that follows the pin (a table under the chart) is told where it
588
+ // moves, so only a chart that shares the tab's crosshair moves the owner.
589
+ // A chart that goes (the band folding to a strip) leaves it nothing to follow.
590
+ const pinnedMoment = useSyncExternalStore(subscribeToLink, link?.pinnedMoment ?? pinsNothing);
591
+ useEffect(() => {
592
+ onPinnedMomentChange?.(pinnedMoment);
593
+ return () => onPinnedMomentChange?.(null);
594
+ }, [onPinnedMomentChange, pinnedMoment]);
584
595
  const publishCursor = link?.publish;
585
596
  const cursorSource = useMemo<CompositeCursorSource | null>(() => baseScene ? createCompositeCursorSource({
586
597
  baseScene,
@@ -773,6 +784,7 @@ function ThemedCompositeChart({
773
784
  restingCursor,
774
785
  updateCursor: updateKeyboardCursor,
775
786
  pin: pinnable ? { pinned: pinnedCursor, toggle: togglePin } : null,
787
+ pinKeys,
776
788
  onActivate,
777
789
  timePick,
778
790
  pricePick,