@gloom-sh/terminal 0.20.3 → 0.20.5

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 (348) hide show
  1. package/README.md +2 -0
  2. package/bin/gloom +9 -0
  3. package/bin/without-bun.cjs +98 -0
  4. package/package.json +3 -1
  5. package/src/account/auth-dialog.tsx +17 -0
  6. package/src/api-client/data.ts +144 -35
  7. package/src/api-client/fx-interventions.ts +64 -0
  8. package/src/api-client/index.ts +1 -0
  9. package/src/api-client/release-summaries.ts +21 -0
  10. package/src/api-client/types/econ.ts +12 -0
  11. package/src/api-client/yield-curves.ts +1 -1
  12. package/src/app/global-shortcuts.ts +4 -1
  13. package/src/app/keybindings/actions.ts +8 -2
  14. package/src/app/keybindings/config.ts +2 -1
  15. package/src/app/keybindings/index.ts +1 -0
  16. package/src/app/keybindings/labels.ts +6 -1
  17. package/src/app/keybindings/resolve.ts +23 -4
  18. package/src/app/keybindings/terminal-keys.ts +35 -0
  19. package/src/app/pane-runtime/index.tsx +2 -2
  20. package/src/app/pane-runtime/ticker-open-runtime.ts +274 -67
  21. package/src/architecture/ui-literals-allowlist.json +1 -1
  22. package/src/capabilities/chart-series.ts +27 -1
  23. package/src/cli/commands/keybindings.ts +5 -5
  24. package/src/cli/commands/market.ts +154 -21
  25. package/src/cli/commands/news-search.ts +60 -10
  26. package/src/cli/commands/overview.ts +16 -1
  27. package/src/cli/commands/plugins.ts +27 -5
  28. package/src/cli/commands/remote.ts +16 -17
  29. package/src/cli/commands/system.ts +20 -4
  30. package/src/cli/commands/ticker.ts +60 -19
  31. package/src/cli/fx-forward.ts +25 -7
  32. package/src/cli/glossary.ts +19 -5
  33. package/src/cli/history-rows.ts +5 -3
  34. package/src/cli/index.ts +8 -8
  35. package/src/cli/known-gaps.ts +27 -1
  36. package/src/cli/listing-arg.ts +11 -1
  37. package/src/cli/name-entries.ts +5 -1
  38. package/src/cli/not-a-ticker.ts +4 -0
  39. package/src/cli/pane-functions/function-help.ts +5 -5
  40. package/src/cli/report-tables.ts +18 -6
  41. package/src/cli/result.ts +15 -7
  42. package/src/cli/types.ts +2 -0
  43. package/src/components/chart/composite/axis-overlays.tsx +22 -0
  44. package/src/components/chart/composite/composite-chart.tsx +54 -13
  45. package/src/components/chart/composite/event-captions.ts +109 -0
  46. package/src/components/chart/composite/event-guides.ts +74 -0
  47. package/src/components/chart/composite/rasterizer.ts +2 -0
  48. package/src/components/chart/composite/text-renderer.ts +2 -0
  49. package/src/components/chart/composite/types.ts +31 -0
  50. package/src/components/command-bar/layout-items/focused-pane.ts +5 -5
  51. package/src/components/command-bar/pane-settings.ts +2 -2
  52. package/src/components/command-bar/routes/root/provider-search.ts +5 -4
  53. package/src/components/command-bar/routes/root/results.ts +6 -2
  54. package/src/components/command-bar/routes/ticker-search/results.ts +51 -0
  55. package/src/components/command-bar/routes/ticker-search/route.ts +3 -2
  56. package/src/components/input-search-bar.tsx +9 -2
  57. package/src/components/layout/detached-pane-shell.tsx +1 -1
  58. package/src/components/layout/floating-pane.tsx +5 -1
  59. package/src/components/layout/pane/footer/index.tsx +21 -14
  60. package/src/components/layout/pane/footer/model.ts +6 -0
  61. package/src/components/layout/pane/header.tsx +2 -0
  62. package/src/components/layout/shell/action-menu-overlay.tsx +10 -5
  63. package/src/components/layout/shell/active-drag.ts +149 -105
  64. package/src/components/layout/shell/drag/drop-zones.ts +162 -0
  65. package/src/components/layout/shell/drag/index.ts +47 -218
  66. package/src/components/layout/shell/drag/live.ts +10 -3
  67. package/src/components/layout/shell/drag/overlays.tsx +182 -5
  68. package/src/components/layout/shell/drag/runtime.ts +29 -6
  69. package/src/components/layout/shell/drag/shared-edges.ts +156 -0
  70. package/src/components/layout/shell/index.tsx +11 -6
  71. package/src/components/layout/shell/menu.ts +11 -2
  72. package/src/components/layout/shell/native/pointer-runtime.ts +25 -0
  73. package/src/components/layout/shell/native/window-state.ts +2 -2
  74. package/src/components/layout/shell/pane/capture.ts +4 -1
  75. package/src/components/layout/shell/pane/layers.tsx +71 -7
  76. package/src/components/layout/shell/terminal-pointer-runtime.ts +18 -9
  77. package/src/components/layout/shell/window-mode/index.ts +8 -10
  78. package/src/components/layout/status-bar.tsx +6 -1
  79. package/src/components/layout/window-edit/mode.ts +39 -7
  80. package/src/components/layout/window-edit/presentation.ts +1 -1
  81. package/src/components/onboarding/first-run-workspace.ts +44 -2
  82. package/src/components/onboarding/onboarding-frame.tsx +11 -2
  83. package/src/components/onboarding/onboarding-keyboard.ts +20 -0
  84. package/src/components/onboarding/onboarding-wizard.tsx +16 -11
  85. package/src/components/onboarding/portfolio-step/positions-panel.tsx +62 -1
  86. package/src/components/onboarding/use-onboarding-progress.ts +12 -4
  87. package/src/components/pane-settings-dialog/desktop.tsx +2 -2
  88. package/src/components/pane-settings-dialog/tui.tsx +2 -2
  89. package/src/components/pane-settings-dialog/value.ts +6 -0
  90. package/src/components/pane-settings-dialog.tsx +3 -3
  91. package/src/components/reader/detail-reader.tsx +4 -0
  92. package/src/components/ui/button.tsx +2 -0
  93. package/src/components/ui/choice-dialog.tsx +1 -0
  94. package/src/components/ui/data-table/index.tsx +4 -3
  95. package/src/components/ui/index.ts +1 -1
  96. package/src/components/ui/list-view.tsx +7 -12
  97. package/src/components/ui/loading.tsx +10 -3
  98. package/src/components/ui/menu.tsx +6 -2
  99. package/src/components/ui/page-stack-view.tsx +3 -0
  100. package/src/components/ui/pane-link-chip.tsx +269 -54
  101. package/src/components/ui/query-bar.tsx +2 -1
  102. package/src/components/ui/quote.ts +14 -1
  103. package/src/components/ui/tabs.tsx +97 -19
  104. package/src/core/state/app/layout-reducer.ts +7 -0
  105. package/src/core/state/app/layout.ts +44 -7
  106. package/src/core/state/app/state.ts +1 -1
  107. package/src/core/state/app/types.ts +22 -2
  108. package/src/data/config/layout.ts +5 -2
  109. package/src/docs/snapshot.json +54 -13
  110. package/src/i18n/es.ts +9 -8
  111. package/src/i18n/ja.ts +9 -8
  112. package/src/i18n/ko.ts +9 -8
  113. package/src/i18n/zh-cn.ts +9 -8
  114. package/src/i18n/zh-tw.ts +9 -8
  115. package/src/layout/pane-manager/floating-actions.ts +17 -0
  116. package/src/layout/pane-manager/floating-stack.ts +187 -0
  117. package/src/layout/pane-manager/floating.ts +4 -2
  118. package/src/layout/pane-manager/gridlock.ts +5 -1
  119. package/src/layout/pane-manager/index.ts +11 -0
  120. package/src/layout/pane-manager/layout-state.ts +10 -3
  121. package/src/market-data/depositary-pair.ts +5 -3
  122. package/src/market-data/futures-board.ts +46 -1
  123. package/src/market-data/futures-contract.ts +12 -3
  124. package/src/market-data/fx-interventions.ts +270 -0
  125. package/src/market-data/market/dated-previous-close.ts +94 -15
  126. package/src/market-data/market/status.ts +17 -1
  127. package/src/news/news-model.ts +44 -2
  128. package/src/plugins/builtin/alerts/cli.ts +4 -4
  129. package/src/plugins/builtin/alerts/format.ts +1 -2
  130. package/src/plugins/builtin/alerts/headless.ts +1 -2
  131. package/src/plugins/builtin/alerts/move-checks.ts +12 -6
  132. package/src/plugins/builtin/alerts/move.ts +30 -9
  133. package/src/plugins/builtin/alerts/pane.tsx +0 -2
  134. package/src/plugins/builtin/alerts/storage.ts +4 -2
  135. package/src/plugins/builtin/alerts/types.ts +12 -0
  136. package/src/plugins/builtin/analytics/risk-client.ts +10 -4
  137. package/src/plugins/builtin/analytics/risk-episodes.ts +5 -4
  138. package/src/plugins/builtin/analytics/risk-headless.ts +4 -2
  139. package/src/plugins/builtin/analytics/risk-sectors.ts +91 -0
  140. package/src/plugins/builtin/awards/index.tsx +1 -1
  141. package/src/plugins/builtin/buildout/index.tsx +1 -0
  142. package/src/plugins/builtin/catalysts/index.tsx +2 -2
  143. package/src/plugins/builtin/cds/headless.ts +4 -0
  144. package/src/plugins/builtin/changelog/index.tsx +292 -101
  145. package/src/plugins/builtin/changelog/versions.ts +293 -0
  146. package/src/plugins/builtin/chart-composer/headless.ts +2 -1
  147. package/src/plugins/builtin/chart-composer/index.tsx +1 -0
  148. package/src/plugins/builtin/chart-composer/intervention-events.ts +105 -0
  149. package/src/plugins/builtin/chart-composer/pane.tsx +21 -7
  150. package/src/plugins/builtin/chat/content/composer.tsx +5 -4
  151. package/src/plugins/builtin/chat/content/index.tsx +12 -2
  152. package/src/plugins/builtin/chat/content/layout-metrics.ts +3 -3
  153. package/src/plugins/builtin/chat/content/open-targets.ts +3 -3
  154. package/src/plugins/builtin/chat/layout.ts +5 -2
  155. package/src/plugins/builtin/chat/message/pane-chip.tsx +61 -40
  156. package/src/plugins/builtin/chat/message/render-state.ts +2 -5
  157. package/src/plugins/builtin/chat/message/terminal.tsx +13 -15
  158. package/src/plugins/builtin/chat/pane-links/previews.ts +51 -5
  159. package/src/plugins/builtin/chat/pane-links/share-card.ts +36 -0
  160. package/src/plugins/builtin/cloud/askg/attached-pane.tsx +10 -5
  161. package/src/plugins/builtin/cloud/askg/controller.ts +141 -5
  162. package/src/plugins/builtin/cloud/askg/executor.ts +113 -4
  163. package/src/plugins/builtin/cloud/askg/manifest.ts +28 -13
  164. package/src/plugins/builtin/cloud/askg/model.ts +14 -4
  165. package/src/plugins/builtin/cloud/askg/pane.tsx +70 -46
  166. package/src/plugins/builtin/cloud/askg/tool-display.ts +1 -0
  167. package/src/plugins/builtin/cloud/askg/turn-parts.tsx +70 -0
  168. package/src/plugins/builtin/cloud/terminal-relay/engine.ts +50 -130
  169. package/src/plugins/builtin/cloud/terminal-relay/policy.ts +327 -7
  170. package/src/plugins/builtin/cloud/terminal-relay/prompts.tsx +2 -1
  171. package/src/plugins/builtin/cloud/terminal-relay/redact.ts +52 -9
  172. package/src/plugins/builtin/commodities-energy/index.tsx +1 -3
  173. package/src/plugins/builtin/commodities-energy/view-state.ts +3 -0
  174. package/src/plugins/builtin/commodity-balances/index.tsx +1 -0
  175. package/src/plugins/builtin/company-attention/index.tsx +1 -1
  176. package/src/plugins/builtin/company-kpis/headless.ts +3 -1
  177. package/src/plugins/builtin/company-kpis/index.tsx +2 -2
  178. package/src/plugins/builtin/cot/headless.ts +14 -2
  179. package/src/plugins/builtin/cot/index.tsx +1 -1
  180. package/src/plugins/builtin/cpi/index.tsx +1 -1
  181. package/src/plugins/builtin/crypto-board/index.tsx +1 -0
  182. package/src/plugins/builtin/dividend-yield/index.tsx +1 -0
  183. package/src/plugins/builtin/doe/index.tsx +1 -1
  184. package/src/plugins/builtin/earnings/index.tsx +2 -2
  185. package/src/plugins/builtin/earnings-calls/headless.ts +5 -1
  186. package/src/plugins/builtin/earnings-calls/index.tsx +1 -0
  187. package/src/plugins/builtin/econ/calendar-model.ts +74 -1
  188. package/src/plugins/builtin/econ/fred-catalog.ts +3 -1
  189. package/src/plugins/builtin/econ/index.tsx +1 -0
  190. package/src/plugins/builtin/econ-statistics/index.tsx +1 -0
  191. package/src/plugins/builtin/econ-statistics/pane.tsx +6 -0
  192. package/src/plugins/builtin/estimate-revisions/index.tsx +1 -0
  193. package/src/plugins/builtin/executives/index.tsx +1 -0
  194. package/src/plugins/builtin/filing-events/index.tsx +1 -0
  195. package/src/plugins/builtin/fixed-income/index.tsx +1 -0
  196. package/src/plugins/builtin/futures/index.tsx +25 -4
  197. package/src/plugins/builtin/futures/model.ts +28 -32
  198. package/src/plugins/builtin/futures/series.ts +4 -3
  199. package/src/plugins/builtin/futures/table.tsx +16 -9
  200. package/src/plugins/builtin/futures/use-board-terms.ts +3 -3
  201. package/src/plugins/builtin/futures-curve/headless.ts +3 -3
  202. package/src/plugins/builtin/futures-curve/index.tsx +1 -1
  203. package/src/plugins/builtin/futures-curve/model.ts +18 -0
  204. package/src/plugins/builtin/gpu/index.tsx +1 -1
  205. package/src/plugins/builtin/help/functions-table.tsx +1 -1
  206. package/src/plugins/builtin/help/index.tsx +14 -4
  207. package/src/plugins/builtin/help/keybindings-editor.tsx +19 -5
  208. package/src/plugins/builtin/holders/index.tsx +1 -0
  209. package/src/plugins/builtin/holders/report-header.ts +2 -2
  210. package/src/plugins/builtin/insider/index.tsx +1 -0
  211. package/src/plugins/builtin/iv-history/index.tsx +1 -1
  212. package/src/plugins/builtin/jobs/index.tsx +1 -0
  213. package/src/plugins/builtin/layout-manager/index.tsx +8 -8
  214. package/src/plugins/builtin/macro-day/headless.ts +27 -8
  215. package/src/plugins/builtin/macro-day/index.tsx +1 -1
  216. package/src/plugins/builtin/macro-day/model.ts +19 -3
  217. package/src/plugins/builtin/macro-day/pane.tsx +14 -9
  218. package/src/plugins/builtin/macro-day/releases.ts +25 -7
  219. package/src/plugins/builtin/market-valuation/index.tsx +1 -0
  220. package/src/plugins/builtin/market-valuation/pane.tsx +8 -0
  221. package/src/plugins/builtin/members/index.tsx +1 -1
  222. package/src/plugins/builtin/mna/index.tsx +1 -0
  223. package/src/plugins/builtin/news/headless.ts +2 -2
  224. package/src/plugins/builtin/news/index.tsx +4 -3
  225. package/src/plugins/builtin/news/wire/index.tsx +5 -1
  226. package/src/plugins/builtin/news/wire/news/detail-view.tsx +4 -0
  227. package/src/plugins/builtin/news/wire/news/list-search.ts +5 -2
  228. package/src/plugins/builtin/options/index.tsx +1 -0
  229. package/src/plugins/builtin/options-positioning/index.tsx +1 -0
  230. package/src/plugins/builtin/pe-band/index.tsx +1 -1
  231. package/src/plugins/builtin/perps/markets-section.tsx +5 -2
  232. package/src/plugins/builtin/plugin-marketplace/pane.tsx +11 -11
  233. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +25 -0
  234. package/src/plugins/builtin/portfolio-list/headless.ts +15 -6
  235. package/src/plugins/builtin/portfolio-list/summary/index.tsx +3 -1
  236. package/src/plugins/builtin/power/index.tsx +1 -1
  237. package/src/plugins/builtin/realized-vol/index.tsx +1 -1
  238. package/src/plugins/builtin/research/event-model.ts +9 -1
  239. package/src/plugins/builtin/research/event-sources.ts +22 -0
  240. package/src/plugins/builtin/research/headless.ts +11 -5
  241. package/src/plugins/builtin/research/index.tsx +4 -0
  242. package/src/plugins/builtin/research-search/index.tsx +1 -0
  243. package/src/plugins/builtin/research-search/pane.tsx +8 -0
  244. package/src/plugins/builtin/revenue-breakdown/index.tsx +1 -0
  245. package/src/plugins/builtin/reverse-dcf/index.tsx +1 -1
  246. package/src/plugins/builtin/risk-factors/index.tsx +1 -0
  247. package/src/plugins/builtin/scanner/headless.ts +52 -13
  248. package/src/plugins/builtin/seasonality/index.tsx +1 -1
  249. package/src/plugins/builtin/sec/index.tsx +1 -0
  250. package/src/plugins/builtin/series-inventory.ts +1 -1
  251. package/src/plugins/builtin/shared/cloud-upgrade.ts +27 -3
  252. package/src/plugins/builtin/shared/scanner-capture.ts +11 -3
  253. package/src/plugins/builtin/shared/series-list-detail.tsx +5 -0
  254. package/src/plugins/builtin/short-interest/index.tsx +1 -0
  255. package/src/plugins/builtin/social-mentions/index.tsx +1 -1
  256. package/src/plugins/builtin/supply-chain/index.tsx +1 -0
  257. package/src/plugins/builtin/thirteenf/data.ts +43 -10
  258. package/src/plugins/builtin/thirteenf/headless.ts +55 -11
  259. package/src/plugins/builtin/thirteenf/model.ts +25 -9
  260. package/src/plugins/builtin/thirteenf/report-notes.ts +27 -6
  261. package/src/plugins/builtin/thirteenf/types.ts +2 -0
  262. package/src/plugins/builtin/ticker-detail/adr-pair/model.ts +1 -1
  263. package/src/plugins/builtin/ticker-detail/financials/model.ts +12 -0
  264. package/src/plugins/builtin/ticker-detail/financials/ratio-table.tsx +3 -3
  265. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +5 -5
  266. package/src/plugins/builtin/ticker-detail/headless.ts +18 -13
  267. package/src/plugins/builtin/ticker-detail/index.tsx +4 -0
  268. package/src/plugins/builtin/ticker-detail/overview/components.tsx +54 -5
  269. package/src/plugins/builtin/ticker-detail/overview/model.ts +6 -4
  270. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +34 -17
  271. package/src/plugins/builtin/ticker-detail/pane.tsx +7 -2
  272. package/src/plugins/builtin/time-sales/client.ts +9 -11
  273. package/src/plugins/builtin/time-sales/index.tsx +1 -1
  274. package/src/plugins/builtin/treasury-auctions/after.ts +267 -0
  275. package/src/plugins/builtin/treasury-auctions/cache.ts +18 -3
  276. package/src/plugins/builtin/treasury-auctions/client.ts +33 -2
  277. package/src/plugins/builtin/treasury-auctions/headless.ts +109 -19
  278. package/src/plugins/builtin/treasury-auctions/index.tsx +14 -4
  279. package/src/plugins/builtin/treasury-auctions/model.ts +256 -28
  280. package/src/plugins/builtin/treasury-auctions/pane.tsx +139 -28
  281. package/src/plugins/builtin/treasury-auctions/treasury-direct.ts +5 -2
  282. package/src/plugins/builtin/treasury-auctions/types.ts +7 -1
  283. package/src/plugins/builtin/vol-surface/index.tsx +1 -1
  284. package/src/plugins/builtin/world-venue-map/index.ts +1 -0
  285. package/src/plugins/builtin/yield-curve/curves.ts +10 -4
  286. package/src/plugins/builtin/yield-curve/headless.ts +6 -2
  287. package/src/plugins/builtin/yield-curve/index.tsx +3 -3
  288. package/src/plugins/builtin/yield-curve/series.ts +10 -0
  289. package/src/plugins/builtin/yield-curve/world.ts +3 -1
  290. package/src/plugins/installer.ts +45 -0
  291. package/src/portfolio/column-values.ts +2 -1
  292. package/src/public/__snapshots__/public-api.test.ts.snap +4 -0
  293. package/src/public/remote.ts +7 -1
  294. package/src/remote/client.ts +191 -11
  295. package/src/remote/controller-utils.ts +13 -1
  296. package/src/remote/controller.ts +88 -26
  297. package/src/remote/endpoint.ts +24 -0
  298. package/src/remote/form.ts +59 -4
  299. package/src/remote/resources.ts +56 -19
  300. package/src/remote/schema.ts +22 -9
  301. package/src/remote/secrets.ts +12 -0
  302. package/src/remote/semantic-helpers.ts +29 -1
  303. package/src/remote/semantic-tree.tsx +44 -15
  304. package/src/remote/server.ts +2 -1
  305. package/src/remote/surface.tsx +192 -0
  306. package/src/remote/types.ts +5 -0
  307. package/src/renderers/cloudflare/worker.ts +16 -1
  308. package/src/renderers/dom/styles.css +40 -6
  309. package/src/renderers/opentui/host.tsx +6 -0
  310. package/src/renderers/share/layout-view.tsx +1 -1
  311. package/src/series/standalone.ts +2 -2
  312. package/src/shares/api.ts +21 -4
  313. package/src/shares/item.ts +73 -0
  314. package/src/shares/pane-item.ts +205 -0
  315. package/src/shares/pane.ts +4 -0
  316. package/src/shares/payload.ts +9 -5
  317. package/src/sources/gloomberb-cloud/news.ts +37 -12
  318. package/src/state/opening-ticker-panes.ts +47 -0
  319. package/src/test-support/cli-context.ts +2 -0
  320. package/src/test-support/preload.ts +4 -1
  321. package/src/tickers/instrument-kind.ts +23 -3
  322. package/src/tickers/renamed-listings.ts +105 -0
  323. package/src/tickers/search/index.ts +103 -16
  324. package/src/time-series/resolve.ts +2 -2
  325. package/src/types/config.ts +5 -0
  326. package/src/types/context-menu.ts +2 -0
  327. package/src/types/financials.ts +1 -0
  328. package/src/types/plugin-commands.ts +140 -0
  329. package/src/types/plugin-context.ts +125 -0
  330. package/src/types/plugin-contributions.ts +55 -0
  331. package/src/types/plugin-definition.ts +234 -0
  332. package/src/types/plugin-notifications.ts +38 -0
  333. package/src/types/plugin-pane-settings.ts +116 -0
  334. package/src/types/plugin-pane-templates.ts +160 -0
  335. package/src/types/plugin-panes.ts +243 -0
  336. package/src/types/plugin-reports.ts +35 -0
  337. package/src/types/plugin-shared.ts +14 -0
  338. package/src/types/plugin-state.ts +71 -0
  339. package/src/types/plugin.ts +14 -1169
  340. package/src/ui/index.tsx +14 -3
  341. package/src/updater/github-releases.ts +23 -0
  342. package/src/utils/central-banks.ts +86 -1
  343. package/src/utils/cli-output.ts +22 -9
  344. package/src/utils/datetime-format.ts +12 -3
  345. package/src/utils/depositary-receipt.ts +28 -3
  346. package/src/utils/fundamentals.ts +14 -0
  347. package/src/utils/max-drawdown.ts +97 -16
  348. package/src/utils/untrusted-text.ts +29 -0
@@ -1,7 +1,7 @@
1
1
  import type { ReactNode } from "react";
2
2
  import { ActionRow, ColumnGrid, ColumnGridPair, RangeTrack, usePaneLinkMenuEntry, type ColumnGridCell, type ColumnGridColumn } from "../../../../components";
3
3
  import { t, tf } from "../../../../i18n";
4
- import { formatMarketPriceWithCurrency, liveQuoteFormatOptions, type MarketFormatOptions } from "../../../../market-data/market/format";
4
+ import { formatMarketPrice, formatMarketPriceWithCurrency, liveQuoteFormatOptions, type MarketFormatOptions } from "../../../../market-data/market/format";
5
5
  import { colors, hoverBg, priceColor } from "../../../../theme/colors";
6
6
  import type { Quote } from "../../../../types/financials";
7
7
  import { Box, Text, useUiCapabilities } from "../../../../ui";
@@ -35,16 +35,63 @@ export function rangeRowChrome(labelWidth: number, endpointWidth: number): numbe
35
35
  return labelWidth + 1 + endpointWidth * 2 + 2;
36
36
  }
37
37
 
38
+ /**
39
+ * How a range row writes its ends: as the quote prints a price ($5,072.00),
40
+ * or, on a row too narrow for those beside a track even under its short
41
+ * label, the bare number: a 27-cell CC=F pane cut its highs, "Day $5,072.00
42
+ * ● $5,28". From 100 up a compact end drops the decimals the low and the
43
+ * high do not need to read apart (5,072 and 5,287, but 150.1 and 150.4, never
44
+ * 150 twice); below 100 it keeps them, or 18.13 and 18.60 would read 18 and 19.
45
+ */
46
+ type RangeEndpointStyle = "price" | "compact";
47
+
48
+ const fractionDigits = (text: string) => /\.(\d+)\D*$/.exec(text)?.[1]!.length ?? 0;
49
+
50
+ /** The options a compact range writes its two ends with: the fewest decimals that still tell them apart. */
51
+ function compactRangeOptions(low: number, high: number, priceOptions: MarketFormatOptions): MarketFormatOptions {
52
+ if (Math.max(Math.abs(low), Math.abs(high)) < 100) return priceOptions;
53
+ // The decimals the price has, read without the cell cap, which drops them to fit.
54
+ const unbounded = { ...priceOptions, maxWidth: undefined };
55
+ const full = Math.max(fractionDigits(formatMarketPrice(low, unbounded)), fractionDigits(formatMarketPrice(high, unbounded)));
56
+ for (let digits = 0; digits < full; digits += 1) {
57
+ const options = { ...priceOptions, fixedFractionDigits: digits, minimumFractionDigits: digits, referencePrice: undefined };
58
+ if (formatMarketPrice(low, options) !== formatMarketPrice(high, options)) return options;
59
+ }
60
+ return priceOptions;
61
+ }
62
+
63
+ /** A range's two ends, in `style`. */
64
+ function formatRangeEndpoints(
65
+ low: number,
66
+ high: number,
67
+ currency: string,
68
+ priceOptions: MarketFormatOptions,
69
+ style: RangeEndpointStyle = "price",
70
+ ): [string, string] {
71
+ if (style === "price") return [formatMarketPriceWithCurrency(low, currency, priceOptions), formatMarketPriceWithCurrency(high, currency, priceOptions)];
72
+ const options = compactRangeOptions(low, high, priceOptions);
73
+ return [formatMarketPrice(low, options), formatMarketPrice(high, options)];
74
+ }
75
+
38
76
  /** The longest endpoint among ranges drawn together, so stacked tracks start and end in one column. */
39
77
  export function rangeEndpointWidth(
40
- values: readonly number[],
78
+ ranges: ReadonlyArray<readonly [low: number, high: number]>,
41
79
  currency: string,
42
80
  priceOptions: MarketFormatOptions,
81
+ style: RangeEndpointStyle = "price",
43
82
  ): number {
44
- const widths = values.map((value) => displayWidth(formatMarketPriceWithCurrency(value, currency, priceOptions)));
83
+ const widths = ranges.flatMap(([low, high]) => formatRangeEndpoints(low, high, currency, priceOptions, style).map(displayWidth));
45
84
  return Math.min(RANGE_ENDPOINT_WIDTH, Math.max(1, ...widths));
46
85
  }
47
86
 
87
+ /**
88
+ * The ends rows of `width` write: the prices while they leave a track of
89
+ * RANGE_MIN_TRACK_WIDTH under the short label, else the compact numbers.
90
+ */
91
+ export function rangeEndpointStyle(width: number, shortLabelWidth: number, priceEndpointWidth: number): RangeEndpointStyle {
92
+ return width - rangeRowChrome(shortLabelWidth, priceEndpointWidth) < RANGE_MIN_TRACK_WIDTH ? "compact" : "price";
93
+ }
94
+
48
95
  /**
49
96
  * Where the price sits in a range, on one row: the label, the low, a track
50
97
  * with a neutral marker and the high. The marker is the position, so no
@@ -62,6 +109,7 @@ export function CompactRangeBar({
62
109
  grow = false,
63
110
  currency,
64
111
  priceOptions,
112
+ endpoints = "price",
65
113
  }: {
66
114
  current: number;
67
115
  low: number;
@@ -80,6 +128,8 @@ export function CompactRangeBar({
80
128
  currency: string;
81
129
  /** The quote's live price options, so the endpoints keep the price's decimals. */
82
130
  priceOptions: MarketFormatOptions;
131
+ /** Shared by ranges drawn together, as `endpointWidth` is (rangeEndpointStyle). */
132
+ endpoints?: RangeEndpointStyle;
83
133
  }) {
84
134
  const { nativePaneChrome } = useUiCapabilities();
85
135
  const range = high - low;
@@ -89,8 +139,7 @@ export function CompactRangeBar({
89
139
  const shownLabel = useShortLabel ? shortLabel : label;
90
140
  const shownLabelWidth = useShortLabel ? displayWidth(shortLabel) : labelWidth;
91
141
  const endpointOptions = { ...priceOptions, maxWidth: endpointWidth };
92
- const lowText = formatMarketPriceWithCurrency(low, currency, endpointOptions);
93
- const highText = formatMarketPriceWithCurrency(high, currency, endpointOptions);
142
+ const [lowText, highText] = formatRangeEndpoints(low, high, currency, endpointOptions, endpoints);
94
143
  const barWidth = Math.max(1, width - rangeRowChrome(shownLabelWidth, endpointWidth));
95
144
 
96
145
  // The desktop and the web size the row and its track by CSS, so the high end keeps to the pane's edge on every frame of a
@@ -31,7 +31,7 @@ import { getPortfolioPositionMetrics, getPortfolioQuoteDisplay, resolvePortfolio
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
33
  import { formatReportedMoney, REPORTING_CURRENCY_NOT_SOURCED } from "../../../../utils/reported-money";
34
- import { enterpriseValueCheck, enterpriseValueNotMeaningful, fundamentalsCurrency, isBankEnterpriseValue, fundamentalsEpsCurrency, reportedEnterpriseValue } from "../../../../utils/fundamentals";
34
+ import { enterpriseValueCheck, enterpriseValueGapIsLarge, enterpriseValueNotMeaningful, fundamentalsCurrency, isBankEnterpriseValue, fundamentalsEpsCurrency, reportedEnterpriseValue } from "../../../../utils/fundamentals";
35
35
  import { formatShortDate } from "../../../../utils/datetime-format";
36
36
  import { safeExternalUrl } from "../../../../utils/external-url";
37
37
  import type { FundBondFacts } from "../../../../api-client/fund-facts";
@@ -232,7 +232,7 @@ export function buildOverviewStats({
232
232
  const { pair, receiptSide } = depositaryPair;
233
233
  const count = ratioCount(pair.ratio);
234
234
  stats.push(receiptSide
235
- ? { label: "ADR Ratio", value: `1:${count}`, detail: [adrRatioText(pair.ratio)!, `${count} sh per ADR`], link: ADR_PAIR }
235
+ ? { label: "ADR Ratio", value: `1:${count}`, detail: [adrRatioText(pair.ratio, pair.ordinary[0])!, `${count} sh per ADR`], link: ADR_PAIR }
236
236
  : { label: "ADR", value: pair.receipt, detail: [`1 ADR = ${count} of these shares`, `1:${count}`], link: ADR_PAIR });
237
237
  }
238
238
  if (cedearRatio) {
@@ -334,9 +334,11 @@ export function buildOverviewStats({
334
334
  } else if (fundamentals?.unavailableFields?.includes("enterpriseValue")) {
335
335
  stats.push({ label: "EV", value: "—" });
336
336
  } else if (enterpriseValue != null) {
337
- // More than 5% from market cap + debt - cash: the provider's, with the computed figure where it fits.
337
+ // More than 10% from market cap + debt - cash: the provider's, with the computed figure where it fits.
338
+ // Closer than that it is the valuation panes' detail (enterpriseValueGapIsLarge).
338
339
  const check = enterpriseValueCheck(priced);
339
- const computed = check?.status === "differs" && check.computed != null ? formatCompact(check.computed) : undefined;
340
+ const computed = check?.status === "differs" && check.computed != null && enterpriseValueGapIsLarge(priced)
341
+ ? formatCompact(check.computed) : undefined;
340
342
  stats.push({
341
343
  label: "EV",
342
344
  value: formatCompactCurrency(enterpriseValue, quoteCurrency),
@@ -38,7 +38,7 @@ import type { TickerRecord } from "../../../types/ticker";
38
38
  import { Box, ScrollBox, Text, useUiCapabilities } from "../../../ui";
39
39
  import { publicTickerKey, resolveExchangeTimeZone } from "../../../utils/exchanges";
40
40
  import { convertCurrency, displayWidth, formatPercentRaw, truncateToDisplayWidth } from "../../../utils/format";
41
- import { appTtmRate, enterpriseValueReconciliationNote, ttmAtAppRate, ttmConversionNote, withBankEnterpriseValue } from "../../../utils/fundamentals";
41
+ import { appTtmRate, enterpriseValueGapIsLarge, enterpriseValueReconciliationNote, ttmAtAppRate, ttmConversionNote, withBankEnterpriseValue } from "../../../utils/fundamentals";
42
42
  import { atRegularSessionPrice } from "../../../market-data/quotes/regular-session-valuation";
43
43
  import { zonedDateKey } from "../../../utils/zoned-date-time";
44
44
  import { sharesOutstandingInReceipts } from "../../../utils/depositary-receipt";
@@ -49,6 +49,7 @@ import {
49
49
  FunctionLinkRow,
50
50
  PositionTable,
51
51
  QuoteBook,
52
+ rangeEndpointStyle,
52
53
  rangeEndpointWidth,
53
54
  rangeRowChrome,
54
55
  textGridColumns,
@@ -249,9 +250,11 @@ function ResolvedOverviewTab({ width, height, focused = false, ticker, financial
249
250
  panelId: "price",
250
251
  timeBasis: chartTimeZone ? { kind: "market", timeZone: chartTimeZone } : undefined,
251
252
  });
252
- // A provider EV off market cap + debt - cash, or why a withdrawn one is unavailable, at the
253
- // regular session price the EV beside it is shown at.
254
- const enterpriseValueNote = enterpriseValueReconciliationNote(atRegularSessionPrice({ quote, fundamentals: withBankEnterpriseValue(fundamentals, profile) }).fundamentals);
253
+ // A provider EV well off market cap + debt - cash, or why a withdrawn one is unavailable, at the
254
+ // regular session price the EV beside it is shown at. A gap of a few percent is the valuation panes' detail.
255
+ const pricedForEnterpriseValue = atRegularSessionPrice({ quote, fundamentals: withBankEnterpriseValue(fundamentals, profile) }).fundamentals;
256
+ const enterpriseValueNote = enterpriseValueGapIsLarge(pricedForEnterpriseValue)
257
+ ? enterpriseValueReconciliationNote(pricedForEnterpriseValue) : undefined;
255
258
  // Months of cash, for a company that burns it, and an offering since its balance sheet that the cash is not in yet.
256
259
  const runway = useMemo(() => financials ? cashRunway(financials) : null, [financials]);
257
260
  const runwayOfferingNote = useOfferingNote(ticker.metadata.ticker, ticker.metadata.exchange, runway?.periodEnd ?? null, runway?.trailing?.kind === "months");
@@ -335,6 +338,16 @@ function ResolvedOverviewTab({ width, height, focused = false, ticker, financial
335
338
  ? truncateToDisplayWidth(usdPerMmbtuText({ value: gasInUsd, currency: gasCurrency, usdPerUnit: gasUsdPerUnit }),
336
339
  Math.max(1, quoteTextWidth - displayWidth(inUsdLabel) - 1))
337
340
  : "";
341
+ // The extended session's line keeps its label and price whole on a narrow pane: the move gives
342
+ // way to its percent, then goes, rather than wrapping a figure across two lines ("(+0." / "08%)").
343
+ const extendedLabelText = extendedQuote ? `${extendedSessionLineLabel(extendedQuote, t)}:` : "";
344
+ const extendedPriceText = extendedQuote ? formatMarketPriceWithCurrency(extendedQuote.price, quote?.currency, moneyOptions) : "";
345
+ const extendedMoveText = extendedQuote
346
+ ? [
347
+ `${formatSignedMarketPrice(extendedQuote.change, moneyOptions)} (${formatPercentRaw(extendedQuote.changePercent)})`,
348
+ formatPercentRaw(extendedQuote.changePercent),
349
+ ].find((move) => displayWidth(extendedLabelText) + 2 + displayWidth(extendedPriceText) + 2 + displayWidth(move) <= quoteTextWidth) ?? ""
350
+ : "";
338
351
  const quoteChangeCells = delisted ? 0 : figureCells(quoteChangeText, "sub") + 1 + figureCells(quotePercentText, "sub");
339
352
  const stackQuoteChange = quoteChangeCells > quoteTextWidth;
340
353
  const stackQuoteSummary = figureCells(quotePriceText) + 2 + quoteChangeCells > quoteTextWidth;
@@ -361,14 +374,20 @@ function ResolvedOverviewTab({ width, height, focused = false, ticker, financial
361
374
  yearRange ? displayWidth(yearRangeLabel) : 0,
362
375
  );
363
376
  // Both ranges share one endpoint width, so stacked tracks start and end in the same column.
364
- const rangeEndpointCells = rangeEndpointWidth([
365
- ...(hasDayRange ? [quote.low!, quote.high!] : []),
366
- ...(yearRange ? [yearRange.low, yearRange.high] : []),
367
- ], quoteCurrency, moneyOptions);
377
+ const rangeValues: Array<[number, number]> = [
378
+ ...(hasDayRange ? [[quote.low!, quote.high!] as [number, number]] : []),
379
+ ...(yearRange ? [[yearRange.low, yearRange.high] as [number, number]] : []),
380
+ ];
381
+ const rangePriceCells = rangeEndpointWidth(rangeValues, quoteCurrency, moneyOptions);
368
382
  const rangeHalfWidth = Math.floor((contentWidth - RANGE_PAIR_GAP) / 2);
369
383
  const rangeInline = hasDayRange && yearRange != null
370
- && rangeHalfWidth - rangeRowChrome(rangeLabelWidth, rangeEndpointCells) >= RANGE_INLINE_MIN_TRACK;
384
+ && rangeHalfWidth - rangeRowChrome(rangeLabelWidth, rangePriceCells) >= RANGE_INLINE_MIN_TRACK;
371
385
  const rangeWidth = rangeInline ? rangeHalfWidth : contentWidth;
386
+ // A pane too narrow for both priced ends beside a track writes them compact, both ranges alike.
387
+ const rangeShortLabelWidth = Math.max(hasDayRange ? displayWidth(delisted ? t("Last") : t("Day")) : 0, yearRange ? displayWidth(t("52W")) : 0);
388
+ const rangeEndpoints = rangeEndpointStyle(rangeWidth, rangeShortLabelWidth, rangePriceCells);
389
+ const rangeEndpointCells = rangeEndpoints === "price" ? rangePriceCells
390
+ : rangeEndpointWidth(rangeValues, quoteCurrency, moneyOptions, rangeEndpoints);
372
391
  const contractLines = contractTerms ? futuresContractLines(contractTerms, futuresSymbol) : [];
373
392
  // Columns that keep every term whole; a narrow pane stacks them in one.
374
393
  const contractColumns = textGridColumns(contractLines.map(contractField), contentWidth);
@@ -503,14 +522,10 @@ function ResolvedOverviewTab({ width, height, focused = false, ticker, financial
503
522
  </Box>
504
523
  ) : null}
505
524
  {extendedQuote && (
506
- <Box flexDirection="row" gap={2}>
507
- <Text fg={colors.textDim}>{extendedSessionLineLabel(extendedQuote, t)}:</Text>
508
- <Text fg={priceColor(extendedQuote.change ?? 0)}>
509
- {formatMarketPriceWithCurrency(extendedQuote.price, quote?.currency, moneyOptions)}
510
- </Text>
511
- <Text fg={priceColor(extendedQuote.change ?? 0)}>
512
- {formatSignedMarketPrice(extendedQuote.change, moneyOptions)} ({formatPercentRaw(extendedQuote.changePercent)})
513
- </Text>
525
+ <Box flexDirection="row" gap={2} minWidth={0} overflow="hidden">
526
+ <Text flexShrink={0} fg={colors.textDim}>{extendedLabelText}</Text>
527
+ <Text flexShrink={0} fg={priceColor(extendedQuote.change ?? 0)}>{extendedPriceText}</Text>
528
+ {extendedMoveText ? <Text flexShrink={0} fg={priceColor(extendedQuote.change ?? 0)}>{extendedMoveText}</Text> : null}
514
529
  </Box>
515
530
  )}
516
531
  {settleText && (
@@ -559,6 +574,7 @@ function ResolvedOverviewTab({ width, height, focused = false, ticker, financial
559
574
  grow={rangeInline}
560
575
  currency={quoteCurrency}
561
576
  priceOptions={moneyOptions}
577
+ endpoints={rangeEndpoints}
562
578
  />
563
579
  )}
564
580
  {yearRange && (
@@ -574,6 +590,7 @@ function ResolvedOverviewTab({ width, height, focused = false, ticker, financial
574
590
  grow={rangeInline}
575
591
  currency={quoteCurrency}
576
592
  priceOptions={moneyOptions}
593
+ endpoints={rangeEndpoints}
577
594
  />
578
595
  )}
579
596
  </Box>
@@ -19,7 +19,8 @@ import {
19
19
  } from "../../../state/app/context";
20
20
  import { useQuoteUpdates } from "../../../state/hooks/quote-streaming";
21
21
  import { getSharedRegistry } from "../../registry";
22
- import { ChoiceDialog, EmptyState, NestedPaneTabs, PaneFooterScope, usePaneFooter, usePaneMenuItems, usePaneTabs } from "../../../components";
22
+ import { ChoiceDialog, EmptyState, NestedPaneTabs, PaneFooterScope, PaneStatusBody, usePaneFooter, usePaneMenuItems, usePaneTabs } from "../../../components";
23
+ import { useTickerPaneOpening } from "../../../state/opening-ticker-panes";
23
24
  import { useOptionalDialog, type PromptContext } from "../../../ui/dialog";
24
25
  import { useThrottledCommitValue } from "../../../react/use-throttled-commit-value";
25
26
  import { resolveOptionsTarget } from "../../../utils/options";
@@ -155,7 +156,9 @@ export function TickerResearchPane({ focused, width, height }: PaneProps) {
155
156
  const { createPaneFromTemplate } = usePluginAppActions();
156
157
  const config = usePaneAppConfig();
157
158
  const paneInstance = usePaneInstance();
158
- const { ticker, financials, error: instrumentError } = usePaneTicker();
159
+ const { symbol, ticker, financials, error: instrumentError } = usePaneTicker();
160
+ // Opened before its listing was found: the pane says so until the lookup settles it.
161
+ const opening = useTickerPaneOpening(paneInstance?.instanceId);
159
162
  const liveStreaming = useLiveStreamingSetting();
160
163
  const streamingTarget = quoteSubscriptionTargetFromTicker(ticker, ticker?.metadata.ticker, "provider");
161
164
  const streamingTargets = useMemo(() => (
@@ -434,6 +437,8 @@ export function TickerResearchPane({ focused, width, height }: PaneProps) {
434
437
  });
435
438
  }, [shownTabId, visibleTabIds]);
436
439
 
440
+ if (!ticker && opening && symbol) return <PaneStatusBody loading subject={symbol} />;
441
+
437
442
  if (!ticker) {
438
443
  const isEmptyFollowCollection = paneInstance?.binding?.kind === "follow" && !!collectionId && collectionTickerCount === 0;
439
444
  const message = instrumentError ?? (isEmptyFollowCollection
@@ -61,25 +61,23 @@ export function validateTape(data: TapeSnapshot, symbol: string, exchange: strin
61
61
  /** The latest tape, or with a `range` that window of the session. */
62
62
  export async function fetchTape(symbol: string, exchange: string, signal?: AbortSignal,
63
63
  client: Pick<typeof apiClient, "getCloudTape"> = apiClient, range?: TapeRange): Promise<TapeSnapshot> {
64
- try { return validateTape(await (range ? client.getCloudTape(symbol, exchange, signal, range) : client.getCloudTape(symbol, exchange, signal)), symbol, exchange); }
64
+ // The tape names US venues by their codes: a listing found as NYSEARCA is asked as ARCA, as it is answered.
65
+ const venue = canonicalExchange(exchange);
66
+ try { return validateTape(await (range ? client.getCloudTape(symbol, venue, signal, range) : client.getCloudTape(symbol, venue, signal)), symbol, exchange); }
65
67
  catch (error) {
66
68
  if (error instanceof ApiRequestError && [404, 503].includes(error.status ?? 0)) throw new Error("Time and sales is not available yet.");
67
69
  // A rejected request answers with an unavailable snapshot; show its reason, not the JSON body.
68
70
  if (error instanceof ApiRequestError) {
69
- const reason = tapeRejection(error.message);
71
+ const reason = tapeGap(error.details);
70
72
  if (reason) throw new Error(reason);
71
73
  }
72
74
  throw error;
73
75
  }
74
76
  }
75
77
 
76
- /** The first stated gap of an unavailable tape snapshot sent as an error body. */
77
- export function tapeRejection(body: string): string | null {
78
- try {
79
- const value = JSON.parse(body) as { gaps?: unknown };
80
- return Array.isArray(value?.gaps) && typeof value.gaps[0] === "string" ? value.gaps[0] : null;
81
- } catch {
82
- // Intentional ignore: an error body that is not JSON names no gap, so the request's own error stands.
83
- return null;
84
- }
78
+ /** The first stated gap of an unavailable tape snapshot, as the request's parsed error body holds it. */
79
+ function tapeGap(details: Readonly<Record<string, unknown>> | undefined): string | null {
80
+ const gaps = details?.gaps;
81
+ return Array.isArray(gaps) && typeof gaps[0] === "string" ? gaps[0] : null;
85
82
  }
83
+
@@ -3,7 +3,7 @@ import { createTickerSurfacePaneTemplate } from "../shared/ticker-surface";
3
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
- defaultPosition: "right", tickerFollower: true, defaultMode: "floating", defaultFloatingSize: { width: 104, height: 28 },
6
+ defaultPosition: "right", shareItem: { ticker: true }, tickerFollower: true, defaultMode: "floating", defaultFloatingSize: { width: 104, height: 28 },
7
7
  tableExport: true, headless: timeSalesHeadless, settings: { title: "Time and Sales", fields: [{ key: "tab", label: "View", type: "select", options: [{ value: "trades", label: "Trades" }, { value: "quotes", label: "NBBO" }] }] } }],
8
8
  paneTemplates: [
9
9
  { ...createTickerSurfacePaneTemplate({ id: "time-sales-tas", paneId: "time-sales", label: "Time and Sales",
@@ -0,0 +1,267 @@
1
+ import { apiClient } from "../../../api-client";
2
+ import type { CloudCurveHistory, CloudCurveId } from "../../../api-client/yield-curves";
3
+ import { createTtlCache } from "../../../data/ttl-cache";
4
+ import { toBasisPoints } from "../../../utils/basis-points";
5
+ import { AUCTION_HISTORY_ALL, type AuctionHistoryWindow } from "./client";
6
+ import { AUCTION_HISTORY_WINDOWS, auctionBenchmark, dealerPct, indirectPct, isPendingAuction, nextAuctionHistoryWindow } from "./model";
7
+ import type { TreasuryAuction } from "./types";
8
+
9
+ /**
10
+ * The after view (docs/research-data.md, Treasury auctions): how an auction
11
+ * ranked against its tenor's own recent history, and what the matching
12
+ * constant-maturity yield did after it.
13
+ *
14
+ * - B/C, indirect and dealer share are each a percentile against the tenor's
15
+ * previous 24 auctions with that figure: the share of them below it, half
16
+ * the ones equal. A tenor is the security type and the benchmark it was sold
17
+ * as (the 10-year note and its 9-Year 10-Month reopenings are one; a 10-year
18
+ * TIPS is another). Fewer than 12 earlier auctions rank nothing.
19
+ * - The yield change is the Treasury par (CMT) yield of the auction's tenor,
20
+ * or the TIPS real yield for a TIPS, from the auction day's close to the
21
+ * close 1, 5 and 20 sessions later, in basis points. An FRN floats and has
22
+ * none; a day the curve has no close for has none.
23
+ */
24
+
25
+ export type AuctionView = "results" | "after";
26
+ export const AUCTION_VIEWS: readonly AuctionView[] = ["results", "after"];
27
+
28
+ const PERCENTILE_LOOKBACK = 24;
29
+ const PERCENTILE_MIN = 12;
30
+
31
+ export interface AuctionAfter {
32
+ btcPercentile: number | null;
33
+ indirectPercentile: number | null;
34
+ dealerPercentile: number | null;
35
+ /** The CMT yield's change, bp, 1, 5 and 20 sessions after the auction day's close. */
36
+ after1d: number | null;
37
+ after5d: number | null;
38
+ after20d: number | null;
39
+ /** The yield read: "7Y", "10Y real"; null when none matches. */
40
+ cmt: string | null;
41
+ }
42
+
43
+ /**
44
+ * The window the after view reads first: two years more than it lists, which
45
+ * gives most tenors their 24 before the oldest row listed. A tenor sold a few
46
+ * times a year (the 30-year TIPS) needs more: widerAfterWindow.
47
+ */
48
+ export function afterLoadWindow(window: AuctionHistoryWindow): AuctionHistoryWindow {
49
+ if (window === AUCTION_HISTORY_ALL) return AUCTION_HISTORY_ALL;
50
+ return AUCTION_HISTORY_WINDOWS.find((next) => next === AUCTION_HISTORY_ALL || next >= window + 730) ?? AUCTION_HISTORY_ALL;
51
+ }
52
+
53
+ /** The first day the after view lists, for a window it read more than: undefined for ALL. */
54
+ export function afterWindowStart(window: AuctionHistoryWindow, now = Date.now()): string | undefined {
55
+ return window === AUCTION_HISTORY_ALL ? undefined : new Date(now - window * 86_400_000).toISOString().slice(0, 10);
56
+ }
57
+
58
+ const DAY_MS = 86_400_000;
59
+ /** A tenor's oldest auction read this close to the window's start may have older ones before it. */
60
+ const MIN_GAP_MS = 400 * DAY_MS;
61
+
62
+ /**
63
+ * The next window the after view should read, or null when the one read is
64
+ * enough: every listed tenor has its 24 auctions before the oldest one listed,
65
+ * or began inside the window (its oldest auction read is further from the
66
+ * window's start than its longest gap between auctions, and at least 400
67
+ * days), or the window is already ALL. Cash management bills are one-offs and
68
+ * never ask for more.
69
+ */
70
+ export function widerAfterWindow(
71
+ listed: readonly TreasuryAuction[],
72
+ loaded: readonly TreasuryAuction[],
73
+ window: AuctionHistoryWindow,
74
+ now = Date.now(),
75
+ ): AuctionHistoryWindow | null {
76
+ if (window === AUCTION_HISTORY_ALL) return null;
77
+ const start = now - window * DAY_MS;
78
+ const byTenor = new Map<string, number[]>();
79
+ for (const auction of loaded) {
80
+ const key = auctionTenorKey(auction);
81
+ if (key && !isPendingAuction(auction)) byTenor.set(key, [...byTenor.get(key) ?? [], Date.parse(auction.auctionDate)]);
82
+ }
83
+ const oldestListed = new Map<string, number>();
84
+ for (const auction of listed) {
85
+ const key = auctionTenorKey(auction);
86
+ if (!key || auction.secType === "CMB" || isPendingAuction(auction)) continue;
87
+ const date = Date.parse(auction.auctionDate);
88
+ oldestListed.set(key, Math.min(oldestListed.get(key) ?? date, date));
89
+ }
90
+ for (const [key, oldest] of oldestListed) {
91
+ const dates = (byTenor.get(key) ?? []).toSorted((left, right) => left - right);
92
+ if (dates.filter((date) => date < oldest).length >= PERCENTILE_LOOKBACK) continue;
93
+ let gap = MIN_GAP_MS;
94
+ for (let index = 1; index < dates.length; index++) gap = Math.max(gap, dates[index]! - dates[index - 1]!);
95
+ if (dates.length && dates[0]! - start <= gap) return nextAuctionHistoryWindow(window);
96
+ }
97
+ return null;
98
+ }
99
+
100
+ const NO_AFTER: AuctionAfter = {
101
+ btcPercentile: null, indirectPercentile: null, dealerPercentile: null, after1d: null, after5d: null, after20d: null, cmt: null,
102
+ };
103
+
104
+ /** The tenor an auction ranks within: its type and the benchmark it was sold as. */
105
+ function auctionTenorKey(auction: TreasuryAuction): string | null {
106
+ const benchmark = auctionBenchmark(auction.securityTerm);
107
+ return benchmark ? `${auction.secType}|${benchmark.count}${benchmark.unit}` : null;
108
+ }
109
+
110
+ /** 0 to 100: the share of `history` below `value`, half of those equal. */
111
+ function percentileOf(value: number, history: readonly number[]): number | null {
112
+ if (history.length < PERCENTILE_MIN) return null;
113
+ const below = history.filter((entry) => entry < value).length;
114
+ const equal = history.filter((entry) => entry === value).length;
115
+ return Math.round(((below + equal / 2) / history.length) * 100);
116
+ }
117
+
118
+ type Metric = (auction: TreasuryAuction) => number | null;
119
+ const METRICS: ReadonlyArray<[keyof Pick<AuctionAfter, "btcPercentile" | "indirectPercentile" | "dealerPercentile">, Metric]> = [
120
+ ["btcPercentile", (auction) => auction.bidToCoverRatio],
121
+ ["indirectPercentile", indirectPct],
122
+ ["dealerPercentile", dealerPct],
123
+ ];
124
+
125
+ /** Each completed auction's percentiles, by id, against the auctions of its tenor before it in `auctions`. */
126
+ export function auctionPercentiles(auctions: readonly TreasuryAuction[]): Map<string, Pick<AuctionAfter, "btcPercentile" | "indirectPercentile" | "dealerPercentile">> {
127
+ const byTenor = new Map<string, TreasuryAuction[]>();
128
+ for (const auction of auctions) {
129
+ const key = auctionTenorKey(auction);
130
+ if (!key || isPendingAuction(auction)) continue;
131
+ byTenor.set(key, [...byTenor.get(key) ?? [], auction]);
132
+ }
133
+ const ranked = new Map<string, Pick<AuctionAfter, "btcPercentile" | "indirectPercentile" | "dealerPercentile">>();
134
+ for (const group of byTenor.values()) {
135
+ group.sort((left, right) => left.auctionDate.localeCompare(right.auctionDate) || left.id.localeCompare(right.id));
136
+ group.forEach((auction, index) => {
137
+ const entry = { btcPercentile: null, indirectPercentile: null, dealerPercentile: null } as Record<string, number | null>;
138
+ for (const [key, metric] of METRICS) {
139
+ const value = metric(auction);
140
+ if (value == null) continue;
141
+ const history: number[] = [];
142
+ for (let earlier = index - 1; earlier >= 0 && history.length < PERCENTILE_LOOKBACK; earlier--) {
143
+ const past = metric(group[earlier]!);
144
+ if (past != null) history.push(past);
145
+ }
146
+ entry[key] = percentileOf(value, history);
147
+ }
148
+ ranked.set(auction.id, entry as Pick<AuctionAfter, "btcPercentile" | "indirectPercentile" | "dealerPercentile">);
149
+ });
150
+ }
151
+ return ranked;
152
+ }
153
+
154
+ /** A curve's tenor and its length in days, as Gloom Cloud stores the US curves. */
155
+ const NOMINAL_TENORS: ReadonlyArray<[string, number]> = [
156
+ ["1M", 30], ["6W", 42], ["2M", 61], ["3M", 91], ["4M", 122], ["6M", 183], ["1Y", 365], ["2Y", 730], ["3Y", 1095],
157
+ ["5Y", 1826], ["7Y", 2557], ["10Y", 3652], ["20Y", 7305], ["30Y", 10957],
158
+ ];
159
+ const REAL_TENORS: ReadonlyArray<[string, number]> = [["5Y", 1826], ["7Y", 2557], ["10Y", 3652], ["20Y", 7305], ["30Y", 10957]];
160
+ const UNIT_DAYS = { day: 1, week: 7, month: 30.44, year: 365.25 } as const;
161
+
162
+ /** The curve and tenor whose yield matches an auction's: the nearest stored tenor to its benchmark; null for an FRN. */
163
+ export function cmtFor(auction: TreasuryAuction): { curve: CloudCurveId; tenor: string } | null {
164
+ if (auction.secType === "FRN") return null;
165
+ const benchmark = auctionBenchmark(auction.securityTerm);
166
+ if (!benchmark) return null;
167
+ const days = benchmark.count * UNIT_DAYS[benchmark.unit];
168
+ const real = auction.secType === "TIPS";
169
+ const tenors = real ? REAL_TENORS : NOMINAL_TENORS;
170
+ const [tenor] = tenors.reduce((best, entry) => Math.abs(entry[1] - days) < Math.abs(best[1] - days) ? entry : best);
171
+ return { curve: real ? "us-real" : "us", tenor };
172
+ }
173
+
174
+ const cmtLabel = (cmt: { curve: CloudCurveId; tenor: string }) => cmt.curve === "us-real" ? `${cmt.tenor} real` : cmt.tenor;
175
+
176
+ /** A curve tenor's closes, oldest first, as `date` and `value` (percent). */
177
+ export type CurveCloses = ReadonlyArray<{ date: string; value: number }>;
178
+
179
+ /** The change from the auction day's close to the close `sessions` later, in bp; null when either is missing. */
180
+ export function yieldChangeAfter(closes: CurveCloses, date: string, sessions: number): number | null {
181
+ let low = 0, high = closes.length;
182
+ while (low < high) {
183
+ const middle = (low + high) >> 1;
184
+ if (closes[middle]!.date < date) low = middle + 1;
185
+ else high = middle;
186
+ }
187
+ const base = closes[low];
188
+ const later = closes[low + sessions];
189
+ if (!base || base.date !== date || !later) return null;
190
+ return toBasisPoints(later.value - base.value, 1);
191
+ }
192
+
193
+ /** The after view's figures for each auction shown, by id. */
194
+ export function projectAuctionAfter(
195
+ shown: readonly TreasuryAuction[],
196
+ history: readonly TreasuryAuction[],
197
+ curves: ReadonlyMap<string, CurveCloses>,
198
+ ): Map<string, AuctionAfter> {
199
+ const percentiles = auctionPercentiles(history);
200
+ return new Map(shown.map((auction) => {
201
+ const cmt = cmtFor(auction);
202
+ const closes = cmt ? curves.get(curveKey(cmt)) : undefined;
203
+ const change = (sessions: number) => closes && !isPendingAuction(auction) ? yieldChangeAfter(closes, auction.auctionDate, sessions) : null;
204
+ return [auction.id, {
205
+ ...NO_AFTER,
206
+ ...percentiles.get(auction.id),
207
+ after1d: change(1), after5d: change(5), after20d: change(20),
208
+ cmt: cmt ? cmtLabel(cmt) : null,
209
+ }];
210
+ }));
211
+ }
212
+
213
+ const curveKey = (cmt: { curve: CloudCurveId; tenor: string }) => `${cmt.curve}:${cmt.tenor}`;
214
+
215
+ /**
216
+ * A curve tenor's closes as read, from `from` (null: its whole history); ten
217
+ * minutes, since a session's close lands once a day. Keyed by curve and tenor
218
+ * alone, so a list that changes reads again only when it needs older closes.
219
+ */
220
+ const curveCache = createTtlCache<{ from: string | null; history: CloudCurveHistory }>({ ttlMs: 10 * 60_000, maxEntries: 64 });
221
+
222
+ export function resetAuctionCurvesForTests(): void {
223
+ curveCache.clear();
224
+ }
225
+
226
+ type CurveRead = (curve: CloudCurveId, tenor: string, from: string | null) => Promise<CloudCurveHistory>;
227
+
228
+ async function readCurve(curve: CloudCurveId, tenor: string, from: string | null, read: CurveRead): Promise<CloudCurveHistory> {
229
+ const key = curveKey({ curve, tenor });
230
+ const load = async () => ({ from, history: await read(curve, tenor, from) });
231
+ const held = await curveCache.load(key, load);
232
+ const covers = held.from == null || (from != null && held.from <= from);
233
+ return covers ? held.history : (await curveCache.load(key, load, { force: true })).history;
234
+ }
235
+
236
+ export interface AuctionCurveRead {
237
+ curves: Map<string, CurveCloses>;
238
+ /** Why a curve the view needs could not be read. */
239
+ errors: string[];
240
+ }
241
+
242
+ /**
243
+ * The closes of every curve tenor the shown auctions match, from `from`, the
244
+ * first day of the window listed (null for ALL: the whole curve).
245
+ */
246
+ export async function loadAuctionCurves(
247
+ shown: readonly TreasuryAuction[],
248
+ from: string | null,
249
+ read: CurveRead = (curve, tenor, start) => apiClient.getCloudCurveHistory(curve, tenor, start),
250
+ ): Promise<AuctionCurveRead> {
251
+ const needed = new Map<string, { curve: CloudCurveId; tenor: string }>();
252
+ for (const auction of shown) {
253
+ const cmt = cmtFor(auction);
254
+ if (cmt && !isPendingAuction(auction)) needed.set(curveKey(cmt), cmt);
255
+ }
256
+ const curves = new Map<string, CurveCloses>();
257
+ const errors: string[] = [];
258
+ await Promise.all([...needed].map(async ([key, { curve, tenor }]) => {
259
+ try {
260
+ const history = await readCurve(curve, tenor, from, read);
261
+ curves.set(key, history.points);
262
+ } catch (error) {
263
+ errors.push(`${cmtLabel({ curve, tenor })} Treasury yields unavailable: ${error instanceof Error ? error.message : String(error)}`);
264
+ }
265
+ }));
266
+ return { curves, errors };
267
+ }
@@ -16,8 +16,11 @@ const DIRECT_CACHE_SOURCE = "treasury-direct";
16
16
  /**
17
17
  * 3: every reported page was validated before this board was cached.
18
18
  * 4: boards carry direct takedown and bill discount rates, which a v3 board lacks.
19
+ * 5: boards carry the low yield and discount rate, and early rows with their high and low swapped are put right.
19
20
  */
20
- const CACHE_SCHEMA_VERSION = 4;
21
+ /** Raised when a board gains fields (5: the low yield; 6: early bills blank an investment rate their swapped discount rates contradict), so a saved board never lacks a column the pane shows. */
22
+ export const CACHE_SCHEMA_VERSION = 6;
23
+ export const DIRECT_CACHE_SCHEMA_VERSION = 2;
21
24
  export const TREASURY_FISCAL_DATA_CONNECTION_ID = "treasury-fiscal-data";
22
25
  export const TREASURY_DIRECT_CONNECTION_ID = "treasury-direct";
23
26
  /**
@@ -59,7 +62,7 @@ const archiveCache = createPluginCache<TreasuryAuction[]>({
59
62
  });
60
63
  /** TreasuryDirect's last weeks and announcements, refreshed as often as the board they are merged into. */
61
64
  const directCache = createPluginCache<TreasuryAuction[]>({
62
- kind: CACHE_KIND, source: DIRECT_CACHE_SOURCE, schemaVersion: 1, policy: CACHE_POLICY, decode,
65
+ kind: CACHE_KIND, source: DIRECT_CACHE_SOURCE, schemaVersion: DIRECT_CACHE_SCHEMA_VERSION, policy: CACHE_POLICY, decode,
63
66
  });
64
67
  let connectionHealth: ConnectionHealthRegistry | null = null;
65
68
 
@@ -167,6 +170,17 @@ function answered(result: TreasuryAuctionsResult): TreasuryAuctionsResult {
167
170
  return result.savedAt != null ? servedFromSavedCopy(result, result.savedAt) : result;
168
171
  }
169
172
 
173
+ /**
174
+ * The archive as saved, while it is still fresh: results that do not change,
175
+ * so a command reads the copy an earlier run saved (a command otherwise asks
176
+ * the source again: saved-copy-persistence.ts) and ALL answers in a second or
177
+ * two instead of walking 10,000 auctions again.
178
+ */
179
+ function savedArchive(key: string): Promise<PluginCacheResult<TreasuryAuction[]>> | null {
180
+ const saved = archiveCache.get(key, { allowExpired: true });
181
+ return saved && !saved.stale ? Promise.resolve(saved) : null;
182
+ }
183
+
170
184
  /**
171
185
  * ALL: the recent auctions since the archive boundary, refreshed hourly, and
172
186
  * the archive before it, from 1979-10-31, cached for weeks and never forced:
@@ -175,9 +189,10 @@ function answered(result: TreasuryAuctionsResult): TreasuryAuctionsResult {
175
189
  */
176
190
  async function loadAllTreasuryAuctions(force: boolean, loader: AuctionLoader, direct: DirectLoader | null): Promise<TreasuryAuctionsResult> {
177
191
  const boundary = auctionArchiveBoundary();
192
+ const key = `archive:${boundary}`;
178
193
  const [recent, archive] = await Promise.all([
179
194
  loadRecentBoard(force, `since:${boundary}`, () => loader({ from: boundary }), direct && { days: DIRECT_LOOKBACK_DAYS, load: direct }, () => boundary),
180
- archiveCache.load(`archive:${boundary}`, walk(FISCAL_DATA, () => loader({
195
+ savedArchive(key) ?? archiveCache.load(key, walk(FISCAL_DATA, () => loader({
181
196
  from: AUCTION_HISTORY_START, before: boundary, pageSize: AUCTION_ARCHIVE_PAGE_SIZE,
182
197
  }))).then(savedCopyForTransientFailure),
183
198
  ]);