@gloom-sh/terminal 0.20.20 → 0.20.21

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 (365) hide show
  1. package/package.json +3 -1
  2. package/src/api-client/data.ts +1 -1
  3. package/src/api-client/equity-screener.ts +17 -0
  4. package/src/api-client/futures-curve.ts +5 -0
  5. package/src/api-client/market-discovery.ts +8 -0
  6. package/src/api-client/members.ts +2 -0
  7. package/src/api-client/paths.ts +3 -0
  8. package/src/api-client/perps.ts +20 -0
  9. package/src/api-client/request.ts +53 -7
  10. package/src/api-client/types/filings-and-calls.ts +2 -0
  11. package/src/app/pane-runtime/plugin-bindings.ts +6 -4
  12. package/src/app/pro-welcome/model.ts +15 -11
  13. package/src/app/pro-welcome/row.tsx +3 -3
  14. package/src/app/pro-welcome/use-pro-welcome.ts +2 -2
  15. package/src/app/runtime/startup.ts +3 -2
  16. package/src/app.tsx +3 -2
  17. package/src/capabilities/asset-data-inputs.ts +5 -0
  18. package/src/capabilities/factories.ts +8 -3
  19. package/src/capabilities/registry.ts +1 -0
  20. package/src/capabilities/types.ts +1 -0
  21. package/src/cli/commands/market.ts +68 -35
  22. package/src/cli/commands/options-chain.ts +2 -2
  23. package/src/cli/commands/overview.ts +10 -9
  24. package/src/cli/commands/ticker.ts +19 -4
  25. package/src/cli/desktop-pane-shot.ts +11 -3
  26. package/src/cli/export-source.ts +35 -2
  27. package/src/cli/glossary.ts +3 -2
  28. package/src/cli/helpers.ts +2 -1
  29. package/src/cli/history-demergers.ts +41 -10
  30. package/src/cli/history-rows.ts +3 -1
  31. package/src/cli/known-gaps.ts +21 -7
  32. package/src/cli/listing-arg.ts +22 -11
  33. package/src/cli/pane-functions/capabilities.ts +4 -9
  34. package/src/cli/pane-functions/catalog-snapshot.json +29 -29
  35. package/src/cli/pane-functions/catalog.ts +1 -18
  36. package/src/cli/pane-functions/data.ts +8 -4
  37. package/src/cli/pane-functions/financial-ratio-shot.ts +20 -5
  38. package/src/cli/pane-functions/freshness.ts +57 -12
  39. package/src/cli/pane-functions/function-help.ts +2 -2
  40. package/src/cli/pane-functions/headless.ts +6 -0
  41. package/src/cli/pane-functions/index.ts +11 -4
  42. package/src/cli/pane-functions/market-session.ts +25 -0
  43. package/src/cli/pane-functions/report-notices.ts +10 -0
  44. package/src/cli/pane-functions/resolver.ts +75 -3
  45. package/src/cli/pane-functions/screenshot-bridge.ts +1 -0
  46. package/src/cli/pane-functions/screenshot-data-evidence.ts +1 -0
  47. package/src/cli/pane-functions/screenshot-payload.ts +38 -5
  48. package/src/cli/pane-functions/screenshot-render.ts +20 -7
  49. package/src/cli/perpetual-contract.ts +14 -1
  50. package/src/cli/report-tables.ts +11 -2
  51. package/src/cli/result.ts +6 -1
  52. package/src/components/chart-table/layout.ts +8 -4
  53. package/src/components/command-bar/list/model.ts +2 -0
  54. package/src/components/command-bar/pane-templates/items.ts +5 -25
  55. package/src/components/command-bar/panel/index.tsx +7 -4
  56. package/src/components/command-bar/routes/root/provider-search.ts +4 -4
  57. package/src/components/command-bar/routes/root/results.ts +6 -2
  58. package/src/components/command-bar/routes/ticker-search/results.ts +19 -0
  59. package/src/components/command-bar/routes/ticker-search/route.ts +3 -3
  60. package/src/components/command-bar/routes/ticker-search/title.ts +23 -0
  61. package/src/components/command-bar/routing/list-state.ts +17 -5
  62. package/src/components/command-bar/selection-runtime.ts +3 -2
  63. package/src/components/command-bar/surface/index.tsx +2 -0
  64. package/src/components/command-bar/workflow/alert.ts +6 -4
  65. package/src/components/command-bar/workflow/collection-actions.ts +2 -1
  66. package/src/components/layout/pane/footer/index.tsx +1 -0
  67. package/src/components/layout/pane/footer/model.ts +20 -7
  68. package/src/components/layout/pane/title.ts +11 -2
  69. package/src/components/price-selector-dialog.tsx +8 -4
  70. package/src/components/ticker/badge/list.tsx +4 -3
  71. package/src/components/ticker/list-table-view.tsx +12 -1
  72. package/src/components/ui/query-bar.tsx +20 -14
  73. package/src/data/cached-query.ts +20 -4
  74. package/src/data/news-pane-snapshots.ts +2 -1
  75. package/src/data/plugin-cache.ts +5 -1
  76. package/src/data/saved-copies.ts +68 -2
  77. package/src/docs/snapshot.json +65 -14
  78. package/src/docs/topics.ts +11 -9
  79. package/src/i18n/es.ts +1 -0
  80. package/src/i18n/ja.ts +1 -0
  81. package/src/i18n/ko.ts +1 -0
  82. package/src/i18n/zh-cn.ts +1 -0
  83. package/src/i18n/zh-tw.ts +1 -0
  84. package/src/market-data/coordinator/index.ts +25 -5
  85. package/src/market-data/depositary-pair.ts +27 -10
  86. package/src/market-data/futures-roll-returns.ts +54 -7
  87. package/src/market-data/fx-closes.ts +14 -0
  88. package/src/market-data/market/futures-product-hours.ts +113 -0
  89. package/src/market-data/market/futures-week.ts +2 -0
  90. package/src/market-data/market/globex-day.ts +9 -2
  91. package/src/market-data/market/status.ts +32 -25
  92. package/src/market-data/market/venue-session.ts +18 -0
  93. package/src/market-data/options-alternatives.ts +49 -7
  94. package/src/market-data/perpetual-open-interest.ts +41 -0
  95. package/src/market-data/quotes/contributions.ts +4 -2
  96. package/src/market-data/quotes/export-identity.ts +11 -3
  97. package/src/market-data/quotes/freshness.ts +3 -2
  98. package/src/market-data/quotes/resolution.ts +9 -2
  99. package/src/market-data/quotes/tick-range.ts +22 -1
  100. package/src/market-data/quotes/time.ts +34 -4
  101. package/src/market-data/split-terms.ts +3 -2
  102. package/src/news/aggregator.ts +1 -0
  103. package/src/news/news-model.ts +12 -2
  104. package/src/news/types.ts +15 -0
  105. package/src/plugins/builtin/alerts/alert-engine.ts +2 -0
  106. package/src/plugins/builtin/alerts/cli-forms.ts +3 -2
  107. package/src/plugins/builtin/alerts/cli-move.ts +5 -2
  108. package/src/plugins/builtin/alerts/cli.ts +50 -25
  109. package/src/plugins/builtin/alerts/command.ts +51 -3
  110. package/src/plugins/builtin/alerts/event-rows.ts +1 -1
  111. package/src/plugins/builtin/alerts/events-pane.tsx +1 -1
  112. package/src/plugins/builtin/alerts/format.ts +67 -8
  113. package/src/plugins/builtin/alerts/headless.ts +22 -6
  114. package/src/plugins/builtin/alerts/index.tsx +26 -25
  115. package/src/plugins/builtin/alerts/move-checks.ts +1 -0
  116. package/src/plugins/builtin/alerts/pane.tsx +15 -6
  117. package/src/plugins/builtin/alerts/pro-rules.ts +9 -4
  118. package/src/plugins/builtin/alerts/quotes.ts +10 -5
  119. package/src/plugins/builtin/alerts/session.ts +28 -0
  120. package/src/plugins/builtin/alerts/types.ts +1 -0
  121. package/src/plugins/builtin/analytics/pane-model.ts +2 -1
  122. package/src/plugins/builtin/analytics/risk-model.ts +2 -2
  123. package/src/plugins/builtin/attention/headless.ts +2 -2
  124. package/src/plugins/builtin/attention/model.ts +7 -2
  125. package/src/plugins/builtin/attention/pane.tsx +2 -1
  126. package/src/plugins/builtin/awards/headless.ts +1 -1
  127. package/src/plugins/builtin/broker-trading/ticket.tsx +13 -5
  128. package/src/plugins/builtin/buildout/detail/company.tsx +0 -1
  129. package/src/plugins/builtin/buildout/detail/ui.tsx +7 -5
  130. package/src/plugins/builtin/buildout/model/normalizers.ts +0 -1
  131. package/src/plugins/builtin/buildout/model/types.ts +0 -1
  132. package/src/plugins/builtin/buildout/pane/index.tsx +9 -0
  133. package/src/plugins/builtin/buildout/pane/status.tsx +11 -0
  134. package/src/plugins/builtin/catalysts/headless.ts +1 -1
  135. package/src/plugins/builtin/chart-composer/headless.ts +14 -6
  136. package/src/plugins/builtin/chart-composer/pane.tsx +2 -1
  137. package/src/plugins/builtin/chart-composer/session-history.ts +14 -2
  138. package/src/plugins/builtin/chat/controller/index.ts +5 -3
  139. package/src/plugins/builtin/chat/controller/session-runtime.ts +18 -8
  140. package/src/plugins/builtin/chat/index.tsx +1 -1
  141. package/src/plugins/builtin/cloud/auth-actions.tsx +4 -2
  142. package/src/plugins/builtin/cloud/mcp-connect/dialog.tsx +4 -1
  143. package/src/plugins/builtin/cloud/thesis/ticker-tab.tsx +2 -1
  144. package/src/plugins/builtin/company-attention/headless.ts +2 -1
  145. package/src/plugins/builtin/company-kpis/headless.ts +1 -1
  146. package/src/plugins/builtin/correlation/headless.ts +3 -3
  147. package/src/plugins/builtin/correlation/history.ts +1 -0
  148. package/src/plugins/builtin/correlation/index.tsx +7 -5
  149. package/src/plugins/builtin/correlation/matrix/selection.ts +21 -3
  150. package/src/plugins/builtin/correlation/relationship/model.ts +5 -0
  151. package/src/plugins/builtin/correlation/relationship/pane.tsx +3 -2
  152. package/src/plugins/builtin/correlation/relationship/view-model.ts +3 -2
  153. package/src/plugins/builtin/credit-documents/headless.ts +1 -1
  154. package/src/plugins/builtin/dividend-yield/client.ts +81 -10
  155. package/src/plugins/builtin/dividend-yield/headless.ts +21 -10
  156. package/src/plugins/builtin/dividend-yield/model.ts +1 -1
  157. package/src/plugins/builtin/dividend-yield/pane.tsx +9 -5
  158. package/src/plugins/builtin/dividend-yield/ranking.ts +15 -5
  159. package/src/plugins/builtin/dividend-yield/reference-price.ts +3 -0
  160. package/src/plugins/builtin/dividend-yield/types.ts +12 -0
  161. package/src/plugins/builtin/dividend-yield/view.ts +30 -7
  162. package/src/plugins/builtin/doe/headless.ts +1 -1
  163. package/src/plugins/builtin/doe/pane.tsx +16 -7
  164. package/src/plugins/builtin/earnings-calls/data.ts +8 -5
  165. package/src/plugins/builtin/earnings-ripple/headless.ts +1 -1
  166. package/src/plugins/builtin/econ/calendar-model.ts +1 -1
  167. package/src/plugins/builtin/econ/index.tsx +26 -18
  168. package/src/plugins/builtin/equity-screener/client.ts +1 -1
  169. package/src/plugins/builtin/equity-screener/headless.ts +149 -31
  170. package/src/plugins/builtin/equity-screener/live.ts +23 -5
  171. package/src/plugins/builtin/equity-screener/model.ts +27 -12
  172. package/src/plugins/builtin/equity-screener/pane.tsx +5 -5
  173. package/src/plugins/builtin/exposure/headless.ts +1 -1
  174. package/src/plugins/builtin/exposure/holdings.ts +2 -2
  175. package/src/plugins/builtin/futures/index.tsx +29 -1
  176. package/src/plugins/builtin/futures/model.ts +93 -10
  177. package/src/plugins/builtin/futures/returns.ts +54 -1
  178. package/src/plugins/builtin/futures/table.tsx +14 -2
  179. package/src/plugins/builtin/futures/use-front-returns.ts +20 -3
  180. package/src/plugins/builtin/futures-curve/client.ts +1 -1
  181. package/src/plugins/builtin/futures-curve/headless.ts +9 -3
  182. package/src/plugins/builtin/futures-curve/model.ts +19 -5
  183. package/src/plugins/builtin/futures-curve/pane.tsx +12 -6
  184. package/src/plugins/builtin/gpu/headless.ts +1 -1
  185. package/src/plugins/builtin/gpu/model.ts +1 -1
  186. package/src/plugins/builtin/help/function-index.ts +16 -8
  187. package/src/plugins/builtin/help/functions-table.tsx +6 -4
  188. package/src/plugins/builtin/help/shortcut-model.ts +7 -2
  189. package/src/plugins/builtin/holders/headless.ts +16 -5
  190. package/src/plugins/builtin/holders/pane.tsx +43 -5
  191. package/src/plugins/builtin/insider/client.ts +118 -11
  192. package/src/plugins/builtin/insider/filing-stories.ts +36 -20
  193. package/src/plugins/builtin/insider/issuer.ts +5 -2
  194. package/src/plugins/builtin/iv-history/headless.ts +2 -0
  195. package/src/plugins/builtin/macro-day/client.ts +2 -3
  196. package/src/plugins/builtin/macro-day/comparison.ts +58 -0
  197. package/src/plugins/builtin/macro-day/headless.ts +47 -3
  198. package/src/plugins/builtin/macro-day/index.tsx +32 -9
  199. package/src/plugins/builtin/macro-day/model.ts +1 -1
  200. package/src/plugins/builtin/macro-day/pane.tsx +99 -12
  201. package/src/plugins/builtin/market-heatmap/index.tsx +2 -2
  202. package/src/plugins/builtin/market-movers/footer.ts +29 -3
  203. package/src/plugins/builtin/market-movers/headless.ts +12 -5
  204. package/src/plugins/builtin/market-movers/index.tsx +3 -3
  205. package/src/plugins/builtin/market-movers/session-body.tsx +6 -3
  206. package/src/plugins/builtin/market-valuation/detail.tsx +3 -3
  207. package/src/plugins/builtin/market-valuation/headless.ts +6 -6
  208. package/src/plugins/builtin/market-valuation/pane.tsx +2 -3
  209. package/src/plugins/builtin/market-valuation/view.ts +6 -8
  210. package/src/plugins/builtin/members/client.ts +9 -2
  211. package/src/plugins/builtin/members/headless.ts +8 -10
  212. package/src/plugins/builtin/members/model.ts +29 -17
  213. package/src/plugins/builtin/members/pane.tsx +10 -12
  214. package/src/plugins/builtin/money-markets/headless.ts +1 -1
  215. package/src/plugins/builtin/news/headless.ts +4 -0
  216. package/src/plugins/builtin/news/index.tsx +3 -1
  217. package/src/plugins/builtin/news/wire/industry-pane.tsx +2 -1
  218. package/src/plugins/builtin/news/wire/news/preset-pane.tsx +1 -1
  219. package/src/plugins/builtin/news/wire/persisted-articles.ts +8 -4
  220. package/src/plugins/builtin/notes/headless.ts +7 -0
  221. package/src/plugins/builtin/notes/index.tsx +1 -1
  222. package/src/plugins/builtin/notes/quick-notes-pane.tsx +18 -2
  223. package/src/plugins/builtin/options/view.tsx +7 -6
  224. package/src/plugins/builtin/options-positioning/headless.ts +4 -4
  225. package/src/plugins/builtin/options-positioning/pane.tsx +7 -3
  226. package/src/plugins/builtin/options-scenario/client.ts +20 -4
  227. package/src/plugins/builtin/options-scenario/headless.ts +1 -1
  228. package/src/plugins/builtin/pe-band/client.ts +5 -9
  229. package/src/plugins/builtin/pe-band/headless.ts +11 -13
  230. package/src/plugins/builtin/pe-band/model.ts +39 -60
  231. package/src/plugins/builtin/pe-band/pane.tsx +14 -15
  232. package/src/plugins/builtin/perps/equity-row.tsx +3 -1
  233. package/src/plugins/builtin/perps/freshness.ts +16 -9
  234. package/src/plugins/builtin/perps/headless.ts +4 -1
  235. package/src/plugins/builtin/perps/markets-section.tsx +16 -10
  236. package/src/plugins/builtin/perps/model.ts +33 -2
  237. package/src/plugins/builtin/perps/pane.tsx +3 -2
  238. package/src/plugins/builtin/perps/status-line.ts +12 -3
  239. package/src/plugins/builtin/perps/venue-markets.ts +38 -0
  240. package/src/plugins/builtin/plugin-marketplace/pane.tsx +4 -3
  241. package/src/plugins/builtin/portfolio-list/cell-version.ts +1 -1
  242. package/src/plugins/builtin/portfolio-list/cli/render.ts +46 -7
  243. package/src/plugins/builtin/portfolio-list/headless.ts +31 -8
  244. package/src/plugins/builtin/portfolio-list/settings.ts +3 -0
  245. package/src/plugins/builtin/portfolio-list/table.tsx +7 -1
  246. package/src/plugins/builtin/power/headless.ts +1 -1
  247. package/src/plugins/builtin/realized-vol/headless.ts +1 -1
  248. package/src/plugins/builtin/research/corporate-actions-pane.tsx +27 -13
  249. package/src/plugins/builtin/scanner/feed.ts +7 -4
  250. package/src/plugins/builtin/scanner/flow-pane.tsx +8 -4
  251. package/src/plugins/builtin/scanner/headless.ts +57 -26
  252. package/src/plugins/builtin/scanner/hilo-pane.tsx +6 -3
  253. package/src/plugins/builtin/scanner/lock-note.ts +3 -2
  254. package/src/plugins/builtin/scanner/us-session.ts +9 -0
  255. package/src/plugins/builtin/seasonality/client.ts +46 -10
  256. package/src/plugins/builtin/seasonality/headless.ts +29 -11
  257. package/src/plugins/builtin/seasonality/model.ts +101 -24
  258. package/src/plugins/builtin/seasonality/pane.tsx +10 -6
  259. package/src/plugins/builtin/sec/filing-content.ts +13 -0
  260. package/src/plugins/builtin/sec/index.tsx +16 -11
  261. package/src/plugins/builtin/sectors/client.ts +27 -5
  262. package/src/plugins/builtin/sectors/headless.ts +2 -1
  263. package/src/plugins/builtin/sectors/index.tsx +22 -10
  264. package/src/plugins/builtin/shared/cloud-resource.ts +3 -3
  265. package/src/plugins/builtin/shared/extended-print.ts +38 -0
  266. package/src/plugins/builtin/shared/pro-feature-wall.tsx +1 -1
  267. package/src/plugins/builtin/shared/report-freshness.ts +7 -3
  268. package/src/plugins/builtin/shared/scanner-capture.ts +16 -3
  269. package/src/plugins/builtin/shared/ticker-company.ts +17 -8
  270. package/src/plugins/builtin/shared/use-quote-board.ts +11 -4
  271. package/src/plugins/builtin/social-mentions/client.ts +7 -3
  272. package/src/plugins/builtin/social-mentions/outliers.tsx +9 -2
  273. package/src/plugins/builtin/thirteenf/api.ts +24 -3
  274. package/src/plugins/builtin/thirteenf/data.ts +21 -8
  275. package/src/plugins/builtin/thirteenf/headless.ts +7 -3
  276. package/src/plugins/builtin/thirteenf/signals-pane.tsx +10 -3
  277. package/src/plugins/builtin/thirteenf/signals.ts +22 -1
  278. package/src/plugins/builtin/ticker-detail/adr-pair/model.ts +4 -2
  279. package/src/plugins/builtin/ticker-detail/financials/model.ts +7 -0
  280. package/src/plugins/builtin/ticker-detail/financials/ratio-table.tsx +15 -6
  281. package/src/plugins/builtin/ticker-detail/financials/ratios.ts +5 -4
  282. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +14 -5
  283. package/src/plugins/builtin/ticker-detail/headless.ts +32 -26
  284. package/src/plugins/builtin/ticker-detail/index.tsx +1 -1
  285. package/src/plugins/builtin/ticker-detail/overview/components.tsx +8 -3
  286. package/src/plugins/builtin/ticker-detail/overview/model.ts +28 -5
  287. package/src/plugins/builtin/ticker-detail/overview/pane.tsx +14 -1
  288. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +9 -8
  289. package/src/plugins/builtin/ticker-detail/pane.tsx +16 -9
  290. package/src/plugins/builtin/ticker-detail/quote-monitor/card.tsx +41 -23
  291. package/src/plugins/builtin/ticker-detail/quote-monitor/rows.ts +30 -13
  292. package/src/plugins/builtin/ticker-detail/settings.ts +9 -2
  293. package/src/plugins/builtin/time-sales/headless.ts +49 -13
  294. package/src/plugins/builtin/time-sales/model.ts +2 -2
  295. package/src/plugins/builtin/time-sales/window.ts +84 -10
  296. package/src/plugins/builtin/vol-surface/charts.tsx +4 -2
  297. package/src/plugins/builtin/vol-surface/events.ts +12 -5
  298. package/src/plugins/builtin/vol-surface/headless.ts +1 -1
  299. package/src/plugins/builtin/vol-surface/pane.tsx +15 -7
  300. package/src/plugins/builtin/world-indices/footer.ts +1 -1
  301. package/src/plugins/builtin/world-venue-map/chokepoint-report.ts +3 -1
  302. package/src/plugins/builtin/world-venue-map/headless.ts +27 -13
  303. package/src/plugins/builtin/yield-curve/client.ts +3 -1
  304. package/src/plugins/duplicates.ts +60 -0
  305. package/src/plugins/loader.ts +12 -3
  306. package/src/plugins/marketplace/model.ts +10 -1
  307. package/src/portfolio/column-values.ts +52 -5
  308. package/src/react/async-resource.ts +8 -7
  309. package/src/renderers/browser/bundled-plugins.ts +2 -1
  310. package/src/renderers/dom/build-assets.ts +20 -0
  311. package/src/renderers/dom/data-table/index.tsx +36 -2
  312. package/src/renderers/dom/es2023-array-methods.ts +57 -0
  313. package/src/renderers/dom/host/surface-fit.ts +64 -13
  314. package/src/renderers/dom/styles.css +6 -1
  315. package/src/renderers/electrobun/bun/external-plugins.ts +16 -6
  316. package/src/renderers/electrobun/shared/protocol.ts +2 -0
  317. package/src/renderers/electrobun/view/cli-pane-shot-entry.tsx +31 -7
  318. package/src/renderers/electrobun/view/cli-pane-shot-frame.tsx +15 -8
  319. package/src/renderers/electrobun/view/external-plugins.ts +1 -0
  320. package/src/renderers/electrobun/view/remote/asset-data-client.ts +1 -0
  321. package/src/series/types.ts +1 -0
  322. package/src/sources/gloomberb-cloud/fred-attribution.ts +6 -5
  323. package/src/sources/gloomberb-cloud/index.ts +42 -5
  324. package/src/sources/gloomberb-cloud/news.ts +15 -2
  325. package/src/sources/gloomberb-cloud/normalizers.ts +9 -0
  326. package/src/sources/history-result.ts +2 -1
  327. package/src/sources/history-retention.ts +14 -2
  328. package/src/sources/listing-symbols.ts +1 -1
  329. package/src/sources/provider-router/cache.ts +32 -3
  330. package/src/sources/provider-router/cached-routes.ts +25 -0
  331. package/src/sources/provider-router/connection-health.ts +1 -0
  332. package/src/sources/provider-router/history.ts +2 -2
  333. package/src/sources/provider-router/index.ts +14 -0
  334. package/src/sources/provider-router/sec-filings-page.ts +25 -0
  335. package/src/sources/sec-edgar/content.ts +67 -36
  336. package/src/tickers/listing-fate.ts +28 -0
  337. package/src/tickers/search/home-listing.ts +3 -0
  338. package/src/tickers/search/index-root-lead.ts +40 -0
  339. package/src/tickers/terminal-codes.ts +7 -4
  340. package/src/time-series/base-series.ts +17 -8
  341. package/src/time-series/fundamentals/historical-valuation.ts +2 -2
  342. package/src/time-series/fundamentals/series.ts +15 -12
  343. package/src/time-series/history-acquisition.ts +2 -0
  344. package/src/time-series/market.ts +3 -1
  345. package/src/time-series/price-comparison.ts +3 -1
  346. package/src/time-series/resolve-context.ts +8 -0
  347. package/src/time-series/resolve.ts +50 -10
  348. package/src/time-series/types.ts +1 -0
  349. package/src/time-series/use-chart-resolution.ts +2 -2
  350. package/src/time-series/valuation-currency.ts +40 -12
  351. package/src/types/data-provider.ts +30 -1
  352. package/src/types/financials.ts +23 -0
  353. package/src/types/headless.ts +23 -0
  354. package/src/types/instrument.ts +1 -0
  355. package/src/utils/crypto-pair.ts +16 -0
  356. package/src/utils/exchange-announcements.ts +2 -1
  357. package/src/utils/exchange-notation.generated.ts +58 -1
  358. package/src/utils/exchanges.ts +43 -1
  359. package/src/utils/format.ts +37 -2
  360. package/src/utils/function-search.ts +38 -0
  361. package/src/utils/fuzzy-search.ts +10 -6
  362. package/src/utils/option-choice.ts +15 -0
  363. package/src/utils/price-history.ts +15 -1
  364. package/src/utils/reason-codes.ts +6 -3
  365. package/src/utils/trailing-dividend.ts +241 -28
@@ -19,6 +19,12 @@ export interface HistoryRetention {
19
19
  readonly requestedEnd: number;
20
20
  readonly observedAt: number;
21
21
  readonly availableStart: number;
22
+ /**
23
+ * When the window is older than every source holds: the first bar any of
24
+ * them has at the interval, after the window's start and before the
25
+ * retained window's (a SPY session in 2015, whose minutes start in 2016).
26
+ */
27
+ readonly firstBarAt?: number;
22
28
  }
23
29
 
24
30
  interface HistoryRecoveryRequest {
@@ -72,9 +78,13 @@ export function parseHistoryRetention(value: unknown, now = Date.now()): History
72
78
  || value.requestedStart >= value.requestedEnd || value.availableStart > value.observedAt
73
79
  || value.observedAt > now + HISTORY_RETENTION_CLOCK_SKEW_MS || now - value.observedAt > HISTORY_RETENTION_MAX_AGE_MS
74
80
  || [value.requestedStart, value.requestedEnd, value.observedAt, value.availableStart].some((time) => time % 1000 !== 0)) return null;
81
+ // A first bar outside the window's start and the retained window's is dropped, not the record.
82
+ const firstBarAt = instant(value.firstBarAt) && value.firstBarAt % 1000 === 0
83
+ && value.firstBarAt > value.requestedStart && value.firstBarAt < value.availableStart ? value.firstBarAt : undefined;
75
84
  return Object.freeze({ version: 1, source: "gloom", symbol: target.symbol, exchange, interval,
76
85
  requestedStart: value.requestedStart, requestedEnd: value.requestedEnd,
77
- observedAt: value.observedAt, availableStart: value.availableStart });
86
+ observedAt: value.observedAt, availableStart: value.availableStart,
87
+ ...(firstBarAt !== undefined ? { firstBarAt } : {}) });
78
88
  }
79
89
 
80
90
  export function parseHistoryRecoveryCandidate(value: unknown, now = Date.now()): HistoryRecoveryCandidate | null {
@@ -137,9 +147,11 @@ export class HistoryRetentionError extends Error {
137
147
  /**
138
148
  * Shown while a chart at an explicit interval reaches back past what the
139
149
  * source keeps at it: the first retained day, read in the listing's zone
140
- * (UTC when unknown), and the length of the window the source keeps.
150
+ * (UTC when unknown), and the length of the window the source keeps. A
151
+ * window older than every source holds names the first day any of them has.
141
152
  */
142
153
  export function historyRetentionNotice(retention: HistoryRetention, interval: string, timeZone: string | null): string {
154
+ if (retention.firstBarAt !== undefined) return historyStartNotice(retention.firstBarAt, interval, timeZone, retention.observedAt);
143
155
  const zone = timeZone ?? "UTC";
144
156
  const day = zonedDateKey(retention.availableStart, zone);
145
157
  const sameYear = day.slice(0, 4) === zonedDateKey(retention.observedAt, zone).slice(0, 4);
@@ -12,7 +12,7 @@ const EXCHANGE_SUFFIX_MAP: Record<string, string> = {
12
12
  IDX: ".JK",
13
13
  NSE: ".NS", BSE: ".BO",
14
14
  ASX: ".AX", NZE: ".NZ",
15
- SET: ".BK", BKK: ".BK", KLSE: ".KL", MYX: ".KL", PSE: ".PS", HOSE: ".VN", HNX: ".VN",
15
+ SET: ".BK", BKK: ".BK", KLSE: ".KL", MYX: ".KL", PSE: ".PS", HOSE: ".VN", HNX: "",
16
16
  LSE: ".L", LSEETF: ".L",
17
17
  XETRA: ".DE", XETR: ".DE", IBIS: ".DE", IBIS2: ".DE", FWB: ".F", FWB2: ".F", GETTEX: ".DE", TGATE: ".DE", SWB: ".SG",
18
18
  EURONEXT: ".AS", AEB: ".AS", AMS: ".AS", SBF: ".PA", EPA: ".PA", "ENEXT.BE": ".BR", BRU: ".BR", BVL: ".LS", LIS: ".LS",
@@ -1,3 +1,4 @@
1
+ import { apiClient } from "../../api-client";
1
2
  import { listingSuffixExchange } from "../listing-symbols";
2
3
  import type { CachedResourceRecord, ResourceStore } from "../../data/resource-store";
3
4
  import type { TimeRange } from "../../time-series/range";
@@ -114,6 +115,7 @@ export function cacheRouterResource<T>(
114
115
  value: T,
115
116
  cachePolicy: CachePolicy,
116
117
  ): void {
118
+ const provenance = askedBySession(kind, sourceKey) ? CLOUD_SESSION_PROVENANCE : null;
117
119
  resources?.set(
118
120
  {
119
121
  namespace: MARKET_NAMESPACE,
@@ -123,10 +125,37 @@ export function cacheRouterResource<T>(
123
125
  sourceKey,
124
126
  },
125
127
  value,
126
- { cachePolicy, ...(SCHEMA_VERSIONS[kind] ? { schemaVersion: SCHEMA_VERSIONS[kind] } : {}) },
128
+ { cachePolicy, ...(SCHEMA_VERSIONS[kind] ? { schemaVersion: SCHEMA_VERSIONS[kind] } : {}), ...(provenance ? { provenance } : {}) },
127
129
  );
128
130
  }
129
131
 
132
+ const CLOUD_SOURCE_KEY = "provider:gloomberb-cloud";
133
+ /** A cloud quote, or financials carrying one, saved from a read that carried a session. */
134
+ const CLOUD_SESSION_PROVENANCE = { session: true } as const;
135
+
136
+ /**
137
+ * Whether this read of Gloom Cloud's quotes carries a session. The service
138
+ * answers a session with its account's feed and anyone else with the delayed
139
+ * one, so each saved copy says which it was (`delayedForSignedOut`).
140
+ */
141
+ function askedBySession(kind: string, sourceKey: string): boolean {
142
+ return sourceKey === CLOUD_SOURCE_KEY && (kind === "quote" || kind === "financials") && apiClient.hasSessionCredential();
143
+ }
144
+
145
+ /**
146
+ * A delayed cloud quote read with no session is the feed anyone gets, not this
147
+ * session's: stale to a process that now has one, so a Pro account reads the
148
+ * listing again, live, rather than for minutes from the copy a signed-out read
149
+ * left. A copy read signed in, a free account's delayed one too, is kept.
150
+ */
151
+ function delayedForSignedOut<T>(record: CachedResourceRecord<T>, kind: string): boolean {
152
+ if (record.stale || record.sourceKey !== CLOUD_SOURCE_KEY || (kind !== "quote" && kind !== "financials")) return false;
153
+ const quote = kind === "quote" ? record.value as Quote : (record.value as TickerFinancials).quote;
154
+ if (quote?.dataSource !== "delayed") return false;
155
+ const provenance = record.provenance as { session?: unknown } | null;
156
+ return provenance?.session !== true && apiClient.hasSessionCredential();
157
+ }
158
+
130
159
  export function sortCachedRecords<T>(
131
160
  records: CachedResourceRecord<T>[],
132
161
  variantKeys: string[],
@@ -201,8 +230,8 @@ export function listCachedResources<T>(
201
230
  // the unqualified BA quote is Boeing's, never BAE Systems' London line.
202
231
  return !(requestedExchange && !declaredExchange && !parsePublicTickerKey(entityKey).exchange
203
232
  && variantExchange(record.variantKey) === undefined);
204
- }).map((record) => {
205
- if (kind !== "financials" || record.sourceKey !== "provider:gloomberb-cloud") return record;
233
+ }).map((record) => delayedForSignedOut(record, kind) ? { ...record, stale: true } : record).map((record) => {
234
+ if (kind !== "financials" || record.sourceKey !== CLOUD_SOURCE_KEY) return record;
206
235
  // A new client can cache an old backend response during a rolling deploy.
207
236
  // Require the metric's own provenance before reusing a cloud yield; retain
208
237
  // valid quotes and other issuer data.
@@ -42,6 +42,15 @@ interface Route {
42
42
  */
43
43
  const IDLE_QUERY_LIMIT = 64;
44
44
 
45
+ /**
46
+ * Datasets with no observation time of their own, dated by when they were
47
+ * read: a copy served again is stamped with that time, and a command that
48
+ * shows it says it was retrieved then (data/saved-copies.ts). Filing
49
+ * documents never change once filed, and quotes, histories, chains and rates
50
+ * carry their own times, so none of those is here.
51
+ */
52
+ const DATED_BY_RETRIEVAL: ReadonlySet<ProviderRouterCachePolicyKey> = new Set(["holders", "analystResearch", "corporateActions", "secFilings"]);
53
+
45
54
  /** One query owns both persisted source selection and live refreshes for a resource. */
46
55
  export class ProviderRouterCachedRoutes {
47
56
  private readonly objectIds = new WeakMap<object, number>();
@@ -104,6 +113,7 @@ export class ProviderRouterCachedRoutes {
104
113
  };
105
114
  const query = new CachedQuery({
106
115
  read,
116
+ datedByRetrieval: DATED_BY_RETRIEVAL.has(route.policy),
107
117
  acceptResult: method === "getExchangeRate" ? (result) => isUsableCachedExchangeRate(
108
118
  result.value as number, String(args[0]).trim().toUpperCase(), result,
109
119
  ) : undefined,
@@ -265,6 +275,21 @@ export class ProviderRouterCachedRoutes {
265
275
  throwLastError: true, error: `No SEC filings provider available for ${symbol}`,
266
276
  };
267
277
  }
278
+ case "getSecFilingsPage": {
279
+ const [symbol, query, listingExchange, requestContext] = args as CachedAssetArgs<"getSecFilingsPage">;
280
+ const page: Array<[string, string | number]> = [
281
+ ["forms", [...new Set(query.forms.map((form) => form.trim().toUpperCase()))].sort().join(",")],
282
+ ["limit", query.limit], ["offset", query.offset ?? 0],
283
+ ];
284
+ const exact = buildVariantKey([["exchange", canonicalExchange(listingExchange)], ...page]);
285
+ return {
286
+ kind: "sec-filings-page", policy: "secFilings", entityKey: this.deps.getEntityKey(symbol, requestContext?.instrument),
287
+ // As getSecFilings: a non-US listing never reads the bare symbol's pages.
288
+ variants: nonUsSecListingVenue(symbol, listingExchange) ? [exact] : [...new Set([exact, buildVariantKey(page)])],
289
+ request: (provider, force) => provider.getSecFilingsPage?.(symbol, query, listingExchange, force ? { ...requestContext, cacheMode: "refresh" } : requestContext),
290
+ throwLastError: true, error: `No SEC filings provider available for ${symbol}`,
291
+ };
292
+ }
268
293
  case "getSecFilingContent":
269
294
  case "getSecFilingDocuments": {
270
295
  const filing = args[0] as SecFilingItem;
@@ -15,6 +15,7 @@ const REQUEST_METHODS = new Set([
15
15
  "getCorporateActions",
16
16
  "getEarningsCalendar",
17
17
  "getSecFilings",
18
+ "getSecFilingsPage",
18
19
  "getSecFilingDocuments",
19
20
  "getSecFilingContent",
20
21
  "getArticleSummary",
@@ -27,7 +27,7 @@ import { resolvePriceHistoryCurrencyUnit } from "../../utils/currency-units";
27
27
  import { calendarHistoryFetchState, calendarHistoryLastBarDate, dropLeadingPlaceholderBars, getPricePointTimestamp, hasUsablePriceHistory, preservePriceHistoryGaps, isPriceHistoryStaleForCurrentWindow, normalizePriceHistory, priceHistoryIntervalMs, type CalendarHistoryFetchState } from "../../utils/price-history";
28
28
  import { noProviderError, noteProviderAnswer, noteProviderMiss, shouldLogProviderError, StaleHistoryError, type ProviderMissNote } from "../provider-errors";
29
29
  import { HistoryCoverageError } from "../history-coverage";
30
- import { servedFromSavedCopy } from "../../data/saved-copies";
30
+ import { markSavedCopy } from "../../data/saved-copies";
31
31
  import {
32
32
  buildVariantKey,
33
33
  compactDate,
@@ -785,7 +785,7 @@ export class ProviderRouterHistoryRoutes {
785
785
  ? { ...fallbackRecord.value, savedCopyBehind: true as const } : fallbackRecord.value;
786
786
  const answer = request.requestedRange ? clip(withReportedGaps(fallbackValue)) : withReportedGaps(fallbackValue);
787
787
  // A refetch that failed, rather than one that found nothing newer, leaves the saved copy answering.
788
- return attempts.misses.failure !== undefined ? servedFromSavedCopy(answer, fallbackRecord.fetchedAt) : answer;
788
+ return attempts.misses.failure !== undefined ? markSavedCopy(answer, fallbackRecord.fetchedAt, true) : answer;
789
789
  }
790
790
  if (coverageError) throw coverageError;
791
791
  if (attempts.coverageError) throw attempts.coverageError;
@@ -18,6 +18,8 @@ import type {
18
18
  QuoteSubscriptionTarget,
19
19
  SearchRequestContext,
20
20
  SecFilingItem,
21
+ SecFilingsPage,
22
+ SecFilingsPageQuery,
21
23
  TickerFinancialsBatchResult,
22
24
  } from "../../types/data-provider";
23
25
  import type { CapabilityRouteSource } from "../../types/capability-route-source";
@@ -57,6 +59,7 @@ import { ProviderRouterSearchRoutes } from "./search";
57
59
  import { collectCapabilityRouteSources, mergeRouteSourcesById, normalizeRouteSource } from "./sources";
58
60
  import type { ProviderRouterCoreDeps } from "./route-types";
59
61
  import { withProviderConnectionHealth } from "./connection-health";
62
+ import { secFilingsPageFromList } from "./sec-filings-page";
60
63
  import { withFiledTrailingEps } from "../../time-series/filed-trailing-eps";
61
64
  import { withShareMultiples } from "../../utils/share-multiples";
62
65
  import {
@@ -69,6 +72,9 @@ import {
69
72
  type BrokerCandidate,
70
73
  } from "./brokers";
71
74
 
75
+ /** The whole list a source without pages is read to, as INS read it before pages: SEC lists cap at this many. */
76
+ const SEC_FILINGS_LIST_LIMIT = 20_000;
77
+
72
78
  /**
73
79
  * One trailing EPS and P/E for every view of a listing: the filed quarters', as PEB and GE read them
74
80
  * (withFiledTrailingEps), and none where the price over it is no multiple of the share (withShareMultiples).
@@ -457,6 +463,14 @@ export class AssetDataRouter implements DataProvider {
457
463
  return (await this.getCachedQuery("getSecFilings", [ticker, count, exchange, context]).load({ force: context?.cacheMode === "refresh", background: this.revalidateInBackground })).value;
458
464
  }
459
465
 
466
+ async getSecFilingsPage(ticker: string, query: SecFilingsPageQuery, exchange?: string, context?: MarketDataRequestContext): Promise<SecFilingsPage> {
467
+ // A source that lists filings but no page of some forms (a plugin's) answers from its whole list, cut here.
468
+ if (!this.providersInPriorityOrder().some((provider) => provider.getSecFilingsPage)) {
469
+ return secFilingsPageFromList(await this.getSecFilings(ticker, SEC_FILINGS_LIST_LIMIT, exchange, context), query);
470
+ }
471
+ return (await this.getCachedQuery("getSecFilingsPage", [ticker, query, exchange, context]).load({ force: context?.cacheMode === "refresh", background: this.revalidateInBackground })).value;
472
+ }
473
+
460
474
  async getSecFilingDocuments(filing: SecFilingItem) {
461
475
  return (await this.getCachedQuery("getSecFilingDocuments", [filing]).load({ force: false, background: this.revalidateInBackground })).value;
462
476
  }
@@ -0,0 +1,25 @@
1
+ import type { SecFilingItem, SecFilingsPage, SecFilingsPageQuery } from "../../types/data-provider";
2
+
3
+ /** A form as the page's filter compares it: `4/A` is `4`. */
4
+ const formBase = (form: string) => form.trim().toUpperCase().replace(/\/A$/, "");
5
+
6
+ /**
7
+ * `getSecFilingsPage` cut from a whole list, for a source that lists a
8
+ * company's filings but has no page of some forms: the forms asked for, each
9
+ * with its amendment, from `offset`, and every form's newest filing day.
10
+ */
11
+ export function secFilingsPageFromList(filings: readonly SecFilingItem[], query: SecFilingsPageQuery): SecFilingsPage {
12
+ const forms = new Set(query.forms.map(formBase).filter(Boolean));
13
+ const matching = forms.size ? filings.filter((filing) => forms.has(formBase(filing.form))) : [...filings];
14
+ const offset = Math.max(0, query.offset ?? 0);
15
+ const page = matching.slice(offset, offset + Math.max(0, query.limit));
16
+ const newestByForm: Record<string, string> = {};
17
+ for (const filing of filings) {
18
+ const time = new Date(filing.filingDate).getTime();
19
+ const form = filing.form.trim();
20
+ if (!form || !Number.isFinite(time)) continue;
21
+ const day = new Date(time).toISOString().slice(0, 10);
22
+ if (!newestByForm[form] || day > newestByForm[form]) newestByForm[form] = day;
23
+ }
24
+ return { filings: page, hasMore: offset + page.length < matching.length, nextOffset: offset + page.length, newestByForm };
25
+ }
@@ -1,7 +1,13 @@
1
+ import { Parser } from "htmlparser2";
2
+ import type { SecFilingItem } from "../../types/data-provider";
1
3
  import { decodeHtmlEntities } from "../../utils/html-entities";
2
4
 
3
5
  const MAX_CONTENT_CHARS = 16_000;
6
+ const TRUNCATION_MARKER = "[truncated]";
4
7
  const OWNERSHIP_FORMS = new Set(["3", "3/A", "4", "4/A", "5", "5/A"]);
8
+ const BLOCK_TAG = /^(?:p|div|section|article|header|footer|li|tr|table|h[1-6]|pre|blockquote)$/;
9
+ const HIDDEN_TAG = /^(?:head|title|script|style|svg|template|ix:header|ix:hidden|ix:references|ix:resources)$/;
10
+ const HIDDEN_STYLE = /(?:^|;)\s*(?:display\s*:\s*none|visibility\s*:\s*hidden)\s*(?:!important\s*)?(?:;|$)/i;
5
11
 
6
12
  export const PDF_FALLBACK_MESSAGE = "This SEC document is a PDF. Inline PDF text extraction is not supported here.";
7
13
 
@@ -162,46 +168,71 @@ function extractOwnershipDocumentSummary(document: string, form: string): string
162
168
  return result || null;
163
169
  }
164
170
 
171
+ function edgarTextBody(document: string): string {
172
+ if (!/^\s*<(?:SEC-DOCUMENT|DOCUMENT)\b/i.test(document)) return document;
173
+ const opening = /<TEXT\s*>/i.exec(document);
174
+ if (!opening) return "";
175
+ const start = opening.index + opening[0].length;
176
+ const closing = /<\/(?:TEXT|DOCUMENT)\s*>/gi;
177
+ closing.lastIndex = start;
178
+ return document.slice(start, closing.exec(document)?.index);
179
+ }
180
+
181
+ function markupToText(markup: string): string {
182
+ const chunks: string[] = [];
183
+ let hiddenDepth = 0;
184
+ let preformatted = false;
185
+ new Parser({
186
+ onopentag(tag, attributes) {
187
+ if (hiddenDepth || HIDDEN_TAG.test(tag) || "hidden" in attributes || HIDDEN_STYLE.test(attributes.style ?? "")) {
188
+ hiddenDepth += 1;
189
+ return;
190
+ }
191
+ if (tag === "pre") preformatted = true;
192
+ if (BLOCK_TAG.test(tag) || tag === "br" || tag === "hr") chunks.push("\n");
193
+ if (tag === "td" || tag === "th") chunks.push(" ");
194
+ },
195
+ onclosetag(tag) {
196
+ if (hiddenDepth) hiddenDepth -= 1;
197
+ else {
198
+ if (tag === "pre") preformatted = false;
199
+ if (BLOCK_TAG.test(tag)) chunks.push("\n");
200
+ }
201
+ },
202
+ ontext(text) {
203
+ if (!hiddenDepth) chunks.push(preformatted ? text : text.replace(/\s+/g, " "));
204
+ },
205
+ }, { recognizeSelfClosing: true }).end(markup);
206
+ return chunks.join("");
207
+ }
208
+
165
209
  export function extractFilingContent(
166
210
  document: string,
167
211
  contentType = "",
168
212
  options: { form?: string; sourceUrl?: string } = {},
169
213
  ): string | null {
170
- if (isPdfDocument(document, contentType, options.sourceUrl)) {
171
- return PDF_FALLBACK_MESSAGE;
172
- }
173
-
174
- const ownershipSummary = options.form ? extractOwnershipDocumentSummary(document, options.form) : null;
175
- if (ownershipSummary) return ownershipSummary;
176
-
177
- const looksLikeMarkup = /html|xml/i.test(contentType) || /^\s*</.test(document);
178
- let text = document;
179
-
180
- if (looksLikeMarkup) {
181
- text = text
182
- .replace(/<head[\s\S]*?<\/head>/gi, " ")
183
- .replace(/<script[\s\S]*?<\/script>/gi, " ")
184
- .replace(/<style[\s\S]*?<\/style>/gi, " ")
185
- .replace(/<svg[\s\S]*?<\/svg>/gi, " ")
186
- .replace(/<div[^>]*display\s*:\s*none[^>]*>[\s\S]*?<\/div>/gi, " ")
187
- .replace(/<ix:header[\s\S]*?<\/ix:header>/gi, " ")
188
- .replace(/<ix:hidden[\s\S]*?<\/ix:hidden>/gi, " ")
189
- .replace(/<ix:references[\s\S]*?<\/ix:references>/gi, " ")
190
- .replace(/<ix:resources[\s\S]*?<\/ix:resources>/gi, " ")
191
- .replace(/<!--[\s\S]*?-->/g, " ")
192
- .replace(/<\/(p|div|section|article|header|footer|li|tr|table|h\d|title)>/gi, "\n")
193
- .replace(/<(br|hr)\s*\/?>/gi, "\n")
194
- .replace(/<(p|div|section|article|header|footer|li|tr|table|h\d|title)[^>]*>/gi, "\n")
195
- .replace(/<td[^>]*>/gi, " ")
196
- .replace(/<[^>]+>/g, " ");
197
- }
198
-
199
- const lines = trimLeadingNoise(collapseDocumentLines(decodeHtmlEntities(text)));
200
- if (lines.length === 0) return null;
214
+ const raw = document.trimEnd();
215
+ const alreadyTruncated = raw.endsWith(TRUNCATION_MARKER);
216
+ const body = edgarTextBody(alreadyTruncated ? raw.slice(0, -TRUNCATION_MARKER.length) : raw);
217
+ if (isPdfDocument(body, contentType, options.sourceUrl)) return PDF_FALLBACK_MESSAGE;
218
+
219
+ const ownershipSummary = options.form ? extractOwnershipDocumentSummary(body, options.form.trim()) : null;
220
+ const looksLikeMarkup = /html|xml/i.test(contentType) || /^\s*<(?:[a-z!?])/i.test(body);
221
+ const result = ownershipSummary ?? trimLeadingNoise(collapseDocumentLines(
222
+ looksLikeMarkup ? markupToText(body) : decodeHtmlEntities(body),
223
+ )).join("\n");
224
+ if (!result) return null;
225
+ return alreadyTruncated || result.length > MAX_CONTENT_CHARS
226
+ ? `${result.slice(0, MAX_CONTENT_CHARS).trimEnd()}\n\n${TRUNCATION_MARKER}`
227
+ : result;
228
+ }
201
229
 
202
- let result = lines.join("\n");
203
- if (result.length > MAX_CONTENT_CHARS) {
204
- result = `${result.slice(0, MAX_CONTENT_CHARS).trimEnd()}\n\n[truncated]`;
205
- }
206
- return result;
230
+ export function filingContentPreview(
231
+ raw: string | null | undefined,
232
+ filing: Pick<SecFilingItem, "form" | "primaryDocumentUrl" | "filingUrl">,
233
+ ): string | null {
234
+ return raw == null ? null : extractFilingContent(raw, "", {
235
+ form: filing.form,
236
+ sourceUrl: filing.primaryDocumentUrl ?? filing.filingUrl,
237
+ });
207
238
  }
@@ -11,6 +11,7 @@ import {
11
11
  quotedListing,
12
12
  startTickerChangeLookup,
13
13
  tickerChangeLine,
14
+ tickerChangeSymbol,
14
15
  type CurrentListing,
15
16
  type FormerIssuer,
16
17
  type MovedTickerChange,
@@ -374,6 +375,33 @@ export async function loadListingFate(
374
375
  }
375
376
  }
376
377
 
378
+ /**
379
+ * The change of a symbol whose company trades under another one now, with
380
+ * nothing new listed under it (`ListingFate.moved`: SQ became XYZ), told
381
+ * before anything else is asked for the symbol: its quote first, then, only
382
+ * for a line that stopped, its change lookup. A command that reads a
383
+ * company's data by symbol (13F holders, a put screen) then asks for the new
384
+ * symbol, rather than waiting on the old one's dead end. Null for a symbol
385
+ * that trades, one the change history is not about (a listing abroad, a
386
+ * pair), and when neither answers.
387
+ */
388
+ export async function movedListing(
389
+ listing: { symbol: string; exchange?: string | null },
390
+ dataProvider: Pick<DataProvider, "getQuote" | "getTickerChanges">,
391
+ ): Promise<MovedTickerChange | null> {
392
+ if (!tickerChangeSymbol(listing.symbol, listing.exchange)) return null;
393
+ // A line that trades asks for no lookup: only a stopped one can be a company that moved.
394
+ const quote = await dataProvider.getQuote(listing.symbol, listing.exchange ?? "")
395
+ .catch(logFailure("tickers-listing-fate", "Could not load a moved listing's quote", null));
396
+ if (!lineMayHaveMoved(quote)) return null;
397
+ return (await loadListingFate(listing, dataProvider, { quote })).moved;
398
+ }
399
+
400
+ /** "SQ became XYZ on 2025-01-21; showing XYZ.": the note of a report read under a moved symbol's new one (`movedListing`). */
401
+ export function movedListingNote(change: MovedTickerChange): string {
402
+ return `${change.note}; showing ${change.tradesAs}.`;
403
+ }
404
+
377
405
  /**
378
406
  * The lines a command says about a symbol's fate beside what it served. With
379
407
  * nothing served, `fate.note`. With data, `fate.delisted` for a listing that
@@ -208,6 +208,9 @@ function isListedEquity(candidate: TickerSearchCandidate): boolean {
208
208
  */
209
209
  export function withHomeListingLead<T extends TickerSearchCandidate>(items: T[], query: string): T[] {
210
210
  if (isQualifiedTickerQuery(query)) return items;
211
+ const namedHome = items.find((item) => item.result?.preferredNameMatch === true && item.homeListing === true
212
+ && item.instrumentClass === "equity" && isListedEquity(item) && item.result && namedByService(query, item.result));
213
+ if (namedHome && items[0] && !items[0].saved) return namedHome === items[0] ? items : moveAhead(items, namedHome, items[0]);
211
214
  const lead = items.find((item) => item.instrumentClass !== "fund" && item.instrumentClass !== "derivative"
212
215
  && !answersOnlyByKeyword(item, query));
213
216
  if (!lead || !isListedEquity(lead)) return items;
@@ -0,0 +1,40 @@
1
+ import type { TickerRecord } from "../../types/ticker";
2
+ import { isUsListingExchange, parsePublicTickerKey } from "../../utils/exchanges";
3
+ import { indexRootFor } from "../index-roots";
4
+ import { candidateExchange } from "./home-listing";
5
+ import { buildTickerSearchCandidates } from "./index";
6
+ import type { TickerSearchCandidate } from "./types";
7
+
8
+ /**
9
+ * A bare index root (SPX, VIX, NDX; `indexRootFor`) with its index leading,
10
+ * as the CLI reads the word: `search spx` names ^SPX before any listing, and
11
+ * `fn SEAS SPX` opens ^SPX. Search lists the listings of those letters
12
+ * (SpaceX's SPX on six German venues) and funds named for the index first, and
13
+ * the index far down or not at all, so the index is added where search did
14
+ * not send it. A US listing or a saved ticker of the letters keeps the lead, as
15
+ * every command keeps it (MOVE is Corvex), with the index right after it. Any
16
+ * other query keeps its order.
17
+ */
18
+ export function withIndexRootCandidate(
19
+ query: string,
20
+ candidates: TickerSearchCandidate[],
21
+ tickers: ReadonlyMap<string, TickerRecord>,
22
+ ): TickerSearchCandidate[] {
23
+ const root = indexRootFor(query);
24
+ if (!root) return candidates;
25
+ const isIndex = (candidate: TickerSearchCandidate) => parsePublicTickerKey(candidate.symbol).symbol === root.symbol;
26
+ const sent = candidates.find(isIndex);
27
+ const [index] = sent ? [sent] : buildTickerSearchCandidates({
28
+ query: root.symbol,
29
+ tickers,
30
+ providerResults: [{ providerId: "gloomberb-cloud", symbol: root.symbol, name: root.name, exchange: "", type: "INDEX" }],
31
+ totalLimit: 1,
32
+ localLimit: 0,
33
+ });
34
+ if (!index) return candidates;
35
+ const rest = candidates.filter((candidate) => !isIndex(candidate));
36
+ const letters = query.trim().toUpperCase();
37
+ const at = rest.findIndex((candidate) => parsePublicTickerKey(candidate.symbol).symbol === letters && !candidate.result?.delisting
38
+ && (candidate.saved || isUsListingExchange(candidateExchange(candidate))));
39
+ return at < 0 ? [index, ...rest] : [...rest.slice(0, at + 1), index, ...rest.slice(at + 1)];
40
+ }
@@ -1,7 +1,7 @@
1
1
  import { futuresContractByCode } from "../market-data/futures-board";
2
2
  import { getListingSymbol, hongKongListingCode, tickerHasListingSuffix } from "../sources/listing-symbols";
3
3
  import { isCurrencyCode } from "../utils/currency-pair";
4
- import { canonicalExchange, isKnownExchangeCode, isPredictionMarketExchange, isSharedExchangeCode, isUsListingExchange } from "../utils/exchanges";
4
+ import { canonicalExchange, isKnownExchangeCode, isPredictionMarketExchange, isSharedExchangeCode, isUsListingExchange, typedExchangeVenue } from "../utils/exchanges";
5
5
 
6
6
  /**
7
7
  * A listing written the way a market data terminal names it, read as the
@@ -558,15 +558,18 @@ const VENUE_FIRST = /^([A-Z][A-Z0-9]{1,11}):([A-Z0-9][A-Z0-9.&-]{0,19})$/;
558
558
  * stay as typed, as does a ticker before a two-letter market code (`ICE:US`,
559
559
  * `ASX:AU`, `BSE:IN`, `AMS:SW`), the code it is written symbol first with.
560
560
  * A code that names several venues (`TSE:7203`) is kept for the listing to
561
- * settle. A prediction market's id (`KALSHI:...`) is not a listing. Null for
562
- * anything else.
561
+ * settle, as is a code Gloom Cloud reads as a venue the app has no code of
562
+ * (`IDX:BBCA`, as Google Sheets writes Jakarta's, is `BBCA:IDX`, which the
563
+ * listing reads as BBCA:JAKARTA). A prediction market's id (`KALSHI:...`) is
564
+ * not a listing. Null for anything else.
563
565
  */
564
566
  export function readVenueFirstListing(raw: string): NearMissListing | null {
565
567
  const typed = raw.trim();
566
568
  const match = VENUE_FIRST.exec(typed.toUpperCase());
567
569
  if (!match) return null;
568
570
  const [, code, symbol] = match as unknown as [string, string, string];
569
- if (!isKnownExchangeCode(code) || isKnownExchangeCode(symbol) || isPredictionMarketExchange(code)) return null;
571
+ if (!(isKnownExchangeCode(code) || typedExchangeVenue(code)) || isKnownExchangeCode(symbol) || typedExchangeVenue(symbol)
572
+ || isPredictionMarketExchange(code)) return null;
570
573
  if (symbol.length === 2 && BLOOMBERG_MARKETS[symbol]) return null;
571
574
  return { typed, symbol: `${symbol}:${isSharedExchangeCode(code) ? code : canonicalExchange(code)}` };
572
575
  }
@@ -20,6 +20,7 @@ import {
20
20
  valuationPriceIssues,
21
21
  } from "./fundamentals";
22
22
  import { extractSecuritySeries } from "./market";
23
+ import type { ValuationCurrencyContext } from "./valuation-currency";
23
24
  import { activeStudyInputSeriesIds } from "./studies/resolve";
24
25
  import { reportingCurrencySeries } from "./reporting-currency";
25
26
  import { compareChartQuoteRecency } from "./live-quotes";
@@ -45,20 +46,26 @@ import { finiteDate } from "./chart-bounds";
45
46
  // A series that fails to load keeps its place with no observations. Dropping it
46
47
  // made a series the user had added disappear from the legend while it still sat
47
48
  // in the series editor, with nothing on screen to explain the difference.
48
- export function unloadableSeries(spec: ChartSeriesSpec, index: number, warning: string): ResolvedSeries {
49
+ export function unloadableSeries(spec: ChartSeriesSpec, index: number, warning: string, listing?: TickerFinancials,
50
+ contractUnit?: string | null): ResolvedSeries {
49
51
  const field = spec.source.kind === "security" ? getTimeSeriesField(spec.source.fieldId) : undefined;
50
52
  const label = spec.source.kind === "security"
51
53
  ? `${instrumentLabel(spec.source)} ${field?.seriesLabel ?? field?.shortLabel ?? spec.source.fieldId.split(".").at(-1) ?? "Series"}`
52
54
  : spec.source.kind === "economic"
53
55
  ? `FRED ${spec.source.seriesId}`
54
56
  : spec.source.seriesId;
57
+ // The unit the series would have had, from its quote or, without one, its symbol (^VIX is points): never the
58
+ // field's bare "currency" template, which named no unit at all.
59
+ const shaped = spec.source.kind === "security" && field?.unit.startsWith("currency")
60
+ ? baseSecuritySeries(spec, { ...(listing ?? emptyFinancials()), priceHistory: [] }, index, null, listing?.quoteMetadata, contractUnit) : null;
61
+ const unit = shaped ? /currency|^unknown$/.test(shaped.unit) ? "" : shaped.unit : field?.unit ?? "";
55
62
  return {
56
63
  id: spec.id,
57
64
  label: spec.label?.trim() || label,
58
65
  legendContext: spec.label?.trim() ? undefined : field?.seriesLabel ?? field?.shortLabel,
59
66
  color: spec.color ?? SERIES_COLORS[index % SERIES_COLORS.length]!,
60
- unit: field?.unit ?? "",
61
- unitGroup: field?.unitGroup ?? "unknown",
67
+ unit,
68
+ unitGroup: shaped?.unitGroup ?? field?.unitGroup ?? "unknown",
62
69
  nativeFrequency: field?.nativeFrequency ?? "daily",
63
70
  dataShape: field?.dataShape ?? "scalar",
64
71
  style: spec.style,
@@ -178,12 +185,12 @@ export function baseSecuritySeries(
178
185
  /** What a futures contract's price counts ("USD / gallon"), from its terms. */
179
186
  contractUnit?: string | null,
180
187
  /** The bars run into pre-market and after-hours trading. */
181
- { extendedHours = false }: { extendedHours?: boolean } = {},
188
+ { extendedHours = false, currencies }: { extendedHours?: boolean; currencies?: ValuationCurrencyContext } = {},
182
189
  ): ResolvedSeries | null {
183
190
  if (spec.source.kind !== "security") return null;
184
191
  const field = getTimeSeriesField(spec.source.fieldId);
185
192
  if (!field) return null;
186
- const points = extractSecuritySeries(financials, spec.source);
193
+ const points = extractSecuritySeries(financials, spec.source, currencies);
187
194
  const valuationFallback = dailyValuationFallbackPeriod(financials, spec.source);
188
195
  const unreportedPeriod = points.length === 0 ? unreportedStatementPeriod(financials, spec.source) : null;
189
196
  const notMeaningful = valuationNotMeaningful(financials, spec.source);
@@ -225,7 +232,9 @@ export function baseSecuritySeries(
225
232
  ? futuresListingPriceBasis(spec.source.instrument.symbol, spec.source.instrument.exchange) : null;
226
233
  // An index's level is points too, never the currency its members trade in.
227
234
  const indexLevel = field.unitGroup === "price" && isMarketFieldId(field.id)
228
- && isIndexLevel(financials.quote?.instrumentType || quoteMetadata?.instrumentType);
235
+ && (isIndexLevel(financials.quote?.instrumentType || quoteMetadata?.instrumentType)
236
+ // Before its quote says so, an index's symbol does (^VIX).
237
+ || !(financials.quote?.instrumentType || quoteMetadata?.instrumentType) && instrumentKind === "index");
229
238
  const yieldIndex = field.unitGroup === "price" && isMarketFieldId(field.id) && isYieldIndexSymbol(spec.source.instrument.symbol);
230
239
  const genericUnit = yieldIndex ? "%" : genericBasis === "points" || indexLevel ? INDEX_POINTS_UNIT : genericBasis === "thirty-seconds" ? "32nds" : null;
231
240
  // A future's price in a currency counts what its contract terms say: heating
@@ -283,7 +292,7 @@ export function baseSecuritySeries(
283
292
  ? barMoveBasisPoints(points.at(-1), display.price - display.change) ?? toBasisPoints(display.change, 1) : undefined;
284
293
  const fieldLabel = field.id === "market.volume" && volumeBasis ? INDEX_MEMBERS_VOLUME_LABEL
285
294
  : yieldIndex ? field.id === "market.ohlcv" ? "Yield" : `${field.shortLabel} Yield` : field.seriesLabel ?? field.shortLabel;
286
- const priceIssues = valuationPriceIssues(financials, spec.source);
295
+ const priceIssues = valuationPriceIssues(financials, spec.source, currencies);
287
296
  // A source with closes only, such as a generic future, has flat bars (open,
288
297
  // high and low filled from the close): nothing to draw as candles.
289
298
  const closesOnly = marketField && points.length > 1
@@ -305,7 +314,7 @@ export function baseSecuritySeries(
305
314
  warning: [valuationFallback ? "Release dates unavailable; showing reported periods." : undefined,
306
315
  notMeaningful ? `N/M: ${notMeaningful.reason} (period to ${notMeaningful.asOf}).` : undefined,
307
316
  field.id === "market.volume" && !volumeUnit && !volumeBasis && points.some((point) => Number.isFinite(point.value) && point.value !== 0)
308
- ? "Volume unit unknown." : statementCurrency?.warning ?? valuationCurrencyWarning(financials, spec.source)].filter(Boolean).join(" ") || undefined,
317
+ ? "Volume unit unknown." : statementCurrency?.warning ?? valuationCurrencyWarning(financials, spec.source, currencies)].filter(Boolean).join(" ") || undefined,
309
318
  nativeFrequency: marketField ? marketSeriesFrequency(spec.source, marketResolution)
310
319
  : valuationFallback ?? (spec.source.period && spec.source.period !== "auto" ? spec.source.period : field.nativeFrequency),
311
320
  ...(unreportedPeriod ? { unreportedPeriod } : {}),
@@ -29,10 +29,10 @@ export function historicalValuation(
29
29
  return { value: comparablePrice === null ? null : valuationAtPrice(statement, metric, comparablePrice), integrity: price.integrity, issue: price.issue };
30
30
  }
31
31
 
32
- export function dailyStatementValuation(financials: TickerFinancials, metric: string, exchange?: string): TimeSeriesPoint[] {
32
+ export function dailyStatementValuation(financials: TickerFinancials, metric: string, exchange?: string,
33
+ currencies = createValuationCurrencyContext(financials)): TimeSeriesPoint[] {
33
34
  const earningsMetric = metric === "pegRatio" ? "trailingPE" : metric;
34
35
  const selected = sourceStatements(financials, "daily", earningsMetric, exchange);
35
- const currencies = createValuationCurrencyContext(financials);
36
36
  const yearEndMonth = fiscalYearEndMonth(financials.annualStatements);
37
37
  const bases: DailyValuationBasis[] = selected.statements.flatMap((statement) => {
38
38
  const usable = valuationAtPrice(statement, earningsMetric, 1, true) !== null;