@gloom-sh/terminal 0.19.5 → 0.20.0

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 (318) hide show
  1. package/LICENSE +0 -4
  2. package/package.json +6 -5
  3. package/patches/@opentui%2Fcore@0.3.2.patch +86 -25
  4. package/patches/electrobun-devkit@2.0.5.patch +148 -0
  5. package/src/api-client/bond-trades.ts +59 -0
  6. package/src/api-client/data.ts +21 -0
  7. package/src/api-client/equity-screener.ts +23 -0
  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 +350 -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/pane-runtime/index.tsx +2 -0
  36. package/src/app/pane-runtime/plugin-bindings.ts +10 -1
  37. package/src/app/runtime/desktop-deeplink.ts +41 -6
  38. package/src/app/star-prompt/status-line.tsx +1 -1
  39. package/src/app.tsx +64 -23
  40. package/src/architecture/ui-tokens-allowlist.json +0 -8
  41. package/src/cli/commands/market.ts +149 -10
  42. package/src/cli/commands/search.ts +21 -3
  43. package/src/cli/commands/ticker.ts +90 -36
  44. package/src/cli/desktop-pane-shot-browser.ts +69 -3
  45. package/src/cli/glossary.ts +3 -3
  46. package/src/cli/known-gaps.ts +8 -0
  47. package/src/cli/listing-arg.ts +12 -0
  48. package/src/cli/pane-functions/capabilities.ts +2 -0
  49. package/src/cli/pane-functions/catalog.ts +25 -5
  50. package/src/cli/pane-functions/function-help.ts +8 -5
  51. package/src/cli/pane-functions/headless.ts +4 -3
  52. package/src/cli/pane-functions/resolver.ts +75 -2
  53. package/src/cli/quote-answer.ts +9 -0
  54. package/src/cli/symbol-list.ts +54 -2
  55. package/src/cli/symbol-rows.ts +14 -2
  56. package/src/cli/ticker-resolution.ts +89 -20
  57. package/src/components/chart/composite/axis-overlays.tsx +60 -27
  58. package/src/components/chart/composite/composite-chart.tsx +118 -63
  59. package/src/components/chart/composite/cursor-source.ts +111 -0
  60. package/src/components/chart/composite/format.ts +168 -6
  61. package/src/components/chart/composite/legend.tsx +8 -4
  62. package/src/components/chart/composite/panel-labels.ts +20 -1
  63. package/src/components/chart/composite/panel-surface.tsx +201 -92
  64. package/src/components/chart/composite/price-axis-labels.tsx +92 -46
  65. package/src/components/chart/composite/price-series.ts +31 -8
  66. package/src/components/chart/composite/scene.ts +154 -59
  67. package/src/components/chart/composite/series-axis-tags.tsx +4 -2
  68. package/src/components/chart/composite/time-axis.ts +13 -5
  69. package/src/components/chart/composite/time-scale.ts +211 -56
  70. package/src/components/chart/composite/types.ts +11 -1
  71. package/src/components/chart/composite/use-composite-chart-keyboard.ts +43 -14
  72. package/src/components/chart/curve/curve-surface.tsx +5 -2
  73. package/src/components/chart/curve/model.ts +4 -1
  74. package/src/components/chart/native/use-bitmap-metrics.ts +81 -0
  75. package/src/components/chart/static/series.ts +3 -0
  76. package/src/components/command-bar/commands/collection-list.ts +81 -0
  77. package/src/components/command-bar/commands/direct/index.ts +6 -0
  78. package/src/components/command-bar/commands/registry.ts +8 -0
  79. package/src/components/command-bar/layout-items/current-layout.ts +22 -1
  80. package/src/components/command-bar/layout-items/focused-pane.ts +22 -1
  81. package/src/components/command-bar/pane-templates/items.ts +19 -3
  82. package/src/components/command-bar/pane-templates/workflow.ts +5 -0
  83. package/src/components/command-bar/routes/root/results.ts +23 -3
  84. package/src/components/command-bar/routes/root/selection.ts +4 -2
  85. package/src/components/command-bar/routes/root/shortcut-feedback.ts +1 -1
  86. package/src/components/command-bar/routes/root/shortcut-items.ts +3 -4
  87. package/src/components/command-bar/routes/root/shortcuts.ts +58 -14
  88. package/src/components/command-bar/routes/root/ticker-first.ts +32 -0
  89. package/src/components/command-bar/surface/environment.ts +2 -0
  90. package/src/components/command-bar/view-model.ts +7 -0
  91. package/src/components/command-bar/workflow/ops.ts +2 -1
  92. package/src/components/command-bar/workflow/tickers.ts +20 -0
  93. package/src/components/data-table/export.ts +4 -1
  94. package/src/components/layout/detached-pane-shell.tsx +10 -37
  95. package/src/components/layout/double-escape-close.ts +90 -0
  96. package/src/components/layout/header.tsx +3 -2
  97. package/src/components/layout/market-summary.ts +6 -3
  98. package/src/components/layout/pane/footer/index.tsx +2 -6
  99. package/src/components/layout/pane/footer/model.ts +6 -12
  100. package/src/components/layout/shell/active-drag.ts +53 -11
  101. package/src/components/layout/shell/drag/magnets.ts +128 -19
  102. package/src/components/layout/shell/menu.ts +15 -1
  103. package/src/components/layout/shell/pane/actions.ts +10 -2
  104. package/src/components/layout/shell/pane/management-shortcuts.ts +13 -51
  105. package/src/components/layout/shell/ticker-link-menu.ts +12 -3
  106. package/src/components/layout/status-bar.tsx +24 -78
  107. package/src/components/layout/status-widget-space.ts +5 -5
  108. package/src/components/onboarding/onboarding-keyboard.ts +5 -1
  109. package/src/components/onboarding/onboarding-wizard.tsx +15 -4
  110. package/src/components/onboarding/portfolio-step/positions-panel.tsx +9 -6
  111. package/src/components/onboarding/use-onboarding-progress.ts +20 -1
  112. package/src/components/price-sparkline/view.tsx +14 -6
  113. package/src/components/ticker/badge/index.tsx +8 -4
  114. package/src/components/ticker/badge/list.tsx +23 -7
  115. package/src/components/ui/column-grid.tsx +8 -2
  116. package/src/components/ui/data-table/index.tsx +5 -1
  117. package/src/components/ui/data-table/opentui/model.ts +4 -1
  118. package/src/components/ui/data-table/render-cell.ts +19 -0
  119. package/src/components/ui/delayed-mark.tsx +59 -7
  120. package/src/components/ui/icon.tsx +1 -8
  121. package/src/components/ui/menu.tsx +6 -1
  122. package/src/components/ui/tabs.tsx +5 -2
  123. package/src/core/state/app/layout.ts +18 -3
  124. package/src/core/state/app/state.ts +2 -0
  125. package/src/core/state/app/types.ts +5 -0
  126. package/src/data/config/layout.ts +3 -0
  127. package/src/data/config/store/normalize.ts +39 -4
  128. package/src/i18n/es.ts +13 -3
  129. package/src/i18n/ja.ts +13 -3
  130. package/src/i18n/ko.ts +13 -3
  131. package/src/i18n/zh-cn.ts +13 -3
  132. package/src/i18n/zh-tw.ts +13 -3
  133. package/src/layout/pane-manager/floating-placement.ts +7 -4
  134. package/src/layout/pane-manager/floating.ts +5 -2
  135. package/src/market-data/bond-funds.ts +19 -0
  136. package/src/market-data/futures-contract.ts +14 -3
  137. package/src/market-data/market/freshness.ts +18 -0
  138. package/src/market-data/market/status.ts +15 -2
  139. package/src/plugins/builtin/bond-calculator/headless.ts +2 -1
  140. package/src/plugins/builtin/bond-calculator/index.tsx +1 -1
  141. package/src/plugins/builtin/bond-calculator/model.ts +14 -5
  142. package/src/plugins/builtin/bond-calculator/pane.tsx +1 -1
  143. package/src/plugins/builtin/buildout/cells.tsx +25 -45
  144. package/src/plugins/builtin/buildout/detail/company.tsx +3 -3
  145. package/src/plugins/builtin/buildout/detail/index.tsx +1 -1
  146. package/src/plugins/builtin/buildout/detail/intel.tsx +4 -7
  147. package/src/plugins/builtin/buildout/detail/site.tsx +4 -4
  148. package/src/plugins/builtin/buildout/detail/ui.tsx +39 -38
  149. package/src/plugins/builtin/buildout/format.ts +23 -1
  150. package/src/plugins/builtin/buildout/model/types.ts +1 -0
  151. package/src/plugins/builtin/buildout/pane/index.tsx +2 -8
  152. package/src/plugins/builtin/buildout/table-model.ts +12 -4
  153. package/src/plugins/builtin/cds/headless.ts +1 -0
  154. package/src/plugins/builtin/cds/index.tsx +1 -1
  155. package/src/plugins/builtin/chat/content/composer.tsx +21 -27
  156. package/src/plugins/builtin/chat/content/index.tsx +31 -3
  157. package/src/plugins/builtin/chat/content/shortcuts.ts +4 -2
  158. package/src/plugins/builtin/chat/content/snapshot.ts +0 -3
  159. package/src/plugins/builtin/cloud/auth-actions.tsx +51 -23
  160. package/src/plugins/builtin/cloud/plugin.tsx +2 -0
  161. package/src/plugins/builtin/cloud/trial-offer-status-widget.tsx +3 -3
  162. package/src/plugins/builtin/cloud/upgrade-status-widget.tsx +44 -12
  163. package/src/plugins/builtin/congress-trades/model.ts +2 -1
  164. package/src/plugins/builtin/congress-trades/pane.tsx +3 -0
  165. package/src/plugins/builtin/correlation/headless.ts +3 -2
  166. package/src/plugins/builtin/crypto-board/pane.tsx +5 -4
  167. package/src/plugins/builtin/custom-view/index.tsx +1 -1
  168. package/src/plugins/builtin/custom-view/loader.ts +85 -8
  169. package/src/plugins/builtin/custom-view/view-spec.ts +28 -0
  170. package/src/plugins/builtin/debt-maturities/headless.ts +11 -2
  171. package/src/plugins/builtin/debt-maturities/model.ts +66 -0
  172. package/src/plugins/builtin/debt-maturities/pane.tsx +23 -4
  173. package/src/plugins/builtin/earnings-ripple/pane.tsx +1 -1
  174. package/src/plugins/builtin/econ/calendar-model.ts +28 -6
  175. package/src/plugins/builtin/equity-screener/client.ts +1 -1
  176. package/src/plugins/builtin/equity-screener/criterion-editor.tsx +16 -19
  177. package/src/plugins/builtin/equity-screener/headless.ts +37 -3
  178. package/src/plugins/builtin/equity-screener/ideas.ts +67 -3
  179. package/src/plugins/builtin/equity-screener/model.ts +238 -27
  180. package/src/plugins/builtin/equity-screener/pane.tsx +88 -18
  181. package/src/plugins/builtin/equity-screener/screen-check.ts +7 -4
  182. package/src/plugins/builtin/equity-screener/watchlist.ts +33 -0
  183. package/src/plugins/builtin/executives/format.ts +5 -4
  184. package/src/plugins/builtin/executives/pane.tsx +1 -1
  185. package/src/plugins/builtin/futures-curve/client.ts +19 -0
  186. package/src/plugins/builtin/futures-curve/headless.ts +52 -13
  187. package/src/plugins/builtin/futures-curve/index.tsx +1 -1
  188. package/src/plugins/builtin/futures-curve/model.ts +77 -6
  189. package/src/plugins/builtin/futures-curve/pane.tsx +19 -3
  190. package/src/plugins/builtin/help/index.tsx +55 -1
  191. package/src/plugins/builtin/insider/model.ts +30 -2
  192. package/src/plugins/builtin/jobs/model.ts +2 -2
  193. package/src/plugins/builtin/macro-day/client.ts +41 -0
  194. package/src/plugins/builtin/macro-day/headless.ts +19 -9
  195. package/src/plugins/builtin/macro-day/model.ts +3 -1
  196. package/src/plugins/builtin/market-movers/index.tsx +4 -3
  197. package/src/plugins/builtin/mna/distress/headless.ts +1 -0
  198. package/src/plugins/builtin/mna/model.ts +2 -2
  199. package/src/plugins/builtin/notes/files.ts +2 -0
  200. package/src/plugins/builtin/notes/owner.tsx +20 -1
  201. package/src/plugins/builtin/notes/quick-notes-pane.tsx +22 -4
  202. package/src/plugins/builtin/notes/store.ts +6 -1
  203. package/src/plugins/builtin/perps/pane.tsx +3 -1
  204. package/src/plugins/builtin/portfolio-list/cli/bulk-symbols.ts +17 -0
  205. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +2 -1
  206. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +2 -1
  207. package/src/plugins/builtin/portfolio-list/header.tsx +1 -1
  208. package/src/plugins/builtin/rate-path/headless.ts +24 -10
  209. package/src/plugins/builtin/research/corporate-actions-pane.tsx +29 -25
  210. package/src/plugins/builtin/research/event-model.ts +10 -3
  211. package/src/plugins/builtin/research/events-headless.ts +20 -2
  212. package/src/plugins/builtin/sec/fund-facts.ts +17 -1
  213. package/src/plugins/builtin/sec/index.tsx +1 -1
  214. package/src/plugins/builtin/series-inventory.ts +1 -0
  215. package/src/plugins/builtin/shared/earnings-report.ts +7 -2
  216. package/src/plugins/builtin/shared/members-menu.tsx +103 -38
  217. package/src/plugins/builtin/shared/use-quote-board.ts +85 -46
  218. package/src/plugins/builtin/short-interest/headless.ts +1 -1
  219. package/src/plugins/builtin/short-interest/model.ts +15 -6
  220. package/src/plugins/builtin/short-interest/publications-model.ts +22 -1
  221. package/src/plugins/builtin/short-interest/publications-pane.tsx +13 -4
  222. package/src/plugins/builtin/short-interest/types.ts +2 -0
  223. package/src/plugins/builtin/short-interest/watch-model.ts +1 -1
  224. package/src/plugins/builtin/thirteenf/overlap-pane.tsx +3 -0
  225. package/src/plugins/builtin/thirteenf/pane.tsx +3 -0
  226. package/src/plugins/builtin/ticker-detail/overview/model.ts +5 -3
  227. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +4 -4
  228. package/src/plugins/builtin/time-sales/pane.tsx +3 -2
  229. package/src/plugins/builtin/trace-bonds/client.ts +7 -4
  230. package/src/plugins/builtin/trace-bonds/detail.tsx +198 -0
  231. package/src/plugins/builtin/trace-bonds/headless.ts +62 -4
  232. package/src/plugins/builtin/trace-bonds/history.ts +155 -0
  233. package/src/plugins/builtin/trace-bonds/index.tsx +1 -1
  234. package/src/plugins/builtin/trace-bonds/pane.tsx +64 -5
  235. package/src/plugins/builtin/volatility/client.ts +6 -1
  236. package/src/plugins/builtin/volatility/headless.ts +0 -1
  237. package/src/plugins/builtin/yield-curve/curves.ts +15 -0
  238. package/src/plugins/builtin/yield-curve/headless.ts +6 -1
  239. package/src/plugins/builtin/yield-curve/index.tsx +5 -8
  240. package/src/plugins/host-modules.ts +22 -3
  241. package/src/plugins/host-smoke.ts +6 -3
  242. package/src/plugins/installer.ts +16 -3
  243. package/src/plugins/plugin-names.ts +11 -2
  244. package/src/portfolio/collection-name.ts +19 -0
  245. package/src/remote/controller.ts +9 -2
  246. package/src/remote/schema.ts +2 -1
  247. package/src/renderers/browser/http-proxy-transport.ts +78 -8
  248. package/src/renderers/cloudflare/http-proxy.ts +73 -3
  249. package/src/renderers/cloudflare/proxy-session.ts +47 -24
  250. package/src/renderers/cloudflare/worker.ts +44 -4
  251. package/src/renderers/desktop/geometry.ts +279 -0
  252. package/src/renderers/desktop/screen-setup.ts +246 -0
  253. package/src/renderers/desktop/sequential-window-host.ts +179 -0
  254. package/src/renderers/desktop/test-utils.ts +71 -0
  255. package/src/renderers/desktop/window-controller.ts +433 -0
  256. package/src/renderers/desktop/window-host.ts +70 -0
  257. package/src/renderers/desktop/window-layouts.ts +630 -0
  258. package/src/renderers/dom/data-frames.ts +15 -4
  259. package/src/renderers/dom/desktop/icons.tsx +0 -2
  260. package/src/renderers/dom/styles.css +0 -3
  261. package/src/renderers/electrobun/bun/application-menu/click.ts +1 -0
  262. package/src/renderers/electrobun/bun/application-menu/index.ts +4 -1
  263. package/src/renderers/electrobun/bun/desktop/backend-requests.ts +19 -8
  264. package/src/renderers/electrobun/bun/desktop/backend.ts +320 -19
  265. package/src/renderers/electrobun/bun/desktop/detached-windows.ts +83 -61
  266. package/src/renderers/electrobun/bun/desktop/host-requests.ts +4 -14
  267. package/src/renderers/electrobun/bun/desktop/initialization.ts +30 -11
  268. package/src/renderers/electrobun/bun/desktop/install-records.ts +59 -0
  269. package/src/renderers/electrobun/bun/desktop/installer-folder.ts +208 -592
  270. package/src/renderers/electrobun/bun/desktop/macos-objc.ts +14 -0
  271. package/src/renderers/electrobun/bun/desktop/screen-setup-file.ts +55 -0
  272. package/src/renderers/electrobun/bun/desktop/state-broadcaster.ts +44 -8
  273. package/src/renderers/electrobun/bun/desktop/update.ts +1 -1
  274. package/src/renderers/electrobun/bun/desktop/workspace/index.ts +298 -97
  275. package/src/renderers/electrobun/bun/desktop/workspace/requests.ts +44 -6
  276. package/src/renderers/electrobun/bun/index.ts +22 -109
  277. package/src/renderers/electrobun/bun/window/create.ts +23 -3
  278. package/src/renderers/electrobun/bun/window/electrobun-window-host.ts +306 -0
  279. package/src/renderers/electrobun/bun/window/events.ts +4 -4
  280. package/src/renderers/electrobun/bun/window/focus.ts +0 -25
  281. package/src/renderers/electrobun/bun/window/frame.ts +2 -1
  282. package/src/renderers/electrobun/bun/window/native-min-size.ts +322 -0
  283. package/src/renderers/electrobun/bun/window/remembered-frame.ts +4 -82
  284. package/src/renderers/electrobun/shared/protocol.ts +44 -2
  285. package/src/renderers/electrobun/view/backend-rpc.ts +16 -1
  286. package/src/renderers/electrobun/view/desktop/window/bridge.ts +63 -3
  287. package/src/renderers/electrobun/view/main.tsx +13 -7
  288. package/src/series/fred-argument.ts +17 -0
  289. package/src/sources/gloomberb-cloud/index.ts +5 -7
  290. package/src/sources/provider-router/batches.ts +18 -3
  291. package/src/sources/provider-router/financial-routes.ts +7 -1
  292. package/src/sources/provider-router/financials.ts +18 -4
  293. package/src/state/app/context/index.tsx +16 -2
  294. package/src/state/desktop-windows.ts +63 -0
  295. package/src/sync/other-window-tabs.ts +62 -0
  296. package/src/tickers/company-name-listing.ts +23 -3
  297. package/src/tickers/listing-fate.ts +147 -1
  298. package/src/tickers/terminal-codes.ts +5 -0
  299. package/src/time-series/types.ts +6 -0
  300. package/src/types/config.ts +10 -1
  301. package/src/types/data-provider.ts +14 -0
  302. package/src/types/desktop-window.ts +71 -2
  303. package/src/types/financials.ts +19 -3
  304. package/src/types/headless.ts +21 -0
  305. package/src/types/plugin.ts +6 -0
  306. package/src/ui/index.tsx +14 -13
  307. package/src/ui/same-props.ts +58 -0
  308. package/src/utils/cli-output.ts +33 -4
  309. package/src/utils/double-escape-close.ts +38 -16
  310. package/src/utils/format.ts +30 -5
  311. package/src/utils/futures-generic.ts +12 -0
  312. package/src/utils/http-proxy-upstream.ts +6 -2
  313. package/src/utils/plugin-proxy-hosts.json +0 -4
  314. package/src/utils/plugin-proxy-hosts.ts +22 -0
  315. package/src/utils/price-earnings.ts +18 -0
  316. package/src/utils/sec-filings.ts +7 -1
  317. package/patches/electrobun@1.18.1.patch +0 -633
  318. package/src/api-client/types.ts +0 -2441
@@ -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";
@@ -235,9 +235,11 @@ export function buildOverviewStats({
235
235
  if (trailingPE != null) {
236
236
  stats.push({ label: "P/E (TTM)", value: formatPriceEarnings(trailingPE) });
237
237
  }
238
+ // Next fiscal year's consensus, and the year it is for: N/M over a loss, a dash when there is none.
238
239
  const forwardPE = liveForwardPE(quote, fundamentals);
239
- if (forwardPE != null) {
240
- stats.push({ label: "Fwd P/E", value: formatPriceEarnings(forwardPE) });
240
+ if (forwardPE != null || forwardPEAsked(fundamentals)) {
241
+ const year = forwardFiscalYear(fundamentals?.forwardEpsPeriodEnd);
242
+ stats.push({ label: year ? `Fwd P/E ${year}` : "Fwd P/E", value: formatPriceEarnings(forwardPE) });
241
243
  }
242
244
  if (fundamentals?.eps != null) {
243
245
  stats.push({ label: "EPS", value: formatReportedMoney(fundamentals.eps, fundamentalsEpsCurrency({ fundamentals, financialCurrency, quote }), true) });
@@ -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);
@@ -1,4 +1,4 @@
1
- import { useEffect, useMemo, useRef, useState } from "react";
1
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
2
  import { Box } from "../../../ui";
3
3
  import { usePaneSettingValue, useShortcut } from "../../../public/react";
4
4
  import { createDataTableCsv } from "../../../components/data-table/export";
@@ -124,7 +124,8 @@ function TimeSalesView({ width, height, focused, symbol, exchange }: PaneProps &
124
124
  ...(!data.connected || resource.snapshotOnly ? [{ id: "snapshot", parts: [{ text: "snapshot", tone: "warning" as const }] }] : [])] : [] });
125
125
  const quoteColumns = useMemo(() => dropColumnsToFit(QUOTES, width - 1, QUOTE_DROP_ORDER), [width]);
126
126
  const columns = tab === "quotes" ? quoteColumns : TRADES;
127
- const selectTab = (value: string) => { setTab(value); setDetail(null); setSelected(null); };
127
+ // Kept between prints, so the tab strip skips the renders the tape gives the pane.
128
+ const selectTab = useCallback((value: string) => { setTab(value); setDetail(null); setSelected(null); }, [setTab]);
128
129
  const { strip: tabStrip, rows: tabRows } = usePaneTabs({ tabs: TABS, activeValue: tab, onSelect: selectTab, focused: focused && !detail, dense: true });
129
130
  const renderCell = (row: TapeRow, column: DataTableColumn): DataTableCell => {
130
131
  if (row.trade) {
@@ -257,6 +257,9 @@ function bondId(raw: Record<string, unknown>, index: number): string {
257
257
  function parseBond(raw: unknown, index: number): CorporateBond | null {
258
258
  const record = recordOrNull(raw);
259
259
  if (!record) return null;
260
+ // A price of zero is no sale (a cancelled or defaulted print): the bond is listed with no last sale, never one at 0.
261
+ const price = numericOrNull(record.lastSalePrice);
262
+ const sold = price == null || price > 0;
260
263
  return {
261
264
  id: bondId(record, index),
262
265
  issuerName: textOrNull(record.issuerName) ?? "",
@@ -264,10 +267,10 @@ function parseBond(raw: unknown, index: number): CorporateBond | null {
264
267
  symbol: textOrNull(record.issueSymbolIdentifier),
265
268
  couponRate: numericOrNull(record.couponRate),
266
269
  maturityDate: saleDate(record.maturityDate),
267
- lastSalePrice: numericOrNull(record.lastSalePrice),
268
- lastSaleYield: numericOrNull(record.lastSaleYield),
269
- priceChangeNumber: saleChange(numericOrNull(record.priceChangeNumber), numericOrNull(record.lastSalePrice)),
270
- lastTradeDate: saleDate(record.lastTradeDate),
270
+ lastSalePrice: sold ? price : null,
271
+ lastSaleYield: sold ? numericOrNull(record.lastSaleYield) : null,
272
+ priceChangeNumber: sold ? saleChange(numericOrNull(record.priceChangeNumber), price) : null,
273
+ lastTradeDate: sold ? saleDate(record.lastTradeDate) : null,
271
274
  traceGradeCode: textOrNull(record.traceGradeCode),
272
275
  };
273
276
  }
@@ -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 } } : {}),
@@ -0,0 +1,155 @@
1
+ import { ApiRequestError } from "../../../api-client/errors";
2
+ import {
3
+ BOND_HISTORY_MAX_DAYS,
4
+ type StoredBondDay,
5
+ type StoredBondPayload,
6
+ type StoredBondPrint,
7
+ } from "../../../api-client/bond-trades";
8
+ import type { apiClient } from "../../../api-client";
9
+ import { signalWithTimeout } from "../../../utils/async-deadline";
10
+ import { formatCompact, MISSING_VALUE } from "../../../utils/format";
11
+ import { zonedDateKey } from "../../../utils/zoned-date-time";
12
+ import type { BondQuery } from "./client";
13
+ import type { TimeSeriesPoint } from "../../../time-series/types";
14
+
15
+ const TAPE_TIME_ZONE = "America/New_York";
16
+ const DAY_MS = 86_400_000;
17
+ /** How long a ticker's lookup waits for its bonds to be kept. */
18
+ const ISSUER_KEEP_TIMEOUT_MS = 5_000;
19
+ /** Prints a history read lists, newest first. */
20
+ const STORED_PRINTS_LIMIT = 200;
21
+
22
+ export type StoredBondClient = Pick<typeof apiClient, "getCloudStoredBond" | "getCloudStoredIssuerBonds">;
23
+
24
+ /** How far back the daily closes reach: their own range, at most the 1,100 days a read takes. */
25
+ export const HISTORY_RANGES = [
26
+ { value: "1M", days: 31 },
27
+ { value: "3M", days: 92 },
28
+ { value: "1Y", days: 366 },
29
+ { value: "3Y", days: BOND_HISTORY_MAX_DAYS },
30
+ ] as const;
31
+ export type HistoryRange = (typeof HISTORY_RANGES)[number]["value"];
32
+
33
+ /** The days a read asks for: `days` up to today in New York, the tape's calendar. */
34
+ function storedHistoryWindow(now = Date.now(), days: number = BOND_HISTORY_MAX_DAYS): { from: string; to: string } {
35
+ const to = zonedDateKey(now, TAPE_TIME_ZONE);
36
+ const from = new Date(Date.parse(`${to}T00:00:00Z`) - (Math.min(days, BOND_HISTORY_MAX_DAYS) - 1) * DAY_MS)
37
+ .toISOString().slice(0, 10);
38
+ return { from, to };
39
+ }
40
+
41
+ /**
42
+ * Since when a bond's prints are held: `Kept since 2023-11-03.`, and while
43
+ * the source's earlier prints are still to be read, that they are. Null
44
+ * before any day was read.
45
+ */
46
+ export function keptSinceText(payload: Pick<StoredBondPayload, "keptSince" | "backfillPending">): string | null {
47
+ if (!payload.keptSince) return null;
48
+ return payload.backfillPending
49
+ ? `Kept since ${payload.keptSince}; earlier prints are still being read.`
50
+ : `Kept since ${payload.keptSince}.`;
51
+ }
52
+
53
+ /** Trades and corrections no cancel names: the prints a history lists. A cancel and what it cancelled say nothing about the price. */
54
+ export function standingPrints(prints: readonly StoredBondPrint[]): StoredBondPrint[] {
55
+ return prints.filter((print) => print.status !== "cancel" && !print.cancelled);
56
+ }
57
+
58
+ /** Days with a price, oldest first: what the chart draws. */
59
+ export function pricedDays(days: readonly StoredBondDay[]): StoredBondDay[] {
60
+ return days.filter((day) => day.price != null);
61
+ }
62
+
63
+ /** Three weeks without a sale breaks the line instead of drawing prices nobody paid. */
64
+ const CHART_GAP_MS = 21 * DAY_MS;
65
+
66
+ /** The daily closes as the chart's points, oldest first, with a break across a long gap between sales. */
67
+ export function bondPricePoints(days: readonly StoredBondDay[]): TimeSeriesPoint[] {
68
+ const points: TimeSeriesPoint[] = [];
69
+ let previous: number | null = null;
70
+ for (const day of pricedDays(days)) {
71
+ const time = Date.parse(`${day.date}T00:00:00Z`);
72
+ if (!Number.isFinite(time)) continue;
73
+ if (previous !== null && time - previous > CHART_GAP_MS) {
74
+ const gap = new Date(previous + DAY_MS);
75
+ points.push({ date: gap, observedAt: gap, value: null });
76
+ }
77
+ const date = new Date(time);
78
+ points.push({ date, observedAt: date, value: day.price });
79
+ previous = time;
80
+ }
81
+ return points;
82
+ }
83
+
84
+ /** Par amount as published: `250K`, `1M+` where only a floor is published. */
85
+ export function formatPrintSize(print: Pick<StoredBondPrint, "quantity" | "quantityCapped">): string {
86
+ if (print.quantity == null) return MISSING_VALUE;
87
+ return `${formatCompact(print.quantity)}${print.quantityCapped ? "+" : ""}`;
88
+ }
89
+
90
+ /** The side the reporting dealer took. */
91
+ export function formatPrintSide(side: StoredBondPrint["side"]): string {
92
+ return side === "buy" ? "Buy" : side === "sell" ? "Sell" : MISSING_VALUE;
93
+ }
94
+
95
+ /** What a kept history says to an account without Gloom Pro. */
96
+ export const PRO_HISTORY_TEXT = "Kept price history needs Gloom Pro.";
97
+
98
+ /**
99
+ * Why a kept history could not be read, in the words the pane and `fn`
100
+ * show, or null for a failure worth reporting as one: the history is Gloom
101
+ * Pro, and a bond the store cannot tie to a company has none.
102
+ */
103
+ export function storedHistoryRefusal(error: unknown): string | null {
104
+ if (!(error instanceof ApiRequestError)) return null;
105
+ if (error.status === 401 || error.status === 403) return PRO_HISTORY_TEXT;
106
+ if (error.status === 404) return "No kept price history for this bond.";
107
+ return null;
108
+ }
109
+
110
+ /** A bond's kept history for the pane, or why there is none to read; any other failure is thrown. */
111
+ export async function loadStoredBond(
112
+ cusip: string,
113
+ client: Pick<StoredBondClient, "getCloudStoredBond">,
114
+ options: { signal?: AbortSignal; now?: number } = {},
115
+ ): Promise<{ history: StoredBondPayload | null; refusal: string | null }> {
116
+ try {
117
+ const history = await client.getCloudStoredBond(cusip, { ...storedHistoryWindow(options.now), limit: STORED_PRINTS_LIMIT }, { signal: options.signal });
118
+ return { history, refusal: null };
119
+ } catch (error) {
120
+ const refusal = storedHistoryRefusal(error);
121
+ if (!refusal) throw error;
122
+ return { history: null, refusal };
123
+ }
124
+ }
125
+
126
+ /**
127
+ * What a TRACE lookup reads of the kept history: one bond's, by its CUSIP;
128
+ * for a ticker, its company's bonds are kept from now on (no history is
129
+ * shown for them until one is opened). Null for a market-wide tape or a
130
+ * name the store cannot read.
131
+ */
132
+ export async function readStoredHistory(
133
+ query: BondQuery | null,
134
+ client: StoredBondClient,
135
+ options: { signal?: AbortSignal; days?: number; now?: number } = {},
136
+ ): Promise<StoredBondPayload | null> {
137
+ if (!query) return null;
138
+ if (query.kind === "cusip") {
139
+ return client.getCloudStoredBond(query.cusip, {
140
+ ...storedHistoryWindow(options.now, options.days),
141
+ limit: STORED_PRINTS_LIMIT,
142
+ }, { signal: options.signal });
143
+ }
144
+ // Asked so its bonds are kept, never waited on for long: the tape is the answer here.
145
+ if (query.ticker) {
146
+ const ticker = query.ticker;
147
+ await Promise.resolve()
148
+ .then(() => client.getCloudStoredIssuerBonds(ticker, { signal: signalWithTimeout(options.signal, ISSUER_KEEP_TIMEOUT_MS) }))
149
+ .catch(() => {
150
+ // Intentional ignore: keeping a company's bonds never changes the tape this report answers with.
151
+ return null;
152
+ });
153
+ }
154
+ return null;
155
+ }
@@ -24,7 +24,7 @@ export const traceBondsModule: PluginModule = {
24
24
  label: "Corporate Bond Tape",
25
25
  description: "Latest corporate and agency bond sales: issuer, coupon, price, yield, and grade.",
26
26
  keywords: ["bond", "bonds", "corporate", "agency", "coupon", "yield", "issuer", "cusip", "credit", "fixed income", "trace"],
27
- shortcut: { prefix: "TRACE", argKind: "text", argOptional: true, argPlaceholder: "issuer, symbol or CUSIP" },
27
+ shortcut: { prefix: "TRACE", argKind: "text", argOptional: true, focusedIssuer: true, argPlaceholder: "issuer, symbol or CUSIP" },
28
28
  headless: traceBondsHeadless,
29
29
  // Its sales date a capture, never the stock quote of a ticker typed as its argument (`TRACE CMLSQ`).
30
30
  reportFreshness: { source: "FINRA", status: "not-a-feed", basis: "last sales" },