@gloom-sh/terminal 0.19.6 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (209) hide show
  1. package/LICENSE +0 -4
  2. package/package.json +6 -5
  3. package/patches/electrobun-devkit@2.0.5.patch +408 -0
  4. package/src/api-client/bond-trades.ts +59 -0
  5. package/src/api-client/crypto-markets.ts +20 -2
  6. package/src/api-client/data.ts +21 -0
  7. package/src/api-client/fund-facts.ts +23 -1
  8. package/src/api-client/index.ts +2 -0
  9. package/src/api-client/types/account.ts +86 -0
  10. package/src/api-client/types/assist.ts +32 -0
  11. package/src/api-client/types/auth.ts +63 -0
  12. package/src/api-client/types/billing.ts +54 -0
  13. package/src/api-client/types/chat.ts +180 -0
  14. package/src/api-client/types/congress.ts +107 -0
  15. package/src/api-client/types/credit.ts +110 -0
  16. package/src/api-client/types/econ.ts +158 -0
  17. package/src/api-client/types/equity-diagnostic.ts +73 -0
  18. package/src/api-client/types/filings-and-calls.ts +356 -0
  19. package/src/api-client/types/index.ts +25 -0
  20. package/src/api-client/types/jobs.ts +147 -0
  21. package/src/api-client/types/market.ts +122 -0
  22. package/src/api-client/types/news.ts +91 -0
  23. package/src/api-client/types/notes-and-theses.ts +172 -0
  24. package/src/api-client/types/quotes.ts +28 -0
  25. package/src/api-client/types/scanners.ts +125 -0
  26. package/src/api-client/types/screener.ts +65 -0
  27. package/src/api-client/types/search.ts +107 -0
  28. package/src/api-client/types/sync.ts +14 -0
  29. package/src/api-client/types/team-collections.ts +43 -0
  30. package/src/api-client/types/team-views.ts +32 -0
  31. package/src/api-client/types/teams.ts +135 -0
  32. package/src/api-client/types/ticker-data.ts +57 -0
  33. package/src/api-client/types/tweets.ts +59 -0
  34. package/src/api-client/types/world-venues.ts +23 -0
  35. package/src/app/runtime/desktop-deeplink.ts +41 -6
  36. package/src/app/runtime/plugin-seed.ts +119 -0
  37. package/src/app/runtime/startup.ts +45 -9
  38. package/src/app/star-prompt/status-line.tsx +1 -1
  39. package/src/app.tsx +2 -7
  40. package/src/architecture/ui-tokens-allowlist.json +0 -8
  41. package/src/cli/board-coins.ts +38 -5
  42. package/src/cli/commands/crypto-hints.ts +8 -1
  43. package/src/cli/commands/market.ts +29 -26
  44. package/src/cli/commands/overview.ts +13 -6
  45. package/src/cli/commands/ticker.ts +78 -18
  46. package/src/cli/company-name-hint.ts +19 -0
  47. package/src/cli/desktop-pane-shot-browser.ts +69 -3
  48. package/src/cli/entry.ts +10 -4
  49. package/src/cli/glossary.ts +25 -0
  50. package/src/cli/helpers.ts +4 -2
  51. package/src/cli/not-a-ticker.ts +26 -1
  52. package/src/cli/pane-functions/catalog.ts +3 -1
  53. package/src/cli/pane-functions/freshness.ts +45 -29
  54. package/src/cli/pane-functions/market-session.ts +14 -5
  55. package/src/cli/restore-plugins.ts +164 -51
  56. package/src/components/chart/composite/use-composite-chart-keyboard.ts +11 -2
  57. package/src/components/chart-table/header.tsx +10 -1
  58. package/src/components/chart-table/layout.ts +14 -5
  59. package/src/components/command-bar/panel/index.tsx +13 -0
  60. package/src/components/command-bar/panel/layout.ts +7 -0
  61. package/src/components/command-bar/panel/runtime.ts +1 -0
  62. package/src/components/command-bar/panel/types.ts +2 -0
  63. package/src/components/data-table/export.ts +4 -1
  64. package/src/components/layout/detached-pane-shell.tsx +10 -37
  65. package/src/components/layout/double-escape-close.ts +90 -0
  66. package/src/components/layout/header.tsx +3 -2
  67. package/src/components/layout/market-summary.ts +6 -3
  68. package/src/components/layout/pane/footer/index.tsx +2 -6
  69. package/src/components/layout/pane/footer/model.ts +6 -12
  70. package/src/components/layout/shell/active-drag.ts +53 -11
  71. package/src/components/layout/shell/drag/magnets.ts +128 -19
  72. package/src/components/layout/shell/pane/actions.ts +6 -2
  73. package/src/components/layout/shell/pane/management-shortcuts.ts +13 -51
  74. package/src/components/layout/status-bar.tsx +4 -78
  75. package/src/components/layout/status-widget-space.ts +5 -5
  76. package/src/components/onboarding/portfolio-step/positions-panel.tsx +1 -1
  77. package/src/components/ui/data-table/index.tsx +5 -1
  78. package/src/components/ui/data-table/render-cell.ts +19 -0
  79. package/src/components/ui/delayed-mark.tsx +59 -7
  80. package/src/components/ui/icon.tsx +1 -8
  81. package/src/components/ui/menu.tsx +6 -1
  82. package/src/i18n/es.ts +6 -3
  83. package/src/i18n/ja.ts +6 -3
  84. package/src/i18n/ko.ts +6 -3
  85. package/src/i18n/zh-cn.ts +6 -3
  86. package/src/i18n/zh-tw.ts +6 -3
  87. package/src/market-data/fund-facts.ts +7 -1
  88. package/src/market-data/market/change-basis.ts +20 -0
  89. package/src/market-data/market/format.ts +62 -2
  90. package/src/market-data/market/futures-week.ts +3 -1
  91. package/src/plugins/builtin/chart-composer/headless.ts +57 -17
  92. package/src/plugins/builtin/chart-composer/session-range.ts +82 -3
  93. package/src/plugins/builtin/chat/content/composer.tsx +21 -27
  94. package/src/plugins/builtin/chat/content/index.tsx +31 -3
  95. package/src/plugins/builtin/chat/content/shortcuts.ts +4 -2
  96. package/src/plugins/builtin/chat/content/snapshot.ts +0 -3
  97. package/src/plugins/builtin/cloud/auth-actions.tsx +51 -23
  98. package/src/plugins/builtin/cloud/trial-offer-status-widget.tsx +3 -3
  99. package/src/plugins/builtin/cloud/upgrade-status-widget.tsx +32 -25
  100. package/src/plugins/builtin/congress-trades/model.ts +2 -1
  101. package/src/plugins/builtin/congress-trades/pane.tsx +3 -0
  102. package/src/plugins/builtin/correlation/compute.ts +8 -2
  103. package/src/plugins/builtin/correlation/headless.ts +10 -9
  104. package/src/plugins/builtin/correlation/history.ts +30 -0
  105. package/src/plugins/builtin/correlation/matrix/model.ts +10 -10
  106. package/src/plugins/builtin/correlation/relationship/model.ts +3 -6
  107. package/src/plugins/builtin/correlation/relationship/pane.tsx +1 -2
  108. package/src/plugins/builtin/crypto-board/client.ts +6 -1
  109. package/src/plugins/builtin/crypto-board/defi-view.tsx +12 -1
  110. package/src/plugins/builtin/crypto-board/defi.ts +44 -7
  111. package/src/plugins/builtin/crypto-board/headless.ts +83 -12
  112. package/src/plugins/builtin/crypto-board/model.ts +30 -6
  113. package/src/plugins/builtin/crypto-board/pane.tsx +13 -2
  114. package/src/plugins/builtin/custom-view/index.tsx +1 -1
  115. package/src/plugins/builtin/custom-view/loader.ts +85 -8
  116. package/src/plugins/builtin/custom-view/view-spec.ts +28 -0
  117. package/src/plugins/builtin/equity-screener/criterion-editor.tsx +13 -4
  118. package/src/plugins/builtin/equity-screener/headless.ts +33 -1
  119. package/src/plugins/builtin/equity-screener/model.ts +58 -15
  120. package/src/plugins/builtin/equity-screener/pane.tsx +36 -6
  121. package/src/plugins/builtin/executives/format.ts +5 -4
  122. package/src/plugins/builtin/executives/pane.tsx +1 -1
  123. package/src/plugins/builtin/help/index.tsx +55 -1
  124. package/src/plugins/builtin/insider/model.ts +30 -2
  125. package/src/plugins/builtin/jobs/model.ts +2 -2
  126. package/src/plugins/builtin/mna/model.ts +2 -2
  127. package/src/plugins/builtin/notes/files.ts +2 -0
  128. package/src/plugins/builtin/notes/owner.tsx +20 -1
  129. package/src/plugins/builtin/notes/quick-notes-pane.tsx +22 -4
  130. package/src/plugins/builtin/notes/store.ts +6 -1
  131. package/src/plugins/builtin/perps/headless.ts +8 -2
  132. package/src/plugins/builtin/portfolio-list/header.tsx +1 -1
  133. package/src/plugins/builtin/research/corporate-actions-pane.tsx +29 -25
  134. package/src/plugins/builtin/risk-factors/index.tsx +2 -28
  135. package/src/plugins/builtin/risk-factors/lock-note.ts +58 -0
  136. package/src/plugins/builtin/risk-factors/pane.tsx +10 -3
  137. package/src/plugins/builtin/scanner/hilo-model.ts +4 -3
  138. package/src/plugins/builtin/sec/fund-facts.ts +45 -11
  139. package/src/plugins/builtin/sec/headless.ts +30 -1
  140. package/src/plugins/builtin/sec/index.tsx +26 -5
  141. package/src/plugins/builtin/series-inventory.ts +1 -0
  142. package/src/plugins/builtin/shared/earnings-report.ts +7 -2
  143. package/src/plugins/builtin/shared/pro-lock-note.ts +5 -1
  144. package/src/plugins/builtin/shared/use-quote-board.ts +85 -46
  145. package/src/plugins/builtin/short-interest/headless.ts +1 -1
  146. package/src/plugins/builtin/short-interest/model.ts +15 -6
  147. package/src/plugins/builtin/short-interest/types.ts +2 -0
  148. package/src/plugins/builtin/thirteenf/overlap-pane.tsx +3 -0
  149. package/src/plugins/builtin/thirteenf/pane.tsx +3 -0
  150. package/src/plugins/builtin/ticker-detail/overview/model.ts +19 -9
  151. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +4 -4
  152. package/src/plugins/builtin/time-sales/headless.ts +23 -7
  153. package/src/plugins/builtin/time-sales/index.tsx +2 -2
  154. package/src/plugins/builtin/trace-bonds/detail.tsx +198 -0
  155. package/src/plugins/builtin/trace-bonds/headless.ts +62 -4
  156. package/src/plugins/builtin/trace-bonds/history.ts +155 -0
  157. package/src/plugins/builtin/trace-bonds/pane.tsx +64 -5
  158. package/src/plugins/extracted-plugins.ts +49 -24
  159. package/src/plugins/installer.ts +234 -32
  160. package/src/plugins/plugin-names.ts +11 -2
  161. package/src/plugins/running-installs.ts +34 -0
  162. package/src/plugins/seed-progress.ts +72 -0
  163. package/src/remote/controller.ts +9 -2
  164. package/src/remote/schema.ts +2 -1
  165. package/src/renderers/cloudflare/http-proxy.ts +67 -8
  166. package/src/renderers/cloudflare/proxy-session.ts +1 -1
  167. package/src/renderers/cloudflare/worker.ts +29 -2
  168. package/src/renderers/dom/desktop/icons.tsx +0 -2
  169. package/src/renderers/dom/styles.css +0 -3
  170. package/src/renderers/electrobun/bun/desktop/backend.ts +14 -0
  171. package/src/renderers/electrobun/bun/desktop/host-requests.ts +14 -7
  172. package/src/renderers/electrobun/bun/desktop/initialization.ts +24 -14
  173. package/src/renderers/electrobun/bun/desktop/install-records.ts +59 -0
  174. package/src/renderers/electrobun/bun/desktop/installer-folder.ts +208 -592
  175. package/src/renderers/electrobun/bun/desktop/macos-objc.ts +14 -0
  176. package/src/renderers/electrobun/bun/desktop/update.ts +1 -1
  177. package/src/renderers/electrobun/bun/index.ts +24 -13
  178. package/src/renderers/electrobun/bun/window/context-menu-thread.ts +84 -0
  179. package/src/renderers/electrobun/bun/window/create.ts +23 -3
  180. package/src/renderers/electrobun/bun/window/electrobun-window-host.ts +4 -4
  181. package/src/renderers/electrobun/bun/window/events.ts +4 -4
  182. package/src/renderers/electrobun/bun/window/frame.ts +2 -1
  183. package/src/renderers/electrobun/bun/window/native-call-thread.ts +224 -0
  184. package/src/renderers/electrobun/bun/window/native-min-size.ts +322 -0
  185. package/src/renderers/electrobun/bun/window/native-timing.ts +10 -0
  186. package/src/renderers/electrobun/bun/window/script-for-webview.ts +15 -0
  187. package/src/renderers/electrobun/bun/window/webview-script-thread.ts +82 -0
  188. package/src/renderers/electrobun/shared/protocol.ts +13 -2
  189. package/src/renderers/electrobun/view/backend-rpc.ts +8 -1
  190. package/src/renderers/electrobun/view/cli-pane-shot-frame.tsx +1 -1
  191. package/src/renderers/electrobun/view/main.tsx +4 -3
  192. package/src/renderers/opentui/start.tsx +3 -0
  193. package/src/sources/gloomberb-cloud/index.ts +5 -7
  194. package/src/sources/provider-router/batches.ts +18 -3
  195. package/src/sources/provider-router/financials.ts +18 -4
  196. package/src/telemetry/stall-reports.ts +21 -4
  197. package/src/types/data-provider.ts +14 -0
  198. package/src/types/financials.ts +15 -3
  199. package/src/types/headless.ts +2 -0
  200. package/src/utils/double-escape-close.ts +38 -16
  201. package/src/utils/format.ts +23 -3
  202. package/src/utils/main-thread-stall.ts +21 -5
  203. package/src/utils/perf-marks.ts +88 -9
  204. package/src/utils/price-earnings.ts +18 -0
  205. package/src/utils/reported-money.ts +9 -2
  206. package/src/utils/sec.ts +34 -3
  207. package/patches/electrobun@1.18.1.patch +0 -633
  208. package/src/api-client/types.ts +0 -2441
  209. package/src/plugins/seed-notice.ts +0 -20
@@ -4,6 +4,7 @@ import { useShortcut } from "../../../react/input";
4
4
  import { colors } from "../../../theme/colors";
5
5
  import { Box, type ScrollBoxRenderable } from "../../../ui";
6
6
  import { isDetailBackNavigationKey } from "../../../utils/back-navigation";
7
+ import { countEscapeTowardClose } from "../../../utils/double-escape-close";
7
8
  import { isPlainKey } from "../../../utils/keyboard";
8
9
  import { nextHeaderSort, type SortDirection } from "../../../utils/sort-values";
9
10
  import { usePluginPaneState, usePluginTickerActions } from "../../runtime";
@@ -106,6 +107,8 @@ export function FundOverlapView({ data, focused, width }: { data: FundDetailData
106
107
  const closeDetail = useCallback(() => { setTarget(null); setEtf(null); }, [setTarget, setEtf]);
107
108
  useShortcut(event => {
108
109
  if (!focused || !open || event.targetEditable || !isDetailBackNavigationKey(event)) return;
110
+ // Ahead of the shell's own Esc handler when restored with it, so it counts the Esc itself.
111
+ countEscapeTowardClose(event);
109
112
  event.preventDefault?.(); event.stopPropagation?.(); closeDetail();
110
113
  }, { phase: "before" });
111
114
  useShortcut(event => {
@@ -16,6 +16,7 @@ import {
16
16
  type ScrollBoxRenderable,
17
17
  } from "../../../ui";
18
18
  import { isDetailBackNavigationKey } from "../../../utils/back-navigation";
19
+ import { countEscapeTowardClose } from "../../../utils/double-escape-close";
19
20
  import { isPlainKey } from "../../../utils/keyboard";
20
21
  import { logFailure } from "../../../utils/log-failure";
21
22
  import { isPlainArrowUp, stopSearchFocusNavigation } from "../../../utils/search-focus-navigation";
@@ -493,6 +494,8 @@ export function FundDetailView({
493
494
  useShortcut((event) => {
494
495
  if (!focused || !openFiling || event.targetEditable) return;
495
496
  if (!isDetailBackNavigationKey(event)) return;
497
+ // Ahead of the shell's own Esc handler when restored with it, so it counts the Esc itself.
498
+ countEscapeTowardClose(event);
496
499
  event.preventDefault?.();
497
500
  event.stopPropagation?.();
498
501
  closeOpenFiling();
@@ -1,4 +1,4 @@
1
- import { formatPriceEarnings, NOT_MEANINGFUL } from "../../../../utils/price-earnings";
1
+ import { forwardFiscalYear, forwardPEAsked, formatPriceEarnings, NOT_MEANINGFUL } from "../../../../utils/price-earnings";
2
2
  import { convertMarketCapitalization } from "../../../../utils/market-capitalization";
3
3
  import { priceColor } from "../../../../theme/colors";
4
4
  import type { CedearRatio, CompanyProfile, DepositaryPair, NextEarnings, Quote, TickerFinancials } from "../../../../types/financials";
@@ -30,7 +30,7 @@ import { NO_CURRENT_DIVIDEND } from "../../../../utils/forward-dividend";
30
30
  import { getPortfolioPositionMetrics, getPortfolioQuoteDisplay, resolvePortfolioMarketValue, resolvePortfolioPositionPnl, portfolioPnlPercent, signedPositionDirection } from "../../../../portfolio/position-metrics";
31
31
  import { listingDividendYield, liveForwardPE, liveMarketCapitalization, liveTrailingPE } from "../../../../market-data/quotes/live-valuation";
32
32
  import { atRegularSessionPrice } from "../../../../market-data/quotes/regular-session-valuation";
33
- import { formatReportedMoney } from "../../../../utils/reported-money";
33
+ import { formatReportedMoney, REPORTING_CURRENCY_NOT_SOURCED } from "../../../../utils/reported-money";
34
34
  import { enterpriseValueCheck, enterpriseValueNotMeaningful, fundamentalsCurrency, fundamentalsEpsCurrency, reportedEnterpriseValue } from "../../../../utils/fundamentals";
35
35
  import { formatShortDate } from "../../../../utils/datetime-format";
36
36
  import { safeExternalUrl } from "../../../../utils/external-url";
@@ -185,7 +185,15 @@ export function buildOverviewStats({
185
185
  runway?: CashRunway | null;
186
186
  }): StatField[] {
187
187
  const stats: StatField[] = [];
188
- const money = (value: number, perShare = false) => formatReportedMoney(value, fundamentalsCurrency({ fundamentals, financialCurrency, quote }), perShare);
188
+ // Amounts no source names the currency of are bare; the first says so after it, once for all of them.
189
+ let unsourcedSaid = false;
190
+ const reported = (value: number, currency: string | undefined, perShare = false): Pick<StatField, "value" | "detail"> => {
191
+ const text = formatReportedMoney(value, currency, perShare);
192
+ if (currency?.trim() || unsourcedSaid || !Number.isFinite(value)) return { value: text };
193
+ unsourcedSaid = true;
194
+ return { value: text, detail: [REPORTING_CURRENCY_NOT_SOURCED, "currency not sourced"] };
195
+ };
196
+ const money = (value: number) => reported(value, fundamentalsCurrency({ fundamentals, financialCurrency, quote }));
189
197
 
190
198
  // An index's 0 is volume nobody counts, not a quiet session: no Volume row.
191
199
  const volume = reportedQuoteVolume(quote);
@@ -235,12 +243,14 @@ export function buildOverviewStats({
235
243
  if (trailingPE != null) {
236
244
  stats.push({ label: "P/E (TTM)", value: formatPriceEarnings(trailingPE) });
237
245
  }
246
+ // Next fiscal year's consensus, and the year it is for: N/M over a loss, a dash when there is none.
238
247
  const forwardPE = liveForwardPE(quote, fundamentals);
239
- if (forwardPE != null) {
240
- stats.push({ label: "Fwd P/E", value: formatPriceEarnings(forwardPE) });
248
+ if (forwardPE != null || forwardPEAsked(fundamentals)) {
249
+ const year = forwardFiscalYear(fundamentals?.forwardEpsPeriodEnd);
250
+ stats.push({ label: year ? `Fwd P/E ${year}` : "Fwd P/E", value: formatPriceEarnings(forwardPE) });
241
251
  }
242
252
  if (fundamentals?.eps != null) {
243
- stats.push({ label: "EPS", value: formatReportedMoney(fundamentals.eps, fundamentalsEpsCurrency({ fundamentals, financialCurrency, quote }), true) });
253
+ stats.push({ label: "EPS", ...reported(fundamentals.eps, fundamentalsEpsCurrency({ fundamentals, financialCurrency, quote }), true) });
244
254
  }
245
255
  if (fundamentals?.pegRatio != null) {
246
256
  stats.push({ label: "PEG", value: formatPriceEarnings(fundamentals.pegRatio, 2) });
@@ -288,13 +298,13 @@ export function buildOverviewStats({
288
298
  });
289
299
  }
290
300
  if (fundamentals?.revenue != null) {
291
- stats.push({ label: "Revenue", value: money(fundamentals.revenue) });
301
+ stats.push({ label: "Revenue", ...money(fundamentals.revenue) });
292
302
  }
293
303
  if (fundamentals?.netIncome != null) {
294
- stats.push({ label: "Net Income", value: money(fundamentals.netIncome) });
304
+ stats.push({ label: "Net Income", ...money(fundamentals.netIncome) });
295
305
  }
296
306
  if (fundamentals?.freeCashFlow != null) {
297
- stats.push({ label: "FCF", value: money(fundamentals.freeCashFlow) });
307
+ stats.push({ label: "FCF", ...money(fundamentals.freeCashFlow) });
298
308
  }
299
309
  const runwayField = runwayStat(runway);
300
310
  if (runwayField) stats.push(runwayField);
@@ -62,8 +62,7 @@ import { describeFundamentalMarketCap } from "../../../utils/market-capitalizati
62
62
  import { liveFiftyTwoWeekRange, liveMarketCapitalization } from "../../../market-data/quotes/live-valuation";
63
63
  import { instrumentTypeLabel } from "../../../tickers/instrument-kind";
64
64
  import { ClippedText } from "../../../components/ui/display";
65
- import { DelayedMark, delayedMarkWidth } from "../../../components/ui/delayed-mark";
66
- import { useFreeQuoteDelay } from "../../../api-client/plan-access";
65
+ import { DelayedMark, delayedMarkWidth, useDelayedMarkMinutes } from "../../../components/ui/delayed-mark";
67
66
  import { safeExternalUrl } from "../../../utils/external-url";
68
67
  import { cashRunway, SHORT_RUNWAY_HISTORY } from "../../../utils/cash-runway";
69
68
  import { useOfferingNote } from "./financials/offerings";
@@ -151,7 +150,7 @@ function ResolvedOverviewTab({ width, height, focused = false, ticker, financial
151
150
  const figureCells = useFigureCells();
152
151
 
153
152
  const quote = financials?.quote;
154
- const quoteDelayMinutes = useFreeQuoteDelay(quote);
153
+ const quoteDelayMinutes = useDelayedMarkMinutes(quote);
155
154
  const fundamentals = financials?.fundamentals;
156
155
  const capitalization = liveMarketCapitalization(quote, fundamentals);
157
156
  const profile = financials?.profile;
@@ -276,7 +275,8 @@ function ResolvedOverviewTab({ width, height, focused = false, ticker, financial
276
275
  const venueText = listingVenue ? (companyName ? ` (${listingVenue})` : listingVenue) : "";
277
276
  const sessionLabel = quoteSessionLabel(quote);
278
277
  const marketStateText = sessionLabel ? t(sessionLabel) : "";
279
- // Signed out or free, the headline price is the delayed one: the mark says so after the session.
278
+ // Signed out or free, the headline price is the delayed one. The status bar says so for the
279
+ // app; where it is hidden, or in a capture of the pane alone, the mark says so after the session.
280
280
  const delayMinutes = sessionQuote ? quoteDelayMinutes : null;
281
281
  const delayCells = delayMinutes != null ? delayedMarkWidth(delayMinutes, nativePaneChrome === true) + 1 : 0;
282
282
  const hasIdentityLine = Boolean(companyName || venueText || marketStateText || delayMinutes != null);
@@ -29,6 +29,12 @@ function listedNote(range: TapeRange, served: number, listed: number): string[]
29
29
 
30
30
  const WINDOW_OPTION = { reportOnly: "lists a window of the session in the text report" };
31
31
 
32
+ /** What each low and high of the report is taken over; the session's is the rule quote and GIP read the day's range by. */
33
+ function tapeRangeBasis(window: string): string {
34
+ return `${window} low and high: every print listed, odd lots included. Regular session low and high: consolidated prints that set a price, `
35
+ + "as quote and GIP read them; odd lots and special-condition prints set none.";
36
+ }
37
+
32
38
  /**
33
39
  * The window `--from`/`--to` ask for, read against the session the latest tape
34
40
  * serves, then fetched as that window. A server that predates windows answers
@@ -75,15 +81,17 @@ export const timeSalesHeadless: HeadlessPaneDefinition<"bundle"> = {
75
81
  ],
76
82
  discovery: { aliases: ["TAS", "QR"], dataRequirements: ["Gloom Cloud SIP trade and quote feed"],
77
83
  limitations: ["Bounded observed window, not a complete session.", "SIP is delayed fifteen minutes without realtime entitlement.", "Quote sizes are round lots.", "No Level 2 or inferred aggressor side."] },
78
- describe: (args) => `Time and sales ${args.argument ?? ""}`,
84
+ // QR is the NBBO view of the same tape: its report leads with the quotes, named as such.
85
+ describe: (args, result) => `${result?.metadata?.view === "quotes" ? "Quote recap" : "Time and sales"} ${args.argument ?? ""}`,
79
86
  async load(args, ctx) {
80
87
  const symbol = args.symbols[0] ?? (typeof args.argument === "string" ? args.argument : "");
81
88
  const instrument = await ctx.resolveInstrument?.(symbol);
82
89
  if (listedAbroad(symbol, instrument?.exchange)) {
83
90
  // Say why the table is empty and where the finest bars for it are, rather than the tape's bare "unavailable".
91
+ const quotesView = ctx.settings?.tab === "quotes";
84
92
  return { complete: false, sections: [
85
- { title: ctx.settings?.tab === "quotes" ? "NBBO" : "Trades", rows: [], empty: subMinuteDataMessage(symbol, "abroad") },
86
- ] };
93
+ { title: quotesView ? "NBBO" : "Trades", rows: [], empty: subMinuteDataMessage(symbol, "abroad") },
94
+ ], ...(quotesView ? { metadata: { view: "quotes" } } : {}) };
87
95
  }
88
96
  const exchange = instrument?.exchange ?? "";
89
97
  const from = String(args.options.from ?? "").trim(), to = String(args.options.to ?? "").trim();
@@ -104,14 +112,22 @@ export const timeSalesHeadless: HeadlessPaneDefinition<"bundle"> = {
104
112
  const freshness = data.feed === "sip"
105
113
  ? { status: "live" as const, cadence: "daily" as const }
106
114
  : { status: "delayed" as const, delayMinutes: Math.round(data.delaySeconds / 60), cadence: "daily" as const };
107
- return { freshness, ...(notes.length ? { notes } : {}), sections: [
115
+ const nbbo = { title: "NBBO", columns: formattedColumns(quotes, { bps }), rows: quotes };
116
+ const tape = [
108
117
  // The last price's rank among the window's prints, whole, as the pane shows it.
109
118
  { title: windowed ? "Window" : "Observed window", columns: formattedColumns(window, { vwap: price, low: price, high: price, pricePercentile: whole }), rows: window },
110
119
  { title: "Regular session", columns: formattedColumns([data.session], { high: price, low: price }), rows: [data.session] },
111
120
  { title: "Trades", columns: formattedColumns(trades, { price }), rows: trades },
112
- { title: "NBBO", columns: formattedColumns(quotes, { bps }), rows: quotes },
113
- ], errors: data.gaps, metadata: { source: data.source, feed: data.feed, delaySeconds: data.delaySeconds,
121
+ ];
122
+ // Each low says what it is the low of: the window's every print, the session's as quote and GIP read it.
123
+ const lows = [...notes, tapeRangeBasis(tape[0]!.title)];
124
+ const quotesView = ctx.settings?.tab === "quotes";
125
+ return { freshness, notes: lows, sections: quotesView ? [nbbo, ...tape] : [...tape, nbbo], errors: data.gaps, metadata: { source: data.source, feed: data.feed, delaySeconds: data.delaySeconds,
114
126
  asOf: data.asOf, observedFrom: data.observedFrom, generatedAt: data.generatedAt, status: data.status, ...(windowed ? { window: windowed.range } : {}),
115
- complete: data.status === "available", capacity: data.capacity, dropped: data.dropped, corrections: data.corrections, cancels: data.cancels, connected: data.connected } };
127
+ complete: data.status === "available", capacity: data.capacity, dropped: data.dropped, corrections: data.corrections, cancels: data.cancels, connected: data.connected,
128
+ ...(quotesView ? { view: "quotes" } : {}) } };
116
129
  },
117
130
  };
131
+
132
+ /** QR: the same tape, its NBBO first, named as such where it answers a listing abroad too. */
133
+ export const quoteRecapHeadless: HeadlessPaneDefinition<"bundle"> = { ...timeSalesHeadless, usListingsOnly: "Quote recap" };
@@ -1,6 +1,6 @@
1
1
  import type { PluginModule } from "../plugin-module";
2
2
  import { createTickerSurfacePaneTemplate } from "../shared/ticker-surface";
3
- import { timeSalesHeadless } from "./headless";
3
+ import { quoteRecapHeadless, timeSalesHeadless } from "./headless";
4
4
  export const timeSalesModule: PluginModule = {
5
5
  panes: [{ id: "time-sales", name: "Time and Sales", icon: "T", get component(): typeof import("./pane").TimeSalesPane { const { TimeSalesPane } = require("./pane"); return TimeSalesPane; },
6
6
  defaultPosition: "right", tickerFollower: true, defaultMode: "floating", defaultFloatingSize: { width: 104, height: 28 },
@@ -12,6 +12,6 @@ export const timeSalesModule: PluginModule = {
12
12
  { ...createTickerSurfacePaneTemplate({ id: "time-sales-qr", paneId: "time-sales", label: "Quote Recap",
13
13
  description: "NBBO history: bid and ask with sizes, venues and spread.",
14
14
  keywords: ["nbbo", "quotes", "bid", "ask", "recap", "qr", "trades", "tick", "ticks", "tick data", "second", "seconds", "intraday", "milliseconds"],
15
- shortcut: "QR", viewKey: "QR", settings: () => ({ tab: "quotes" }) }), headless: timeSalesHeadless },
15
+ shortcut: "QR", viewKey: "QR", settings: () => ({ tab: "quotes" }) }), headless: quoteRecapHeadless },
16
16
  ],
17
17
  };
@@ -0,0 +1,198 @@
1
+ import { useCallback, useMemo, useState } from "react";
2
+ import {
3
+ ChartTableHeader,
4
+ DataTableView,
5
+ loadingText,
6
+ spanAxisFormatter,
7
+ staticSeries,
8
+ useChartTableSelection,
9
+ type DataTableCell,
10
+ type DataTableColumn,
11
+ type StatItem,
12
+ } from "../../../components";
13
+ import { fitChartTableColumns } from "../../../components/chart-table";
14
+ import type { StoredBondPayload, StoredBondPrint } from "../../../api-client/bond-trades";
15
+ import { colors } from "../../../theme/colors";
16
+ import { MISSING_VALUE } from "../../../utils/format";
17
+ import { compareSortValues, nextHeaderSort, type SortPreference } from "../../../utils/sort-values";
18
+ import type { CorporateBond } from "./client";
19
+ import { bondPricePoints, formatPrintSide, formatPrintSize, standingPrints } from "./history";
20
+ import { formatBondDecimal } from "./model";
21
+
22
+ type PrintColumnId = "date" | "time" | "price" | "yield" | "size" | "side";
23
+ type PrintColumn = DataTableColumn & { id: PrintColumnId };
24
+
25
+ /** A kept print as a row: its place in the read names it, as two prints can share every field. */
26
+ interface PrintRow extends StoredBondPrint {
27
+ id: string;
28
+ }
29
+
30
+ const PRINT_COLUMNS: readonly PrintColumn[] = [
31
+ { id: "date", label: "Date", width: 11, align: "left" },
32
+ { id: "price", label: "Price", width: 9, align: "right" },
33
+ { id: "yield", label: "Yield", width: 8, align: "right" },
34
+ { id: "size", label: "Size", width: 7, align: "right" },
35
+ { id: "time", label: "Time", width: 9, align: "left" },
36
+ { id: "side", label: "Side", width: 5, align: "left" },
37
+ ];
38
+ /** A narrow pane keeps what was printed and when; the time of day and the dealer's side go first. */
39
+ const PRINT_DROP_ORDER: readonly PrintColumnId[] = ["side", "time", "size"];
40
+
41
+ type PrintSort = SortPreference<PrintColumnId>;
42
+ /** Newest print first; a third header click returns here. */
43
+ const DEFAULT_PRINT_SORT: PrintSort = { columnId: "date", direction: "desc" };
44
+
45
+ function printSortValue(columnId: PrintColumnId, row: PrintRow): string | number | null {
46
+ switch (columnId) {
47
+ case "date":
48
+ return `${row.date} ${row.time ?? ""}`;
49
+ case "time":
50
+ return row.time;
51
+ case "price":
52
+ return row.price;
53
+ case "yield":
54
+ return row.yield;
55
+ case "size":
56
+ return row.quantity;
57
+ case "side":
58
+ return row.side;
59
+ }
60
+ }
61
+
62
+ /** Rows in the sort, ties in the order the read listed them (newest first). */
63
+ function sortPrints(rows: readonly PrintRow[], sort: PrintSort): PrintRow[] {
64
+ const columnId = sort.columnId ?? "date";
65
+ return rows
66
+ .map((row, index) => ({ row, index }))
67
+ .sort((left, right) => compareSortValues(printSortValue(columnId, left.row), printSortValue(columnId, right.row), sort.direction)
68
+ || left.index - right.index)
69
+ .map(({ row }) => row);
70
+ }
71
+
72
+ const isPrintColumnId = (value: string): value is PrintColumnId => PRINT_COLUMNS.some((column) => column.id === value);
73
+
74
+ const NO_ROWS: PrintRow[] = [];
75
+ const printDate = (row: PrintRow) => new Date(`${row.date}T00:00:00Z`);
76
+ const printId = (row: PrintRow) => row.id;
77
+ /** Prices on the chart's axis: `52.5`, `101.25`. */
78
+ const formatPriceAxis = spanAxisFormatter((value, digits) => value.toFixed(digits));
79
+
80
+ function renderPrintCell(row: PrintRow, column: PrintColumn): DataTableCell {
81
+ switch (column.id) {
82
+ case "date":
83
+ return { text: row.date, value: row.date, color: colors.textMuted };
84
+ case "time":
85
+ return { text: row.time ?? MISSING_VALUE, color: colors.textDim };
86
+ case "price":
87
+ return { text: formatBondDecimal(row.price, 3), value: row.price, color: colors.textBright };
88
+ case "yield":
89
+ return { text: formatBondDecimal(row.yield, 3), value: row.yield, color: colors.text };
90
+ case "size":
91
+ return { text: formatPrintSize(row), value: row.quantity, color: colors.text };
92
+ case "side":
93
+ return { text: formatPrintSide(row.side), color: colors.textDim };
94
+ }
95
+ }
96
+
97
+ /**
98
+ * One bond's kept history: its last sale and since when its prints are kept,
99
+ * the daily closes as a line, then the prints behind them, newest first. The
100
+ * selected print is the chart's cursor. Without Gloom Pro, or while the
101
+ * history loads, the band says so and the table waits.
102
+ */
103
+ export function BondHistoryDetail({
104
+ bond,
105
+ history,
106
+ loading,
107
+ refusal,
108
+ focused,
109
+ width,
110
+ height,
111
+ }: {
112
+ bond: CorporateBond;
113
+ history: StoredBondPayload | null;
114
+ loading: boolean;
115
+ /** Why no history is read (`Kept price history needs Gloom Pro.`), or null. */
116
+ refusal: string | null;
117
+ focused: boolean;
118
+ width: number;
119
+ height: number;
120
+ }) {
121
+ const [sort, setSort] = useState<PrintSort>(DEFAULT_PRINT_SORT);
122
+ const listed = useMemo<PrintRow[]>(
123
+ () => (history ? standingPrints(history.trades).map((print, index) => ({ ...print, id: `${print.date}_${print.time ?? ""}_${index}` })) : NO_ROWS),
124
+ [history],
125
+ );
126
+ const rows = useMemo(() => sortPrints(listed, sort), [listed, sort]);
127
+ const [selectedId, setSelectedId] = useState<string | null>(null);
128
+ const shownId = selectedId && rows.some((row) => row.id === selectedId) ? selectedId : rows[0]?.id ?? null;
129
+ const select = useCallback((id: string | null) => setSelectedId(id), []);
130
+ const link = useChartTableSelection({ rows, getId: printId, getDate: printDate, selectedId: shownId, onSelect: select, focused });
131
+ // A server from before daily closes were served answers none.
132
+ const series = useMemo(() => [staticSeries(
133
+ bondPricePoints(history?.days ?? []),
134
+ { id: "bond-price", label: "Price", color: colors.positive, calendarSpaced: true },
135
+ )], [history]);
136
+ const charted = series[0]!.points.filter((point) => point.value != null).length;
137
+ const figures: StatItem[] = [
138
+ { id: "price", label: "Last", value: formatBondDecimal(bond.lastSalePrice, 3), ...(bond.lastTradeDate ? { detail: bond.lastTradeDate } : {}) },
139
+ { id: "yield", label: "Yield", value: formatBondDecimal(bond.lastSaleYield, 3) },
140
+ ...(history?.keptSince ? [{
141
+ id: "kept",
142
+ label: "Kept since",
143
+ value: history.keptSince,
144
+ ...(history.backfillPending ? { detail: "earlier prints being read", detailVariants: ["reading earlier"] } : {}),
145
+ }] : []),
146
+ ...(bond.cusip ? [{ id: "cusip", label: "CUSIP", value: bond.cusip }] : []),
147
+ ];
148
+ const columns = useMemo(() => fitChartTableColumns(PRINT_COLUMNS, width, PRINT_DROP_ORDER), [width]);
149
+ const empty = refusal
150
+ ?? (history?.backfillPending ? "No kept prints yet; the source's earlier prints are still being read." : null)
151
+ ?? (history?.keptSince ? `No kept prints since ${history.keptSince}.` : "No kept prints.");
152
+ const header = (
153
+ <ChartTableHeader
154
+ width={width}
155
+ height={height}
156
+ tableRows={rows.length}
157
+ figures={figures}
158
+ tableColumns={columns}
159
+ chart={charted >= 2 || loading ? {
160
+ series,
161
+ formatValue: (value: number) => formatBondDecimal(value, 3),
162
+ formatAxisValue: formatPriceAxis,
163
+ remoteKind: "bond-price-history",
164
+ loading,
165
+ ...link,
166
+ } : null}
167
+ />
168
+ );
169
+ return (
170
+ <DataTableView<PrintRow, PrintColumn>
171
+ focused={focused}
172
+ rootWidth={width}
173
+ rootHeight={height}
174
+ rootBefore={header}
175
+ selection={{ kind: "id", selectedId: shownId, getId: printId, onChange: select }}
176
+ columns={columns}
177
+ items={rows}
178
+ sortColumnId={sort.columnId}
179
+ sortDirection={sort.direction}
180
+ onHeaderClick={(columnId) => {
181
+ if (isPrintColumnId(columnId)) {
182
+ setSort((current) => nextHeaderSort(current, columnId, {
183
+ firstDirection: (id) => (id === "side" ? "asc" : "desc"),
184
+ resetTo: DEFAULT_PRINT_SORT,
185
+ }));
186
+ }
187
+ }}
188
+ onSortChange={(columnId, direction) => {
189
+ if (isPrintColumnId(columnId)) setSort({ columnId, direction });
190
+ }}
191
+ resetScrollKey={`${sort.columnId ?? ""}:${sort.direction}`}
192
+ getItemKey={printId}
193
+ renderCell={renderPrintCell}
194
+ selectedTextOverridesCellColor
195
+ emptyStateTitle={loading ? loadingText("kept prints") : empty}
196
+ />
197
+ );
198
+ }
@@ -5,10 +5,21 @@ import {
5
5
  fetchBondTape,
6
6
  issuerFallbackText,
7
7
  noPrintsText,
8
+ parseBondQuery,
8
9
  quotedCompanyName,
9
10
  type CorporateBond,
10
11
  } from "./client";
11
12
  import { bondStackPriority, formatBondChange, formatBondDecimal, sharesOneIssuer, type BondColumnId } from "./model";
13
+ import {
14
+ HISTORY_RANGES,
15
+ keptSinceText,
16
+ pricedDays,
17
+ readStoredHistory,
18
+ storedHistoryRefusal,
19
+ type HistoryRange,
20
+ } from "./history";
21
+ import { logFailure } from "../../../utils/log-failure";
22
+ import type { StoredBondPayload } from "../../../api-client/bond-trades";
12
23
 
13
24
  const decimal = (digits: number) => (value: unknown) => (
14
25
  typeof value === "number" ? formatBondDecimal(value, digits) : "—"
@@ -57,6 +68,29 @@ function reportRow(bond: CorporateBond) {
57
68
  };
58
69
  }
59
70
 
71
+ const HISTORY_COLUMNS: HeadlessPaneColumn[] = [
72
+ { key: "date", header: "Date" },
73
+ { key: "price", header: "Price", align: "right", format: decimal(3) },
74
+ { key: "yield", header: "Yield", align: "right", format: decimal(3) },
75
+ { key: "prints", header: "Prints", align: "right" },
76
+ ];
77
+
78
+ /** A bond's kept daily closes in the range, newest first, titled by since when prints are kept. */
79
+ function historySection(history: StoredBondPayload, range: HistoryRange) {
80
+ const days = HISTORY_RANGES.find((entry) => entry.value === range)!.days;
81
+ const from = new Date(Date.parse(`${history.to}T00:00:00Z`) - (days - 1) * 86_400_000).toISOString().slice(0, 10);
82
+ // A server from before daily closes were served answers none.
83
+ const rows = pricedDays(history.days ?? []).filter((day) => day.date >= from).reverse();
84
+ return {
85
+ title: history.keptSince ? `Daily closes, kept since ${history.keptSince}` : "Daily closes",
86
+ columns: HISTORY_COLUMNS,
87
+ rows: rows.map((day) => ({ id: day.date, date: day.date, price: day.price, yield: day.yield, prints: day.prints })),
88
+ empty: history.backfillPending
89
+ ? "No kept prints yet; the source's earlier prints are still being read."
90
+ : `No kept prints since ${from}.`,
91
+ };
92
+ }
93
+
60
94
  /** The latest corporate and agency bond sales, or one issuer's, symbol's or CUSIP's, asked of the tape itself. */
61
95
  export const traceBondsHeadless: HeadlessPaneDefinition<"bundle"> = {
62
96
  shape: "bundle",
@@ -66,20 +100,37 @@ export const traceBondsHeadless: HeadlessPaneDefinition<"bundle"> = {
66
100
  placeholder: "issuer, symbol or CUSIP",
67
101
  description: "Issuer name (matched from its start), symbol root, stock ticker or CUSIP. Leave it out for the market's latest sales.",
68
102
  },
69
- options: [],
103
+ options: [
104
+ {
105
+ key: "range",
106
+ type: "enum",
107
+ description: "How far back a CUSIP's kept daily closes reach (Gloom Pro).",
108
+ values: HISTORY_RANGES.map((entry) => ({ value: entry.value })),
109
+ defaultValue: "3M",
110
+ example: "--range 1Y",
111
+ },
112
+ ],
70
113
  discovery: {
71
114
  aliases: ["TRACE"],
72
- dataRequirements: ["Corporate and agency bond last sales"],
115
+ dataRequirements: ["Corporate and agency bond last sales", "Kept bond prints (Gloom Pro)"],
73
116
  limitations: [
74
117
  "One page of 100 bonds, most recent last sale first",
75
118
  "An issuer name matches the start of the issuer's name; a symbol matches the tape's own symbol root, which can differ from the stock ticker. A ticker with no bonds under either is asked once more by the name its quote gives the company",
76
119
  "An issuer's bonds that have matured are left out; a CUSIP shows its bond either way",
120
+ "A CUSIP or a ticker looked up here is kept from then on, with the prints the source still publishes for it (about three years); a CUSIP's daily closes start where its prints are kept, and nothing before that is shown",
77
121
  ],
78
122
  },
79
123
  describe: "Latest corporate and agency bond sales",
80
124
  freshness: { source: "FINRA", status: "not-a-feed", basis: "last sales", observedKey: "lastTradeDate" },
81
125
  async load(args, ctx) {
82
126
  const argument = Array.isArray(args.argument) ? args.argument.join(" ") : args.argument ?? "";
127
+ // A CUSIP's kept history, and a ticker's bonds kept from now on, read beside the tape: Gloom Pro, and never what fails it.
128
+ const stored = readStoredHistory(parseBondQuery(argument), ctx.apiClient, { signal: ctx.signal })
129
+ .then((history) => ({ history, note: null }))
130
+ .catch((error: unknown) => {
131
+ if (ctx.signal.aborted) return { history: null, note: null };
132
+ return { history: null, note: storedHistoryRefusal(error) ?? logFailure("trace-bonds.headless", "Load kept bond prints failed", "Kept price history unavailable.")(error) };
133
+ });
83
134
  const tape = await fetchBondTape(argument, {
84
135
  signal: ctx.signal,
85
136
  // A stock ticker with no bonds of its own: its company, as its quote names it.
@@ -90,6 +141,10 @@ export const traceBondsHeadless: HeadlessPaneDefinition<"bundle"> = {
90
141
  });
91
142
  const { query, bonds, tradeDate, truncated, issuer, failures } = tape;
92
143
  const shown = issuer && bonds.length > 0;
144
+ const range = (HISTORY_RANGES.some((entry) => entry.value === args.options.range) ? args.options.range : "3M") as HistoryRange;
145
+ const { history, note: historyNote } = await stored;
146
+ ctx.signal.throwIfAborted();
147
+ const kept = history ? keptSinceText(history) : null;
93
148
  return {
94
149
  sections: [{
95
150
  // An empty answer is its message alone, dated in its own words.
@@ -97,10 +152,12 @@ export const traceBondsHeadless: HeadlessPaneDefinition<"bundle"> = {
97
152
  columns: reportColumns(bonds),
98
153
  rows: bonds.map(reportRow),
99
154
  ...(query ? { empty: noPrintsText(query, tradeDate, issuer) } : {}),
100
- }],
155
+ }, ...(history ? [historySection(history, range)] : [])],
101
156
  complete: failures.length === 0,
102
157
  ...(failures.length > 0 ? { errors: failures } : {}),
103
- ...(truncated ? { notes: [TRUNCATED_TEXT] } : {}),
158
+ ...(truncated || kept || historyNote ? {
159
+ notes: [...(truncated ? [TRUNCATED_TEXT] : []), ...(kept ? [kept] : []), ...(historyNote ? [historyNote] : [])],
160
+ } : {}),
104
161
  ...(shown ? { warnings: [issuerFallbackText(query!, issuer)] } : {}),
105
162
  metadata: {
106
163
  tradeDate,
@@ -108,6 +165,7 @@ export const traceBondsHeadless: HeadlessPaneDefinition<"bundle"> = {
108
165
  ...(query ? { query: query.text } : {}),
109
166
  ...(issuer ? { issuerName: issuer.name, company: issuer.company } : {}),
110
167
  ...(truncated ? { truncated } : {}),
168
+ ...(history ? { keptSince: history.keptSince, backfillPending: history.backfillPending } : {}),
111
169
  },
112
170
  // One issuer's rows are each issue's own last sale, however old: a history, not stale rows.
113
171
  ...(query ? { freshness: { oldest: null } } : {}),