@gloom-sh/terminal 0.20.9 → 0.20.10

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 (128) hide show
  1. package/package.json +1 -1
  2. package/src/api-client/auth.ts +6 -0
  3. package/src/api-client/data.ts +1 -0
  4. package/src/api-client/earnings.ts +15 -0
  5. package/src/api-client/index.ts +14 -3
  6. package/src/api-client/types/account.ts +10 -0
  7. package/src/api-client/types/billing.ts +10 -0
  8. package/src/api-client/types/econ.ts +19 -7
  9. package/src/api-client/types/market.ts +7 -0
  10. package/src/api-client/types/screener.ts +2 -0
  11. package/src/cli/commands/market.ts +18 -8
  12. package/src/cli/commands/overview.ts +26 -7
  13. package/src/cli/commands/ticker.ts +40 -15
  14. package/src/cli/desktop-pane-shot.ts +39 -0
  15. package/src/cli/errors.ts +20 -3
  16. package/src/cli/fx-pair.ts +11 -2
  17. package/src/cli/history-rows.ts +34 -3
  18. package/src/cli/index.ts +1 -1
  19. package/src/cli/listing-arg.ts +51 -13
  20. package/src/cli/pane-functions/headless.ts +4 -2
  21. package/src/cli/pane-functions/index.ts +1 -0
  22. package/src/cli/pane-functions/resolver.ts +2 -1
  23. package/src/cli/pane-functions/screenshot-assessment.ts +73 -5
  24. package/src/cli/pane-functions/screenshot-types.ts +4 -0
  25. package/src/components/chart/composite/chart-layout.ts +7 -4
  26. package/src/components/chart/composite/composite-chart.tsx +6 -16
  27. package/src/components/chart/composite/toolbar.tsx +258 -82
  28. package/src/components/chart/composite/use-composite-chart-keyboard.ts +5 -6
  29. package/src/components/command-bar/list/model.ts +13 -0
  30. package/src/components/command-bar/routes/ticker-search/actions.ts +2 -0
  31. package/src/components/command-bar/routes/ticker-search/results.ts +15 -8
  32. package/src/components/command-bar/surface/index.tsx +10 -5
  33. package/src/components/command-bar/workflow/alert.ts +21 -7
  34. package/src/components/data-table/table-pane.ts +3 -1
  35. package/src/components/layout/pane/footer/model.ts +26 -1
  36. package/src/components/metric-treemap/heat-surface.tsx +2 -1
  37. package/src/components/metric-treemap/index.tsx +3 -2
  38. package/src/components/ui/confirm-dialog.tsx +253 -7
  39. package/src/components/ui/data-table/index.tsx +1 -1
  40. package/src/components/ui/data-table/types.ts +7 -0
  41. package/src/components/ui/list-view.tsx +4 -3
  42. package/src/components/ui/status.tsx +9 -6
  43. package/src/docs/snapshot.json +36 -0
  44. package/src/i18n/es.ts +12 -0
  45. package/src/i18n/ja.ts +12 -0
  46. package/src/i18n/ko.ts +12 -0
  47. package/src/i18n/zh-cn.ts +12 -0
  48. package/src/i18n/zh-tw.ts +12 -0
  49. package/src/market-data/fx-closes.ts +14 -2
  50. package/src/market-data/market/change-basis.ts +35 -1
  51. package/src/market-data/market/status.ts +37 -0
  52. package/src/market-data/performance.ts +4 -1
  53. package/src/market-data/quotes/live-valuation.ts +25 -2
  54. package/src/market-data/realized-volatility.ts +3 -0
  55. package/src/market-data/us-bond-market.ts +115 -0
  56. package/src/plugins/builtin/account-management/invite-row.tsx +54 -0
  57. package/src/plugins/builtin/account-management/keyboard.ts +3 -0
  58. package/src/plugins/builtin/account-management/model.ts +1 -0
  59. package/src/plugins/builtin/account-management/pane.tsx +51 -5
  60. package/src/plugins/builtin/account-management/trial-cancel.ts +32 -7
  61. package/src/plugins/builtin/cloud/askg/pane-session.ts +94 -0
  62. package/src/plugins/builtin/cloud/askg/pane.tsx +40 -83
  63. package/src/plugins/builtin/congress-trades/pane.tsx +8 -2
  64. package/src/plugins/builtin/correlation/compute.ts +4 -3
  65. package/src/plugins/builtin/earnings/board-model.ts +33 -0
  66. package/src/plugins/builtin/earnings/board-table.ts +50 -11
  67. package/src/plugins/builtin/earnings/board.tsx +29 -13
  68. package/src/plugins/builtin/earnings/calendar.tsx +15 -3
  69. package/src/plugins/builtin/earnings/client.ts +4 -1
  70. package/src/plugins/builtin/earnings/headless.ts +27 -14
  71. package/src/plugins/builtin/econ/calendar-source.ts +3 -0
  72. package/src/plugins/builtin/help/index.tsx +1 -1
  73. package/src/plugins/builtin/ipo-calendar/model.ts +3 -3
  74. package/src/plugins/builtin/iv-history/headless.ts +12 -10
  75. package/src/plugins/builtin/macro-day/headless.ts +15 -5
  76. package/src/plugins/builtin/macro-day/model.ts +17 -4
  77. package/src/plugins/builtin/macro-day/releases.ts +36 -15
  78. package/src/plugins/builtin/market-halts/model.ts +3 -2
  79. package/src/plugins/builtin/market-movers/headless.ts +2 -1
  80. package/src/plugins/builtin/market-movers/index.tsx +3 -2
  81. package/src/plugins/builtin/market-movers/model.ts +75 -22
  82. package/src/plugins/builtin/market-movers/screener.ts +2 -1
  83. package/src/plugins/builtin/market-movers/table.ts +7 -5
  84. package/src/plugins/builtin/pe-band/model.ts +4 -0
  85. package/src/plugins/builtin/portfolio-list/cell-version.ts +4 -4
  86. package/src/plugins/builtin/portfolio-list/cli/render.ts +9 -4
  87. package/src/plugins/builtin/portfolio-list/pane/index.tsx +2 -1
  88. package/src/plugins/builtin/portfolio-list/summary/index.tsx +24 -7
  89. package/src/plugins/builtin/portfolio-list/summary/totals.ts +40 -11
  90. package/src/plugins/builtin/portfolio-list/table.tsx +13 -1
  91. package/src/plugins/builtin/research/analyst-headless.ts +9 -1
  92. package/src/plugins/builtin/research/analyst-pane.tsx +10 -4
  93. package/src/plugins/builtin/research/client.ts +25 -1
  94. package/src/plugins/builtin/research/corporate-actions-pane.tsx +2 -1
  95. package/src/plugins/builtin/research/event-model.ts +3 -13
  96. package/src/plugins/builtin/research/event-sources.ts +3 -1
  97. package/src/plugins/builtin/short-interest/headless.ts +2 -0
  98. package/src/plugins/builtin/short-interest/publications-headless.ts +2 -0
  99. package/src/plugins/builtin/short-interest/watch-headless.ts +1 -0
  100. package/src/plugins/builtin/yield-curve/headless.ts +5 -1
  101. package/src/plugins/builtin/yield-curve/index.tsx +5 -0
  102. package/src/portfolio/column-values.ts +47 -14
  103. package/src/portfolio/return-metrics.ts +4 -2
  104. package/src/renderers/dom/host/image-surface.tsx +19 -9
  105. package/src/renderers/dom/host/input.tsx +4 -0
  106. package/src/renderers/electrobun/view/cli-pane-shot-entry.tsx +23 -1
  107. package/src/sources/gloomberb-cloud/normalizers.ts +2 -0
  108. package/src/sources/provider-errors.ts +12 -0
  109. package/src/sources/provider-router/index.ts +12 -4
  110. package/src/state/pane-session.ts +145 -0
  111. package/src/tickers/search/home-listing.ts +44 -1
  112. package/src/tickers/search/index.ts +5 -2
  113. package/src/tickers/search/ranking.ts +7 -7
  114. package/src/tickers/us-listing.ts +11 -5
  115. package/src/time-series/base-series.ts +7 -1
  116. package/src/time-series/fundamentals/current-valuation.ts +8 -0
  117. package/src/time-series/fundamentals/series.ts +6 -0
  118. package/src/time-series/resolve.ts +1 -0
  119. package/src/types/financials.ts +20 -0
  120. package/src/types/headless.ts +9 -0
  121. package/src/ui/host.tsx +2 -0
  122. package/src/utils/exchanges.ts +13 -8
  123. package/src/utils/price-earnings.ts +17 -10
  124. package/src/utils/price-history-integrity.ts +15 -0
  125. package/src/utils/reason-codes.ts +79 -0
  126. package/src/utils/share-multiples.cases.json +889 -0
  127. package/src/utils/share-multiples.ts +254 -0
  128. package/src/utils/untrusted-text.ts +11 -0
@@ -24,6 +24,7 @@ import {
24
24
  } from "../../../cli/desktop-pane-shot-routes";
25
25
  import { openShotApiSocket, type ShotApiSocketSend } from "./cli-pane-shot-socket";
26
26
  import { instrumentFromTicker } from "../../../market-data/request-types";
27
+ import { buildQuoteKey, instrumentFromQuoteTarget } from "../../../market-data/selectors";
27
28
  import type { RendererHost } from "../../../ui/host";
28
29
  import { DomHostProviders } from "../../dom/dom-host-providers";
29
30
  import { webUiHost } from "./ui-host";
@@ -328,6 +329,8 @@ function waitForShotReadiness(): () => void {
328
329
 
329
330
  function createShotDataProvider(payload: DesktopPaneShotPayload): DataProvider {
330
331
  const cloudProvider = createGloomberbCloudProvider();
332
+ // The instruments a stream subscription has had its one frame for.
333
+ const streamedQuotes = new Set<string>();
331
334
  const bridge: Partial<DataProvider> = {
332
335
  id: payload.marketDataProviderId ?? cloudProvider.id,
333
336
  getQuote: (symbol, exchange, context) => requestShotMarketData<Quote>("getQuote", [symbol, exchange, context]),
@@ -371,7 +374,26 @@ function createShotDataProvider(payload: DesktopPaneShotPayload): DataProvider {
371
374
  getSecFilingDocuments: (filing) => requestShotMarketData<SecFilingDocument[]>("getSecFilingDocuments", [filing]),
372
375
  getSecFilingContent: (filing) => requestShotMarketData<string | null>("getSecFilingContent", [filing]),
373
376
  getEarningsCalendar: (symbols) => requestShotMarketData<EarningsEvent[]>("getEarningsCalendar", [symbols]).then(reviveEarningsEvents),
374
- subscribeQuotes: () => () => {},
377
+ subscribeQuotes: (targets, onQuote) => {
378
+ // A capture has no stream. Each target gets the quote a poll reads, once,
379
+ // so a pane that streams its rows (Market Movers with live on) shows them
380
+ // as its user sees them, not as its list alone draws them.
381
+ const fresh = targets.filter((target) => {
382
+ const key = buildQuoteKey(instrumentFromQuoteTarget(target));
383
+ if (streamedQuotes.has(key)) return false;
384
+ streamedQuotes.add(key);
385
+ return true;
386
+ });
387
+ if (fresh.length > 0) {
388
+ void requestShotMarketData<QuoteBatchResult[]>("getQuotesBatch", [fresh, {}])
389
+ .then((results) => results.forEach((result, index) => {
390
+ const target = fresh[index];
391
+ if (target && result?.quote) onQuote(target, result.quote);
392
+ }))
393
+ .catch(logFailure("desktop-pane-shot", "Could not load the quotes a pane streams for a screenshot"));
394
+ }
395
+ return () => {};
396
+ },
375
397
  };
376
398
  const fallback = new Proxy(cloudProvider, {
377
399
  get(target, property) {
@@ -284,6 +284,8 @@ export function mapPricePoint(
284
284
  ...(typeof point.rescaled === "number" && Number.isFinite(point.rescaled) && point.rescaled > 0 && point.rescaled !== 1
285
285
  ? { rescaled: point.rescaled } : {}),
286
286
  ...(typeof point.contract === "string" && FUTURES_CONTRACT_CODE.test(point.contract) ? { contract: point.contract } : {}),
287
+ ...(point.closeRebuilt === true ? { closeRebuilt: true } : {}),
288
+ ...(point.closeCopied === true ? { closeCopied: true } : {}),
287
289
  };
288
290
  }
289
291
 
@@ -195,6 +195,18 @@ export function isNoSourceAnswer(error: unknown): boolean {
195
195
  return error instanceof Error && !(error instanceof ProviderBusyError) && isNoProviderMessage(error.message);
196
196
  }
197
197
 
198
+ /**
199
+ * A source that answered it has nothing for a listing it knows: a miss that
200
+ * does not say the symbol is unknown, or one that crossed the desktop or
201
+ * screenshot bridge, which carries only its message, the service's bare
202
+ * NO_DATA. A source that failed, and a symbol no source knows, are not.
203
+ */
204
+ export function isNoDataAnswer(error: unknown): boolean {
205
+ if (error instanceof Error && error.message.trim() === "NO_DATA") return true;
206
+ return isProviderMiss(error) && !error.notFound && !/^(?:NOT_FOUND|BAD_MAPPING)$/.test(error.message.trim())
207
+ && notATickerSymbol(error.message) === null;
208
+ }
209
+
198
210
  export function shouldLogProviderError(error: unknown): boolean {
199
211
  if (isProviderMiss(error)) return false;
200
212
  const message = error instanceof Error ? error.message : String(error);
@@ -56,6 +56,7 @@ import { collectCapabilityRouteSources, mergeRouteSourcesById, normalizeRouteSou
56
56
  import type { ProviderRouterCoreDeps } from "./route-types";
57
57
  import { withProviderConnectionHealth } from "./connection-health";
58
58
  import { withFiledTrailingEps } from "../../time-series/filed-trailing-eps";
59
+ import { withShareMultiples } from "../../utils/share-multiples";
59
60
  import {
60
61
  contextFromCachedTarget,
61
62
  getBrokerCandidates,
@@ -66,6 +67,13 @@ import {
66
67
  type BrokerCandidate,
67
68
  } from "./brokers";
68
69
 
70
+ /**
71
+ * One trailing EPS and P/E for every view of a listing: the filed quarters', as PEB and GE read them
72
+ * (withFiledTrailingEps), and none where the price over it is no multiple of the share (withShareMultiples).
73
+ */
74
+ const withTrailingMultiples = <T extends Parameters<typeof withFiledTrailingEps>[0] & Parameters<typeof withShareMultiples>[0]>(financials: T): T =>
75
+ withShareMultiples(withFiledTrailingEps(financials));
76
+
69
77
  const providerLog = debugLog.createLogger("asset-data-router");
70
78
 
71
79
  /**
@@ -216,7 +224,7 @@ export class AssetDataRouter implements DataProvider {
216
224
  for (const target of valid) {
217
225
  const key = target.symbol.toUpperCase();
218
226
  const financials = cached.get(key);
219
- if (financials) cached.set(key, withFiledTrailingEps(this.knownFinancials(financials, listingOf(target, contextFromCachedTarget(target)))));
227
+ if (financials) cached.set(key, withTrailingMultiples(this.knownFinancials(financials, listingOf(target, contextFromCachedTarget(target)))));
220
228
  }
221
229
  return cached;
222
230
  }
@@ -268,7 +276,7 @@ export class AssetDataRouter implements DataProvider {
268
276
  const results = answered.map((result) => {
269
277
  if (!result.financials) return result;
270
278
  const quoted = result.financials.quote ? this.withDatedQuote(result.financials, dated[next++]!, listingOfResult(result)) : result.financials;
271
- const financials = withFiledTrailingEps(quoted);
279
+ const financials = withTrailingMultiples(quoted);
272
280
  return financials === result.financials ? result : { ...result, financials };
273
281
  });
274
282
  const restored = new Map(results.map((result) => {
@@ -283,11 +291,11 @@ export class AssetDataRouter implements DataProvider {
283
291
  const { context, datesChangeBasis } = splitDating(requestContext);
284
292
  exchange = this.resolvePublicExchange(ticker, exchange, context);
285
293
  const financials = await this.financialRoutes.getTickerFinancials(ticker, exchange, context);
286
- if (!financials.quote) return withFiledTrailingEps(financials);
294
+ if (!financials.quote) return withTrailingMultiples(financials);
287
295
  const listing = listingOf({ symbol: ticker, exchange }, context);
288
296
  const [quote] = await this.datedAnswers([{ quote: financials.quote, listing }], datesChangeBasis);
289
297
  // One trailing EPS and P/E for every view of the listing: the filed quarters', as PEB and GE read them.
290
- return withFiledTrailingEps(this.withDatedQuote(financials, quote!, listing));
298
+ return withTrailingMultiples(this.withDatedQuote(financials, quote!, listing));
291
299
  }
292
300
 
293
301
  async getQuote(ticker: string, exchange?: string, requestContext?: MarketDataRequestContext): Promise<Quote> {
@@ -0,0 +1,145 @@
1
+ import {
2
+ useCallback,
3
+ useEffect,
4
+ useMemo,
5
+ useSyncExternalStore,
6
+ type SetStateAction,
7
+ } from "react";
8
+ import { useOptionalPaneInstanceId } from "./app/context";
9
+
10
+ /**
11
+ * Memory a pane keeps for as long as the pane exists, rather than for as long
12
+ * as it is mounted.
13
+ *
14
+ * Docking, floating, stacking or fullscreening a pane draws it in another
15
+ * place in the tree, so its component mounts again. What it shows has to come
16
+ * back on the first frame: a pane that reads it from component state, or has to
17
+ * fetch it again, draws its empty state in between and loses the selection.
18
+ * What the user chose and can save belongs in pane state (`usePluginPaneState`,
19
+ * `usePaneSettingValue`); this holds what cannot be saved or must not be: a
20
+ * live conversation with its answer still coming in, a transcript, a draft.
21
+ * It is in memory only, so a relaunch starts without it, and a shared layout
22
+ * never carries it.
23
+ */
24
+
25
+ /**
26
+ * How long a pane's memory outlives its last mounted view. A move between the
27
+ * dock and a floating window mounts the new view in the commit that unmounts
28
+ * the old one; a closed pane never mounts again, and its memory is released
29
+ * after this.
30
+ */
31
+ export const PANE_SESSION_GRACE_MS = 2_000;
32
+
33
+ interface SessionEntry {
34
+ id: string;
35
+ value: unknown;
36
+ dispose: ((value: never) => void) | undefined;
37
+ holders: number;
38
+ timer: ReturnType<typeof setTimeout> | null;
39
+ }
40
+
41
+ const sessions = new Map<string, SessionEntry>();
42
+
43
+ function scheduleRelease(entry: SessionEntry): void {
44
+ if (entry.timer) clearTimeout(entry.timer);
45
+ entry.timer = setTimeout(() => {
46
+ entry.timer = null;
47
+ if (entry.holders > 0 || sessions.get(entry.id) !== entry) return;
48
+ sessions.delete(entry.id);
49
+ entry.dispose?.(entry.value as never);
50
+ }, PANE_SESSION_GRACE_MS);
51
+ }
52
+
53
+ /** Finds a pane's session or makes it. One a render makes and nothing mounts is released like any other. */
54
+ function acquire<T>(paneId: string, key: string, create: () => T, dispose: ((value: T) => void) | undefined): SessionEntry {
55
+ const id = `${paneId}\u0000${key}`;
56
+ const existing = sessions.get(id);
57
+ if (existing) return existing;
58
+ const entry: SessionEntry = { id, value: create(), dispose: dispose as SessionEntry["dispose"], holders: 0, timer: null };
59
+ sessions.set(id, entry);
60
+ scheduleRelease(entry);
61
+ return entry;
62
+ }
63
+
64
+ /** Test hook: releases every pane's memory now, so one test's panes never start on another's. */
65
+ export function resetPaneSessionsForTests(): void {
66
+ for (const entry of [...sessions.values()]) {
67
+ if (entry.timer) clearTimeout(entry.timer);
68
+ entry.timer = null;
69
+ sessions.delete(entry.id);
70
+ entry.dispose?.(entry.value as never);
71
+ }
72
+ }
73
+
74
+ function useScopedPaneId(paneId?: string): string {
75
+ const contextId = useOptionalPaneInstanceId();
76
+ const scoped = paneId ?? contextId;
77
+ if (!scoped) throw new Error("A pane session requires a pane id or PaneInstanceProvider");
78
+ return scoped;
79
+ }
80
+
81
+ /**
82
+ * An object that lives as long as the pane does: the same one in every view
83
+ * the pane is drawn in, made by `create` the first time. `dispose` runs once
84
+ * the pane has had no mounted view for the grace period (the pane was closed).
85
+ * Read it during render; it never changes identity while the pane exists.
86
+ */
87
+ export function usePaneSession<T>(
88
+ key: string,
89
+ create: () => T,
90
+ dispose?: (value: T) => void,
91
+ paneId?: string,
92
+ ): T {
93
+ const scopedPaneId = useScopedPaneId(paneId);
94
+ const entry = useMemo(() => acquire(scopedPaneId, key, create, dispose), [scopedPaneId, key]);
95
+ useEffect(() => {
96
+ entry.holders += 1;
97
+ if (entry.timer) {
98
+ clearTimeout(entry.timer);
99
+ entry.timer = null;
100
+ }
101
+ return () => {
102
+ entry.holders -= 1;
103
+ if (entry.holders <= 0) scheduleRelease(entry);
104
+ };
105
+ }, [entry]);
106
+ return entry.value as T;
107
+ }
108
+
109
+ interface StateBox<T> {
110
+ value: T;
111
+ listeners: Set<() => void>;
112
+ }
113
+
114
+ /**
115
+ * `useState` for a selection or draft that cannot be saved with the pane: the
116
+ * value is kept for the pane, so the view mounted after a dock change starts on
117
+ * it. A setter held by the view it unmounted still lands, on the value the new
118
+ * view reads. See `usePaneSession` for what belongs here and what belongs in
119
+ * pane state.
120
+ */
121
+ export function usePaneSessionState<T>(
122
+ key: string,
123
+ initial: T | (() => T),
124
+ paneId?: string,
125
+ ): [T, (value: SetStateAction<T>) => void] {
126
+ const box = usePaneSession<StateBox<T>>(key, () => ({
127
+ value: typeof initial === "function" ? (initial as () => T)() : initial,
128
+ listeners: new Set(),
129
+ }), undefined, paneId);
130
+ const subscribe = useCallback((listener: () => void) => {
131
+ box.listeners.add(listener);
132
+ return () => {
133
+ box.listeners.delete(listener);
134
+ };
135
+ }, [box]);
136
+ const getSnapshot = useCallback(() => box.value, [box]);
137
+ const value = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
138
+ const setValue = useCallback((next: SetStateAction<T>) => {
139
+ const resolved = typeof next === "function" ? (next as (previous: T) => T)(box.value) : next;
140
+ if (Object.is(resolved, box.value)) return;
141
+ box.value = resolved;
142
+ for (const listener of [...box.listeners]) listener();
143
+ }, [box]);
144
+ return [value, setValue];
145
+ }
@@ -1,6 +1,6 @@
1
1
  import { canonicalExchange, isUsListingExchange } from "../../utils/exchanges";
2
2
  import { companyLines, companyNameExtraWords, companyNameMatch, namedByService, type CompanyLineFacts } from "../company-name";
3
- import { answersOnlyByKeyword, isPlaceholderLine, isQualifiedTickerQuery, readsAsUsTicker } from "./ranking";
3
+ import { answersOnlyByKeyword, getIssuerGroupKey, isPlaceholderLine, isQualifiedTickerQuery, normalizeTickerSymbol, readsAsUsTicker } from "./ranking";
4
4
  import type { TickerSearchCandidate } from "./types";
5
5
 
6
6
  /** Venues that only quote shares listed elsewhere: the OTC tiers, Frankfurt's open market and Germany's regional exchanges. */
@@ -187,6 +187,49 @@ export function withHomeListingLead<T extends TickerSearchCandidate>(items: T[],
187
187
  return [...rest.slice(0, after), home, ...rest.slice(after)];
188
188
  }
189
189
 
190
+ /**
191
+ * A US ticker typed that is also a large company's short name leads with the
192
+ * US line, as a bare ticker resolves, then the rows the service marks with
193
+ * the word as typed: the company the word names, ahead of the ticker's other
194
+ * rows. "aia" is the iShares Asia 50 ETF's AIA, then AIA Group's 1299; "byd"
195
+ * is Boyd Gaming's BYD, then BYD Company's 002594 and 1211. Under the
196
+ * ticker, each company's first row then comes before further venues of one
197
+ * already listed (Boyd Gaming's BYD on IEX, the ETF's AIA in Mexico), which
198
+ * would push the other companies out of a short list. A line on a US
199
+ * exchange, a home line and a saved row are no such copies, and a line
200
+ * with no name of its own is no other company. The lead's own
201
+ * home line, which `withHomeListingLead` put right after it, stays there. A
202
+ * name typed as a name (`Aia`) or with its venue (AIA:NASDAQ) asks for
203
+ * something else.
204
+ */
205
+ export function withNamedCompanyAfterUsLead<T extends TickerSearchCandidate>(items: T[], query: string): T[] {
206
+ if (isQualifiedTickerQuery(query) || !readsAsUsTicker(query)) return items;
207
+ const typed = normalizeTickerSymbol(query);
208
+ const exact = (item: T) => normalizeTickerSymbol(item.symbol || item.label) === typed;
209
+ const [lead, next] = items;
210
+ if (!lead || lead.kind !== "search" || !exact(lead) || !isUsListingExchange(candidateExchange(lead))) return items;
211
+ const at = next && !exact(next) && next.result?.homeListing === true ? 2 : 1;
212
+ const named = items.slice(at).filter((item) => item.kind === "search" && !exact(item) && !!item.result && namedByService(query, item.result));
213
+ let rest = items.slice(at).filter((item) => !named.includes(item));
214
+ const companyOf = (item: T) => getIssuerGroupKey(item.detail) || item.id;
215
+ const listed = new Set(items.slice(0, at).filter(exact).map(companyOf));
216
+ const copies = rest.filter((item) => {
217
+ if (!exact(item)) return false;
218
+ const further = listed.has(companyOf(item));
219
+ listed.add(companyOf(item));
220
+ return further && item.kind === "search" && !item.saved && item.result?.homeListing !== true
221
+ && !isUsListingExchange(candidateExchange(item));
222
+ });
223
+ const others = rest.filter((item) => !copies.includes(item));
224
+ // A line with no name of its own (a nameless Buenos Aires DK) is no other company the copies would crowd out.
225
+ const ownName = (item: T) => !!item.result?.name?.trim() && !isPlaceholderLine(item);
226
+ const last = others.findLastIndex((item) => exact(item) && ownName(item));
227
+ const crowding = copies.length > 0 && last >= 0 && rest.indexOf(copies[0]!) < rest.indexOf(others[last]!);
228
+ if (!named.length && !crowding) return items;
229
+ if (crowding) rest = [...others.slice(0, last + 1), ...copies, ...others.slice(last + 1)];
230
+ return [...items.slice(0, at), ...named, ...rest];
231
+ }
232
+
190
233
  /** `items` with `home` moved just ahead of `lead`. */
191
234
  function moveAhead<T>(items: readonly T[], home: T, lead: T): T[] {
192
235
  const rest = items.filter((item) => item !== home);
@@ -41,7 +41,7 @@ import { endsInLegalForm, readNearMissListing, readVenueFirstListing, readTermin
41
41
  import { isProviderBusy, ProviderBusyError, SEARCH_BUSY_MESSAGE } from "../../sources/provider-errors";
42
42
  import { settleWithin } from "../../utils/async-deadline";
43
43
  import { companyNameExtraWords } from "../company-name";
44
- import { withHomeListingLead } from "./home-listing";
44
+ import { withHomeListingLead, withNamedCompanyAfterUsLead } from "./home-listing";
45
45
  import { answeredInFull, rememberSearchAnswer, withKnownListings } from "./listing-index";
46
46
  import { savedAbroadForBareSymbol, savedUsListingOf } from "./bare-symbol";
47
47
  import { delistingLabel, parseListingWithdrawal, withdrawalLabel } from "../../market-data/quotes/delisting";
@@ -356,7 +356,10 @@ export function buildTickerSearchCandidates({
356
356
  query,
357
357
  );
358
358
  const providerItems = createProviderTickerSearchCandidates(filteredProviderResults, tickers, candidateOptions);
359
- const ranked = withHomeListingLead(withSuccessorFirst(rankTickerSearchItems([...localItems, ...providerItems], query), query), query);
359
+ const ranked = withNamedCompanyAfterUsLead(
360
+ withHomeListingLead(withSuccessorFirst(rankTickerSearchItems([...localItems, ...providerItems], query), query), query),
361
+ query,
362
+ );
360
363
  return limitTickerSearchCandidates(companyListingsFirst(assignTickerSearchCategories(ranked, query), query), totalLimit, localLimit);
361
364
  }
362
365
 
@@ -371,17 +371,17 @@ export function rankTickerSearchItems<T extends Pick<TickerSearchRankableItem, "
371
371
  const bIssuerRank = exactIssuerRank.get(exactIssuerKey(b)) ?? Number.POSITIVE_INFINITY;
372
372
  if (aIssuerRank !== bIssuerRank) return aIssuerRank - bIssuerRank;
373
373
  }
374
- if (b.score !== a.score) return b.score - a.score;
375
- const aSaved = isSavedSearchItem(a.item);
376
- const bSaved = isSavedSearchItem(b.item);
377
- if (aSaved !== bSaved) return aSaved ? -1 : 1;
378
- // Rows that answer to the same typed name (GOOGL and GOOG for "Google")
379
- // keep the order the server gave them rather than the shorter symbol first.
380
- if (a.symbolMatchRank === 2) {
374
+ // Rows the server sent for the name as typed (GOOGL and GOOG for "Google"; Microsoft, Micron and
375
+ // Microchip for "micro", largest first) keep its order, rather than the shorter name or symbol first.
376
+ if (a.symbolMatchRank === 2 && !isSavedSearchItem(a.item) && !isSavedSearchItem(b.item)) {
381
377
  const aProviderRank = a.item.providerRank ?? Number.POSITIVE_INFINITY;
382
378
  const bProviderRank = b.item.providerRank ?? Number.POSITIVE_INFINITY;
383
379
  if (aProviderRank !== bProviderRank) return aProviderRank - bProviderRank;
384
380
  }
381
+ if (b.score !== a.score) return b.score - a.score;
382
+ const aSaved = isSavedSearchItem(a.item);
383
+ const bSaved = isSavedSearchItem(b.item);
384
+ if (aSaved !== bSaved) return aSaved ? -1 : 1;
385
385
  if (a.item.label.length !== b.item.label.length) return a.item.label.length - b.item.label.length;
386
386
  return a.index - b.index;
387
387
  };
@@ -1,6 +1,6 @@
1
1
  import { logFailure } from "../utils/log-failure";
2
2
  import type { DataProvider } from "../types/data-provider";
3
- import { canonicalExchange, isUsListingExchange, parsePublicTickerKey } from "../utils/exchanges";
3
+ import { canonicalExchange, isUsListingExchange, isUsOtcVenue, parsePublicTickerKey } from "../utils/exchanges";
4
4
  import { sameCompany } from "./company-name";
5
5
  import { LISTING_SEARCH_LIMIT } from "./search";
6
6
  import { classifyInstrumentKind } from "./search/ranking";
@@ -15,21 +15,27 @@ export interface UsListing {
15
15
  /**
16
16
  * A company's own listing on a US exchange, found by its name: Sanofi's SNY,
17
17
  * Toyota's TM. Funds and contracts that carry its name are not its listing.
18
- * Null when search knows no US line of the company.
18
+ * With `otc`, a line over the counter counts when the company has none on an
19
+ * exchange. Null when search knows no such US line of the company.
19
20
  */
20
21
  export async function findUsListingOfCompany(
21
22
  dataProvider: Pick<DataProvider, "search">,
22
23
  company: string | null | undefined,
24
+ { otc = false }: { otc?: boolean } = {},
23
25
  ): Promise<UsListing | null> {
24
26
  const name = company?.trim();
25
27
  if (!name) return null;
26
28
  const results = await dataProvider.search(name, { limit: LISTING_SEARCH_LIMIT }).catch(logFailure("tickers-us-listing", "Could not search US listing", []));
29
+ let overTheCounter: UsListing | null = null;
27
30
  for (const result of results) {
28
31
  const exchange = canonicalExchange(result.exchange === "SMART" ? result.primaryExchange : result.exchange || result.primaryExchange);
29
32
  const kind = classifyInstrumentKind(result.brokerContract?.secType || result.type);
30
- if (!isUsListingExchange(exchange) || kind === "fund" || kind === "derivative") continue;
33
+ const listed = isUsListingExchange(exchange);
34
+ if (!(listed || (otc && isUsOtcVenue(exchange))) || kind === "fund" || kind === "derivative") continue;
31
35
  if (!sameCompany(result.name, name) || parsePublicTickerKey(result.symbol).exchange) continue;
32
- return { symbol: result.symbol.toUpperCase(), exchange, name: result.name };
36
+ const line = { symbol: result.symbol.toUpperCase(), exchange, name: result.name };
37
+ if (listed) return line;
38
+ overTheCounter ??= line;
33
39
  }
34
- return null;
40
+ return overTheCounter;
35
41
  }
@@ -1,5 +1,6 @@
1
1
  import { resolveAssetDisplayKind } from "../market-data/market/format";
2
2
  import { hasValidQuoteObservationTime } from "../market-data/quotes/freshness";
3
+ import { getActiveQuoteDisplay, getRegularSessionDisplay } from "../market-data/market/status";
3
4
  import type { HistorySession } from "../types/price-history";
4
5
  import { appendLiveQuotePoint, hasUnknownBondHistoryBasis } from "./chart-data";
5
6
  import type { LiveBarAccumulator } from "./live-bars";
@@ -135,6 +136,8 @@ export function baseSecuritySeries(
135
136
  quoteMetadata: QuoteMetadata | null | undefined = financials.quoteMetadata,
136
137
  /** What a futures contract's price counts ("USD / gallon"), from its terms. */
137
138
  contractUnit?: string | null,
139
+ /** The bars run into pre-market and after-hours trading. */
140
+ { extendedHours = false }: { extendedHours?: boolean } = {},
138
141
  ): ResolvedSeries | null {
139
142
  if (spec.source.kind !== "security") return null;
140
143
  const field = getTimeSeriesField(spec.source.fieldId);
@@ -217,10 +220,13 @@ export function baseSecuritySeries(
217
220
  const listingExchange = canonicalExchange(marketExchange) === "SMART" || usOption
218
221
  ? canonicalExchange(sessionExchange) || (routedUsListing ? "NYSE" : marketExchange)
219
222
  : marketExchange;
223
+ // The move of the price the chart ends on: the regular session's, its close
224
+ // once it is over, as `quote` heads Last; the latest print's, an after-hours
225
+ // one included, where the bars run into extended hours.
220
226
  const latestChangePercent = marketField && field.unit.startsWith("currency")
221
227
  && !unknownBondBasis
222
228
  && financials.quote && hasValidQuoteObservationTime(financials.quote)
223
- ? financials.quote.changePercent
229
+ ? (extendedHours ? getActiveQuoteDisplay(financials.quote) : getRegularSessionDisplay(financials.quote))?.changePercent
224
230
  : undefined;
225
231
  const priceIssues = valuationPriceIssues(financials, spec.source);
226
232
  // A source with closes only, such as a generic future, has flat bars (open,
@@ -129,6 +129,8 @@ function currentDerivedValuation(
129
129
  ))
130
130
  .at(-1)?.candidate;
131
131
  if (!statement) return null;
132
+ // A P/E `valuation` withdraws (utils/share-multiples) is withdrawn here too, never read again as the price over EPS.
133
+ if (metric === "trailingPE" && financials.fundamentals?.notMeaningful?.trailingPE) return { value: null, date: current.date, statement };
132
134
  // The listing's EV needs no price in the statement's currency: an ADR's converts the statement instead.
133
135
  const listing = listingEnterpriseMultiple(financials, statement, metric);
134
136
  if (listing !== undefined) return { value: listing, date: current.date, statement };
@@ -202,6 +204,12 @@ function currentValuation(financials: TickerFinancials, period: SeriesPeriod | u
202
204
  */
203
205
  export function valuationNotMeaningful(financials: TickerFinancials, source: SecuritySeriesSource): { reason: string; asOf: string } | undefined {
204
206
  const [namespace, metric = ""] = canonicalTimeSeriesFieldId(source.fieldId).split(".");
207
+ if (namespace === "valuation" && (metric === "trailingPE" || metric === "forwardPE" || metric === "pegRatio")) {
208
+ const reason = financials.fundamentals?.notMeaningful?.[metric];
209
+ const asOf = financials.fundamentals?.trailingEpsPeriodEnd
210
+ ?? [...financials.quarterlyStatements, ...financials.annualStatements].map((row) => row.date).sort().at(-1);
211
+ return reason && asOf ? { reason: reason[0]!.toUpperCase() + reason.slice(1), asOf: asOf.slice(0, 10) } : undefined;
212
+ }
205
213
  if (namespace !== "valuation" || metric !== "evEbitda") return undefined;
206
214
  // A daily series ends on the trailing twelve months, as its current point does.
207
215
  const period = source.period === "daily" || source.period === "auto" || !source.period ? "ttm" : source.period;
@@ -8,6 +8,7 @@ import { createValuationCurrencyContext } from "../valuation-currency";
8
8
  import { valuationPriceAtOrBefore, valuationQuoteIssue, type ValuationPriceIssue } from "../valuation-price";
9
9
  import type { SecuritySeriesSource, TimeSeriesPoint } from "../types";
10
10
  import { isBankOrInsurerIndustry } from "../../utils/ebitda";
11
+ import { notTheShare } from "../../utils/share-multiples";
11
12
  import { currentDerivedValuationPoint, currentValuationStatements, providerCurrentValuationPoint } from "./current-valuation";
12
13
  import { dailyStatementValuation, dailyValuationFallbackPeriod, historicalValuation } from "./historical-valuation";
13
14
  import { FUNDAMENTAL_IDS, QUOTE_DERIVED_VALUATION_IDS, VALUATION_IDS, valuationSeriesUsesLiveQuote } from "./metric-ids";
@@ -16,6 +17,9 @@ import { sourceStatements } from "./source-statements";
16
17
  import { fundamentalValue, metricAvailability } from "./statement-fields";
17
18
  import { valuationAtPrice } from "./valuation-multiples";
18
19
 
20
+ /** The multiples of a share's price over its company's earnings (notTheShare withdraws them). */
21
+ const SHARE_PRICE_EARNINGS = new Set(["trailingPE", "forwardPE", "realizedNtmPE", "pegRatio"]);
22
+
19
23
  /** Extracts the selected statement snapshot, retaining known availability dates without reconstructing prior vintages. */
20
24
  export function extractFundamentalSeries(
21
25
  financials: TickerFinancials | null,
@@ -49,6 +53,8 @@ export function extractFundamentalSeries(
49
53
  }
50
54
 
51
55
  if (namespace !== "valuation" || !VALUATION_IDS.has(metric)) return [];
56
+ // A warrant's, a right's, a unit's or an unratioed receipt's price over its company's EPS is no P/E at any date.
57
+ if (SHARE_PRICE_EARNINGS.has(metric) && notTheShare(financials)) return [];
52
58
  // A bank's or an insurer's EBITDA measures nothing: its EV/EBITDA is N/M throughout (valuationNotMeaningful).
53
59
  if (metric === "evEbitda" && isBankOrInsurerIndustry(financials.profile?.industry)) return [];
54
60
  const fallback = dailyValuationFallbackPeriod(financials, source);
@@ -1033,6 +1033,7 @@ async function resolveChartSpecPass(
1033
1033
  history?.resolution,
1034
1034
  quoteMetadata,
1035
1035
  contractUnit,
1036
+ { extendedHours: history?.extendedHours === true },
1036
1037
  );
1037
1038
  if (!base) throw new Error(`Unknown field ${source.fieldId}.`);
1038
1039
  let result = builtBars ? withBuiltBarSize(base, builtBars) : base;
@@ -414,6 +414,12 @@ export interface Fundamentals extends DepositaryReceiptFacts {
414
414
  epsCurrency?: string;
415
415
  /** Set when `trailingPE` divides the price by the trailing EPS converted from another currency. */
416
416
  trailingPEConversion?: TrailingPEConversion;
417
+ /**
418
+ * What the trailing EPS was worked out from where Gloom Cloud did not take
419
+ * its source's: `statements` (net income over shares), `home` (a receipt's
420
+ * home line, per receipt), `cpo` (a CPO line's company, per CPO).
421
+ */
422
+ trailingEpsBasis?: "statements" | "home" | "cpo";
417
423
  /** Provider-reported issuer market cap; marketCapCurrency identifies its units when known. */
418
424
  marketCap?: number;
419
425
  marketCapCurrency?: string;
@@ -475,6 +481,12 @@ export interface Fundamentals extends DepositaryReceiptFacts {
475
481
  */
476
482
  trailingEpsSource?: "filed-quarters" | "served";
477
483
  trailingEpsPeriodEnd?: string;
484
+ /**
485
+ * Why a multiple is withdrawn though its figures are numbers (utils/share-multiples): a warrant's price over its
486
+ * company's EPS, a receipt's with no ratio on record, an EPS that is not net income over the shares. The multiple
487
+ * itself is absent; every view reads it as N/M with this reason.
488
+ */
489
+ notMeaningful?: Partial<Record<"trailingPE" | "forwardPE" | "pegRatio", string>>;
478
490
  operatingMargin?: number;
479
491
  profitMargin?: number;
480
492
  revenueGrowth?: number;
@@ -1170,6 +1182,14 @@ export interface PricePoint {
1170
1182
  rescaled?: number;
1171
1183
  /** A continuous future's bar (NG=F): the contract it closes on (NGZ26). A change from the bar before is a roll. */
1172
1184
  contract?: string;
1185
+ /** A currency pair's daily bar whose source repeated its open as its close: the close is the next session's open. */
1186
+ closeRebuilt?: boolean;
1187
+ /**
1188
+ * A currency pair's daily bar whose source repeated its open as its close, which no next open in its week rebuilds
1189
+ * (none, or one over 5% away): its close is no day's close, and returns leave the bar out
1190
+ * (pricePointCloseCopied).
1191
+ */
1192
+ closeCopied?: boolean;
1173
1193
  }
1174
1194
 
1175
1195
  export interface StatementHistoryAttempt {
@@ -823,6 +823,15 @@ export interface HeadlessPaneDefinition<Shape extends HeadlessPaneShape = Headle
823
823
  * in the US never shows that company's numbers.
824
824
  */
825
825
  usListingsOnly?: string;
826
+ /**
827
+ * The data covers US over-the-counter lines too (FINRA's short interest
828
+ * and weekly off-exchange volume, the SEC's fails to deliver, daily
829
+ * closes), so a listing abroad is offered its company's OTC line when it
830
+ * has no US exchange listing (Tencent's TCEHY for 0700.HK). Without it
831
+ * only exchange listings are offered, as options, trades and FINRA's
832
+ * daily short volume cover no OTC line.
833
+ */
834
+ usListingsOtc?: boolean;
826
835
  /**
827
836
  * A sentence that answer adds for a listing abroad, after its US listing:
828
837
  * where to read the nearest data the function has for it (time and sales
package/src/ui/host.tsx CHANGED
@@ -204,6 +204,8 @@ export interface InputRenderable {
204
204
  setCursorOffset?(offset: number): void;
205
205
  focus?(): void;
206
206
  blur?(): void;
207
+ /** Whether the field has the keyboard now: the keys typed go to it. */
208
+ readonly focused?: boolean;
207
209
  }
208
210
 
209
211
  export interface TextareaRenderable extends InputRenderable {
@@ -177,21 +177,26 @@ export function usShareClassSpellings(symbol: string, exchange?: string | null):
177
177
  return [`${match[1]}.${match[2]}`, `${match[1]}-${match[2]}`, `${match[1]}/${match[2]}`];
178
178
  }
179
179
 
180
+ /** Canonical US over-the-counter venues: OTC, and the OTC Markets tiers' listing codes. */
181
+ const US_OTC_EXCHANGES: ReadonlySet<string> = new Set(["OTC", "PINK", "PNK", "OQB", "OQX", "OEM", "OBB"]);
182
+
180
183
  /** Canonical US equity venues: the listing exchanges plus other lit and OTC venues. */
181
184
  const US_EQUITY_EXCHANGES: ReadonlySet<string> = new Set([
182
185
  ...US_LISTING_EXCHANGES,
183
186
  "BYX",
184
187
  "IEX",
185
- "OTC",
186
- "PINK",
187
- // Listing codes for the OTC Markets tiers.
188
- "PNK",
189
- "OQB",
190
- "OQX",
191
- "OEM",
192
- "OBB",
188
+ ...US_OTC_EXCHANGES,
193
189
  ]);
194
190
 
191
+ /**
192
+ * A US over-the-counter venue, by its code (OTC, PNK, OQX) or as a quote
193
+ * names it ("OTC MARKETS OTCPK" for TCEHY, "Other OTC").
194
+ */
195
+ export function isUsOtcVenue(value?: string): boolean {
196
+ const venue = canonicalExchange(value);
197
+ return US_OTC_EXCHANGES.has(venue) || /^(?:OTC MARKETS\b|OTCPK$|OTCQX$|OTCQB$|PINX$|OTHER OTC$)/.test(venue);
198
+ }
199
+
195
200
  /** A US venue a stock or fund trades on, listed or over the counter. */
196
201
  export function isUsEquityExchange(value?: string): boolean {
197
202
  return US_EQUITY_EXCHANGES.has(canonicalExchange(value));