gloomberb 0.20.4 → 0.20.6

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 (316) hide show
  1. package/README.md +3 -1
  2. package/README.zh-CN.md +1 -1
  3. package/bin/gloom +9 -0
  4. package/bin/without-bun.cjs +98 -0
  5. package/package.json +4 -1
  6. package/src/api-client/data.ts +148 -37
  7. package/src/api-client/hk-tenders.ts +59 -0
  8. package/src/api-client/index.ts +1 -0
  9. package/src/api-client/types/econ.ts +30 -0
  10. package/src/api-client/yield-curves.ts +1 -1
  11. package/src/app/global-shortcuts.ts +4 -1
  12. package/src/app/keybindings/actions.ts +6 -0
  13. package/src/app/keybindings/config.ts +2 -1
  14. package/src/app/keybindings/index.ts +1 -0
  15. package/src/app/keybindings/labels.ts +6 -1
  16. package/src/app/keybindings/resolve.ts +23 -4
  17. package/src/app/keybindings/terminal-keys.ts +35 -0
  18. package/src/app/pane-runtime/index.tsx +2 -2
  19. package/src/app/pane-runtime/ticker-open-runtime.ts +68 -40
  20. package/src/app.tsx +18 -13
  21. package/src/architecture/floating-promise-allowlist.json +313 -0
  22. package/src/architecture/ui-literals-allowlist.json +1 -1
  23. package/src/capabilities/chart-series.ts +27 -1
  24. package/src/cli/commands/keybindings.ts +5 -5
  25. package/src/cli/commands/market.ts +238 -57
  26. package/src/cli/commands/news-search.ts +81 -14
  27. package/src/cli/commands/overview.ts +27 -6
  28. package/src/cli/commands/remote.ts +16 -17
  29. package/src/cli/commands/system.ts +1 -1
  30. package/src/cli/commands/ticker.ts +3 -1
  31. package/src/cli/early-command.ts +2 -0
  32. package/src/cli/errors.ts +10 -1
  33. package/src/cli/fx-forward.ts +89 -7
  34. package/src/cli/fx-pair.ts +1 -1
  35. package/src/cli/fx-quote-rate.ts +23 -0
  36. package/src/cli/glossary.ts +19 -5
  37. package/src/cli/help.ts +1 -0
  38. package/src/cli/history-rows.ts +5 -3
  39. package/src/cli/index-roots.ts +5 -4
  40. package/src/cli/index.ts +40 -3
  41. package/src/cli/known-gaps.ts +38 -9
  42. package/src/cli/listing-arg.ts +17 -5
  43. package/src/cli/name-entries.ts +5 -1
  44. package/src/cli/not-a-ticker.ts +4 -0
  45. package/src/cli/options.ts +52 -3
  46. package/src/cli/output-file.ts +5 -3
  47. package/src/cli/pane-functions/catalog.ts +15 -0
  48. package/src/cli/pane-functions/function-help.ts +4 -4
  49. package/src/cli/pane-functions/headless.ts +9 -4
  50. package/src/cli/pane-functions/index.ts +6 -4
  51. package/src/cli/pane-functions/resolver.ts +2 -2
  52. package/src/cli/result.ts +21 -2
  53. package/src/cli/spreadsheet-hint.ts +7 -3
  54. package/src/cli/treasury-yields.ts +5 -3
  55. package/src/components/chart/composite/legend.tsx +40 -2
  56. package/src/components/command-bar/pane-settings.ts +2 -2
  57. package/src/components/command-bar/routes/root/results.ts +6 -2
  58. package/src/components/command-bar/workflow/tickers.ts +2 -2
  59. package/src/components/data-table/view.tsx +9 -2
  60. package/src/components/input-search-bar.tsx +9 -2
  61. package/src/components/layout/pane/header.tsx +2 -0
  62. package/src/components/layout/shell/pane/capture.ts +4 -1
  63. package/src/components/layout/status-bar.tsx +6 -1
  64. package/src/components/onboarding/first-run-workspace.ts +44 -2
  65. package/src/components/onboarding/onboarding-frame.tsx +11 -2
  66. package/src/components/onboarding/onboarding-keyboard.ts +16 -0
  67. package/src/components/onboarding/onboarding-wizard.tsx +8 -8
  68. package/src/components/onboarding/portfolio-step/positions-panel.tsx +62 -1
  69. package/src/components/onboarding/use-onboarding-progress.ts +12 -4
  70. package/src/components/pane-settings-dialog/desktop.tsx +2 -2
  71. package/src/components/pane-settings-dialog/tui.tsx +2 -2
  72. package/src/components/pane-settings-dialog/value.ts +6 -0
  73. package/src/components/pane-settings-dialog.tsx +3 -3
  74. package/src/components/reader/detail-reader.tsx +4 -0
  75. package/src/components/ui/data-table/opentui/index.tsx +11 -4
  76. package/src/components/ui/data-table/opentui/model.ts +8 -6
  77. package/src/components/ui/data-table/types.ts +6 -1
  78. package/src/components/ui/index.ts +1 -1
  79. package/src/components/ui/page-stack-view.tsx +3 -0
  80. package/src/components/ui/pane-link-chip.tsx +269 -54
  81. package/src/components/ui/query-bar.tsx +2 -1
  82. package/src/components/ui/table-layout.ts +38 -1
  83. package/src/components/ui/tabs.tsx +97 -19
  84. package/src/core/state/app/layout-reducer.ts +7 -0
  85. package/src/core/state/app/layout.ts +44 -7
  86. package/src/core/state/app/state.ts +1 -1
  87. package/src/core/state/app/types.ts +22 -2
  88. package/src/docs/snapshot.json +30 -13
  89. package/src/market-data/depositary-pair.ts +5 -3
  90. package/src/market-data/market/change-basis.ts +9 -5
  91. package/src/market-data/market/dated-previous-close.ts +147 -17
  92. package/src/market-data/market/status.ts +17 -1
  93. package/src/market-data/quotes/contributions.ts +2 -0
  94. package/src/market-data/quotes/listing-enterprise-value.ts +50 -0
  95. package/src/plugins/builtin/alerts/metric-data.ts +15 -2
  96. package/src/plugins/builtin/analytics/risk-client.ts +10 -4
  97. package/src/plugins/builtin/analytics/risk-episodes.ts +5 -4
  98. package/src/plugins/builtin/analytics/risk-headless.ts +4 -2
  99. package/src/plugins/builtin/analytics/risk-sectors.ts +91 -0
  100. package/src/plugins/builtin/awards/index.tsx +1 -1
  101. package/src/plugins/builtin/backtest/headless.ts +1 -1
  102. package/src/plugins/builtin/buildout/index.tsx +1 -0
  103. package/src/plugins/builtin/catalysts/index.tsx +2 -2
  104. package/src/plugins/builtin/cds/headless.ts +4 -0
  105. package/src/plugins/builtin/cds/model.ts +0 -6
  106. package/src/plugins/builtin/chart-composer/formula.ts +16 -3
  107. package/src/plugins/builtin/chart-composer/headless-schema.ts +2 -0
  108. package/src/plugins/builtin/chart-composer/headless.ts +4 -2
  109. package/src/plugins/builtin/chart-composer/index.tsx +1 -0
  110. package/src/plugins/builtin/chart-composer/presets.ts +1 -0
  111. package/src/plugins/builtin/chat/content/composer.tsx +5 -4
  112. package/src/plugins/builtin/chat/content/index.tsx +12 -2
  113. package/src/plugins/builtin/chat/content/layout-metrics.ts +3 -3
  114. package/src/plugins/builtin/chat/content/open-targets.ts +3 -3
  115. package/src/plugins/builtin/chat/layout.ts +5 -2
  116. package/src/plugins/builtin/chat/message/pane-chip.tsx +61 -40
  117. package/src/plugins/builtin/chat/message/terminal.tsx +13 -15
  118. package/src/plugins/builtin/chat/pane-links/previews.ts +51 -5
  119. package/src/plugins/builtin/chat/pane-links/share-card.ts +36 -0
  120. package/src/plugins/builtin/cloud/askg/pane.tsx +55 -13
  121. package/src/plugins/builtin/cloud/askg/tool-display.ts +1 -0
  122. package/src/plugins/builtin/cloud/terminal-relay/redact.ts +5 -3
  123. package/src/plugins/builtin/commodity-balances/index.tsx +1 -0
  124. package/src/plugins/builtin/company-attention/index.tsx +1 -1
  125. package/src/plugins/builtin/company-kpis/headless.ts +3 -1
  126. package/src/plugins/builtin/company-kpis/index.tsx +2 -2
  127. package/src/plugins/builtin/cot/index.tsx +1 -1
  128. package/src/plugins/builtin/cpi/index.tsx +1 -1
  129. package/src/plugins/builtin/credit-boards/cdx-pane.tsx +20 -7
  130. package/src/plugins/builtin/credit-boards/client.ts +8 -0
  131. package/src/plugins/builtin/credit-boards/headless.ts +4 -1
  132. package/src/plugins/builtin/credit-boards/model.ts +58 -4
  133. package/src/plugins/builtin/credit-boards/series.ts +63 -6
  134. package/src/plugins/builtin/credit-boards/sovr-pane.tsx +3 -2
  135. package/src/plugins/builtin/credit-conditions/headless.ts +24 -6
  136. package/src/plugins/builtin/credit-conditions/index.tsx +1 -1
  137. package/src/plugins/builtin/credit-conditions/model.ts +12 -6
  138. package/src/plugins/builtin/credit-conditions/series.ts +2 -1
  139. package/src/plugins/builtin/crypto-board/index.tsx +1 -0
  140. package/src/plugins/builtin/dividend-yield/index.tsx +1 -0
  141. package/src/plugins/builtin/doe/index.tsx +1 -1
  142. package/src/plugins/builtin/earnings-calls/headless.ts +5 -1
  143. package/src/plugins/builtin/earnings-calls/index.tsx +1 -0
  144. package/src/plugins/builtin/econ/calendar-model.ts +115 -8
  145. package/src/plugins/builtin/econ/calendar-source.ts +7 -1
  146. package/src/plugins/builtin/econ/fred-catalog.ts +3 -1
  147. package/src/plugins/builtin/econ/index.tsx +42 -8
  148. package/src/plugins/builtin/econ/types.ts +3 -0
  149. package/src/plugins/builtin/econ-statistics/index.tsx +1 -0
  150. package/src/plugins/builtin/econ-statistics/pane.tsx +6 -0
  151. package/src/plugins/builtin/estimate-revisions/index.tsx +1 -0
  152. package/src/plugins/builtin/executives/index.tsx +1 -0
  153. package/src/plugins/builtin/filing-events/index.tsx +1 -0
  154. package/src/plugins/builtin/fixed-income/index.tsx +3 -0
  155. package/src/plugins/builtin/futures-curve/headless.ts +3 -3
  156. package/src/plugins/builtin/futures-curve/index.tsx +1 -1
  157. package/src/plugins/builtin/futures-curve/model.ts +18 -0
  158. package/src/plugins/builtin/fx-matrix/index.tsx +44 -14
  159. package/src/plugins/builtin/gpu/index.tsx +1 -1
  160. package/src/plugins/builtin/help/functions-table.tsx +1 -1
  161. package/src/plugins/builtin/help/index.tsx +11 -1
  162. package/src/plugins/builtin/help/keybindings-editor.tsx +7 -3
  163. package/src/plugins/builtin/holders/index.tsx +1 -0
  164. package/src/plugins/builtin/holders/report-header.ts +2 -2
  165. package/src/plugins/builtin/insider/index.tsx +1 -0
  166. package/src/plugins/builtin/iv-history/index.tsx +1 -1
  167. package/src/plugins/builtin/jobs/index.tsx +1 -0
  168. package/src/plugins/builtin/macro-day/headless.ts +27 -8
  169. package/src/plugins/builtin/macro-day/index.tsx +1 -1
  170. package/src/plugins/builtin/macro-day/model.ts +19 -3
  171. package/src/plugins/builtin/macro-day/pane.tsx +14 -9
  172. package/src/plugins/builtin/macro-day/releases.ts +25 -7
  173. package/src/plugins/builtin/market-valuation/index.tsx +1 -0
  174. package/src/plugins/builtin/market-valuation/pane.tsx +8 -0
  175. package/src/plugins/builtin/members/index.tsx +1 -1
  176. package/src/plugins/builtin/mna/index.tsx +1 -0
  177. package/src/plugins/builtin/news/index.tsx +1 -0
  178. package/src/plugins/builtin/news/wire/index.tsx +5 -1
  179. package/src/plugins/builtin/news/wire/news/detail-view.tsx +4 -0
  180. package/src/plugins/builtin/news/wire/news/list-search.ts +5 -2
  181. package/src/plugins/builtin/options/index.tsx +1 -0
  182. package/src/plugins/builtin/options-positioning/index.tsx +1 -0
  183. package/src/plugins/builtin/pe-band/index.tsx +1 -1
  184. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +25 -0
  185. package/src/plugins/builtin/portfolio-list/cli/render.ts +20 -3
  186. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +5 -1
  187. package/src/plugins/builtin/portfolio-list/headless.ts +15 -6
  188. package/src/plugins/builtin/power/index.tsx +1 -1
  189. package/src/plugins/builtin/realized-vol/index.tsx +1 -1
  190. package/src/plugins/builtin/research/headless-schema.ts +4 -3
  191. package/src/plugins/builtin/research/headless.ts +10 -4
  192. package/src/plugins/builtin/research/index.tsx +4 -0
  193. package/src/plugins/builtin/research/relative-valuation-columns.ts +145 -47
  194. package/src/plugins/builtin/research/relative-valuation-currency.ts +31 -0
  195. package/src/plugins/builtin/research/relative-valuation-headless.ts +25 -8
  196. package/src/plugins/builtin/research/relative-valuation-model.ts +40 -9
  197. package/src/plugins/builtin/research/relative-valuation-pane.tsx +3 -2
  198. package/src/plugins/builtin/research/relative-valuation-peers.ts +2 -2
  199. package/src/plugins/builtin/research-search/index.tsx +1 -0
  200. package/src/plugins/builtin/research-search/pane.tsx +8 -0
  201. package/src/plugins/builtin/revenue-breakdown/index.tsx +1 -0
  202. package/src/plugins/builtin/reverse-dcf/index.tsx +1 -1
  203. package/src/plugins/builtin/risk-factors/index.tsx +1 -0
  204. package/src/plugins/builtin/scanner/headless.ts +52 -13
  205. package/src/plugins/builtin/seasonality/index.tsx +1 -1
  206. package/src/plugins/builtin/sec/index.tsx +1 -0
  207. package/src/plugins/builtin/series-inventory.ts +1 -1
  208. package/src/plugins/builtin/shared/scanner-capture.ts +11 -3
  209. package/src/plugins/builtin/shared/series-list-detail.tsx +5 -0
  210. package/src/plugins/builtin/short-interest/index.tsx +1 -0
  211. package/src/plugins/builtin/social-mentions/index.tsx +1 -1
  212. package/src/plugins/builtin/supply-chain/index.tsx +1 -0
  213. package/src/plugins/builtin/thirteenf/api.ts +47 -4
  214. package/src/plugins/builtin/thirteenf/data.ts +43 -10
  215. package/src/plugins/builtin/thirteenf/headless.ts +55 -11
  216. package/src/plugins/builtin/thirteenf/model.ts +25 -9
  217. package/src/plugins/builtin/thirteenf/report-notes.ts +27 -6
  218. package/src/plugins/builtin/thirteenf/types.ts +2 -0
  219. package/src/plugins/builtin/ticker-detail/adr-pair/model.ts +1 -1
  220. package/src/plugins/builtin/ticker-detail/data-panes/historical-prices.tsx +8 -7
  221. package/src/plugins/builtin/ticker-detail/data-panes/history-bars.ts +8 -5
  222. package/src/plugins/builtin/ticker-detail/financials/model.ts +18 -2
  223. package/src/plugins/builtin/ticker-detail/financials/ratio-table.tsx +3 -3
  224. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +6 -6
  225. package/src/plugins/builtin/ticker-detail/headless.ts +24 -17
  226. package/src/plugins/builtin/ticker-detail/index.tsx +4 -0
  227. package/src/plugins/builtin/ticker-detail/overview/model.ts +6 -4
  228. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +6 -4
  229. package/src/plugins/builtin/time-sales/client.ts +9 -11
  230. package/src/plugins/builtin/time-sales/index.tsx +1 -1
  231. package/src/plugins/builtin/treasury-auctions/after.ts +267 -0
  232. package/src/plugins/builtin/treasury-auctions/cache.ts +54 -5
  233. package/src/plugins/builtin/treasury-auctions/client.ts +33 -2
  234. package/src/plugins/builtin/treasury-auctions/headless.ts +150 -22
  235. package/src/plugins/builtin/treasury-auctions/hk-headless.ts +126 -0
  236. package/src/plugins/builtin/treasury-auctions/hk-view.tsx +347 -0
  237. package/src/plugins/builtin/treasury-auctions/hk.ts +363 -0
  238. package/src/plugins/builtin/treasury-auctions/index.tsx +27 -4
  239. package/src/plugins/builtin/treasury-auctions/model.ts +264 -28
  240. package/src/plugins/builtin/treasury-auctions/pane.tsx +176 -41
  241. package/src/plugins/builtin/treasury-auctions/treasury-direct.ts +5 -2
  242. package/src/plugins/builtin/treasury-auctions/types.ts +7 -1
  243. package/src/plugins/builtin/vol-surface/index.tsx +1 -1
  244. package/src/plugins/builtin/world-venue-map/index.ts +1 -0
  245. package/src/plugins/builtin/yield-curve/curves.ts +10 -4
  246. package/src/plugins/builtin/yield-curve/headless.ts +6 -2
  247. package/src/plugins/builtin/yield-curve/index.tsx +3 -3
  248. package/src/plugins/builtin/yield-curve/series.ts +10 -0
  249. package/src/plugins/builtin/yield-curve/world.ts +3 -1
  250. package/src/portfolio/collection-name.ts +22 -0
  251. package/src/portfolio/column-values.ts +2 -1
  252. package/src/public/__snapshots__/public-api.test.ts.snap +4 -0
  253. package/src/public/remote.ts +7 -1
  254. package/src/remote/client.ts +191 -11
  255. package/src/remote/controller-utils.ts +13 -1
  256. package/src/remote/controller.ts +88 -26
  257. package/src/remote/endpoint.ts +24 -0
  258. package/src/remote/form.ts +59 -4
  259. package/src/remote/resources.ts +44 -18
  260. package/src/remote/schema.ts +21 -9
  261. package/src/remote/secrets.ts +12 -0
  262. package/src/remote/semantic-tree.tsx +14 -2
  263. package/src/remote/server.ts +2 -1
  264. package/src/remote/surface.tsx +192 -0
  265. package/src/remote/types.ts +5 -0
  266. package/src/renderers/dom/data-table/frozen-column.ts +3 -1
  267. package/src/renderers/dom/data-table/index.tsx +27 -9
  268. package/src/renderers/dom/data-table/row.tsx +2 -0
  269. package/src/renderers/electrobun/bun/desktop/backend.ts +27 -24
  270. package/src/renderers/electrobun/bun/desktop/detached-windows.ts +3 -3
  271. package/src/renderers/electrobun/bun/desktop/snapshot-commit.ts +77 -0
  272. package/src/renderers/electrobun/shared/protocol.ts +4 -0
  273. package/src/renderers/electrobun/view/backend-rpc.ts +3 -0
  274. package/src/renderers/electrobun/view/desktop/window/bridge.ts +3 -0
  275. package/src/renderers/opentui/host.tsx +6 -0
  276. package/src/series/standalone.ts +2 -2
  277. package/src/shares/api.ts +21 -4
  278. package/src/shares/item.ts +73 -0
  279. package/src/shares/pane-item.ts +205 -0
  280. package/src/shares/pane.ts +4 -0
  281. package/src/shares/payload.ts +9 -5
  282. package/src/sources/gloomberb-cloud/news.ts +2 -0
  283. package/src/sources/gloomberb-cloud/normalizers.ts +9 -5
  284. package/src/sources/provider-router/cache.ts +3 -1
  285. package/src/sync/controller.ts +17 -2
  286. package/src/sync/other-window-tabs.ts +32 -1
  287. package/src/sync/react.ts +4 -4
  288. package/src/tickers/renamed-listings.ts +105 -0
  289. package/src/tickers/search/index.ts +103 -16
  290. package/src/time-series/bar-spacing.ts +33 -0
  291. package/src/time-series/base-series.ts +21 -3
  292. package/src/time-series/chart-bounds.ts +31 -0
  293. package/src/time-series/field-catalog.ts +17 -0
  294. package/src/time-series/fundamentals.ts +143 -11
  295. package/src/time-series/ice-credit.ts +32 -6
  296. package/src/time-series/resolve.ts +11 -7
  297. package/src/time-series/session-bar.ts +78 -9
  298. package/src/time-series/studies/formula.ts +53 -10
  299. package/src/time-series/studies/pair.ts +18 -7
  300. package/src/time-series/studies/units.ts +49 -2
  301. package/src/time-series/types.ts +12 -0
  302. package/src/types/desktop-window.ts +2 -0
  303. package/src/types/financials.ts +7 -0
  304. package/src/types/headless.ts +8 -0
  305. package/src/types/plugin-pane-settings.ts +2 -0
  306. package/src/types/plugin-panes.ts +22 -0
  307. package/src/utils/central-banks.ts +86 -1
  308. package/src/utils/cli-output.ts +6 -3
  309. package/src/utils/datetime-format.ts +12 -3
  310. package/src/utils/depositary-receipt.ts +28 -3
  311. package/src/utils/ebitda.ts +128 -0
  312. package/src/utils/format.ts +1 -1
  313. package/src/utils/fundamentals.ts +14 -0
  314. package/src/utils/max-drawdown.ts +97 -16
  315. package/src/utils/shell-word.ts +13 -0
  316. package/src/utils/untrusted-text.ts +29 -0
@@ -4,6 +4,7 @@ import {
4
4
  } from "./portable-layout";
5
5
  import { safeExternalUrl } from "../utils/external-url";
6
6
  import { isRecord } from "../utils/guards";
7
+ import { parseShareItem, type ShareItem } from "./item";
7
8
 
8
9
  const MAX_SHARE_BYTES = 128 * 1024;
9
10
  const MAX_TITLE_LENGTH = 200;
@@ -69,7 +70,8 @@ export type SharePayload =
69
70
  | { kind: "table"; data: TableShareData }
70
71
  | { kind: "chart"; data: ChartShareData }
71
72
  | { kind: "article"; data: ArticleShareData }
72
- | { kind: "pane"; data: PaneShareData };
73
+ /** `item` sits beside `data`, which apps before it read strictly and would refuse with it inside. */
74
+ | { kind: "pane"; data: PaneShareData; item?: ShareItem };
73
75
 
74
76
  function shortString(value: unknown, max = MAX_TITLE_LENGTH): value is string {
75
77
  return typeof value === "string" && value.length > 0 && value.length <= max;
@@ -195,12 +197,14 @@ export function parseSharePayload(value: unknown): SharePayload | null {
195
197
  let json: string;
196
198
  try { json = JSON.stringify(value); } catch { /* Intentional ignore: Circular or unserializable input is not a valid share payload. */ return null; }
197
199
  if (new TextEncoder().encode(json).byteLength > MAX_SHARE_BYTES) return null;
198
- if (value.kind === "table" && isTableData(value.data)) return value as unknown as SharePayload;
199
- if (value.kind === "chart" && isChartData(value.data)) return value as unknown as SharePayload;
200
- if (value.kind === "article" && isArticleData(value.data)) return value as unknown as SharePayload;
200
+ if (value.kind === "table" && isTableData(value.data)) return { kind: "table", data: value.data };
201
+ if (value.kind === "chart" && isChartData(value.data)) return { kind: "chart", data: value.data };
202
+ if (value.kind === "article" && isArticleData(value.data)) return { kind: "article", data: value.data };
201
203
  if (value.kind === "pane") {
202
204
  const data = parsePaneData(value.data);
203
- if (data) return { kind: "pane", data };
205
+ // An item this app cannot read leaves the pane as it was shared, without one.
206
+ const item = parseShareItem(value.item);
207
+ if (data) return { kind: "pane", data, ...(item ? { item } : {}) };
204
208
  }
205
209
  return null;
206
210
  }
@@ -199,6 +199,8 @@ type CloudNewsClient = Pick<typeof apiClient, "getCloudNews" | "searchCloudNews"
199
199
 
200
200
  /** The NI code of the metal markets: prices, futures, bullion and the trusts that hold it, not a miner's releases. */
201
201
  export const METALS_NEWS_TOPIC = "metals";
202
+ /** The topic the service tags oil, gas and power market stories with. */
203
+ export const ENERGY_NEWS_TOPIC = "energy";
202
204
 
203
205
  /**
204
206
  * What a ticker no story is filed under is searched by: a coin pair's coin
@@ -29,6 +29,7 @@ import { parseOptionTicker } from "../../utils/options";
29
29
  import { reconcileQuoteDayRange } from "../../market-data/quotes/day-range";
30
30
  import { redactUnavailableFundamentals } from "../../utils/fundamentals";
31
31
  import { readWithdrawnObservations } from "../../utils/statement-gaps";
32
+ import { isBankOrInsurerIndustry, withStatementEbitda } from "../../utils/ebitda";
32
33
  import { parseListingDelisting } from "../../market-data/quotes/delisting";
33
34
  import { readIntradayBar, readStaleReason } from "../../market-data/quotes/intraday-bar";
34
35
  import { readSessionSplit } from "../../market-data/quotes/session-split";
@@ -313,11 +314,13 @@ function mapCloudNextEarnings(value: NextEarnings | undefined): NextEarnings | u
313
314
 
314
315
  /**
315
316
  * A served statement row with withdrawn values read as declared gaps, without
316
- * the per-issuer provenance the service can still attach.
317
+ * the per-issuer provenance the service can still attach, and its EBITDA
318
+ * operating income plus D&A whatever the service sent: derived where the row
319
+ * reports no operating income, except for a bank or an insurer (`derive`).
317
320
  */
318
- function mapCloudStatement(row: FinancialStatement): FinancialStatement {
321
+ function mapCloudStatement(row: FinancialStatement, derive: boolean): FinancialStatement {
319
322
  const { earningsResult: _earnings, operatingResult: _operating, operatingResultAggregation: _aggregation, ...statement } = row;
320
- return readWithdrawnObservations(statement);
323
+ return withStatementEbitda(readWithdrawnObservations(statement), derive);
321
324
  }
322
325
 
323
326
  export function mapCloudFinancials(
@@ -329,6 +332,7 @@ export function mapCloudFinancials(
329
332
  const divisor = rawQuote ? resolveCurrencyUnit(rawQuote.currency).divisor : 1;
330
333
  const exchange = rawQuote?.listingExchangeName ?? rawQuote?.exchangeName ?? "";
331
334
  const coin = isRoundTheClockCoin(rawQuote?.symbol, exchange);
335
+ const derive = !isBankOrInsurerIndustry(financials.profile?.industry);
332
336
  return {
333
337
  quote,
334
338
  quoteMetadata: financials.quoteMetadata,
@@ -338,8 +342,8 @@ export function mapCloudFinancials(
338
342
  fundamentals: mapCloudFundamentals(financials.fundamentals),
339
343
  financialCurrency: financials.financialCurrency,
340
344
  statementHistory: financials.statementHistory,
341
- annualStatements: (financials.annualStatements ?? []).map(mapCloudStatement),
342
- quarterlyStatements: (financials.quarterlyStatements ?? []).map(mapCloudStatement),
345
+ annualStatements: (financials.annualStatements ?? []).map((row) => mapCloudStatement(row, derive)),
346
+ quarterlyStatements: (financials.quarterlyStatements ?? []).map((row) => mapCloudStatement(row, derive)),
343
347
  priceHistory: (financials.priceHistory ?? []).map((point) =>
344
348
  point.date instanceof Date
345
349
  ? point
@@ -13,7 +13,9 @@ const MARKET_NAMESPACE = "market";
13
13
  const HOT_READ_TOUCH_MS = 10 * 60_000;
14
14
  // A record written under another version is a miss: bump these instead of
15
15
  // repairing older records on read.
16
- export const FINANCIALS_SCHEMA_VERSION = 13;
16
+ // 14: EBITDA is operating income plus D&A (utils/ebitda.ts), whatever an older record holds.
17
+ // 15: a row without operating income derives it for EBITDA (utils/ebitda.ts), a bank's or an insurer's excepted.
18
+ export const FINANCIALS_SCHEMA_VERSION = 15;
17
19
  export const QUOTE_SCHEMA_VERSION = 3;
18
20
  export const MARKET_METADATA_SCHEMA_VERSION = 2;
19
21
  // Refresh persisted provider metadata through the managed backend on upgrade.
@@ -52,6 +52,7 @@ const OBSERVE_DEBOUNCE_MS = 250;
52
52
  const MAX_CONFLICT_RETRIES = 3;
53
53
  const SYNC_HISTORY_UNREADABLE = "This device's sync history could not be read, so sync is paused and local data is kept.";
54
54
  const SYNC_HISTORY_UNSAVED = "This device's sync history could not be saved, so sync is paused until it can be.";
55
+ const SYNC_COLLECT_FAILED = "This device's changes could not be gathered, so they were not synced.";
55
56
 
56
57
  /** Merge history storage refused to write; kept here to write again, and read instead of the older stored copy. */
57
58
  interface UnsavedHistory {
@@ -244,10 +245,15 @@ export class CloudSyncController {
244
245
  if (this.pushTimer) clearTimeout(this.pushTimer);
245
246
  this.pushTimer = setTimeout(() => {
246
247
  this.pushTimer = null;
247
- void this.requestSync({ reason });
248
+ this.startSync({ reason });
248
249
  }, PUSH_DEBOUNCE_MS);
249
250
  }
250
251
 
252
+ /** A sync nobody waits on. Its failures end in the status; anything that escapes is logged. */
253
+ startSync(options: { reason?: string; force?: boolean } = {}): void {
254
+ this.requestSync(options).catch(logFailure("sync.controller", "Sync failed"));
255
+ }
256
+
251
257
  async requestSync(options: { reason?: string; force?: boolean } = {}): Promise<void> {
252
258
  if (this.inFlight) {
253
259
  this.syncQueued = true;
@@ -308,7 +314,16 @@ export class CloudSyncController {
308
314
  const pulled = await this.runPull(runtime, transport, generation, sessionIdentity);
309
315
  if (!pulled || !this.isCurrent(runtime, transport, generation, sessionIdentity)) return;
310
316
 
311
- const snapshot = await this.assembleSnapshot(runtime, generation, sessionIdentity);
317
+ let snapshot: SyncSnapshot | null;
318
+ try {
319
+ snapshot = await this.assembleSnapshot(runtime, generation, sessionIdentity);
320
+ } catch (error) {
321
+ // Nothing is pushed: the pull's "synced" no longer holds for this device's changes.
322
+ logFailure("sync.controller", "Collect sync contributor data failed")(error);
323
+ if (!this.isCurrent(runtime, transport, generation, sessionIdentity)) return;
324
+ this.setStatus({ phase: "error", transportId: transport.id, error: SYNC_COLLECT_FAILED });
325
+ return;
326
+ }
312
327
  if (!snapshot || !this.isCurrent(runtime, transport, generation, sessionIdentity)) return;
313
328
  const signature = snapshotContentSignature(snapshot);
314
329
  if (!options.force && signature === this.lastSignature) return;
@@ -1,6 +1,9 @@
1
- import type { AppState } from "../core/state/app/state";
1
+ import type { Dispatch } from "react";
2
+ import type { AppAction, AppState } from "../core/state/app/state";
3
+ import { saveConfigImmediately } from "../state/config-save-scheduler";
2
4
  import type { AppConfig } from "../types/config";
3
5
  import type { OtherWindowTab } from "../types/desktop-window";
6
+ import { logFailure } from "../utils/log-failure";
4
7
 
5
8
  /**
6
9
  * Cloud sync runs in the desktop app's main window, whose state holds only
@@ -60,3 +63,31 @@ export function withoutOtherWindowTabs(config: AppConfig, others: readonly Other
60
63
  const layout = byActive >= 0 ? config.layout : shown.layout;
61
64
  return { ...config, layouts, activeLayoutIndex, layout };
62
65
  }
66
+
67
+ /**
68
+ * The dispatch a config sync applies through in the main window. A config that
69
+ * changes another window's tab is saved whole at once, and nothing else would
70
+ * write that change: a failed save is logged and `onSaveFailure` tells the
71
+ * person.
72
+ */
73
+ export function createSyncConfigDispatch({ dispatch, otherWindowTabs, currentConfig, onSaveFailure }: {
74
+ dispatch: Dispatch<AppAction>;
75
+ otherWindowTabs: () => readonly OtherWindowTab[];
76
+ currentConfig: () => AppConfig;
77
+ onSaveFailure: () => void;
78
+ }): Dispatch<AppAction> {
79
+ return (action) => {
80
+ if (action.type !== "SET_CONFIG") {
81
+ dispatch(action);
82
+ return;
83
+ }
84
+ const others = otherWindowTabs();
85
+ if (changesOtherWindowTabs(action.config, others)) {
86
+ saveConfigImmediately(action.config).catch((error: unknown) => {
87
+ logFailure("sync.other-window-tabs", "Saving tabs synced to other windows failed")(error);
88
+ onSaveFailure();
89
+ });
90
+ }
91
+ dispatch({ ...action, config: withoutOtherWindowTabs(action.config, others, currentConfig()) });
92
+ };
93
+ }
package/src/sync/react.ts CHANGED
@@ -54,14 +54,14 @@ export function useCloudSyncRuntime({
54
54
 
55
55
  useEffect(() => {
56
56
  if (!initialized) return;
57
- void cloudSyncController.requestSync({ reason: "startup" });
57
+ cloudSyncController.startSync({ reason: "startup" });
58
58
  }, [initialized, pluginRegistry]);
59
59
 
60
60
  useEffect(() => {
61
61
  if (!initialized || !appActive) return;
62
- void cloudSyncController.requestSync({ reason: "foreground" });
62
+ cloudSyncController.startSync({ reason: "foreground" });
63
63
  const timer = setInterval(() => {
64
- void cloudSyncController.requestSync({ reason: "poll" });
64
+ cloudSyncController.startSync({ reason: "poll" });
65
65
  }, CLOUD_SYNC_POLL_MS);
66
66
  return () => clearInterval(timer);
67
67
  }, [appActive, initialized]);
@@ -70,7 +70,7 @@ export function useCloudSyncRuntime({
70
70
  if (!initialized) return;
71
71
  // Email verification makes the Cloud transport available. Force the first
72
72
  // sync so a workspace completed before verification is uploaded promptly.
73
- void cloudSyncController.requestSync({ reason: "session-verified", force: true });
73
+ cloudSyncController.startSync({ reason: "session-verified", force: true });
74
74
  }, (accountId) => cloudSyncController.resetAccount(accountId),
75
75
  () => cloudSyncController.retireSession()), [initialized]);
76
76
 
@@ -0,0 +1,105 @@
1
+ import { normalizeSearchText } from "./search/ranking";
2
+
3
+ /**
4
+ * A listing abroad whose company renamed itself and moved to a new symbol:
5
+ * the change history the data service keeps is of US listings, so `quote
6
+ * ELET3.SA` found nothing and its hint searched for the dead symbol again.
7
+ */
8
+ export interface RenamedListing {
9
+ /** The symbol it left, as the venue writes it. */
10
+ from: string;
11
+ /** The symbol it trades as now. */
12
+ to: string;
13
+ /** The venue's symbol suffix, as `quote` takes it (`.SA`). */
14
+ suffix: string;
15
+ exchange: string;
16
+ /** Its name now. */
17
+ name: string;
18
+ /** The names people still search for, the one it went by first: its brand, then its legal name. */
19
+ formerNames: readonly [string, ...string[]];
20
+ /** The day a class that no longer trades was converted into the `to` line (YYYY-MM-DD). */
21
+ convertedOn?: string;
22
+ }
23
+
24
+ /** The name it went by: "Eletrobras". */
25
+ function renamedListingFormerName(listing: RenamedListing): string {
26
+ return listing.formerNames[0];
27
+ }
28
+
29
+ /**
30
+ * Checked in, each from the issuer's own notice. Eletrobras (Centrais
31
+ * Elétricas Brasileiras S.A.) renamed itself AXIA Energia in November 2025,
32
+ * and each of its B3 lines took the new code: ELET3 AXIA3, the class B
33
+ * preferred ELET6 AXIA6, the class A preferred ELET5 AXIA5. On 5 Jun 2026,
34
+ * moving to the Novo Mercado, AXIA converted both preferred classes into its
35
+ * common shares, which trade as AXIA3 (AXIA's release of 9 Jun 2026), so
36
+ * the preferred codes, old and new, lead there. Its ADSs' change (EBR to
37
+ * AXIA) is in the US history already. A name leads to the common shares,
38
+ * listed first.
39
+ */
40
+ const ELETROBRAS = ["Eletrobras", "Centrais Elétricas Brasileiras"] as const;
41
+ const AXIA_PREFERRED_CONVERTED = "2026-06-05";
42
+ const RENAMED_LISTINGS: readonly RenamedListing[] = [
43
+ { from: "ELET3", to: "AXIA3", suffix: ".SA", exchange: "B3", name: "AXIA Energia", formerNames: ELETROBRAS },
44
+ ...["ELET6", "AXIA6", "ELET5", "AXIA5"].map((from): RenamedListing => ({ from, to: "AXIA3", suffix: ".SA", exchange: "B3",
45
+ name: "AXIA Energia", formerNames: ELETROBRAS, convertedOn: AXIA_PREFERRED_CONVERTED })),
46
+ ];
47
+
48
+ /** "5 Jun 2026". */
49
+ function conversionDay(date: string): string {
50
+ return new Date(`${date}T00:00:00Z`).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric", timeZone: "UTC" });
51
+ }
52
+
53
+ /** `AXIA3.SA`: the new listing as `quote` takes it. */
54
+ export function renamedListingSymbol(listing: RenamedListing): string {
55
+ return `${listing.to}${listing.suffix}`;
56
+ }
57
+
58
+ /**
59
+ * The renamed listing a symbol (`ELET3`, `ELET3.SA`, `ELET3:B3`) or a name
60
+ * (`eletrobras`) means, else null.
61
+ */
62
+ export function renamedListingFor(query: string): RenamedListing | null {
63
+ const typed = query.trim().toUpperCase();
64
+ if (!typed) return null;
65
+ const bySymbol = RENAMED_LISTINGS.find((listing) =>
66
+ typed === listing.from || typed === `${listing.from}${listing.suffix}` || typed === `${listing.from}:${listing.exchange}`);
67
+ if (bySymbol) return bySymbol;
68
+ const words = normalizeSearchText(query);
69
+ return words ? RENAMED_LISTINGS.find((listing) => listing.formerNames.some((name) => normalizeSearchText(name) === words)) ?? null : null;
70
+ }
71
+
72
+ /**
73
+ * "It is now AXIA3.SA (AXIA Energia, formerly Eletrobras): `gloom quote
74
+ * AXIA3.SA`.", after the line naming the old symbol; for a converted class,
75
+ * "It was converted into AXIA3.SA on 5 Jun 2026 ...".
76
+ */
77
+ export function renamedListingHint(listing: RenamedListing): string {
78
+ const now = renamedListingSymbol(listing);
79
+ const named = `${now} (${listing.name}, formerly ${renamedListingFormerName(listing)})`;
80
+ return listing.convertedOn
81
+ ? `It was converted into ${named} on ${conversionDay(listing.convertedOn)}: \`gloom quote ${now}\`.`
82
+ : `It is now ${named}: \`gloom quote ${now}\`.`;
83
+ }
84
+
85
+ /** What search says the new line was: "Eletrobras (ELET3)", or "Eletrobras (ELET6, converted 5 Jun 2026)". */
86
+ export function renamedListingFormerLine(listing: RenamedListing): string {
87
+ const converted = listing.convertedOn ? `, converted ${conversionDay(listing.convertedOn)}` : "";
88
+ return `${renamedListingFormerName(listing)} (${listing.from}${converted})`;
89
+ }
90
+
91
+ /**
92
+ * "Read ELET3.SA as AXIA3.SA: Eletrobras is AXIA Energia now.", or "Read
93
+ * "eletrobras" as ..." for its name; for a converted class, "Read ELET6 as
94
+ * AXIA3.SA: those preferred shares were converted into AXIA Energia's common
95
+ * shares on 5 Jun 2026."
96
+ */
97
+ export function renamedListingReadAs(typed: string, listing: RenamedListing): string {
98
+ const word = typed.trim();
99
+ // A name is quoted, as every name read as a listing is; the CLI puts it back in the user's spelling.
100
+ const shown = listing.formerNames.some((name) => normalizeSearchText(word) === normalizeSearchText(name)) ? `"${word}"` : word;
101
+ const now = renamedListingSymbol(listing);
102
+ return listing.convertedOn
103
+ ? `Read ${shown} as ${now}: those preferred shares were converted into ${listing.name}'s common shares on ${conversionDay(listing.convertedOn)}.`
104
+ : `Read ${shown} as ${now}: ${renamedListingFormerName(listing)} is ${listing.name} now.`;
105
+ }
@@ -35,6 +35,7 @@ import {
35
35
  } from "./result";
36
36
 
37
37
  import { typedPerpetualListing } from "../perpetual-listing";
38
+ import { renamedListingFor, renamedListingFormerLine, type RenamedListing } from "../renamed-listings";
38
39
  import { endsInLegalForm, readNearMissListing, readVenueFirstListing, readTerminalListingCode } from "../terminal-codes";
39
40
  import { isProviderBusy, ProviderBusyError, SEARCH_BUSY_MESSAGE } from "../../sources/provider-errors";
40
41
  import { settleWithin } from "../../utils/async-deadline";
@@ -268,13 +269,19 @@ export async function searchTickerCandidates({
268
269
  // A search that hides contracts still shows them when asked: "AAPL OPT".
269
270
  includeOptionContracts: includeOptionContracts || parseAssetClassQuery(query)?.code === "OPT",
270
271
  });
271
- const { results, busy, unreachable } = await searchProviderResults(
272
- dataProvider,
273
- query,
274
- searchContext,
275
- onPartial ? (found) => onPartial(assemble(found)) : undefined,
276
- true,
277
- );
272
+ const renamed = renamedListingFor(rawQuery);
273
+ const [searched, renamedRow] = await Promise.all([
274
+ searchProviderResults(
275
+ dataProvider,
276
+ query,
277
+ searchContext,
278
+ onPartial ? (found) => onPartial(assemble(found)) : undefined,
279
+ true,
280
+ ),
281
+ renamed ? renamedListingRow(dataProvider, renamed, searchContext) : null,
282
+ ]);
283
+ const { busy, unreachable } = searched;
284
+ const results = renamedRow ? withRenamedListingRow(searched.results, renamedRow) : searched.results;
278
285
  // The symbol's lines are named at once the next time it is typed. An answer that may have
279
286
  // been cut short and found none of the lines leaves the ones search named before standing,
280
287
  // as the bar showed them, unless the search was a broker account's own.
@@ -319,7 +326,36 @@ export function buildTickerSearchCandidates({
319
326
  );
320
327
  const providerItems = createProviderTickerSearchCandidates(filteredProviderResults, tickers, candidateOptions);
321
328
  const ranked = withHomeListingLead(withSuccessorFirst(rankTickerSearchItems([...localItems, ...providerItems], query), query), query);
322
- return limitTickerSearchCandidates(assignTickerSearchCategories(ranked, query), totalLimit, localLimit);
329
+ return limitTickerSearchCandidates(companyListingsFirst(assignTickerSearchCategories(ranked, query), query), totalLimit, localLimit);
330
+ }
331
+
332
+ /**
333
+ * The row of the listing a renamed one moved to (AXIA3 for ELET3 or
334
+ * "eletrobras"), as search lists it under its new symbol, carrying the old
335
+ * name and symbol so it answers to them and says what it was. Null when
336
+ * search does not list it.
337
+ */
338
+ async function renamedListingRow(
339
+ dataProvider: DataProvider,
340
+ renamed: RenamedListing,
341
+ searchContext?: SearchRequestContext,
342
+ ): Promise<InstrumentSearchResult | null> {
343
+ const found = await searchProviderResults(dataProvider, renamed.to, searchContext)
344
+ .catch(logFailure("tickers.search", "Search for a renamed listing's new symbol failed", null));
345
+ const row = found?.results.find((result) => result.symbol.toUpperCase() === renamed.to
346
+ && canonicalExchange(result.exchange) === canonicalExchange(renamed.exchange));
347
+ return row ? {
348
+ ...row,
349
+ searchAliases: [...new Set([...(row.searchAliases ?? []), ...renamed.formerNames, renamed.from, `${renamed.from}${renamed.suffix}`])],
350
+ formerName: renamedListingFormerLine(renamed),
351
+ } : null;
352
+ }
353
+
354
+ /** Search's rows with the renamed listing's row first, in place of the row it already had of it and of its old symbol on the venue. */
355
+ function withRenamedListingRow(results: InstrumentSearchResult[], row: InstrumentSearchResult): InstrumentSearchResult[] {
356
+ const venue = canonicalExchange(row.exchange);
357
+ return [row, ...results.filter((result) => canonicalExchange(result.exchange) !== venue
358
+ || (result.symbol.toUpperCase() !== row.symbol.toUpperCase() && !row.searchAliases?.includes(result.symbol.toUpperCase())))];
323
359
  }
324
360
 
325
361
  /** Whether a query is the start of a merged company's name, as the service matched it ("Golden Ocean"). */
@@ -386,22 +422,47 @@ export function symbolSearchQuery(query: string): string {
386
422
  return trimmed.slice(0, -1).toUpperCase();
387
423
  }
388
424
 
389
- export function resolveTickerSearch(options: ResolveTickerSearchOptions): Promise<ResolvedTickerSearch | null> {
390
- const requested = normalizeTickerInput(options.activeTicker, options.query);
391
- if (!requested) return Promise.resolve(null);
425
+ /** The symbol `resolveTickerSearch` looks a normalized query up as first, and the spellings it reads it in. */
426
+ function lookupSpelling(requested: string, tickers: ReadonlyMap<string, TickerRecord>) {
392
427
  // `NET:` lists NET's venues instead of settling on one.
393
428
  const pickListing = isListingPickerQuery(requested);
394
429
  const typed = symbolSearchQuery(requested);
395
430
  // A futures board code no security uses is its future (TTF is TTF=F), unless a saved ticker holds it.
396
- const future = pickListing || options.tickers.has(typed) ? null : bareFuturesCode(typed);
431
+ const future = pickListing || tickers.has(typed) ? null : bareFuturesCode(typed);
397
432
  // A currency pair is the one listing the service has for it, however it is written: EUR/USD and
398
433
  // JPY=X are EURUSD=X and USDJPY=X. USD-NGN and USDNGN, which a security could also be written as
399
434
  // (MNT-USD is a coin), are the pair only when nothing is listed under those letters.
400
435
  const pair = pickListing || future ? null : currencyPairSpelling(typed);
401
436
  // A coin pair written as crypto exchanges write it (BTC/GBP, or BTC/GBP:KRAKEN) is the crypto venue's BTC-GBP,
402
437
  // and what was typed when the venue has no such coin.
403
- const coin = pickListing || future || pair || options.tickers.has(typed) ? null : typedCoinPairListing(typed);
438
+ const coin = pickListing || future || pair || tickers.has(typed) ? null : typedCoinPairListing(typed);
404
439
  const symbol = future?.symbol ?? coin?.symbol ?? (pair && !pair.ambiguous ? pair.symbol : typed);
440
+ return { pickListing, typed, pair, coin, symbol };
441
+ }
442
+
443
+ /** The saved ticker a symbol names, as written or as a saved listing reads it. */
444
+ function savedTickerFor(symbol: string, tickers: ReadonlyMap<string, TickerRecord>): TickerRecord | null {
445
+ return tickers.get(symbol)
446
+ ?? findExactTickerSearchMatch(createLocalTickerSearchCandidates(tickers.values()), symbol)?.ticker
447
+ ?? null;
448
+ }
449
+
450
+ /**
451
+ * The saved ticker a query names as `resolveTickerSearch` reads it, with no
452
+ * source asked: `JPM US Equity` is JPM, `BRK/B` BRK-B, `TTF` its future TTF=F.
453
+ * Null when none is saved, or for `NET:`, which asks for a choice of listings.
454
+ */
455
+ export function savedTickerForQuery(query: string, tickers: ReadonlyMap<string, TickerRecord>): TickerRecord | null {
456
+ const requested = normalizeTickerInput(null, query);
457
+ if (!requested) return null;
458
+ const { pickListing, symbol } = lookupSpelling(requested, tickers);
459
+ return pickListing ? null : savedTickerFor(symbol, tickers);
460
+ }
461
+
462
+ export function resolveTickerSearch(options: ResolveTickerSearchOptions): Promise<ResolvedTickerSearch | null> {
463
+ const requested = normalizeTickerInput(options.activeTicker, options.query);
464
+ if (!requested) return Promise.resolve(null);
465
+ const { pickListing, typed, pair, coin, symbol } = lookupSpelling(requested, options.tickers);
405
466
  const literal = resolveTickerSymbol(symbol, options, pickListing ? requested : null);
406
467
  const alternatives = pickListing ? [] : [...dottedVenueQueries(symbol), ...pair?.ambiguous ? [pair.symbol] : [], ...coin ? [typed] : []];
407
468
  // A listing suffix search does not carry (CEZ.PR) is read from its own quote, as `quote` reads it.
@@ -473,9 +534,7 @@ async function resolveTickerSymbol(
473
534
  /** The `NET:` text that asked for every venue, or null to settle on one. */
474
535
  pickerQuery: string | null,
475
536
  ): Promise<ResolvedTickerSearch | null> {
476
- const local = tickers.get(symbol)
477
- ?? findExactTickerSearchMatch(createLocalTickerSearchCandidates(tickers.values()), symbol)?.ticker
478
- ?? null;
537
+ const local = savedTickerFor(symbol, tickers);
479
538
  if (local) {
480
539
  const contracts = new Map((local.metadata.broker_contracts ?? []).flatMap((brokerContract) => {
481
540
  const key = searchContractKey({ brokerContract, type: local.metadata.assetCategory || "" });
@@ -925,6 +984,34 @@ function assignTickerSearchCategories<T extends TickerSearchCandidate>(items: T[
925
984
  }) as T[];
926
985
  }
927
986
 
987
+ /**
988
+ * A query that names a company lists the company's listings before the
989
+ * mutual funds that carry its name: "banorte" is GFNORTEO (Grupo Financiero
990
+ * Banorte) and its other lines first, then the four Banorte Siefore pension
991
+ * funds search ranked above it. Only when the primary listing's name holds
992
+ * every word of the query and every fund ranked above it is a mutual fund: a
993
+ * future or an ETF the query names keeps its lead (GC=F for "gold", LIT for
994
+ * "lithium", Fidelity's ETFs for "fidelity"). Only the primary listing and
995
+ * the lines under its own name move: another company's listing keeps its
996
+ * place behind the funds.
997
+ */
998
+ function companyListingsFirst<T extends TickerSearchCandidate>(items: T[], query: string): T[] {
999
+ const primary = items.findIndex((item) => item.category === "Primary Listing");
1000
+ const firstFund = items.findIndex((item) => item.category === "Funds & Derivatives");
1001
+ if (primary < 0 || firstFund < 0 || firstFund > primary) return items;
1002
+ const ahead = items.slice(0, primary).filter((item) => item.category === "Funds & Derivatives");
1003
+ if (!ahead.every((item) => /mutual\s*fund/i.test(item.instrumentType ?? item.result?.type ?? ""))) return items;
1004
+ const wanted = normalizeSearchText(query).split(" ").filter(Boolean);
1005
+ const lead = items[primary]!;
1006
+ const leadName = normalizeSearchText(lead.result?.name ?? lead.ticker?.metadata.name ?? lead.detail ?? "");
1007
+ if (!wanted.length || !wanted.every((word) => ` ${leadName} `.includes(` ${word} `))) return items;
1008
+ const listings = items.filter((item) => item === lead || (item.category === "Other Listings"
1009
+ && normalizeSearchText(item.result?.name ?? item.ticker?.metadata.name ?? item.detail ?? "") === leadName));
1010
+ const before = items.slice(0, firstFund).filter((item) => !listings.includes(item));
1011
+ const rest = items.slice(firstFund).filter((item) => !listings.includes(item));
1012
+ return [...before, ...listings, ...rest];
1013
+ }
1014
+
928
1015
  function limitTickerSearchCandidates<T extends TickerSearchCandidate>(
929
1016
  items: T[],
930
1017
  totalLimit: number,
@@ -17,3 +17,36 @@ export function barSizeFromGap(gapMs: number): "1d" | "1wk" | "1mo" {
17
17
  const days = gapMs / DAY_MS;
18
18
  return days >= 25 ? "1mo" : days >= 6 ? "1wk" : "1d";
19
19
  }
20
+
21
+ const BAR_SIZE_ORDER = { "1d": 0, "1wk": 1, "1mo": 2 } as const;
22
+
23
+ /** Whether bars are each the start of a week, all on one weekday, or of a month, in its first week. */
24
+ function startPeriods(times: readonly number[], size: "1wk" | "1mo"): boolean {
25
+ const dates = times.filter(Number.isFinite).map((time) => new Date(time));
26
+ return size === "1wk" ? new Set(dates.map((date) => date.getUTCDay())).size === 1 : dates.every((date) => date.getUTCDate() <= 7);
27
+ }
28
+
29
+ /** Fewer bars than this cannot say they are coarser than asked: three Mondays of a thin listing are no weekly bars. */
30
+ const MIN_COARSER_BARS = 4;
31
+
32
+ type DailyOrLonger = "1d" | "1wk" | "1mo";
33
+
34
+ /**
35
+ * The size of bars asked for as `requested`: the request, not the spacing,
36
+ * unless the source stated the size it served (`stated`). A thinly traded
37
+ * listing's daily bars sit a week or two apart (B95 on SGX traded on 13 Oct,
38
+ * 22 Oct and 6 Nov), which the spacing reads as weekly. Bars the source
39
+ * served finer than asked show it in their spacing; coarser ones only when
40
+ * there are at least four and each starts its period, as weekly and monthly
41
+ * bars do.
42
+ */
43
+ export function requestedBarSize(times: readonly number[], requested: DailyOrLonger, stated?: string | null): DailyOrLonger {
44
+ if (stated === "1d" || stated === "1wk" || stated === "1mo") return stated;
45
+ const gap = medianBarGap(times);
46
+ if (gap == null) return requested;
47
+ const read = barSizeFromGap(gap);
48
+ if (BAR_SIZE_ORDER[read] < BAR_SIZE_ORDER[requested]) return read;
49
+ const bars = new Set(times.filter(Number.isFinite)).size;
50
+ return BAR_SIZE_ORDER[read] > BAR_SIZE_ORDER[requested] && bars >= MIN_COARSER_BARS && startPeriods(times, read as "1wk" | "1mo")
51
+ ? read : requested;
52
+ }
@@ -7,9 +7,12 @@ import { CHART_RESOLUTION_STEP_MS, type ManualChartResolution } from "./resoluti
7
7
  import type { Quote, QuoteMetadata, TickerFinancials } from "../types/financials";
8
8
  import type { FredSeriesLoadResult } from "../sources/gloomberb-cloud/fred-series";
9
9
  import { extractFredSeries } from "./economic";
10
+ import { isIceSpreadSeries } from "./ice-credit";
11
+ import { BASIS_POINT_UNIT, BP_PER_PERCENT } from "./studies/units";
10
12
  import { getTimeSeriesField, isMarketFieldId } from "./field-catalog";
11
13
  import {
12
14
  unreportedStatementPeriod,
15
+ valuationNotMeaningful,
13
16
  dailyValuationFallbackPeriod,
14
17
  valuationCurrencyWarning,
15
18
  valuationPriceIssues,
@@ -122,6 +125,7 @@ export function baseSecuritySeries(
122
125
  const points = extractSecuritySeries(financials, spec.source);
123
126
  const valuationFallback = dailyValuationFallbackPeriod(financials, spec.source);
124
127
  const unreportedPeriod = points.length === 0 ? unreportedStatementPeriod(financials, spec.source) : null;
128
+ const notMeaningful = valuationNotMeaningful(financials, spec.source);
125
129
  const symbol = instrumentLabel(spec.source);
126
130
  const statementCurrency = field.id.startsWith("fundamental.") && field.unit.startsWith("currency")
127
131
  ? reportingCurrencySeries(points, financials.financialCurrency) : null;
@@ -220,11 +224,13 @@ export function baseSecuritySeries(
220
224
  ...(volumeBasis ? { volumeBasis } : {}),
221
225
  ...(priceIssues.length ? { valuationPriceIssues: priceIssues } : {}),
222
226
  warning: [valuationFallback ? "Release dates unavailable; showing reported periods." : undefined,
227
+ notMeaningful ? `N/M: ${notMeaningful.reason} (period to ${notMeaningful.asOf}).` : undefined,
223
228
  field.id === "market.volume" && !volumeUnit && !volumeBasis && points.some((point) => Number.isFinite(point.value) && point.value !== 0)
224
229
  ? "Volume unit unknown." : statementCurrency?.warning ?? valuationCurrencyWarning(financials, spec.source)].filter(Boolean).join(" ") || undefined,
225
230
  nativeFrequency: marketField ? marketSeriesFrequency(spec.source, marketResolution)
226
231
  : valuationFallback ?? (spec.source.period && spec.source.period !== "auto" ? spec.source.period : field.nativeFrequency),
227
232
  ...(unreportedPeriod ? { unreportedPeriod } : {}),
233
+ ...(notMeaningful ? { notMeaningful } : {}),
228
234
  ...(marketField ? { historyResolution: marketResolution } : {}),
229
235
  timestampMode: spec.source.timestampMode,
230
236
  dataShape: field.dataShape,
@@ -278,12 +284,18 @@ export function baseEconomicSeries(
278
284
  const catalogUnit = fredCatalogUnit(units);
279
285
  // "Percent Change from Year Ago" and "Percent per Annum" are percent too.
280
286
  const isPercent = units.toLowerCase().includes("percent");
287
+ // An ICE option-adjusted spread reads in bp, as CRD and `fred` print it and CDX quotes, not FRED's percentage points.
288
+ const basisPoints = isPercent && /^percent$/i.test(units) && isIceSpreadSeries(spec.source.seriesId);
289
+ const points = extractFredSeries(data.observations, { providerId: "fred", timestampMode: "period-end" });
281
290
  return {
282
291
  id: spec.id,
283
292
  label: spec.label?.trim() || data.info?.title?.trim() || spec.source.seriesId,
293
+ expression: `FRED:${spec.source.seriesId}`,
284
294
  color: spec.color ?? SERIES_COLORS[index % SERIES_COLORS.length]!,
285
- unit: isPercent ? "%" : catalogUnit,
286
- unitGroup: isPercent ? "percent" : `economic:${catalogUnit.toLowerCase()}`,
295
+ ...(basisPoints ? BASIS_POINT_UNIT : {
296
+ unit: isPercent ? "%" : catalogUnit,
297
+ unitGroup: isPercent ? "percent" : `economic:${catalogUnit.toLowerCase()}`,
298
+ }),
287
299
  nativeFrequency: "auto",
288
300
  timestampMode: "period-end",
289
301
  dataShape: "scalar",
@@ -292,7 +304,10 @@ export function baseEconomicSeries(
292
304
  axis: spec.axis === "right" ? "right" : "left",
293
305
  panelId: spec.panelId,
294
306
  interpolation: spec.interpolation,
295
- points: extractFredSeries(data.observations, { providerId: "fred", timestampMode: "period-end" }),
307
+ // Rounded off the float's last digits: 0.93 × 100 is 93, not 93.00000000000001.
308
+ points: basisPoints
309
+ ? points.map((point) => typeof point.value === "number" ? { ...point, value: Number((point.value * BP_PER_PERCENT).toPrecision(12)) } : point)
310
+ : points,
296
311
  warning: "FRED vintage dates are unavailable; observations use period dates.",
297
312
  };
298
313
  }
@@ -312,6 +327,9 @@ export function baseCapabilitySeries(
312
327
  ...loaded,
313
328
  id: spec.id,
314
329
  label: spec.label?.trim() || loaded.label || (spec.source.kind === "capability" ? spec.source.seriesId : spec.id),
330
+ // A geographic series writes as GEO:, which only the chart composer spells; it keeps its label.
331
+ ...(spec.source.kind === "capability" && spec.source.capabilityId !== "geo-series"
332
+ ? { expression: `CAP:${spec.source.capabilityId}:${spec.source.seriesId}` } : {}),
315
333
  color: spec.color ?? loaded.color ?? SERIES_COLORS[index % SERIES_COLORS.length]!,
316
334
  style: spec.style,
317
335
  transform: spec.transform,
@@ -288,6 +288,37 @@ export function capabilityRequestBounds(view: DateBounds, range: DateBounds, mov
288
288
  };
289
289
  }
290
290
 
291
+ /** The middle gap between a series' observations, in ms; 0 with fewer than two. */
292
+ function medianStep(times: readonly number[]): number {
293
+ const steps = times.slice(1).map((time, index) => time - times[index]!).sort((left, right) => left - right);
294
+ return steps.length ? steps[Math.floor(steps.length / 2)]! : 0;
295
+ }
296
+
297
+ /**
298
+ * A chart of published series alone (FRED, capability datasets) opens at its oldest observation when
299
+ * every series starts well inside the range: the ICE spreads FRED keeps three
300
+ * years of, on a 5Y chart, would leave two blank years on the left. Well
301
+ * inside is more than two of the series' own steps after the range's start,
302
+ * so a quarterly series whose first quarter in the range falls a month in
303
+ * moves nothing.
304
+ */
305
+ export function startAtOldestObservation(bounds: DateBounds, series: readonly ResolvedSeries[]): DateBounds {
306
+ if (bounds.start === null || bounds.end === null) return bounds;
307
+ let oldest = Number.POSITIVE_INFINITY;
308
+ let step = 0;
309
+ for (const entry of series) {
310
+ const times = entry.points
311
+ .filter((point) => point.value !== null && Number.isFinite(point.date.getTime()))
312
+ .map((point) => point.date.getTime())
313
+ .sort((left, right) => left - right);
314
+ if (times.length < 2) continue;
315
+ oldest = Math.min(oldest, times[0]!);
316
+ step = Math.max(step, medianStep(times));
317
+ }
318
+ if (!Number.isFinite(oldest) || oldest >= bounds.end || oldest - bounds.start <= 2 * step) return bounds;
319
+ return { start: oldest, end: bounds.end };
320
+ }
321
+
291
322
  /**
292
323
  * A chart of capability series alone (CHOKE's vessel transits) ends at its
293
324
  * newest observation, not today: such data is published days late, and an