gloomberb 0.20.6 → 0.20.8

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 (639) hide show
  1. package/README.ja.md +74 -0
  2. package/README.md +2 -0
  3. package/README.zh-CN.md +2 -0
  4. package/package.json +6 -1
  5. package/src/account/auth-model.ts +22 -0
  6. package/src/api-client/auth.ts +7 -2
  7. package/src/api-client/awards.ts +5 -0
  8. package/src/api-client/bond-trades.ts +22 -0
  9. package/src/api-client/catalysts.ts +11 -1
  10. package/src/api-client/data.ts +30 -6
  11. package/src/api-client/debt-maturities.ts +7 -0
  12. package/src/api-client/equity-screener.ts +17 -0
  13. package/src/api-client/errors.ts +2 -0
  14. package/src/api-client/exchange-announcements.ts +14 -7
  15. package/src/api-client/fund-facts.ts +41 -7
  16. package/src/api-client/futures-curve.ts +14 -1
  17. package/src/api-client/geo.ts +10 -0
  18. package/src/api-client/hiring.ts +2 -0
  19. package/src/api-client/index.ts +3 -0
  20. package/src/api-client/insider-signals.ts +14 -0
  21. package/src/api-client/members.ts +30 -2
  22. package/src/api-client/money-markets.ts +11 -1
  23. package/src/api-client/paths.ts +6 -1
  24. package/src/api-client/perps.ts +2 -0
  25. package/src/api-client/request.ts +2 -1
  26. package/src/api-client/socket.ts +11 -4
  27. package/src/api-client/types/econ.ts +2 -1
  28. package/src/api-client/types/filings-and-calls.ts +6 -0
  29. package/src/api-client/types/market.ts +4 -0
  30. package/src/api-client/web-experiments.ts +5 -6
  31. package/src/app/runtime/update.ts +2 -1
  32. package/src/architecture/floating-promise-allowlist.json +33 -106
  33. package/src/architecture/shortcut-labels-allowlist.json +1 -0
  34. package/src/capabilities/asset-data-inputs.ts +183 -0
  35. package/src/capabilities/factories.ts +8 -2
  36. package/src/cli/base-converter.ts +36 -2
  37. package/src/cli/commands/api.ts +2 -2
  38. package/src/cli/commands/command-utils.ts +18 -0
  39. package/src/cli/commands/hong-kong-movers.ts +50 -0
  40. package/src/cli/commands/market.ts +568 -143
  41. package/src/cli/commands/options-chain.ts +7 -1
  42. package/src/cli/commands/overview.ts +74 -14
  43. package/src/cli/commands/plugins.ts +7 -6
  44. package/src/cli/commands/search.ts +71 -12
  45. package/src/cli/commands/system.ts +15 -10
  46. package/src/cli/commands/ticker.ts +97 -44
  47. package/src/cli/content-figures.ts +45 -0
  48. package/src/cli/context.ts +5 -0
  49. package/src/cli/desktop-pane-shot-routes.ts +13 -4
  50. package/src/cli/desktop-pane-shot.ts +147 -12
  51. package/src/cli/earnings-calendar.ts +36 -5
  52. package/src/cli/export-source.ts +17 -3
  53. package/src/cli/fx-pair.ts +111 -11
  54. package/src/cli/glossary.ts +36 -2
  55. package/src/cli/help.ts +1 -1
  56. package/src/cli/history-export.ts +29 -11
  57. package/src/cli/history-rows.ts +130 -21
  58. package/src/cli/index.ts +8 -5
  59. package/src/cli/known-gaps.ts +45 -1
  60. package/src/cli/listing-arg.ts +366 -19
  61. package/src/cli/pane-functions/capabilities.ts +2 -2
  62. package/src/cli/pane-functions/catalog.ts +105 -9
  63. package/src/cli/pane-functions/discovery.ts +2 -0
  64. package/src/cli/pane-functions/dom.ts +50 -13
  65. package/src/cli/pane-functions/freshness.ts +45 -8
  66. package/src/cli/pane-functions/function-help.ts +9 -6
  67. package/src/cli/pane-functions/headless.ts +77 -6
  68. package/src/cli/pane-functions/index.ts +141 -23
  69. package/src/cli/pane-functions/options.ts +1 -3
  70. package/src/cli/pane-functions/plugin-code.ts +169 -0
  71. package/src/cli/pane-functions/report.ts +10 -0
  72. package/src/cli/pane-functions/resolver.ts +69 -21
  73. package/src/cli/pane-functions/screenshot-assessment.ts +98 -7
  74. package/src/cli/pane-functions/screenshot-data-evidence.ts +3 -1
  75. package/src/cli/pane-functions/screenshot-types.ts +6 -0
  76. package/src/cli/quote-answer.ts +106 -3
  77. package/src/cli/registry.ts +42 -4
  78. package/src/cli/report-tables.ts +26 -6
  79. package/src/cli/result.ts +30 -2
  80. package/src/cli/series-search.ts +17 -7
  81. package/src/cli/statement-filings.ts +22 -8
  82. package/src/cli/symbol-args.ts +9 -0
  83. package/src/cli/ticker-resolution.ts +3 -2
  84. package/src/cli/unknown-command.ts +111 -14
  85. package/src/components/chart/composite/format.ts +15 -1
  86. package/src/components/chart/composite/legend.tsx +101 -47
  87. package/src/components/chart/composite/panel-labels.ts +4 -4
  88. package/src/components/chart/composite/panel-surface.tsx +4 -6
  89. package/src/components/chart/composite/scene/build.ts +180 -0
  90. package/src/components/chart/composite/scene/cursor.ts +226 -0
  91. package/src/components/chart/composite/scene/domain.ts +170 -0
  92. package/src/components/chart/composite/scene/markers.ts +115 -0
  93. package/src/components/chart/composite/scene/panels.ts +85 -0
  94. package/src/components/chart/composite/scene/points.ts +169 -0
  95. package/src/components/chart/composite/scene/projection.ts +105 -0
  96. package/src/components/chart/composite/scene/timeline.ts +71 -0
  97. package/src/components/chart/composite/scene.ts +12 -1066
  98. package/src/components/chart/composite/types.ts +4 -2
  99. package/src/components/chart/curve/model.ts +2 -2
  100. package/src/components/chart-table/axis.ts +18 -6
  101. package/src/components/command-bar/layout-items/focused-pane.ts +3 -0
  102. package/src/components/command-bar/list/model.ts +9 -0
  103. package/src/components/command-bar/pane-templates/items.ts +61 -15
  104. package/src/components/command-bar/pane-templates/workflow.ts +16 -5
  105. package/src/components/command-bar/routes/root/plugin-install.ts +7 -46
  106. package/src/components/command-bar/routes/root/provider-search.ts +8 -5
  107. package/src/components/command-bar/routes/root/results.ts +6 -1
  108. package/src/components/command-bar/routes/root/runtime.ts +1 -0
  109. package/src/components/command-bar/routes/root/shortcut-feedback.ts +4 -1
  110. package/src/components/command-bar/routes/ticker-search/actions.ts +7 -5
  111. package/src/components/command-bar/routes/ticker-search/results.ts +51 -3
  112. package/src/components/command-bar/view-model.ts +12 -0
  113. package/src/components/command-bar/workflow/ops.ts +21 -4
  114. package/src/components/command-bar/workflow/ticker-listing-picker.ts +3 -1
  115. package/src/components/command-bar/workflow/tickers.ts +6 -2
  116. package/src/components/data-table/view.tsx +46 -1
  117. package/src/components/form-modal/confirm.tsx +3 -2
  118. package/src/components/form-modal/content.tsx +3 -2
  119. package/src/components/form-modal/field-row.tsx +2 -0
  120. package/src/components/form-modal/host.tsx +18 -3
  121. package/src/components/form-modal/remote-reads.test-helpers.ts +34 -0
  122. package/src/components/index.ts +1 -1
  123. package/src/components/layout/pane/title.ts +21 -5
  124. package/src/components/layout/shell/pane/layers.tsx +20 -14
  125. package/src/components/layout/shell/pane-occlusion.ts +21 -0
  126. package/src/components/onboarding/desks-step.tsx +7 -1
  127. package/src/components/onboarding/onboarding-keyboard.ts +48 -6
  128. package/src/components/onboarding/onboarding-wizard.tsx +47 -8
  129. package/src/components/onboarding/portfolio-step/positions-panel.tsx +17 -3
  130. package/src/components/onboarding/use-onboarding-progress.ts +57 -14
  131. package/src/components/onboarding/wizard-positions.ts +2 -0
  132. package/src/components/paged-rows.ts +11 -5
  133. package/src/components/ticker/list-table-view.tsx +24 -5
  134. package/src/components/toggle-list.tsx +44 -1
  135. package/src/components/ui/data-table/opentui/index.tsx +7 -6
  136. package/src/components/ui/data-table/opentui/model.ts +7 -3
  137. package/src/components/ui/data-table/types.ts +13 -2
  138. package/src/components/ui/fields.tsx +16 -4
  139. package/src/components/ui/query-bar.tsx +43 -9
  140. package/src/components/ui/table-layout.ts +56 -2
  141. package/src/core/app-services.ts +7 -2
  142. package/src/core/connection-health.ts +26 -0
  143. package/src/core/state/app/layout.ts +12 -4
  144. package/src/data/config/layout.ts +3 -1
  145. package/src/data/config/store/node.ts +4 -2
  146. package/src/docs/snapshot.json +794 -215
  147. package/src/i18n/es.ts +6 -1
  148. package/src/i18n/ja.ts +6 -1
  149. package/src/i18n/ko.ts +6 -1
  150. package/src/i18n/zh-cn.ts +6 -1
  151. package/src/i18n/zh-tw.ts +6 -1
  152. package/src/layout/pane-follow.ts +1 -1
  153. package/src/layout/pane-manager/gridlock.ts +18 -5
  154. package/src/layout/pane-manager/index.ts +1 -0
  155. package/src/layout/pane-manager/transient.ts +56 -0
  156. package/src/layout-marketplace/gallery.tsx +2 -1
  157. package/src/layout-marketplace/model.ts +4 -10
  158. package/src/market-data/commodity-names.ts +24 -0
  159. package/src/market-data/connection-follow.ts +9 -7
  160. package/src/market-data/coordinator/auxiliary.ts +4 -3
  161. package/src/market-data/coordinator/entries.ts +22 -1
  162. package/src/market-data/coordinator/financials.ts +2 -3
  163. package/src/market-data/coordinator/index.ts +67 -12
  164. package/src/market-data/coordinator/quotes.ts +2 -3
  165. package/src/market-data/fund-facts.ts +7 -1
  166. package/src/market-data/futures-board.ts +38 -4
  167. package/src/market-data/futures-contract.ts +5 -2
  168. package/src/market-data/fx-closes.ts +4 -1
  169. package/src/market-data/market/bar-period.ts +15 -0
  170. package/src/market-data/market/change-basis.ts +49 -8
  171. package/src/market-data/market/dated-previous-close.ts +133 -10
  172. package/src/market-data/market/format.ts +4 -2
  173. package/src/market-data/market/freshness.ts +22 -6
  174. package/src/market-data/market/status.ts +32 -4
  175. package/src/market-data/options-alternatives.ts +21 -9
  176. package/src/market-data/published-futures-sessions.ts +9 -0
  177. package/src/market-data/published-nse-sessions.ts +16 -1
  178. package/src/market-data/quotes/balance-sheet-rate.ts +34 -0
  179. package/src/market-data/quotes/delisting.ts +26 -2
  180. package/src/market-data/quotes/freshness.ts +77 -0
  181. package/src/market-data/quotes/listing-enterprise-value.ts +250 -19
  182. package/src/market-data/quotes/regular-session-valuation.ts +8 -0
  183. package/src/market-data/realized-volatility.ts +3 -1
  184. package/src/market-data/request-types.ts +2 -0
  185. package/src/market-data/selectors.ts +1 -0
  186. package/src/news/aggregator.ts +3 -3
  187. package/src/plugins/builtin/account-management/delete-account.ts +78 -0
  188. package/src/plugins/builtin/account-management/pane.tsx +22 -19
  189. package/src/plugins/builtin/account-management/password-dialog.tsx +75 -0
  190. package/src/plugins/builtin/alerts/alert-engine.ts +15 -0
  191. package/src/plugins/builtin/alerts/alert-log.ts +3 -2
  192. package/src/plugins/builtin/alerts/cli-forms.ts +1 -1
  193. package/src/plugins/builtin/alerts/cli.ts +94 -13
  194. package/src/plugins/builtin/alerts/format.ts +8 -2
  195. package/src/plugins/builtin/alerts/headless.ts +1 -1
  196. package/src/plugins/builtin/alerts/index.tsx +13 -6
  197. package/src/plugins/builtin/alerts/metric-command.ts +1 -1
  198. package/src/plugins/builtin/alerts/pane.tsx +5 -3
  199. package/src/plugins/builtin/alerts/research-builder.ts +12 -0
  200. package/src/plugins/builtin/analytics/index.tsx +3 -3
  201. package/src/plugins/builtin/analytics/risk-client.ts +14 -3
  202. package/src/plugins/builtin/analytics/risk-pane.tsx +3 -3
  203. package/src/plugins/builtin/attention/pane.tsx +1 -1
  204. package/src/plugins/builtin/attention/trending.tsx +1 -1
  205. package/src/plugins/builtin/awards/detail.tsx +4 -1
  206. package/src/plugins/builtin/awards/headless.ts +7 -3
  207. package/src/plugins/builtin/awards/model.ts +11 -0
  208. package/src/plugins/builtin/awards/pane.tsx +12 -5
  209. package/src/plugins/builtin/backtest/client.ts +7 -2
  210. package/src/plugins/builtin/backtest/headless.ts +2 -1
  211. package/src/plugins/builtin/backtest/pane.tsx +4 -2
  212. package/src/plugins/builtin/bond-calculator/pane.tsx +1 -1
  213. package/src/plugins/builtin/broker-manager/sign-in-end.ts +1 -1
  214. package/src/plugins/builtin/broker-trading/orders.tsx +2 -2
  215. package/src/plugins/builtin/buildout/company/pane.tsx +1 -1
  216. package/src/plugins/builtin/buildout/model/index.ts +2 -2
  217. package/src/plugins/builtin/catalysts/headless.ts +9 -6
  218. package/src/plugins/builtin/catalysts/model.ts +72 -10
  219. package/src/plugins/builtin/catalysts/pane.tsx +10 -7
  220. package/src/plugins/builtin/cds/pane.tsx +5 -3
  221. package/src/plugins/builtin/central-bank-rates/pane.tsx +3 -2
  222. package/src/plugins/builtin/chart-composer/catalog-series.ts +59 -0
  223. package/src/plugins/builtin/chart-composer/headless-schema.ts +2 -1
  224. package/src/plugins/builtin/chart-composer/headless.ts +104 -23
  225. package/src/plugins/builtin/chart-composer/index.tsx +6 -3
  226. package/src/plugins/builtin/chart-composer/legend-names.ts +19 -0
  227. package/src/plugins/builtin/chart-composer/pane.tsx +37 -10
  228. package/src/plugins/builtin/chart-composer/presets.ts +63 -6
  229. package/src/plugins/builtin/chart-composer/roll-events.ts +38 -0
  230. package/src/plugins/builtin/chart-composer/series-catalog.ts +12 -5
  231. package/src/plugins/builtin/chart-composer/series-expression.ts +8 -4
  232. package/src/plugins/builtin/chart-composer/series-listings.ts +33 -9
  233. package/src/plugins/builtin/chart-composer/use-series-catalog.ts +2 -2
  234. package/src/plugins/builtin/clinical-trials/client.ts +13 -0
  235. package/src/plugins/builtin/clinical-trials/index.tsx +1 -1
  236. package/src/plugins/builtin/clinical-trials/pane.tsx +77 -27
  237. package/src/plugins/builtin/clinical-trials/search.ts +117 -0
  238. package/src/plugins/builtin/cloud/askg/conversation-store.ts +17 -6
  239. package/src/plugins/builtin/cloud/askg/lock-note.ts +4 -2
  240. package/src/plugins/builtin/cloud/askg/manifest.ts +3 -2
  241. package/src/plugins/builtin/cloud/askg/pane.tsx +2 -2
  242. package/src/plugins/builtin/cloud/askg/sources.ts +3 -3
  243. package/src/plugins/builtin/cloud/one-tap/one-tap-prompt.tsx +7 -3
  244. package/src/plugins/builtin/cloud/team/acm-tab.tsx +1 -1
  245. package/src/plugins/builtin/cloud/team/pane.tsx +17 -10
  246. package/src/plugins/builtin/cloud/team/views.ts +15 -3
  247. package/src/plugins/builtin/cloud/terminal-relay/redact.ts +105 -16
  248. package/src/plugins/builtin/cloud/thesis/board-pane.tsx +17 -2
  249. package/src/plugins/builtin/cloud/thesis/module.tsx +3 -2
  250. package/src/plugins/builtin/cloud/thesis/store.ts +17 -3
  251. package/src/plugins/builtin/commodities-energy/index.tsx +35 -3
  252. package/src/plugins/builtin/commodity-balances/index.tsx +1 -1
  253. package/src/plugins/builtin/company-attention/app-rank.tsx +1 -1
  254. package/src/plugins/builtin/company-attention/building.tsx +1 -1
  255. package/src/plugins/builtin/company-attention/model.ts +2 -1
  256. package/src/plugins/builtin/company-attention/moves.tsx +1 -1
  257. package/src/plugins/builtin/company-attention/pane.tsx +1 -1
  258. package/src/plugins/builtin/company-attention/signals.tsx +1 -1
  259. package/src/plugins/builtin/company-kpis/pane.tsx +1 -1
  260. package/src/plugins/builtin/correlation/headless.ts +7 -5
  261. package/src/plugins/builtin/correlation/history.ts +17 -6
  262. package/src/plugins/builtin/correlation/index.tsx +1 -1
  263. package/src/plugins/builtin/correlation/relationship/history.ts +1 -1
  264. package/src/plugins/builtin/correlation/relationship/pane.tsx +1 -1
  265. package/src/plugins/builtin/cot/headless.ts +10 -3
  266. package/src/plugins/builtin/cot/pane.tsx +2 -2
  267. package/src/plugins/builtin/cpi/pane.tsx +1 -1
  268. package/src/plugins/builtin/credit-boards/model.ts +1 -1
  269. package/src/plugins/builtin/credit-documents/pane.tsx +1 -1
  270. package/src/plugins/builtin/crypto-board/defi-view.tsx +2 -2
  271. package/src/plugins/builtin/crypto-board/defi.ts +9 -3
  272. package/src/plugins/builtin/crypto-board/headless.ts +19 -10
  273. package/src/plugins/builtin/crypto-board/model.ts +8 -0
  274. package/src/plugins/builtin/crypto-board/pane.tsx +11 -5
  275. package/src/plugins/builtin/crypto-board/series.ts +17 -3
  276. package/src/plugins/builtin/crypto-board/supply.ts +26 -3
  277. package/src/plugins/builtin/crypto-etf-flows/headless.ts +3 -2
  278. package/src/plugins/builtin/crypto-etf-flows/model.ts +13 -3
  279. package/src/plugins/builtin/crypto-etf-flows/pane.tsx +6 -3
  280. package/src/plugins/builtin/custom-view/pane.tsx +5 -5
  281. package/src/plugins/builtin/debt-maturities/client.ts +5 -0
  282. package/src/plugins/builtin/debt-maturities/headless.ts +3 -1
  283. package/src/plugins/builtin/debt-maturities/model.ts +1 -0
  284. package/src/plugins/builtin/debt-maturities/pane.tsx +1 -1
  285. package/src/plugins/builtin/dividend-yield/pane.tsx +1 -1
  286. package/src/plugins/builtin/doe/model.ts +1 -1
  287. package/src/plugins/builtin/doe/pane.tsx +1 -1
  288. package/src/plugins/builtin/earnings/board.tsx +2 -2
  289. package/src/plugins/builtin/earnings/history.tsx +1 -1
  290. package/src/plugins/builtin/earnings-calls/calendar.tsx +1 -1
  291. package/src/plugins/builtin/earnings-calls/data.ts +2 -1
  292. package/src/plugins/builtin/earnings-calls/headless.ts +15 -0
  293. package/src/plugins/builtin/earnings-calls/model.ts +68 -8
  294. package/src/plugins/builtin/earnings-calls/pane.tsx +29 -8
  295. package/src/plugins/builtin/earnings-calls/transcript-view.tsx +32 -2
  296. package/src/plugins/builtin/earnings-ripple/pane.tsx +1 -1
  297. package/src/plugins/builtin/econ/calendar-model.ts +94 -2
  298. package/src/plugins/builtin/econ/detail-view.tsx +15 -11
  299. package/src/plugins/builtin/econ/index.tsx +25 -9
  300. package/src/plugins/builtin/econ/types.ts +4 -1
  301. package/src/plugins/builtin/equity-screener/headless.ts +23 -7
  302. package/src/plugins/builtin/equity-screener/index.tsx +3 -0
  303. package/src/plugins/builtin/equity-screener/live.ts +39 -12
  304. package/src/plugins/builtin/equity-screener/model.ts +86 -5
  305. package/src/plugins/builtin/equity-screener/pane.tsx +20 -21
  306. package/src/plugins/builtin/equity-screener/results.ts +12 -3
  307. package/src/plugins/builtin/equity-screener/ticker-check.tsx +2 -2
  308. package/src/plugins/builtin/estimate-revisions/pane.tsx +2 -2
  309. package/src/plugins/builtin/executives/pane.tsx +2 -2
  310. package/src/plugins/builtin/exposure/pane.tsx +1 -1
  311. package/src/plugins/builtin/fear-greed/data.ts +3 -1
  312. package/src/plugins/builtin/fear-greed/headless.ts +8 -2
  313. package/src/plugins/builtin/fear-greed/pane.tsx +8 -4
  314. package/src/plugins/builtin/filing-events/pane.tsx +1 -1
  315. package/src/plugins/builtin/futures/index.tsx +5 -4
  316. package/src/plugins/builtin/futures/model.ts +17 -9
  317. package/src/plugins/builtin/futures/returns.ts +2 -0
  318. package/src/plugins/builtin/futures/series.ts +44 -8
  319. package/src/plugins/builtin/futures/table.tsx +3 -3
  320. package/src/plugins/builtin/futures-curve/client.ts +1 -0
  321. package/src/plugins/builtin/futures-curve/headless.ts +14 -12
  322. package/src/plugins/builtin/futures-curve/index.tsx +7 -4
  323. package/src/plugins/builtin/futures-curve/model.ts +93 -7
  324. package/src/plugins/builtin/futures-curve/pane.tsx +18 -7
  325. package/src/plugins/builtin/fx-matrix/amount.ts +2 -1
  326. package/src/plugins/builtin/fx-matrix/index.tsx +9 -0
  327. package/src/plugins/builtin/gpu/changes.tsx +1 -1
  328. package/src/plugins/builtin/gpu/equities.tsx +1 -1
  329. package/src/plugins/builtin/gpu/pane.tsx +2 -2
  330. package/src/plugins/builtin/help/function-card.tsx +4 -2
  331. package/src/plugins/builtin/help/function-index.ts +12 -6
  332. package/src/plugins/builtin/help/index.tsx +1 -1
  333. package/src/plugins/builtin/holders/beneficial-view.tsx +1 -1
  334. package/src/plugins/builtin/holders/fund-holders.ts +22 -1
  335. package/src/plugins/builtin/holders/headless.ts +5 -4
  336. package/src/plugins/builtin/holders/pane.tsx +8 -4
  337. package/src/plugins/builtin/holders/report-header.ts +23 -0
  338. package/src/plugins/builtin/insider/base-values.ts +55 -0
  339. package/src/plugins/builtin/insider/headless.ts +307 -83
  340. package/src/plugins/builtin/insider/index.tsx +65 -23
  341. package/src/plugins/builtin/insider/insiders.tsx +26 -16
  342. package/src/plugins/builtin/insider/model.ts +2 -2
  343. package/src/plugins/builtin/insider/signals-cells.tsx +4 -1
  344. package/src/plugins/builtin/insider/signals-model.ts +13 -5
  345. package/src/plugins/builtin/insider/signals.tsx +5 -3
  346. package/src/plugins/builtin/insider/tickers.tsx +466 -0
  347. package/src/plugins/builtin/ipo-calendar/pane.tsx +1 -1
  348. package/src/plugins/builtin/iv-history/client.ts +35 -4
  349. package/src/plugins/builtin/iv-history/headless.ts +10 -4
  350. package/src/plugins/builtin/iv-history/model.ts +85 -16
  351. package/src/plugins/builtin/iv-history/pane.tsx +2 -2
  352. package/src/plugins/builtin/iv-history/screen-pane.tsx +6 -3
  353. package/src/plugins/builtin/jobs/pane.tsx +5 -5
  354. package/src/plugins/builtin/macro-day/pane.tsx +1 -1
  355. package/src/plugins/builtin/macro-day/release-table.ts +5 -5
  356. package/src/plugins/builtin/macro-day/releases.ts +11 -9
  357. package/src/plugins/builtin/market-movers/headless.ts +6 -2
  358. package/src/plugins/builtin/market-movers/screener.ts +18 -4
  359. package/src/plugins/builtin/members/breadth-pane.tsx +3 -3
  360. package/src/plugins/builtin/members/client.ts +24 -2
  361. package/src/plugins/builtin/members/headless.ts +68 -9
  362. package/src/plugins/builtin/members/index.tsx +7 -6
  363. package/src/plugins/builtin/members/model.ts +99 -13
  364. package/src/plugins/builtin/members/pane.tsx +72 -20
  365. package/src/plugins/builtin/mna/distress/pane.tsx +2 -1
  366. package/src/plugins/builtin/mna/pane.tsx +1 -1
  367. package/src/plugins/builtin/money-markets/client.ts +43 -15
  368. package/src/plugins/builtin/money-markets/headless.ts +18 -11
  369. package/src/plugins/builtin/money-markets/index.tsx +7 -6
  370. package/src/plugins/builtin/money-markets/model.ts +20 -5
  371. package/src/plugins/builtin/money-markets/pane.tsx +28 -17
  372. package/src/plugins/builtin/news/wire/news/footer.ts +11 -1
  373. package/src/plugins/builtin/news/wire/news/table.tsx +15 -5
  374. package/src/plugins/builtin/notes/headless.ts +94 -0
  375. package/src/plugins/builtin/notes/index.tsx +3 -1
  376. package/src/plugins/builtin/notes/store.ts +10 -3
  377. package/src/plugins/builtin/options/footer.ts +8 -2
  378. package/src/plugins/builtin/options/open-interest-as-of.ts +12 -3
  379. package/src/plugins/builtin/options/view.tsx +10 -1
  380. package/src/plugins/builtin/options-calculator/pane.tsx +1 -1
  381. package/src/plugins/builtin/options-positioning/client.ts +35 -8
  382. package/src/plugins/builtin/options-positioning/headless.ts +17 -7
  383. package/src/plugins/builtin/options-positioning/index.tsx +10 -0
  384. package/src/plugins/builtin/options-positioning/pane.tsx +16 -7
  385. package/src/plugins/builtin/options-scenario/csp-screen-pane.tsx +1 -1
  386. package/src/plugins/builtin/options-scenario/pane.tsx +1 -1
  387. package/src/plugins/builtin/pe-band/pane.tsx +2 -2
  388. package/src/plugins/builtin/perps/cascade-tabs.tsx +2 -2
  389. package/src/plugins/builtin/perps/client.ts +54 -15
  390. package/src/plugins/builtin/perps/headless.ts +39 -13
  391. package/src/plugins/builtin/perps/index.tsx +2 -1
  392. package/src/plugins/builtin/perps/model.ts +43 -1
  393. package/src/plugins/builtin/perps/pane.tsx +35 -18
  394. package/src/plugins/builtin/portfolio-list/allocation-rows.ts +74 -0
  395. package/src/plugins/builtin/portfolio-list/cell-version.ts +1 -0
  396. package/src/plugins/builtin/portfolio-list/cli/period-report.ts +7 -3
  397. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +37 -4
  398. package/src/plugins/builtin/portfolio-list/cli/render.ts +214 -46
  399. package/src/plugins/builtin/portfolio-list/headless.ts +32 -10
  400. package/src/plugins/builtin/portfolio-list/income.ts +63 -30
  401. package/src/plugins/builtin/portfolio-list/index.tsx +4 -4
  402. package/src/plugins/builtin/portfolio-list/pane/data.ts +16 -6
  403. package/src/plugins/builtin/portfolio-list/pane/fx-day-moves.ts +52 -0
  404. package/src/plugins/builtin/portfolio-list/pane/index.tsx +81 -13
  405. package/src/plugins/builtin/portfolio-list/pane/target-weights.tsx +178 -0
  406. package/src/plugins/builtin/portfolio-list/period-pnl.ts +44 -5
  407. package/src/plugins/builtin/portfolio-list/settings.ts +12 -6
  408. package/src/plugins/builtin/portfolio-list/summary/index.tsx +9 -4
  409. package/src/plugins/builtin/portfolio-list/summary/totals.ts +21 -2
  410. package/src/plugins/builtin/portfolio-list/table.tsx +33 -25
  411. package/src/plugins/builtin/portfolio-list/use-throttled-ticker-order.ts +40 -3
  412. package/src/plugins/builtin/power/gas.tsx +2 -2
  413. package/src/plugins/builtin/power/prices.tsx +2 -2
  414. package/src/plugins/builtin/primary-dealers/pane.tsx +10 -11
  415. package/src/plugins/builtin/rate-path/model.ts +9 -0
  416. package/src/plugins/builtin/rate-path/pane.tsx +6 -5
  417. package/src/plugins/builtin/realized-vol/fx-proxy.ts +27 -0
  418. package/src/plugins/builtin/realized-vol/headless.ts +8 -6
  419. package/src/plugins/builtin/realized-vol/pane.tsx +13 -7
  420. package/src/plugins/builtin/relative-rotation/pane.tsx +1 -1
  421. package/src/plugins/builtin/research/analyst-headless.ts +5 -1
  422. package/src/plugins/builtin/research/analyst-model.ts +7 -1
  423. package/src/plugins/builtin/research/analyst-pane.tsx +1 -1
  424. package/src/plugins/builtin/research/relative-valuation-basis.ts +44 -4
  425. package/src/plugins/builtin/research/relative-valuation-headless.ts +59 -14
  426. package/src/plugins/builtin/research/relative-valuation-model.ts +65 -26
  427. package/src/plugins/builtin/research/relative-valuation-pane.tsx +42 -17
  428. package/src/plugins/builtin/revenue-breakdown/pane.tsx +1 -1
  429. package/src/plugins/builtin/reverse-dcf/client.ts +34 -4
  430. package/src/plugins/builtin/reverse-dcf/headless.ts +30 -15
  431. package/src/plugins/builtin/reverse-dcf/model.ts +190 -29
  432. package/src/plugins/builtin/reverse-dcf/pane.tsx +35 -13
  433. package/src/plugins/builtin/risk-factors/pane.tsx +2 -2
  434. package/src/plugins/builtin/roadmap/pane.tsx +2 -2
  435. package/src/plugins/builtin/scanner/flow-pane.tsx +4 -4
  436. package/src/plugins/builtin/scanner/headless.ts +15 -1
  437. package/src/plugins/builtin/seasonality/pane.tsx +1 -1
  438. package/src/plugins/builtin/sec/fund-facts-view.tsx +5 -2
  439. package/src/plugins/builtin/sec/fund-facts.ts +66 -6
  440. package/src/plugins/builtin/sec/headless.ts +8 -4
  441. package/src/plugins/builtin/sec/index.tsx +41 -13
  442. package/src/plugins/builtin/shared/report-freshness.ts +15 -6
  443. package/src/plugins/builtin/shared/ticker-company.ts +111 -0
  444. package/src/plugins/builtin/shared/use-quote-board.ts +37 -2
  445. package/src/plugins/builtin/shared/volatility/live-session.ts +23 -0
  446. package/src/plugins/builtin/shared/volatility-indices.ts +2 -0
  447. package/src/plugins/builtin/short-interest/publications-pane.tsx +1 -1
  448. package/src/plugins/builtin/short-volume/pane.tsx +1 -1
  449. package/src/plugins/builtin/social-mentions/outliers.tsx +3 -3
  450. package/src/plugins/builtin/social-mentions/pane.tsx +2 -2
  451. package/src/plugins/builtin/supply-chain/graph-pane.tsx +1 -1
  452. package/src/plugins/builtin/supply-chain/model.ts +18 -6
  453. package/src/plugins/builtin/supply-chain/pane.tsx +1 -1
  454. package/src/plugins/builtin/themes/pane.tsx +4 -4
  455. package/src/plugins/builtin/thirteenf/api.ts +1 -0
  456. package/src/plugins/builtin/thirteenf/format.ts +5 -0
  457. package/src/plugins/builtin/thirteenf/headless.ts +2 -2
  458. package/src/plugins/builtin/thirteenf/model.ts +128 -5
  459. package/src/plugins/builtin/thirteenf/overlap-pane.tsx +1 -1
  460. package/src/plugins/builtin/thirteenf/report-notes.ts +10 -3
  461. package/src/plugins/builtin/thirteenf/signals-pane.tsx +1 -1
  462. package/src/plugins/builtin/thirteenf/table.ts +2 -2
  463. package/src/plugins/builtin/thirteenf/types.ts +12 -0
  464. package/src/plugins/builtin/ticker-detail/data-panes/historical-prices.tsx +27 -14
  465. package/src/plugins/builtin/ticker-detail/data-panes/returns-history.ts +6 -3
  466. package/src/plugins/builtin/ticker-detail/data-panes/returns-model.ts +14 -0
  467. package/src/plugins/builtin/ticker-detail/data-panes/returns-pane.tsx +4 -1
  468. package/src/plugins/builtin/ticker-detail/financials/aggregation.ts +87 -19
  469. package/src/plugins/builtin/ticker-detail/financials/exchange-results.ts +54 -0
  470. package/src/plugins/builtin/ticker-detail/financials/model.ts +114 -9
  471. package/src/plugins/builtin/ticker-detail/financials/ratios.ts +37 -20
  472. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +42 -19
  473. package/src/plugins/builtin/ticker-detail/headless-schema.ts +3 -2
  474. package/src/plugins/builtin/ticker-detail/headless.ts +90 -31
  475. package/src/plugins/builtin/ticker-detail/overview/model.ts +22 -15
  476. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +5 -2
  477. package/src/plugins/builtin/ticker-detail/quote-monitor/card.tsx +12 -7
  478. package/src/plugins/builtin/ticker-detail/quote-monitor/index.tsx +21 -0
  479. package/src/plugins/builtin/trace-bonds/client.ts +107 -10
  480. package/src/plugins/builtin/trace-bonds/detail.tsx +1 -1
  481. package/src/plugins/builtin/trace-bonds/headless.ts +20 -5
  482. package/src/plugins/builtin/trace-bonds/pane.tsx +15 -4
  483. package/src/plugins/builtin/treasury-auctions/hk-view.tsx +1 -1
  484. package/src/plugins/builtin/treasury-auctions/pane.tsx +1 -1
  485. package/src/plugins/builtin/treasury-daily/pane.tsx +2 -2
  486. package/src/plugins/builtin/vol-surface/charts.tsx +30 -5
  487. package/src/plugins/builtin/vol-surface/client.ts +40 -12
  488. package/src/plugins/builtin/vol-surface/events.ts +213 -0
  489. package/src/plugins/builtin/vol-surface/headless.ts +82 -13
  490. package/src/plugins/builtin/vol-surface/index.tsx +5 -1
  491. package/src/plugins/builtin/vol-surface/model.ts +42 -6
  492. package/src/plugins/builtin/vol-surface/pane.tsx +95 -23
  493. package/src/plugins/builtin/volatility/dvol.ts +14 -2
  494. package/src/plugins/builtin/volatility/headless.ts +3 -2
  495. package/src/plugins/builtin/volatility/index.tsx +1 -1
  496. package/src/plugins/builtin/volatility/pane.tsx +1 -1
  497. package/src/plugins/builtin/volatility/series.ts +7 -3
  498. package/src/plugins/builtin/world-venue-map/activity-series.ts +89 -0
  499. package/src/plugins/builtin/world-venue-map/chokepoint-report.ts +123 -0
  500. package/src/plugins/builtin/world-venue-map/evidence.ts +2 -0
  501. package/src/plugins/builtin/world-venue-map/geo-series.ts +35 -1
  502. package/src/plugins/builtin/world-venue-map/headless.ts +58 -9
  503. package/src/plugins/builtin/world-venue-map/index.ts +6 -3
  504. package/src/plugins/builtin/world-venue-map/layered-pane.tsx +6 -1
  505. package/src/plugins/builtin/world-venue-map/pane.tsx +4 -3
  506. package/src/plugins/builtin/yield-curve/index.tsx +12 -10
  507. package/src/plugins/builtin/yield-curve/swaps.tsx +1 -1
  508. package/src/plugins/extracted-plugins.ts +14 -10
  509. package/src/plugins/installer.ts +17 -1
  510. package/src/plugins/marketplace/feed.ts +14 -0
  511. package/src/plugins/marketplace/install-offer.ts +64 -0
  512. package/src/plugins/registry/contributions.ts +46 -8
  513. package/src/plugins/registry/index.ts +5 -0
  514. package/src/portfolio/collection-name.ts +38 -4
  515. package/src/portfolio/column-values.ts +35 -4
  516. package/src/portfolio/period-pnl.ts +4 -2
  517. package/src/portfolio/valuation-basis.ts +23 -1
  518. package/src/react/async-resource.ts +24 -8
  519. package/src/remote/endpoint.ts +38 -12
  520. package/src/remote/secrets.ts +22 -6
  521. package/src/remote/server.ts +20 -4
  522. package/src/renderers/dom/data-table/index.tsx +2 -1
  523. package/src/renderers/dom/data-table/row.tsx +49 -7
  524. package/src/renderers/dom/desktop/controls.tsx +2 -0
  525. package/src/renderers/dom/desktop/query-bar.tsx +57 -7
  526. package/src/renderers/dom/host/surface-3d.tsx +46 -5
  527. package/src/renderers/dom/styles.css +17 -0
  528. package/src/renderers/electrobun/view/backend-rpc.ts +15 -21
  529. package/src/renderers/electrobun/view/cli-pane-shot-entry.tsx +16 -61
  530. package/src/renderers/electrobun/view/cli-pane-shot-socket.ts +134 -0
  531. package/src/renderers/electrobun/view/host-route.ts +119 -0
  532. package/src/renderers/electrobun/view/rpc-timeout.ts +6 -5
  533. package/src/renderers/opentui/toast-host.tsx +6 -3
  534. package/src/renderers/opentui/ui-host.tsx +29 -5
  535. package/src/series/registry.ts +1 -0
  536. package/src/series/standalone-catalog.ts +40 -0
  537. package/src/series/types.ts +10 -0
  538. package/src/series/validate.ts +5 -0
  539. package/src/shares/portable-layout.ts +2 -7
  540. package/src/sources/gloomberb-cloud/dated-chunks.ts +133 -0
  541. package/src/sources/gloomberb-cloud/index.ts +46 -5
  542. package/src/sources/gloomberb-cloud/news.ts +15 -9
  543. package/src/sources/gloomberb-cloud/normalizers.ts +17 -0
  544. package/src/sources/history-coverage.ts +13 -0
  545. package/src/sources/history-result.ts +1 -0
  546. package/src/sources/provider-errors.ts +9 -0
  547. package/src/sources/provider-router/batches.ts +7 -3
  548. package/src/sources/provider-router/financial-routes.ts +3 -1
  549. package/src/sources/provider-router/history.ts +6 -4
  550. package/src/sources/provider-router/index.ts +5 -1
  551. package/src/sources/provider-router/primary.ts +4 -3
  552. package/src/sources/provider-router/retrieved-at.ts +12 -0
  553. package/src/state/hooks/quote-streaming.ts +14 -6
  554. package/src/team/store.ts +17 -4
  555. package/src/telemetry/crash-reports.ts +3 -1
  556. package/src/test-support/cli-context.ts +3 -2
  557. package/src/test-support/test-env.ts +7 -0
  558. package/src/theme/themes.ts +16 -9
  559. package/src/theme/tone-contrast.ts +29 -5
  560. package/src/tickers/company-name-listing.ts +31 -3
  561. package/src/tickers/company-name.ts +9 -0
  562. package/src/tickers/index-roots.ts +56 -4
  563. package/src/tickers/instrument-kind.ts +22 -1
  564. package/src/tickers/listing-name.ts +7 -2
  565. package/src/tickers/listing-venues.ts +17 -2
  566. package/src/tickers/search/home-listing.ts +2 -0
  567. package/src/tickers/search/index.ts +69 -11
  568. package/src/tickers/search/major-listings.json +595 -592
  569. package/src/tickers/search/ranking.ts +19 -1
  570. package/src/tickers/terminal-codes.ts +20 -6
  571. package/src/time-series/bar-aggregation.ts +3 -2
  572. package/src/time-series/base-series.ts +18 -1
  573. package/src/time-series/chart-data.ts +9 -6
  574. package/src/time-series/chart-seed.ts +11 -3
  575. package/src/time-series/currency-conversion.ts +1 -0
  576. package/src/time-series/date-window.ts +8 -0
  577. package/src/time-series/formula-months.ts +57 -0
  578. package/src/time-series/fundamentals/current-valuation.ts +244 -0
  579. package/src/time-series/fundamentals/historical-valuation.ts +99 -0
  580. package/src/time-series/fundamentals/metric-ids.ts +61 -0
  581. package/src/time-series/fundamentals/period-points.ts +104 -0
  582. package/src/time-series/fundamentals/quarterly-ttm.ts +220 -0
  583. package/src/time-series/fundamentals/series.ts +164 -0
  584. package/src/time-series/fundamentals/source-statements.ts +178 -0
  585. package/src/time-series/fundamentals/statement-fields.ts +154 -0
  586. package/src/time-series/fundamentals/statement-merge.ts +124 -0
  587. package/src/time-series/fundamentals/statement.ts +114 -0
  588. package/src/time-series/fundamentals/valuation-multiples.ts +50 -0
  589. package/src/time-series/fundamentals.ts +18 -1407
  590. package/src/time-series/leverage.ts +12 -4
  591. package/src/time-series/live-bars.ts +12 -7
  592. package/src/time-series/live-quotes.ts +6 -2
  593. package/src/time-series/market.ts +10 -3
  594. package/src/time-series/price-comparison.ts +106 -0
  595. package/src/time-series/range.ts +10 -0
  596. package/src/time-series/resolve-context.ts +7 -2
  597. package/src/time-series/resolve.ts +61 -5
  598. package/src/time-series/series-name.ts +2 -2
  599. package/src/time-series/series-presentation.ts +91 -2
  600. package/src/time-series/session-bar.ts +13 -7
  601. package/src/time-series/spec.ts +21 -2
  602. package/src/time-series/studies/formula.ts +262 -36
  603. package/src/time-series/studies/leverage.ts +9 -3
  604. package/src/time-series/studies/resolve.ts +7 -2
  605. package/src/time-series/types.ts +34 -0
  606. package/src/time-series/use-chart-resolution.ts +18 -1
  607. package/src/types/data-provider.ts +7 -0
  608. package/src/types/financials.ts +112 -1
  609. package/src/types/headless.ts +64 -3
  610. package/src/types/instrument.ts +6 -0
  611. package/src/types/plugin-context.ts +9 -0
  612. package/src/types/plugin-pane-templates.ts +6 -0
  613. package/src/types/plugin-panes.ts +7 -0
  614. package/src/types/price-history.ts +6 -0
  615. package/src/ui/host.tsx +3 -1
  616. package/src/ui/index.tsx +7 -2
  617. package/src/utils/cli-output.ts +21 -1
  618. package/src/utils/currency-units.ts +14 -0
  619. package/src/utils/datetime-format.ts +11 -0
  620. package/src/utils/debug-log.ts +29 -0
  621. package/src/utils/exchange-announcements.ts +26 -3
  622. package/src/utils/exchange-notation.generated.ts +3 -4
  623. package/src/utils/exchange-results.ts +144 -0
  624. package/src/utils/exchanges.ts +10 -0
  625. package/src/utils/financial-statements.ts +212 -22
  626. package/src/utils/fire-and-forget.ts +1 -1
  627. package/src/utils/fiscal-period.ts +41 -3
  628. package/src/utils/format.ts +10 -6
  629. package/src/utils/fundamentals.ts +179 -12
  630. package/src/utils/futures-generic.ts +26 -0
  631. package/src/utils/lease-liabilities.ts +15 -5
  632. package/src/utils/lookup-token.ts +22 -0
  633. package/src/utils/max-drawdown.ts +25 -4
  634. package/src/utils/price-history-integrity.ts +56 -8
  635. package/src/utils/price-history.ts +6 -2
  636. package/src/utils/price-window.ts +38 -2
  637. package/src/utils/replace-file.ts +47 -0
  638. package/src/utils/rpc-timeout-error.ts +16 -2
  639. package/src/utils/untrusted-text.ts +14 -0
@@ -1,9 +1,11 @@
1
1
  import { logFailure } from "../../utils/log-failure";
2
+ import { isTransientFailure } from "../../api-client/errors";
2
3
  import { normalizeTickerSymbol } from "../../tickers/search/ranking";
3
4
  import type { CliCommandDef } from "../../types/plugin";
4
5
  import { TIME_RANGES, type TimeRange } from "../../time-series/range";
5
- import { CHART_RESOLUTION_STEP_MS, RANGE_HISTORY_RESOLUTION } from "../../time-series/resolution";
6
+ import { CHART_RESOLUTION_STEP_MS, isIntradayResolution, RANGE_HISTORY_RESOLUTION } from "../../time-series/resolution";
6
7
  import { yearToDateStartIndex } from "../../market-data/market/year-to-date";
8
+ import { barCloseSession } from "../../market-data/market/bar-period";
7
9
  import type { EarningsEvent, MarketDataRequestContext, QuoteBatchResult, QuoteSubscriptionTarget, SecFilingItem } from "../../types/data-provider";
8
10
  import { companyDataNotes, type CompanyFrom } from "../../types/company-from";
9
11
  import type { NewsArticle, NewsFeed, NewsQuery } from "../../news/types";
@@ -33,7 +35,7 @@ import {
33
35
  } from "../../market-data/market/status";
34
36
  import { formatCompact, formatCurrency, formatDistributionAmount, formatNumber, formatPercent } from "../../utils/format";
35
37
  import { withCliServices, withMarketData } from "../context";
36
- import { isoDate, parsePositiveInt, requireOneArg, takeFlag, takeOption } from "./command-utils";
38
+ import { isoDate, parsePositiveInt, requireOneArg, takeFlag, takeOption, typedCompanyName } from "./command-utils";
37
39
  import type { BuiltinCliCommandDef } from "../command-options";
38
40
  import { CLI_COMMAND_GROUPS, TABLE_SECTION_OPTION } from "../help";
39
41
  import { CLI_EXIT_CODES } from "../exit-codes";
@@ -60,7 +62,7 @@ import {
60
62
  ratingReason,
61
63
  } from "../../plugins/builtin/research/analyst-model";
62
64
  import { getPublishedUsEquityCalendarYears, getPublishedUsEquitySession } from "../../market-data/published-us-sessions";
63
- import { awaitingFirstDelayedPrint, isQuoteStaleForCurrentSession, noPrintsTodayText } from "../../market-data/quotes/freshness";
65
+ import { awaitingFirstDelayedPrint, isQuoteStaleForCurrentSession, noPrintsTodayText, nominalPriceText, nominalSessionLabel } from "../../market-data/quotes/freshness";
64
66
  import {
65
67
  coinOptionsAlternativesText, isCoinWithoutOptions, isOptionsUnavailableError, listedOptionsAlternative, optionsUnavailableTitle,
66
68
  } from "../../market-data/options-alternatives";
@@ -73,10 +75,11 @@ import { loadStatementFilings } from "../statement-filings";
73
75
  import { loadBankFigures } from "../bank-section";
74
76
  import { latestFinancialPeriod } from "../../utils/latest-financial-period";
75
77
  import type { FuturesContractTermsPayload } from "../../api-client/futures-curve";
76
- import { currencyCodeLabel } from "../../utils/currency-units";
78
+ import { currencyCodeLabel, currencyUnitLabel, resolveCurrencyUnit } from "../../utils/currency-units";
77
79
  import { fxRateDigits, quotedFxPair } from "../../utils/currency-pair";
78
80
  import {
79
- futuresContractLines, futuresPricePer, futuresRollLines, futuresTickOption, isFuturesInstrument, loadFuturesPriceUnit, loadUsdPerMmbtu, usdPerMmbtuText, type UsdPerMmbtu,
81
+ futuresContractLines, futuresPricePer, futuresPriceUnit, futuresRollLines, futuresTickOption, isFuturesInstrument, loadFuturesContractTerms, loadUsdPerMmbtu,
82
+ usdPerMmbtuText, type UsdPerMmbtu,
80
83
  } from "../../market-data/futures-contract";
81
84
  import {
82
85
  chainHasExpiry,
@@ -90,6 +93,7 @@ import {
90
93
  formatOptionDollarCell,
91
94
  formatOptionGammaCell,
92
95
  formatOptionIvCell,
96
+ formatOptionLastCell,
93
97
  formatOptionQuoteCell,
94
98
  isMarkedChain,
95
99
  MARKED_OPTION_FIELDS,
@@ -108,12 +112,15 @@ import {
108
112
  expirationHint, expiredExpiryText, expiryIsoDate, isLiveOptionExpiry, liveDefaultExpiry, liveOptionExpiries, missingExpiryMessage,
109
113
  OPTION_EXPIRATION_FORMAT, OPTION_EXPIRATION_PLACEHOLDER, optionExpiryVenue, withLiveExpiryList,
110
114
  } from "../../utils/option-expiry";
111
- import { DATE_OPTION_EXAMPLES, isoDateOption, isoDateToday } from "../../utils/calendar-date";
115
+ import { calendarMonthsBefore, DATE_OPTION_EXAMPLES, isoDateOption, isoDateToday } from "../../utils/calendar-date";
112
116
  import { apiClient } from "../../api-client";
113
117
  import { CLOUD_QUOTE_DELAY_MINUTES } from "../../api-client/plan-rules";
114
118
  import type { ExchangeAnnouncementsPayload } from "../../api-client/exchange-announcements";
115
- import { exchangeAnnouncementsPage, listsExchangeAnnouncements, type ExchangeAnnouncementsPage } from "../../utils/exchange-announcements";
116
- import { dailyFxLeg, fxCloseOnDate, type FxCloseReading } from "../../market-data/fx-closes";
119
+ import {
120
+ exchangeAnnouncementsPage, exchangeAnnouncementsPublisher, isRoutineReturn, listsExchangeAnnouncements, type ExchangeAnnouncementsPage,
121
+ } from "../../utils/exchange-announcements";
122
+ import { dailyFxLeg, fxCloseOnDate, fxCloseOnOrBefore, loadDailyFxCloses, type FxCloseReading } from "../../market-data/fx-closes";
123
+ import { zonedDateTimeParts } from "../../utils/zoned-date-time";
117
124
  import { declaredDividends } from "../../utils/declared-dividends";
118
125
  import {
119
126
  DEFAULT_LEAPS_CRITERIA, LEAPS_EXTRA_COLUMNS, LEAPS_USAGE, parseLeapsCriteria, runLeapsScreen, takeLeapsOptions,
@@ -127,15 +134,16 @@ import {
127
134
  selectReportTables,
128
135
  type CliReportTables,
129
136
  } from "../report-tables";
130
- import { historyCoverageNotice } from "../../sources/history-coverage";
137
+ import { historyCoverageNotice, WindowBeforeFirstBarError } from "../../sources/history-coverage";
131
138
  import { fetchHistoryResult } from "../../sources/history-result";
132
139
  import { settleWithin } from "../../utils/async-deadline";
133
140
  import type { FxInterventionsPayload } from "../../api-client/fx-interventions";
134
141
  import {
135
142
  fxInterventionLatestNote, fxInterventionPair, fxInterventionWindowNote, loadFxInterventions, type FxInterventionPair,
136
143
  } from "../../market-data/fx-interventions";
137
- import { maxDrawdownText, maxRunUp, maxRunUpText } from "../../utils/max-drawdown";
138
- import { isPastPriceWindow, loadPriceWindowHistory, PRICE_WINDOW_FROM_HELP, PRICE_WINDOW_TO_HELP, priceWindowInterval, priceWindowText, readPriceWindow, type PriceWindow } from "../../utils/price-window";
144
+ import { maxDrawdownText, maxRunUp, maxRunUpText, measuredUntil } from "../../utils/max-drawdown";
145
+ import { ALL_HISTORY_REACH_MONTHS, subtractTimeRange } from "../../time-series/date-window";
146
+ import { historyFirstBarDay, isPastPriceWindow, loadPriceWindowHistory, PRICE_WINDOW_FROM_HELP, PRICE_WINDOW_TO_HELP, priceWindowInterval, priceWindowText, readPriceWindow, type PriceWindow } from "../../utils/price-window";
139
147
  import {
140
148
  BAR_INTERVAL_LABELS,
141
149
  closedPeriodBarDay,
@@ -146,15 +154,16 @@ import {
146
154
  historyExportUnit,
147
155
  historyFacts,
148
156
  historyFlagNote,
157
+ historyOpenNote,
149
158
  historyWickNote,
150
159
  historyContractDrawdown,
151
160
  historyRollNote,
152
161
  historyThinNote,
153
162
  historyGapNote,
154
163
  historyJumpNote,
164
+ historyRescaleNote,
155
165
  historyUnbrokenFrom,
156
166
  dailyRebuildSpans,
157
- historyAllRangeYears,
158
167
  historyIntervalsByRange,
159
168
  historyMissingVolumeNote,
160
169
  historyVenueVolumeNote,
@@ -183,11 +192,11 @@ import {
183
192
  symbolListNotes,
184
193
  type HistoryListRow,
185
194
  } from "../history-export";
186
- import { fail, isCliFailure, NO_DATA_CODE } from "../errors";
195
+ import { fail, failWithError, isCliFailure, NO_DATA_CODE } from "../errors";
187
196
  import { createConcurrencyLimiter, mapWithConcurrency } from "../../utils/concurrency";
188
197
  import { MISSING_VOLUME_TEXT } from "../../utils/price-history-integrity";
189
198
  import { CRYPTO_BOARD_HINT, quoteNotes } from "./crypto-hints";
190
- import { bareFuturesCode, futuresBoardContract, futuresContractByWord } from "../../market-data/futures-board";
199
+ import { bareFuturesCode, futuresBoardContract } from "../../market-data/futures-board";
191
200
  import { commodityNamedIn, commoditySearchName } from "../../market-data/commodity-names";
192
201
  import { newsEmptyMessage } from "./news-hints";
193
202
  import { centralBankInNews, centralBankShortNamed } from "../../utils/central-banks";
@@ -225,6 +234,7 @@ import { fxPairListing, fxQuoteRateMove, fxQuoteRateObservation, METAL_NAMES, re
225
234
  import { quoteBarNotes } from "../../market-data/quotes/intraday-bar";
226
235
  import { cedearRatioText, depositaryPairText, isReceiptSide, listingCedearRatio, listingDepositaryPair } from "../../market-data/depositary-pair";
227
236
  import { isPesoDollarPair, loadPesoDollarRates, pesoDollarRateLines, pesoDollarRatesJson } from "../peso-dollar-rates";
237
+ import { withBalanceSheetRate } from "../../market-data/quotes/balance-sheet-rate";
228
238
  import { atRegularSessionPrice, regularSessionValuationPrice } from "../../market-data/quotes/regular-session-valuation";
229
239
  import { viewMarketCapitalization } from "../../utils/market-capitalization";
230
240
  import {
@@ -263,8 +273,10 @@ import {
263
273
  listingChoiceNotes,
264
274
  listingReadNotes,
265
275
  failUnchosenListing,
276
+ futureByWordLine,
266
277
  loadBareVenues,
267
278
  loadForListing,
279
+ ownedCodeNotes,
268
280
  loadListingQuote,
269
281
  loadListingQuoteAnswer,
270
282
  listingFateLoader,
@@ -275,6 +287,9 @@ import {
275
287
  isTitleCaseWord,
276
288
  requireCliListing,
277
289
  resolveCliListing,
290
+ joinCompanyNameWords,
291
+ resolveNamedListing,
292
+ MAX_CHOICE_LOOKUPS,
278
293
  type CliListing,
279
294
  type ListingIdentity,
280
295
  } from "../listing-arg";
@@ -286,9 +301,9 @@ import {
286
301
  analyzeTaxEquivalent, distributionBasis, loadTreasuryTenors, noBondFigures, parseTaxRates, TAX_RATE_HELP_OPTIONS, taxEquivalentJson, type TaxRates,
287
302
  } from "../../market-data/tax-equivalent";
288
303
  import { CBOE_YIELD_INDEX_CLOSE } from "../../plugins/builtin/shared/treasury-cutoffs";
289
- import { earningsCalendarFailure, earningsChoiceNote, earningsDateLabel, isListingAbroad, noListingCalendarNote, undatedListingsNote } from "../earnings-calendar";
304
+ import { earningsCalendarFailure, earningsChoiceNote, earningsDateLabel, isListingAbroad, lastReportedDay, noListingCalendarNote, undatedListingsNote } from "../earnings-calendar";
290
305
  import { formatBasisPoints, toBasisPoints } from "../../utils/basis-points";
291
- import { providerMissReason } from "../../sources/provider-errors";
306
+ import { isUnservedWithoutReason, notATickerSymbol, providerMissReason } from "../../sources/provider-errors";
292
307
  import { isNetworkFailure } from "../../utils/network-failure";
293
308
  import { withSavedCopy, type ReportFreshness } from "../pane-functions/freshness";
294
309
  import { isNotATickerMessage } from "../not-a-ticker";
@@ -300,7 +315,7 @@ import { readNameEntries, readPhraseArgument } from "../name-entries";
300
315
  import { readSymbolList, SymbolListError } from "../symbol-list";
301
316
  import { notASymbolError } from "../symbol-cells";
302
317
  import { cliPerpetualContract, perpetualContractStats, type PerpetualContractPayload } from "../perpetual-contract";
303
- import { knownGapMessage, subMinuteDataMessage } from "../known-gaps";
318
+ import { isSubMinuteInterval, knownGapMessage, subMinuteDataMessage } from "../known-gaps";
304
319
  import { phraseSearchReport } from "./search";
305
320
  import { secRegistrantMismatchMessage, SecRegistrantMismatchError, areDifferentCompanies } from "../../sources/sec-registrant";
306
321
  import { isCryptoPairSymbol, isRoundTheClockCoin } from "../../utils/crypto-pair";
@@ -313,8 +328,8 @@ import {
313
328
  import { noSecReportsNotice, nonUsSecListingVenue, secFilingItemCodes } from "../../utils/sec";
314
329
  import type { MarketContext } from "../types";
315
330
  import { windowRows } from "../row-window";
316
- import { answerQuote, errorMessage, notUsTickerSentence } from "../quote-answer";
317
- import { crossRate, describeFxConversion, describeFxLegs, describeFxRate, formatFxAmount, formatFxRate, FX_USAGE, parseFxArgs, type FxQuotedFigure } from "../fx-pair";
331
+ import { answerQuote, errorMessage, notUsTickerSentence, withJoinedCompanyNames } from "../quote-answer";
332
+ import { crossRate, describeFxConversion, describeFxLegs, describeFxRate, formatFxAmount, formatFxRate, FX_USAGE, fxSideCode, fxSubUnit, fxUnitRate, parseFxArgs, type FxQuotedFigure, type FxRequest } from "../fx-pair";
318
333
  import {
319
334
  describeCarrySides,
320
335
  describeShortRate,
@@ -354,7 +369,7 @@ import {
354
369
  unvaluedHoldersNote,
355
370
  } from "../../plugins/builtin/holders/report-rows";
356
371
  import { fetchBeneficialOwners } from "../../plugins/builtin/holders/beneficial-client";
357
- import { fundHoldersAnswer } from "../../plugins/builtin/holders/fund-holders";
372
+ import { noHoldersAnswer } from "../../plugins/builtin/holders/fund-holders";
358
373
  import { centralBankEventsMessage } from "../central-bank-events";
359
374
  import { classSharesAsOf, classSharesToday } from "../../plugins/builtin/holders/client";
360
375
  import {
@@ -418,15 +433,20 @@ type FinancialsCliData = TickerFinancials & {
418
433
  providerId: string | null;
419
434
  };
420
435
 
436
+ /** The ranges as other tools spell them, which `--range` reads too: a week of sessions is 5d. */
437
+ const HISTORY_RANGE_ALIASES = "5d, 1mo, 3mo, 6mo, 1y, 5y and max";
438
+
421
439
  /**
422
440
  * A range as typed, in any case and as other tools spell it: `1mo`, `1m` and
423
- * `1 month` are 1M, `1wk` 1W, `5yr` 5Y, `max` ALL.
441
+ * `1 month` are 1M, `1wk` and `5d` (a week's five sessions) 1W, `5yr` 5Y,
442
+ * `max` ALL.
424
443
  */
425
444
  export function readHistoryRange(value: string): HistoryRange | null {
426
445
  const typed = value.trim().toUpperCase().replace(/\s+/g, "");
427
446
  if (typed === "MAX") return "ALL";
428
447
  const spelled = /^(\d+)(D|DAYS?|W|WKS?|WEEKS?|M|MOS?|MONTHS?|Y|YRS?|YEARS?)$/.exec(typed);
429
448
  const range = (spelled ? `${spelled[1]}${spelled[2]![0]}` : typed) as HistoryRange;
449
+ if (range === "5D" as HistoryRange || range === "7D" as HistoryRange) return "1W";
430
450
  return VALID_RANGES.has(range) ? range : null;
431
451
  }
432
452
 
@@ -442,7 +462,7 @@ function rangeTypedAsSymbol(entry: string): HistoryRange | null {
442
462
 
443
463
  function parseRange(value: string | undefined, ctx: Parameters<CliCommandDef["execute"]>[1]): HistoryRange {
444
464
  const range = readHistoryRange(value ?? "1Y");
445
- if (!range) ctx.fail(`Unknown range "${value}".`, `Use one of ${HISTORY_RANGES.join(", ")}.`);
465
+ if (!range) ctx.fail(`Unknown range "${value}".`, `Use one of ${HISTORY_RANGES.join(", ")}, or ${HISTORY_RANGE_ALIASES}.`);
446
466
  return range!;
447
467
  }
448
468
 
@@ -693,21 +713,30 @@ function quoteColumns() {
693
713
  return [
694
714
  ...QUOTE_LEAD_COLUMNS.map((column) => EXTENDED_KEYS.has(column.key) ? { ...column, stackPriority: 1 } : column),
695
715
  { key: "currency", header: "Cur", shrink: false, stackPriority: 3, format: currencyCell },
696
- // Whether the price is real-time, delayed or stale: a feed state, not where it came from. A stale
697
- // row says so here, so the closing line's "N of M stale" always points at rows the table marks.
698
- {
699
- key: "feed",
700
- header: "Feed",
701
- shrink: false,
702
- stackPriority: 4,
703
- format: (value: unknown) => value === "stale" ? cliStyles.warning(value) : String(value ?? ""),
704
- },
705
- { key: "updatedAt", header: "Updated", shrink: false, stackPriority: 5 },
716
+ ...FEED_COLUMNS,
706
717
  ...CHANGE_BASIS_EXPORT_COLUMNS,
707
718
  ...EXTENDED_CHANGE_EXPORT_COLUMNS,
708
719
  ];
709
720
  }
710
721
 
722
+ /**
723
+ * Whether the price is real-time, delayed, stale or nominal: a feed state, not where it came from. A stale or
724
+ * nominal row says so here, so the closing line's "N of M stale" or "N of M nominal" always points at rows the
725
+ * table marks, in `quote` and in `compare`.
726
+ */
727
+ const FEED_COLUMNS = [
728
+ {
729
+ key: "feed",
730
+ header: "Feed",
731
+ shrink: false,
732
+ stackPriority: 4,
733
+ format: (value: unknown) => value === "stale" || value === "nominal" ? cliStyles.warning(value) : String(value ?? ""),
734
+ },
735
+ // A nominal price names the session it is from ("6 Nov close"), not the last print; JSON keeps both.
736
+ { key: "updatedAt", header: "Updated", shrink: false, stackPriority: 5,
737
+ format: (value: unknown, row: QuoteRow) => row.nominalLabel || (typeof value === "string" ? formatUtcTime(value) : "") },
738
+ ];
739
+
711
740
  /**
712
741
  * A yield index's move in basis points, the move the table shows (`+2.2bp`), which an export of a table holding a
713
742
  * yield adds after its other columns; Chg% keeps the percent change it always held, blank for no yield.
@@ -742,12 +771,18 @@ function compareColumns() {
742
771
  ...CHANGE_BASIS_EXPORT_COLUMNS,
743
772
  ...EXTENDED_CHANGE_EXPORT_COLUMNS,
744
773
  ...DAY_RANGE_EXPORT_COLUMNS,
774
+ // After the columns an export already had, so one read by position stays where it was; the table shows them after Cur.
775
+ ...FEED_COLUMNS,
745
776
  ];
746
777
  }
747
778
 
748
- /** What the Feed cell says: stale wins over the feed's own live or delayed, as the closing line counts it. */
749
- function quoteFeedState(quote: QuoteCliRecord["quote"], now: number): "stale" | "live" | "delayed" | "" {
779
+ /**
780
+ * What the Feed cell says: nominal for a price nothing traded at (Quote.nominalPrice), then stale, over the feed's
781
+ * own live or delayed, as the closing line counts them.
782
+ */
783
+ function quoteFeedState(quote: QuoteCliRecord["quote"], now: number): "nominal" | "stale" | "live" | "delayed" | "" {
750
784
  if (!quote) return "";
785
+ if (quote.nominalPrice) return "nominal";
751
786
  if (isQuoteStaleForCurrentSession(quote, now)) return "stale";
752
787
  return quote.dataSource === "live" || quote.dataSource === "delayed" ? quote.dataSource : "";
753
788
  }
@@ -770,6 +805,38 @@ function changeBasisNotes(results: QuoteCliRecord[], now = Date.now()): string[]
770
805
  return [...new Set(results.flatMap((result) => changeBasisNote(rowChangeBasis(result), now) ?? []))];
771
806
  }
772
807
 
808
+ /** How long `quote --json` waits for the share counts its market caps are put on; a row without one keeps its source's cap. */
809
+ const QUOTE_MARKET_CAP_WAIT_MS = 4_000;
810
+
811
+ /**
812
+ * Each quote's market cap on the basis valuation and RV show it
813
+ * (viewMarketCapitalization): the share count they show times the regular
814
+ * session's price, the source's own figure where the count is not the cap's.
815
+ * NPN:JSE read 568.36B ZAR in `quote --json` beside 579.69B in `valuation`
816
+ * and RV on 11 Nov 2026, on the source's count. Read in one batch, waited for
817
+ * briefly; null where no count came in time.
818
+ */
819
+ async function quoteViewMarketCaps(results: readonly QuoteBatchResult[], market: MarketContext): Promise<Array<number | null> | null> {
820
+ const asked = results.flatMap((result, index) => result.quote?.marketCap != null && result.quote.instrumentType !== "INDEX" ? [index] : []);
821
+ if (asked.length === 0 || !market.dataProvider.getTickerFinancialsBatch) return null;
822
+ const read = await settleWithin(market.dataProvider.getTickerFinancialsBatch(asked.map((index) => ({
823
+ symbol: results[index]!.target.symbol, exchange: results[index]!.target.exchange,
824
+ }))), QUOTE_MARKET_CAP_WAIT_MS).catch(logFailure("cli.commands-market", "Read share counts for quote market caps failed", null));
825
+ if (!read) return null;
826
+ return results.map((result, index) => {
827
+ const at = asked.indexOf(index);
828
+ const fundamentals = at < 0 ? undefined : read[at]?.financials?.fundamentals;
829
+ if (!result.quote || !fundamentals) return null;
830
+ const cap = viewMarketCapitalization(result.quote, fundamentals, regularSessionValuationPrice(result.quote));
831
+ return cap && cap.currency === result.quote.currency ? cap.value : null;
832
+ });
833
+ }
834
+
835
+ /** A quote with the market cap valuation and RV show for it, where one was read. */
836
+ function withViewMarketCap(quote: Quote | null | undefined, marketCap: number | null | undefined): Quote | null | undefined {
837
+ return quote && marketCap != null && marketCap !== quote.marketCap ? { ...quote, marketCap } : quote;
838
+ }
839
+
773
840
  /** The quote as `--json` gives it: `previousCloseDate`, the exchange-local date of its previous close, follows `previousClose`. */
774
841
  function withPreviousCloseDate(quote: Quote | null | undefined): (Quote & { previousCloseDate?: string | null }) | null {
775
842
  if (!quote) return null;
@@ -874,6 +941,8 @@ function quoteRows(results: QuoteCliRecord[], now = Date.now()) {
874
941
  // Last, so a row read by position keeps every field where it was.
875
942
  changeBasis: predates ? "" : basisLabel(result, now),
876
943
  changeBasisNote: changeBasisNote(rowChangeBasis(result), now) ?? "",
944
+ // A price nothing traded at names the venue session it is the nominal close of; the quote keeps its last trade.
945
+ ...quote?.nominalPrice ? { nominalLabel: nominalSessionLabel(quote) ?? undefined } : {},
877
946
  };
878
947
  });
879
948
  }
@@ -1071,8 +1140,6 @@ function earningsRows(events: ResolvedEarningsEvent[]) {
1071
1140
  }));
1072
1141
  }
1073
1142
 
1074
- /** Symbols at most whose venues a command looks up to name the company each bare one went to. */
1075
- const MAX_CHOICE_LOOKUPS = 10;
1076
1143
 
1077
1144
  /**
1078
1145
  * The line `quote` prints beside a symbol that changed, as `history` and
@@ -1116,10 +1183,11 @@ async function runQuote(rawArgs: string[], ctx: Parameters<CliCommandDef["execut
1116
1183
  }
1117
1184
  // With several symbols, --exchange is for the ones that name no exchange of their own, and one that names no
1118
1185
  // listing (EQT:NYSE:US) is named in a line while the others are quoted.
1186
+ // A word that names a company is read once its quote says no listing trades as it (answerQuote).
1119
1187
  const resolvedListings = await Promise.all(symbols.filter((symbol) => !notASymbolError(symbol)).map(async (symbol) => {
1120
- if (symbols.length === 1) return { symbol, listing: await requireCliListing(symbol, exchange, market, ctx) };
1188
+ if (symbols.length === 1) return { symbol, listing: await requireCliListing(symbol, exchange, market, ctx, { companyWord: false }) };
1121
1189
  try {
1122
- return { symbol, listing: await resolveCliListing(symbol, exchange, market, { ownExchangeWins: true }) };
1190
+ return { symbol, listing: await resolveCliListing(symbol, exchange, market, { ownExchangeWins: true, companyWord: false }) };
1123
1191
  } catch (error) {
1124
1192
  if (error instanceof ListingArgError) return { symbol, error };
1125
1193
  throw error;
@@ -1144,12 +1212,14 @@ async function runQuote(rawArgs: string[], ctx: Parameters<CliCommandDef["execut
1144
1212
  // Each row prints what its move is from (Chg Basis).
1145
1213
  const results = await market.dataProvider.getQuotesBatch(targets, { forceRefresh: ctx.cliOptions.refresh, revalidate: true, datesChangeBasis: true });
1146
1214
  const listingOf = (result: QuoteBatchResult, index: number) => listings[targets.indexOf(result.target)] ?? listings[index]!;
1147
- const asked = results.map(listingOf);
1148
1215
  const request = { command: commandName, noun: "quote" };
1149
- const answers = await Promise.all(results.map((result, index) => {
1150
- const listing = asked[index]!;
1216
+ const quoted = await Promise.all(results.map((result, index) => {
1217
+ const listing = listingOf(result, index);
1151
1218
  return answerQuote(result, listing, market, request, ctx.cliOptions.refresh, venues.get(listing) ?? null, { datesChangeBasis: true });
1152
1219
  }));
1220
+ // "MTN Group" typed apart is MTN Group, one row, where "Group" alone would read as UnitedHealth Group.
1221
+ const { answers, asked } = listed ? { answers: quoted, asked: results.map(listingOf) }
1222
+ : await withJoinedCompanyNames(quoted, results.map(listingOf), market, request, ctx.cliOptions.refresh, true);
1153
1223
  const now = Date.now();
1154
1224
  const symbolChanges = await Promise.all(answers.map(async ({ result }, index) => {
1155
1225
  const listing = asked[index]!;
@@ -1178,8 +1248,9 @@ async function runQuote(rawArgs: string[], ctx: Parameters<CliCommandDef["execut
1178
1248
  if (symbols.length === 1 && failed) {
1179
1249
  ctx.fail(failed.message, [quoteChangeLine(tickerChanges[0], formerIssuers[0]), failed.details].filter(Boolean).join("\n") || undefined);
1180
1250
  }
1181
- // A futures quote adds its dated settlement and contract terms, as `ticker` prints them; `compare` stays a table.
1182
- const contracts = await Promise.all(answers.map(({ result }) => commandName === "quote" && result.quote
1251
+ // A futures quote adds its dated settlement and contract terms, as `ticker` prints them; `compare` stays a table, whose
1252
+ // future still prints to its tick and measures its move from the settle, as `quote` does.
1253
+ const contracts = await Promise.all(answers.map(({ result }) => result.quote
1183
1254
  ? cliFuturesContract(result.quote.symbol || result.target.symbol, result.quote.instrumentType)
1184
1255
  : null));
1185
1256
  // A future's move the source measured from something other than the session before's settlement of the same contract is measured from it, in the row and in every line.
@@ -1191,10 +1262,11 @@ async function runQuote(rawArgs: string[], ctx: Parameters<CliCommandDef["execut
1191
1262
  return { change: sent.change, changePercent: sent.changePercent, previousClose: sent.previousClose };
1192
1263
  });
1193
1264
  // A contract that is not its root's front (NGF27, NG2) prints the front's own price beside it, read in one batch.
1194
- const fronts = await loadFuturesFrontQuotes(contracts, market.dataProvider);
1265
+ // Both go in the contract block, which `compare` does not print.
1266
+ const fronts = commandName === "quote" ? await loadFuturesFrontQuotes(contracts, market.dataProvider) : contracts.map(() => null);
1195
1267
  // A per-MWh gas price (TTF) adds its dollars per MMBtu at the day's rate, to read beside Henry Hub.
1196
- const gasInUsd = await Promise.all(answers.map(({ result }, index) => loadUsdPerMmbtu(
1197
- getRegularSessionDisplay(result.quote)?.price, contracts[index], result.quote?.currency, (currency) => market.dataProvider.getExchangeRate(currency))));
1268
+ const gasInUsd = await Promise.all(answers.map(({ result }, index) => commandName === "quote" ? loadUsdPerMmbtu(
1269
+ getRegularSessionDisplay(result.quote)?.price, contracts[index], result.quote?.currency, (currency) => market.dataProvider.getExchangeRate(currency)) : null));
1198
1270
  // A perpetual adds its funding per eight hours and open interest, the figures PERP lists beside its mark.
1199
1271
  const perpetualContracts = await Promise.all(answers.map(({ result }) => commandName === "quote" && result.quote
1200
1272
  ? cliPerpetualContract(result.quote)
@@ -1204,6 +1276,8 @@ async function runQuote(rawArgs: string[], ctx: Parameters<CliCommandDef["execut
1204
1276
  const venue = result.quote && !listing.saved ? bareListingNote(listing, result.quote) : null;
1205
1277
  return venue && notes.includes(venue) ? suggestUsTicker(listing.symbol, market) : null;
1206
1278
  }));
1279
+ // JSON's market cap is the one valuation and RV show, on the share count they show (viewMarketCapitalization).
1280
+ const viewCaps = ctx.cliOptions.format === "json" ? await quoteViewMarketCaps(answers.map(({ result }) => result), market) : null;
1207
1281
  // Each row names its listing by key (SAN:EPA) and company, so the table needs no line above it.
1208
1282
  const data = answers.map(({ result, listing, failure }, index) => ({
1209
1283
  target: result.target,
@@ -1212,7 +1286,7 @@ async function runQuote(rawArgs: string[], ctx: Parameters<CliCommandDef["execut
1212
1286
  ...quoteSessionFields(result.quote),
1213
1287
  // What `change` is measured from, with the label and holiday note the table shows.
1214
1288
  changeBasis: changeBasisJson(quoteChangeBasis(result.quote, { terms: contracts[index] }), now),
1215
- quote: withPreviousCloseDate(result.quote),
1289
+ quote: withPreviousCloseDate(withViewMarketCap(result.quote, viewCaps?.[index])),
1216
1290
  ...sourceMoves[index] ? { sourceMove: sourceMoves[index] } : {},
1217
1291
  ...contracts[index] ? { futuresContract: contracts[index] } : {},
1218
1292
  ...fronts[index] ? { futuresFront: fronts[index] } : {},
@@ -1245,7 +1319,7 @@ async function runQuote(rawArgs: string[], ctx: Parameters<CliCommandDef["execut
1245
1319
  const ended = stopped && liveCompanies[index] ? `${stopped}. ${liveCompanies[index]}` : stopped;
1246
1320
  // Open by its venue's calendar, before the delayed feed's first print: Last is the previous close until then.
1247
1321
  const awaiting = ended ? null : awaitingFirstDelayedPrint(row.quote, now);
1248
- const quiet = ended || awaiting ? null : noPrintsTodayText(row.quote, now);
1322
+ const quiet = ended || awaiting ? null : nominalPriceText(row.quote) ?? noPrintsTodayText(row.quote, now);
1249
1323
  const waiting = awaiting && row.quote
1250
1324
  ? `${label}: open since ${utcClock(awaiting.open)} UTC; Last is the previous close until the first delayed print, about ${utcClock(awaiting.expected)} UTC`
1251
1325
  : null;
@@ -1267,9 +1341,9 @@ async function runQuote(rawArgs: string[], ctx: Parameters<CliCommandDef["execut
1267
1341
  // A commodity's word read as a security's ticker (WTI is W&T Offshore, GOLD is Gold.com) names the future it may have meant.
1268
1342
  ...data.flatMap((row, index) => {
1269
1343
  const listing = asked[index]!;
1270
- const contract = listing.exchange || !row.quote || isFuturesInstrument(row.target.symbol, row.quote.instrumentType)
1271
- ? null : futuresContractByWord(row.target.symbol);
1272
- return contract ? [`${row.target.symbol} is ${row.listing.name || "a security"}; for ${contract.name}, quote the future ${contract.symbol}.`] : [];
1344
+ const line = listing.exchange || !row.quote || isFuturesInstrument(row.target.symbol, row.quote.instrumentType)
1345
+ ? null : futureByWordLine(row.target.symbol, row.listing.name, commandName);
1346
+ return line ? [line] : [];
1273
1347
  }),
1274
1348
  // A cell shows only "unavailable", and an exported row only its status, so stderr names each failure; the JSON rows carry each reason.
1275
1349
  ...ctx.cliOptions.format !== "json" ? quoteNotes(data.filter((_row, index) => !endedNotes[index])) : [],
@@ -1278,12 +1352,18 @@ async function runQuote(rawArgs: string[], ctx: Parameters<CliCommandDef["execut
1278
1352
  const columns = [...commandName === "compare" ? compareColumns() : quoteColumns(), ...holdsYield ? [CHANGE_BP_EXPORT_COLUMN] : []];
1279
1353
  const basisNotes = changeBasisNotes(data, now);
1280
1354
  const midNotes = extendedMidNotes(data);
1355
+ // Another listing a row's code names (00700 on TWSE is 700.HK on HKEX) is said under the table, not as a warning on the row.
1356
+ const listingNotes = answers.flatMap((answer) => answer.footnotes ?? []);
1357
+ const exportNotes = [...midNotes, ...listingNotes];
1358
+ const footnotes = [...basisNotes, ...listingNotes];
1359
+ // JSON has no table to put them under: they stay with its warnings.
1360
+ const warnings = [...notes, ...ctx.cliOptions.format === "json" ? listingNotes : []];
1281
1361
  if (ctx.cliOptions.format !== "json") await primeBoardCoins(notes);
1282
1362
  // Only yield indices: their change is in bp, so the text header drops the percent sign (CSV keeps the percent it holds).
1283
1363
  const yieldsOnly = data.length > 0 && data.every((row) => isYieldIndexSymbol(row.target.symbol));
1284
1364
  ctx.printResult({
1285
1365
  data,
1286
- warnings: notes.length > 0 ? notes : undefined,
1366
+ warnings: warnings.length > 0 ? warnings : undefined,
1287
1367
  // A Cboe yield index stops at its 15:00 ET close, before the Treasury's curve is taken: the line says so, so its
1288
1368
  // close does not read as a contradiction of DGS10 or GC for the same day.
1289
1369
  // Dated by the quotes as served, which say whether one is the saved copy.
@@ -1305,9 +1385,10 @@ async function runQuote(rawArgs: string[], ctx: Parameters<CliCommandDef["execut
1305
1385
  }),
1306
1386
  // A row with no price or move says why in its status column, as the warnings do.
1307
1387
  exportStatus: quoteExportStatus,
1308
- ...(midNotes.length > 0 ? { exportNotes: midNotes } : {}),
1309
- details: quoteDetailsText,
1310
- ...(basisNotes.length ? { footnote: basisNotes.join("\n") } : {}),
1388
+ ...(exportNotes.length > 0 ? { exportNotes } : {}),
1389
+ // `compare` is the table alone: no contract block under it.
1390
+ details: commandName === "quote" ? quoteDetailsText : compareDetailsText,
1391
+ ...(footnotes.length ? { footnote: footnotes.join("\n") } : {}),
1311
1392
  columns,
1312
1393
  textColumns: quoteTextColumns(yieldsOnly
1313
1394
  ? columns.map((column) => column.key === "changePercent" ? { ...column, header: "Chg" } : column)
@@ -1363,7 +1444,11 @@ async function answerPhrase(phrase: string, market: MarketContext, ctx: Paramete
1363
1444
  * line for a symbol that is not a US ticker though it is one slip from one.
1364
1445
  */
1365
1446
  function quoteDetailsText(data: QuoteCliRecord[]): string {
1366
- return [quoteFuturesContractText(data), ...data.flatMap((row) => notUsTickerLine(row) ?? [])].filter(Boolean).join("\n\n");
1447
+ return [quoteFuturesContractText(data), compareDetailsText(data)].filter(Boolean).join("\n\n");
1448
+ }
1449
+
1450
+ function compareDetailsText(data: QuoteCliRecord[]): string {
1451
+ return data.flatMap((row) => notUsTickerLine(row) ?? []).join("\n\n");
1367
1452
  }
1368
1453
 
1369
1454
  /**
@@ -1437,18 +1522,32 @@ function yieldIndexFields(result: QuoteBatchResult): { unit?: "percent"; changeB
1437
1522
  * formats keep the error as thrown, and so does no connection at all, which
1438
1523
  * the board cannot get past either.
1439
1524
  */
1440
- function failHistory(error: unknown, symbol: string, ctx: Parameters<CliCommandDef["execute"]>[1]): never {
1525
+ function failHistory(error: unknown, symbol: string, ctx: Parameters<CliCommandDef["execute"]>[1], range?: TimeRange): never {
1526
+ // A window before the listing's first bar has none to give, asked now or later: "No bars before 2014-09-17 for BTC-USD."
1527
+ if (error instanceof WindowBeforeFirstBarError) failWithError({ code: NO_DATA_CODE, message: error.message, retryable: false });
1528
+ // A range of intraday bars no source has current bars for (a venue with daily bars only, or bars behind its last
1529
+ // session) says so and offers the daily view, never that no provider is available. A coin keeps the crypto board's
1530
+ // pointer below: its bars trade around the clock, so a miss is the feed's, not a venue's hours.
1531
+ const resolution = range ? RANGE_HISTORY_RESOLUTION[range] : null;
1532
+ if (range && resolution && isIntradayResolution(resolution) && !isCryptoPairSymbol(symbol) && isUnservedWithoutReason(error)) {
1533
+ failWithError({
1534
+ code: NO_DATA_CODE,
1535
+ message: `No current ${BAR_INTERVAL_LABELS[resolution]} bars for ${symbol}.`,
1536
+ details: `For daily bars: gloom history ${symbol} --range 1M`,
1537
+ retryable: true,
1538
+ });
1539
+ }
1441
1540
  if (ctx.cliOptions.format !== "text" || !isCryptoPairSymbol(symbol) || isNetworkFailure(error)) throw error;
1442
1541
  return ctx.fail(errorMessage(error) ?? `No history available for ${symbol}`, CRYPTO_BOARD_HINT);
1443
1542
  }
1444
1543
 
1445
1544
  const HISTORY_USAGE = "history <symbol...> [--range <range> | --from <year|date> [--to <year|date>]]";
1446
- const HISTORY_ALL_RANGE = `ALL gives the full history the source has, up to ${historyAllRangeYears()} years`;
1545
+ const HISTORY_ALL_RANGE = "ALL gives the whole history the source keeps, from its first bar, and says where that is";
1447
1546
  const HISTORY_YTD_RANGE = "YTD starts at the prior year's last close, the one year-to-date returns are measured from";
1448
1547
  /** Options people reach for to ask for dates, which history answers with --from and --to (or --start and --end). */
1449
1548
  const DATE_WINDOW_OPTIONS = new Set(["--since", "--until", "--date", "--start-date", "--end-date"]);
1450
- /** Options people reach for to pick a bar size, which history derives from the range. */
1451
- const BAR_SIZE_OPTIONS = new Set(["--interval", "--resolution", "--bar", "--bars", "--bar-size", "--granularity", "--timeframe", "--frequency", "--freq", "--tick", "--ticks"]);
1549
+ /** Options people reach for to pick a bar size, which history takes as --interval. */
1550
+ const BAR_SIZE_OPTIONS = new Set(["--resolution", "--bar", "--bars", "--bar-size", "--granularity", "--timeframe", "--frequency", "--freq", "--tick", "--ticks"]);
1452
1551
 
1453
1552
  /** The symbol `history` was given: the first word that is not an option or the value after one. */
1454
1553
  function historySymbolArg(args: readonly string[]): string | undefined {
@@ -1484,10 +1583,61 @@ function historyOptionHint(flag: string, args: readonly string[]): string | null
1484
1583
  if (DATE_WINDOW_OPTIONS.has(flag)) {
1485
1584
  return `history takes dates as --from and --to (or --start and --end), each a year or a date (--from 2007 --to 2009), or a --range: ${HISTORY_RANGES.join(", ")}.`;
1486
1585
  }
1487
- if (BAR_SIZE_OPTIONS.has(flag)) return `history serves each --range in one bar size. ${subMinuteDataMessage(historySymbolArg(args))}`;
1586
+ if (BAR_SIZE_OPTIONS.has(flag)) return historyBarSizeHint(historySymbolArg(args));
1488
1587
  return null;
1489
1588
  }
1490
1589
 
1590
+ /** What `history` says to a bar size asked for, as an option or in a symbol's place: it picks one per range, and where finer bars are. */
1591
+ function historyBarSizeHint(symbol: string | undefined): string {
1592
+ return `history serves each --range in one bar size; --interval daily, weekly or monthly picks one. ${subMinuteDataMessage(symbol)}`;
1593
+ }
1594
+
1595
+ /** The bar sizes `--interval` takes, by the words people write them in. */
1596
+ const HISTORY_INTERVALS: Readonly<Record<string, HistoryInterval>> = {
1597
+ daily: "1d", day: "1d", "1d": "1d", d: "1d",
1598
+ weekly: "1wk", week: "1wk", "1wk": "1wk", "1w": "1wk", w: "1wk",
1599
+ monthly: "1mo", month: "1mo", "1mo": "1mo", mo: "1mo",
1600
+ };
1601
+
1602
+ /** A bar size `--interval` picks in place of the one the range or window comes in. */
1603
+ type HistoryInterval = "1d" | "1wk" | "1mo";
1604
+
1605
+ /** `--interval daily|weekly|monthly`, the bar size every range and window is read in; null without it. */
1606
+ function takeHistoryInterval(args: string[], ctx: Parameters<CliCommandDef["execute"]>[1]): HistoryInterval | null {
1607
+ const typed = takeOption(args, "--interval");
1608
+ if (typed == null) return null;
1609
+ const interval = HISTORY_INTERVALS[typed.trim().toLowerCase()];
1610
+ // An intraday size says where intraday bars are, as one typed in a symbol's place does.
1611
+ if (!interval) ctx.fail(`--interval is daily, weekly or monthly, not "${typed}".`, historyBarSizeHint(historySymbolArg(args)));
1612
+ return interval!;
1613
+ }
1614
+
1615
+ /** The window a range reaches back over, ending today: what `--interval` reads it as, ALL over every year a source keeps. */
1616
+ function rangePriceWindow(range: TimeRange, now = new Date()): PriceWindow {
1617
+ const from = range === "ALL" ? calendarMonthsBefore(now, ALL_HISTORY_REACH_MONTHS) : subtractTimeRange(now, range);
1618
+ return { from: from.toISOString().slice(0, 10), to: now.toISOString().slice(0, 10) };
1619
+ }
1620
+
1621
+ /**
1622
+ * A bar size typed in a symbol's place (`history GC=F 1s`, `30s`, `1m`,
1623
+ * `4h`, `tick`), which no listing is: `history GC=F 1s` printed a year of
1624
+ * daily bars and a row for a ticker 1S. False for any other word.
1625
+ */
1626
+ function barSizeTypedAsSymbol(entry: string): boolean {
1627
+ return isSubMinuteInterval(entry) || /^\s*\d+\s*(m|mins?|minutes?|h|hrs?|hours?)\s*$/i.test(entry);
1628
+ }
1629
+
1630
+ /**
1631
+ * Fails `history` on a bar size typed in a symbol's place, with where finer
1632
+ * bars are; `1m`, which also reads as a month, names that range too.
1633
+ */
1634
+ function failHistoryBarSize(entry: string, args: readonly string[], ctx: Parameters<CliCommandDef["execute"]>[1]): never {
1635
+ const symbol = args.find((arg) => arg !== entry && !barSizeTypedAsSymbol(arg) && !rangeTypedAsSymbol(arg));
1636
+ const range = rangeTypedAsSymbol(entry);
1637
+ const what = range ? `reads as a bar size or a range, not a symbol (a range is --range ${range})` : "is a bar size, not a symbol";
1638
+ return ctx.fail(`"${entry}" ${what}.`, historyBarSizeHint(symbol));
1639
+ }
1640
+
1491
1641
  /** "Asked from 1990-01-01, data starts 1995-01-03 (first available bar)" when the bars start over a week into the window. */
1492
1642
  function windowHistoryNotes(window: PriceWindow, rows: readonly { date: string }[]): string[] {
1493
1643
  const first = rows[0]?.date.slice(0, 10);
@@ -1503,10 +1653,11 @@ function ytdHistoryNotes(rows: readonly { date: string }[]): string[] {
1503
1653
  return first && last && first > `${Number(last.slice(0, 4)) - 1}-12-31` ? [`Asked YTD, data starts ${first} (first available bar)`] : [];
1504
1654
  }
1505
1655
 
1506
- /** What `history` was asked for: a range, or a window of dates in its place. */
1656
+ /** What `history` was asked for: a range, or a window of dates in its place, and the bar size `--interval` picked. */
1507
1657
  interface HistoryAsk {
1508
1658
  range: HistoryRange;
1509
1659
  window: PriceWindow | null;
1660
+ interval: HistoryInterval | null;
1510
1661
  }
1511
1662
 
1512
1663
  /** One listing's bars as `history` prints them, with what its heading, warnings and closing line say. */
@@ -1523,15 +1674,153 @@ interface ListingHistory {
1523
1674
  volume: HistoryVolume | null;
1524
1675
  freshness: ReportFreshness | undefined;
1525
1676
  notes: string[];
1677
+ /** A continuous future that follows the most traded month (GC=F), as its contract terms say: its bars are that month's. */
1678
+ mostTraded: boolean;
1679
+ /** `--currency`: what the prices were converted from and into, and the daily FX series read. */
1680
+ fx?: HistoryConversion;
1681
+ }
1682
+
1683
+ /** A history's prices converted into another currency at each bar's daily FX close (`convertListingHistory`). */
1684
+ interface HistoryConversion {
1685
+ /** The codes as the prices are written, a minor unit as such (GBp, ZAc). */
1686
+ from: string;
1687
+ to: string;
1688
+ /** The pairs whose daily closes were read, as `fx` names them (USD/ZAR), with the symbol they are read under (ZAR=X). */
1689
+ series: Array<{ pair: string; symbol: string }>;
1690
+ /** The first and last FX close read. */
1691
+ firstDate: string | null;
1692
+ lastDate: string | null;
1693
+ }
1694
+
1695
+ /**
1696
+ * `history --currency`'s code: three letters, the currency the prices are
1697
+ * converted into; null without the option. A minor unit (GBp, GBX, ZAc, ILA)
1698
+ * is that unit, as `fx` reads it, never upper-cased into a currency: GBp is
1699
+ * pence, GBP pounds.
1700
+ */
1701
+ function takeHistoryCurrency(args: string[], ctx: Parameters<CliCommandDef["execute"]>[1]): string | null {
1702
+ const typed = takeOption(args, "--currency");
1703
+ if (typed == null) return null;
1704
+ const minor = fxSubUnit(typed);
1705
+ const code = minor?.code ?? typed.trim().toUpperCase();
1706
+ const major = minor?.currency ?? code;
1707
+ if (!dailyFxLeg(major) && major !== "USD") ctx.fail(`--currency takes a currency's code, such as USD: "${typed}" is none.`);
1708
+ return code;
1709
+ }
1710
+
1711
+ /**
1712
+ * `history --currency USD`: each bar's prices converted from the listing's
1713
+ * currency at the daily FX close of its date, the close before it on a day
1714
+ * with none (a Sunday bar on Tadawul), never a rate of another week. A price
1715
+ * in a minor unit (pence, GBp or GBX; cents, ZAc; agorot, ILA) is read as its
1716
+ * fraction of the major currency, whose closes are read, and a minor unit
1717
+ * converted into is the same fraction: 115.8 GBp is £1.158, never 115.8
1718
+ * pounds, and GBp into GBP is no FX at all. A bar
1719
+ * still forming is converted at the latest close. Each row keeps its rate,
1720
+ * that close's date and its own close in `fxRate`, `fxDate` and
1721
+ * `localClose`, and a warning names the FX series read. Volume stays in
1722
+ * shares. Daily, weekly and monthly bars of a listing priced in a currency
1723
+ * only: index points, a pair's rate and intraday bars are refused. A history
1724
+ * already in the currency is as served.
1725
+ */
1726
+ async function convertListingHistory(
1727
+ history: ListingHistory,
1728
+ to: string,
1729
+ market: MarketContext,
1730
+ ctx: Parameters<CliCommandDef["execute"]>[1],
1731
+ ): Promise<ListingHistory> {
1732
+ const { unit } = history;
1733
+ const from = unit.kind === "currency" ? unit.currency : null;
1734
+ if (!from) {
1735
+ ctx.fail(`--currency converts prices in a currency; ${history.listing.key} is in ${unit.unit ?? "no stated unit"}.`);
1736
+ }
1737
+ if (history.intraday) ctx.fail("--currency converts daily, weekly and monthly bars at each date's daily FX close: give a range of a month or longer.");
1738
+ // Each side as its major currency and how many of its unit make one (GBp: GBP, 100).
1739
+ const fromUnit = resolveCurrencyUnit(from), toUnit = resolveCurrencyUnit(to);
1740
+ if ((fromUnit.currency === toUnit.currency && fromUnit.divisor === toUnit.divisor) || history.data.length === 0) return history;
1741
+ const client = market.fxHistory ?? apiClient;
1742
+ const since = history.data[0]!.date.slice(0, 10);
1743
+ // Pence into pounds is no FX: the same currency's closes cancel.
1744
+ const sameCurrency = fromUnit.currency === toUnit.currency;
1745
+ const codes = sameCurrency ? [] : [...new Set([fromUnit.currency, toUnit.currency].filter((code) => code !== "USD"))];
1746
+ const unread = codes.filter((code) => !dailyFxLeg(code));
1747
+ if (unread.length > 0) ctx.fail(`No daily FX closes for ${unread.join(" or ")} to convert ${history.listing.key} into ${to}.`);
1748
+ const legs = await Promise.all(codes.map(async (code) => {
1749
+ try {
1750
+ return [code, await loadDailyFxCloses(code, since, client)] as const;
1751
+ } catch (error) {
1752
+ return ctx.fail(`The daily ${code} FX closes could not be read to convert ${history.listing.key} into ${to}.`, errorMessage(error) ?? undefined);
1753
+ }
1754
+ }));
1755
+ const closes = new Map(legs);
1756
+ const venue = history.identity.exchange || undefined;
1757
+ const now = Date.now();
1758
+ const usdPer = (code: string, date: string) => code === "USD" || sameCurrency ? { date, rate: 1 } : fxCloseOnOrBefore(closes.get(code)!, date);
1759
+ // A minor unit is its fraction of the major currency's rate: a price in pence is a hundredth of one in pounds.
1760
+ const units = toUnit.divisor / fromUnit.divisor;
1761
+ const used: string[] = [];
1762
+ const data = history.data.map((row): HistoryRow => {
1763
+ // A week's or month's close is its last session's.
1764
+ const day = barCloseSession(row.interval, row.date, venue, now);
1765
+ const fromRate = usdPer(fromUnit.currency, day), toRate = usdPer(toUnit.currency, day);
1766
+ const fxDate = codes.length === 0 ? null : fromRate && toRate ? [fromRate.date, toRate.date].sort()[0]! : null;
1767
+ const rate = fromRate && toRate ? fromRate.rate / toRate.rate * units : null;
1768
+ if (fxDate) used.push(fxDate);
1769
+ // To a millionth: past it a product of two prices is float noise.
1770
+ const convert = (value: number | null) => value == null || rate == null ? null : Math.round(value * rate * 1e6) / 1e6;
1771
+ return {
1772
+ ...row, open: convert(row.open), high: convert(row.high), low: convert(row.low), close: convert(row.close),
1773
+ currency: to, unit: to, fxRate: rate, fxDate, localClose: row.close,
1774
+ };
1775
+ });
1776
+ const series = codes.map((code) => {
1777
+ const leg = dailyFxLeg(code)!;
1778
+ return { pair: leg.invert ? `USD/${code}` : `${code}/USD`, symbol: leg.instrument.symbol };
1779
+ });
1780
+ const sorted = [...used].sort();
1781
+ const fx: HistoryConversion = { from: from!, to, series, firstDate: sorted[0] ?? null, lastDate: sorted.at(-1) ?? null };
1782
+ return {
1783
+ ...history, data, fx,
1784
+ unit: { kind: "currency", currency: to, unit: currencyUnitLabel(to, { ofMajor: true }) },
1785
+ // Printed as prices in the currency are: cents, and four places under one unit.
1786
+ decimals: Math.max(...data.map((row) => row.close ?? 0)) >= 1 ? 2 : 4,
1787
+ notes: [historyConversionNote(fx, data), ...history.notes],
1788
+ };
1789
+ }
1790
+
1791
+ /**
1792
+ * The line a converted history says first: "Prices in USD, converted from ZAR
1793
+ * at each date's daily close of USD/ZAR (ZAR=X), 2026-10-12 to 2026-11-10;
1794
+ * the 2026-11-11 bar at the 2026-11-10 close." A bar no close was found for
1795
+ * is said too.
1796
+ */
1797
+ function historyConversionNote(fx: HistoryConversion, rows: readonly HistoryRow[]): string {
1798
+ const to = currencyUnitLabel(fx.to, { ofMajor: true }), from = currencyUnitLabel(fx.from, { ofMajor: true });
1799
+ // A minor unit of the same currency (GBp into GBP) is its fraction, read at no FX close.
1800
+ if (fx.series.length === 0) {
1801
+ const [fromUnit, toUnit] = [resolveCurrencyUnit(fx.from), resolveCurrencyUnit(fx.to)];
1802
+ const [many, one] = fromUnit.divisor > toUnit.divisor ? [fx.from, fx.to] : [fx.to, fx.from];
1803
+ return `Prices in ${to}, converted from ${from} at ${Math.max(fromUnit.divisor, toUnit.divisor) / Math.min(fromUnit.divisor, toUnit.divisor)} ${many} to 1 ${one}.`;
1804
+ }
1805
+ const pairs = fx.series.map(({ pair, symbol }) => `${pair} (${symbol})`).join(" and ");
1806
+ const span = fx.firstDate && fx.lastDate ? `, ${fx.firstDate === fx.lastDate ? fx.firstDate : `${fx.firstDate} to ${fx.lastDate}`}` : "";
1807
+ const last = rows.at(-1);
1808
+ const lastDay = last?.date.slice(0, 10);
1809
+ const latest = last?.interval === "1d" && last.fxDate && lastDay && last.fxDate < lastDay && last.partial
1810
+ ? `; the ${lastDay} bar, still forming, at the ${last.fxDate} close` : "";
1811
+ const missing = rows.filter((row) => row.fxRate == null).length;
1812
+ const blank = missing > 0 ? `; ${missing} ${missing === 1 ? "bar" : "bars"} with no FX close in the week before left blank` : "";
1813
+ return `Prices in ${to}, converted from ${from} at each date's daily close of ${pairs}${span}${latest}${blank}.`;
1526
1814
  }
1527
1815
 
1528
1816
  /** The command a listing that cannot be served is pointed back at: `history`, `history --range 5Y`. */
1529
- function historyCommand({ range, window }: HistoryAsk): string {
1817
+ function historyCommand({ range, window, interval }: HistoryAsk): string {
1530
1818
  // A window that runs to today retries to the day it is run on, not the one it was first run on.
1531
- return window ? `history --from ${window.from}${isPastPriceWindow(window) ? ` --to ${window.to}` : ""}` : range === "1Y" ? "history" : `history --range ${range}`;
1819
+ const asked = window ? `history --from ${window.from}${isPastPriceWindow(window) ? ` --to ${window.to}` : ""}` : range === "1Y" ? "history" : `history --range ${range}`;
1820
+ return interval ? `${asked} --interval ${BAR_INTERVAL_LABELS[interval]}` : asked;
1532
1821
  }
1533
1822
 
1534
- /** How long `history` waits for a future's contract terms to name its unit before using the catalog's. */
1823
+ /** How long `history` waits for a future's contract terms (its unit, how it rolls) before using the catalog's unit alone. */
1535
1824
  const HISTORY_PRICE_UNIT_WAIT_MS = 1_500;
1536
1825
  /** How long a yen pair's answer waits for Japan's intervention record, read beside it; the note is left out after. */
1537
1826
  const INTERVENTION_NOTE_WAIT_MS = 3_000;
@@ -1615,13 +1904,18 @@ async function loadListingHistory(
1615
1904
  const venues = lookups ? loadBareVenues(listing, market) : null;
1616
1905
  const { symbol, exchange } = listing.request;
1617
1906
  const context = { cacheMode: ctx.cliOptions.refresh ? "refresh" as const : "default" as const };
1618
- const load = () => window ? loadPriceWindowHistory(market.dataProvider, symbol, exchange, window, context)
1907
+ // --interval reads a range as the dates it reaches back over, in the bar size asked: ALL in daily bars is every day kept.
1908
+ const read = window ?? (ask.interval ? rangePriceWindow(loadRange) : null);
1909
+ const load = () => read ? loadPriceWindowHistory(market.dataProvider, symbol, exchange, read, context, ask.interval ?? undefined)
1619
1910
  : market.dataProvider.getPriceHistoryWithMetadata
1620
1911
  ? market.dataProvider.getPriceHistoryWithMetadata(symbol, exchange, loadRange, context)
1621
1912
  : market.dataProvider.getPriceHistory(symbol, exchange, loadRange, context).then((points): PriceHistoryResult => ({ points, resolution: null }));
1622
1913
  const quoteAnswer = loadListingQuoteAnswer(market.dataProvider, listing);
1623
- // A future's prices are in its contract's unit (US cents / bushel), as FUT and G spell it; asked beside the bars.
1624
- const priceUnit = isFuturesInstrument(symbol, null) ? settleWithin(loadFuturesPriceUnit(symbol), HISTORY_PRICE_UNIT_WAIT_MS) : Promise.resolve(null);
1914
+ // A future's contract terms, asked beside the bars: its prices are in its contract's unit (US cents / bushel), as FUT
1915
+ // and G spell it, and a continuous symbol on the most traded month (GC=F) says so, as `quote` does.
1916
+ const futures = isFuturesInstrument(symbol, null);
1917
+ const futuresTerms = futures ? settleWithin(loadFuturesContractTerms(symbol), HISTORY_PRICE_UNIT_WAIT_MS) : Promise.resolve(null);
1918
+ const priceUnit = futures ? futuresTerms.then((terms) => futuresPriceUnit(futuresBoardContract(symbol), terms)) : Promise.resolve(null);
1625
1919
  const quoted = quoteAnswer.then((answer) => answer.quote);
1626
1920
  // USDJPY=X's bars name Japan's interventions they span.
1627
1921
  const interventionPair = fxInterventionPair(symbol, exchange);
@@ -1630,7 +1924,7 @@ async function loadListingHistory(
1630
1924
  const request = { command: historyCommand(ask), noun: "history", ...(fate ? { fate } : {}) };
1631
1925
  const [answered, quote] = await Promise.all([
1632
1926
  loadForListing(listing, market, ctx, load, (loaded) => loaded.points.length === 0, request)
1633
- .catch((error) => failHistory(error, listing.key, ctx)),
1927
+ .catch((error) => failHistory(error, listing.key, ctx, window ? undefined : loadRange)),
1634
1928
  quoted,
1635
1929
  ]);
1636
1930
  // A bare symbol several companies list is never served from the one the data service picked, in a range or a window:
@@ -1641,7 +1935,7 @@ async function loadListingHistory(
1641
1935
  const lastTraded = quote || window ? null : noQuoteLastTraded(loaded);
1642
1936
  // The size the bars were served in, else the one asked for, never their spacing alone: B95 on SGX trades a few
1643
1937
  // times a month, and its daily bars a week or two apart are still daily (requestedBarSize).
1644
- const asked = window ? priceWindowInterval(window) : RANGE_HISTORY_RESOLUTION[loadRange];
1938
+ const asked = ask.interval ?? (window ? priceWindowInterval(window) : RANGE_HISTORY_RESOLUTION[loadRange]);
1645
1939
  const resolution = loaded.resolution ?? (dailyOrLongerBarSize(asked).barSize
1646
1940
  ? requestedBarSize(loaded.points.map((point) => new Date(point.date).getTime()), asked as "1d" | "1wk" | "1mo") : null);
1647
1941
  // While the session trades the day's bar is the quote's, whatever range the history was cut for (withSessionBar).
@@ -1654,6 +1948,7 @@ async function loadListingHistory(
1654
1948
  // Without a quote currency, the listing metadata research reads (as `ticker` does) may still state it.
1655
1949
  const listed = quote?.currency ? quote : await market.dataProvider.getQuoteMetadata?.(symbol, exchange).catch(logFailure("cli.commands-market", "Read quote metadata for history failed", null));
1656
1950
  const unit = historyUnit(listing.key, listed ?? quote, await priceUnit);
1951
+ const mostTraded = /=F$/i.test(listing.symbol) && (await futuresTerms)?.roll?.mostTraded === true;
1657
1952
  const traded = {
1658
1953
  listing: listing.key, exchange: quote?.listingExchangeName || exchange || undefined, instrumentType: quote?.instrumentType,
1659
1954
  };
@@ -1718,26 +2013,33 @@ async function loadListingHistory(
1718
2013
  const gaps = historyGapNote(data, traded);
1719
2014
  const coverage = window ? historyCoverageNotice(loaded.coverageStart, Date.parse(`${window.from}T00:00:00Z`), loaded.coverageNote)
1720
2015
  : range === "YTD" ? null : historyCoverageWarning(range, loaded);
2016
+ // A window before the listing's bars begin says where they do.
2017
+ const firstDay = data.length === 0 && window ? await historyFirstBarDay(market.dataProvider, symbol, exchange, context) : null;
1721
2018
  const notes = [
1722
2019
  ...lastTraded ? [`${noQuoteLastTradeNote(listing.symbol, lastTraded)}.`] : [],
1723
2020
  // A window the source has no bar in (a typo, a weekend, a listing that had not started) is said, not an empty table alone.
1724
- ...data.length === 0 ? [emptyHistoryNote(listing.key, ask)] : [],
2021
+ ...data.length === 0 ? [emptyHistoryNote(listing.key, ask, firstDay)] : [],
2022
+ // A read of the oldest dates failed: the bars stop short of the window, and say where.
2023
+ ...loaded.truncatedBefore ? [`Bars before ${loaded.truncatedBefore} could not be read; the history shown starts there. Try again for the rest.`] : [],
1725
2024
  // FB's bars are the fund listed there now; META's from 2021 are from when it was FB.
1726
2025
  ...fate ? listingFateNotes(await fate(), { served: data.length > 0, firstDate: data[0]?.date }) : [],
1727
2026
  ...lookups ? await listingChoiceNotes(listing, market, quote, venues) : [],
2027
+ // MOVE's bars are Corvex's, GOLD's Gold.com's: the index or future the code is typed for is named, as `quote` names it.
2028
+ ...ownedCodeNotes(listing, quote, "history"),
1728
2029
  // ALL says where the source's bars start (BTC-USD's in 2014-09), unless the coverage line does.
1729
2030
  ...window ? [...windowHistoryNotes(window, data), coverage ?? []]
1730
2031
  : range === "YTD" ? ytdHistoryNotes(data) : [...historyNotes(range, interval, data[0]?.date, Date.now(), coverage != null), coverage ?? []],
1731
2032
  // The status line says how far a bar still forming runs; the note is for the bars it does not name.
1732
- gaps ?? [], historyJumpNote(data) ?? [], historyFlagNote(data) ?? [], historyWickNote(data) ?? [], historyMissingVolumeNote(data) ?? [],
2033
+ gaps ?? [], historyJumpNote(data) ?? [], historyRescaleNote(data) ?? [], historyFlagNote(data) ?? [], historyOpenNote(data) ?? [], historyWickNote(data) ?? [],
2034
+ historyMissingVolumeNote(data) ?? [],
1733
2035
  historyVenueVolumeNote(data) ?? [],
1734
2036
  // NG=F's rows are November's to the 23rd and December's from the 26th: each roll named, and thin bars said.
1735
- historyRollNote(listing.symbol, data) ?? [], historyThinNote(data) ?? [],
2037
+ historyRollNote(listing.symbol, data, { mostTraded }) ?? [], historyThinNote(data) ?? [],
1736
2038
  historyBarStatusNote(forming ? served : data, { tradingDay: venueTradingDay(venue, Date.now()) }) ?? [],
1737
2039
  await interventionWindowNote(interventions, interventionPair, data) ?? [],
1738
2040
  ].flat();
1739
2041
  return {
1740
- listing, identity, unit, data, resolution, interval, intraday, volume, freshness, notes,
2042
+ listing, identity, unit, data, resolution, interval, intraday, volume, freshness, notes, mostTraded,
1741
2043
  decimals: historyPriceDecimals(data, listing.saved?.metadata.assetCategory, priceDivisor),
1742
2044
  };
1743
2045
  }
@@ -1769,18 +2071,26 @@ async function stoppedUsListingHistory(
1769
2071
  * A continuous future's history is the front month's, not the contract its
1770
2072
  * quote names now: NG=F's rows from before the roll are November's under a
1771
2073
  * quote of "Natural Gas Dec 2026". The heading says "Natural Gas front month"
1772
- * once the bars name their contracts.
2074
+ * once the bars name their contracts, and "Gold most traded month" for a
2075
+ * symbol that follows the most traded month (GC=F).
1773
2076
  */
1774
- function frontMonthIdentity(identity: ListingIdentity, symbol: string, rows: readonly HistoryRow[]): ListingIdentity {
2077
+ function frontMonthIdentity(identity: ListingIdentity, symbol: string, rows: readonly HistoryRow[], mostTraded: boolean): ListingIdentity {
1775
2078
  if (!/=F$/i.test(symbol) || !rows.some((row) => row.contract)) return identity;
1776
2079
  const board = futuresBoardContract(symbol);
1777
2080
  const name = board?.name ?? identity.name?.replace(/\s+[A-Z][a-z]{2}\s+\d{4}$/, "");
1778
- return name ? { ...identity, name: `${name} front month` } : identity;
2081
+ return name ? { ...identity, name: `${name} ${mostTraded ? "most traded month" : "front month"}` } : identity;
1779
2082
  }
1780
2083
 
1781
- /** What a listing with no bar for what was asked says, in a warning and in a list's status column. */
1782
- function emptyHistoryNote(symbol: string, { range, window }: HistoryAsk): string {
1783
- return window ? `No bars for ${symbol} from ${priceWindowText(window)}.` : `No bars for ${symbol} in ${range}.`;
2084
+ /**
2085
+ * What a listing with no bar for what was asked says, in a warning and in a
2086
+ * list's status column; a window before its first bar (`firstDay`) says
2087
+ * where its bars start: "No bars for KO from 1950 to 1951; KO's daily bars
2088
+ * start 1962-01-02."
2089
+ */
2090
+ function emptyHistoryNote(symbol: string, { range, window }: HistoryAsk, firstDay: string | null = null): string {
2091
+ if (!window) return `No bars for ${symbol} in ${range}.`;
2092
+ const starts = firstDay && firstDay > window.to ? `; ${symbol}'s daily bars start ${firstDay}` : "";
2093
+ return `No bars for ${symbol} from ${priceWindowText(window)}${starts}.`;
1784
2094
  }
1785
2095
 
1786
2096
  /** A bar's prices to the decimals its history prints them to. */
@@ -1825,6 +2135,7 @@ const HISTORY_FLAG_TEXT_COLUMN: CliResultColumn = {
1825
2135
  row.unsettled ? cliStyles.muted("unsettled") : "",
1826
2136
  row.roll && typeof row.contract === "string" ? cliStyles.muted(`roll to ${row.contract}`) : "",
1827
2137
  row.thin ? cliStyles.muted("thin") : "",
2138
+ row.settleOnly ? cliStyles.muted("settle only") : "",
1828
2139
  typeof row.status === "string" ? cliStyles.warning(row.status) : "",
1829
2140
  ].filter(Boolean).join(" "),
1830
2141
  };
@@ -1861,19 +2172,28 @@ async function runHistory(rawArgs: string[], ctx: Parameters<CliCommandDef["exec
1861
2172
  // --from 2007 --to 2009: those years' bars, daily up to five years, in place of a range ending now.
1862
2173
  const window = historyWindowOption(args, rangeOption, ctx);
1863
2174
  const range = parseRange(rangeOption, ctx);
2175
+ // --interval daily: the bar size every range and window is read in, ALL in daily bars included.
2176
+ const interval = takeHistoryInterval(args, ctx);
1864
2177
  const requestedExchange = takeOption(args, "--exchange");
2178
+ // `--currency USD`: every bar's prices at its date's daily FX close.
2179
+ const currencyAsked = takeHistoryCurrency(args, ctx);
1865
2180
  // One row a date and a close column a symbol, as a spreadsheet lays several series side by side.
1866
2181
  const wide = takeFlag(args, "--wide");
1867
2182
  // A continuous future stitched across its rolls, by difference unless `ratio` follows.
1868
2183
  const backAdjust = takeBackAdjust(args, ctx);
1869
2184
  // Stitching reads daily bars: five years, which come weekly as a range, are read as the window from five years back, which comes daily.
1870
- const ask: HistoryAsk = { range, window: window ?? (backAdjust && range === "5Y" ? yearsBackWindow(5) : null) };
2185
+ const ask: HistoryAsk = { range, window: window ?? (backAdjust && range === "5Y" && !interval ? yearsBackWindow(5) : null), interval };
1871
2186
  // A list from a file or standard input (`-`), or several symbols typed (AAPL MSFT, AAPL,MSFT), is one long table.
1872
2187
  // One argument with spaces stays one, as before: it may be a company's name.
1873
2188
  const file = args.some((arg) => arg === "--file" || arg.startsWith("--file=")) ? takeOption(args, "--file") ?? "" : undefined;
1874
2189
  // `history swiss franc` is the franc's pair, not SWISS (a Copenhagen listing) and FRANC.
1875
2190
  const currency = file != null || requestedExchange ? null : currencyNameStop(args, "history");
1876
2191
  if (currency) ctx.fail(currency.message, currency.details);
2192
+ // `history GC=F 1s` asks for bars of a second, which no listing named 1S has: it says where the finest bars are.
2193
+ // Whole arguments only: a quoted name ("3M Company") is one argument, and a name, never a bar size.
2194
+ const words = args.filter((arg, index) => !arg.startsWith("-") && !(index > 0 && args[index - 1]!.startsWith("--") && !args[index - 1]!.includes("=")));
2195
+ const barSize = file == null ? words.find((arg) => !/\s/.test(arg.trim()) && barSizeTypedAsSymbol(arg)) : undefined;
2196
+ if (barSize) failHistoryBarSize(barSize, words, ctx);
1877
2197
  if (wide || file != null || args.includes("-") || uniqueEntries(args).length > 1 || args.some((arg) => /[,;]/.test(arg))) {
1878
2198
  // `history CC=F 1mo` asks for a month of cocoa, not for cocoa and 1MO: it says which option reads it.
1879
2199
  const typedRange = rangeOption == null && !window ? args.find((arg) => rangeTypedAsSymbol(arg)) : undefined;
@@ -1889,17 +2209,19 @@ async function runHistory(rawArgs: string[], ctx: Parameters<CliCommandDef["exec
1889
2209
  ctx.fail(`"${typedRange}" reads as a range, not a symbol: give it as --range ${range}.`, `gloom history ${words.map(shell).join(" ")}`);
1890
2210
  }
1891
2211
  if (backAdjust) ctx.fail("--back-adjust stitches one continuous future, such as ES=F.", `Usage: gloom ${HISTORY_USAGE}`);
1892
- return runHistoryList(args, file, requestedExchange, ask, ctx, { wide });
2212
+ return runHistoryList(args, file, requestedExchange, ask, ctx, { wide, currency: currencyAsked });
1893
2213
  }
2214
+ if (backAdjust && currencyAsked) ctx.fail("--back-adjust stitches a future's prices in its contract's unit; --currency converts a listing's.");
1894
2215
  const raw = requireOneArg(args, HISTORY_USAGE, "symbol", ctx);
1895
2216
  await withMarketData(ctx, async (market) => {
1896
2217
  const listing = await requireCliListing(raw, requestedExchange, market, ctx);
1897
- const history = await loadListingHistory(listing, market, ctx, ask, { lookups: true }).catch((error: unknown) => {
2218
+ const loaded = await loadListingHistory(listing, market, ctx, ask, { lookups: true }).catch((error: unknown) => {
1898
2219
  // A word no source serves that names a currency (`history yen`) says which pair to ask for.
1899
2220
  const currency = !requestedExchange && isNoProviderError(error) ? currencyNameMiss(raw, "history") : null;
1900
2221
  if (currency) ctx.fail(currency.message, currency.details);
1901
2222
  throw error;
1902
2223
  });
2224
+ const history = currencyAsked ? await convertListingHistory(loaded, currencyAsked, market, ctx) : loaded;
1903
2225
  const { identity, unit, interval, intraday, volume, freshness } = history;
1904
2226
  // Raw stays the default; --back-adjust stitches the contracts at the rolls the warning names, and lists them.
1905
2227
  const stitched = backAdjust ? await backAdjustListingHistory(history, backAdjust, market, ctx) : null;
@@ -1914,9 +2236,16 @@ async function runHistory(rawArgs: string[], ctx: Parameters<CliCommandDef["exec
1914
2236
  // of a continuous future, never from one month's close to another's across a roll.
1915
2237
  // A yield (^TNX) falls and rises by its level, in bp, and its largest rise is said too.
1916
2238
  const yieldUnits = isYieldIndexSymbol(history.listing.symbol);
1917
- const contractDrawdown = historyContractDrawdown(data, yieldUnits ? "yield" : "return");
1918
- const drawdown = contractDrawdown?.drawdown ?? null;
1919
- const runUp = yieldUnits ? maxRunUp(data) : null;
2239
+ // A week's or month's close is dated by its last session (March 2026 is Tue 31 Mar), not the 1st its bar is dated by.
2240
+ const closes = interval === "1wk" || interval === "1mo"
2241
+ ? data.map((row) => ({ ...row, date: barCloseSession(interval, row.date, identity.exchange || undefined, Date.now()) }))
2242
+ : data;
2243
+ const contractDrawdown = historyContractDrawdown(closes, yieldUnits ? "yield" : "return");
2244
+ // A window's last week can close after the dates asked for (--to 2003, a week ending Fri 2 Jan 2004): measured to its end.
2245
+ const until = ask.window?.to;
2246
+ const drawdown = contractDrawdown ? measuredUntil(contractDrawdown.drawdown, until) : null;
2247
+ const rose = yieldUnits ? maxRunUp(closes) : null;
2248
+ const runUp = rose && measuredUntil(rose, until);
1920
2249
  const moveText = interval ? { basis: `${BAR_INTERVAL_LABELS[interval]} closes${contractDrawdown?.contract ? `, ${contractDrawdown.contract}` : ""}`, price,
1921
2250
  date: (text: string) => intraday ? formatUtcTime(text) : text.slice(0, 10) } : null;
1922
2251
  ctx.printResult({
@@ -1938,13 +2267,14 @@ async function runHistory(rawArgs: string[], ctx: Parameters<CliCommandDef["exec
1938
2267
  maxDrawdown: drawdown && contractDrawdown?.contract ? { ...drawdown, contract: contractDrawdown.contract } : drawdown,
1939
2268
  ...(runUp ? { maxRunUp: runUp } : {}),
1940
2269
  asOf: freshness?.asOf ?? null,
2270
+ ...(history.fx ? { converted: history.fx } : {}),
1941
2271
  ...(volume ? { volumeUnit: volume.unit, volumePeriod: interval === "1d" ? "UTC day" : interval } : {}),
1942
2272
  ...(stitched ? { backAdjust: { method: backAdjust, rolls: stitched.rolls, ...(stitched.unstitched.length > 0 ? { unstitched: stitched.unstitched } : {}) } } : {}),
1943
2273
  },
1944
2274
  ...(notes.length > 0 ? { warnings: notes } : {}),
1945
2275
  freshness,
1946
2276
  }, {
1947
- heading: [listingHeading(frontMonthIdentity(identity, history.listing.symbol, data)), cliStyles.muted(historyFacts(unit, data).join(" · ")),
2277
+ heading: [listingHeading(frontMonthIdentity(identity, history.listing.symbol, data, history.mostTraded)), cliStyles.muted(historyFacts(unit, data).join(" · ")),
1948
2278
  ...drawdown && moveText ? [cliStyles.muted(maxDrawdownText(drawdown, moveText))] : [],
1949
2279
  ...runUp && moveText ? [cliStyles.muted(maxRunUpText(runUp, moveText))] : []].join("\n"),
1950
2280
  dateKey: "date",
@@ -2179,7 +2509,7 @@ async function runHistoryList(
2179
2509
  exchange: string | undefined,
2180
2510
  ask: HistoryAsk,
2181
2511
  ctx: Parameters<CliCommandDef["execute"]>[1],
2182
- { wide = false }: { wide?: boolean } = {},
2512
+ { wide = false, currency = null }: { wide?: boolean; currency?: string | null } = {},
2183
2513
  ) {
2184
2514
  const usage = `Usage: gloom ${HISTORY_USAGE}`;
2185
2515
  await withMarketData(ctx, async (market) => {
@@ -2189,15 +2519,36 @@ async function runHistoryList(
2189
2519
  if (symbols.length === 0) ctx.fail(refused.length === 1 ? refused[0]!.message : `No history to read: ${refusedList(refused)} are not symbols.`, usage);
2190
2520
  // A long list is a batch, not a lookup: it skips the per-symbol venue and moved-company lookups, as `quote` does.
2191
2521
  const lookups = symbols.length <= MAX_CHOICE_LOOKUPS;
2192
- const listed = await mapWithConcurrency(symbols, HISTORY_LIST_CONCURRENCY, async (symbol): Promise<ListedHistory> => {
2522
+ // Words typed apart that name one company ("Elbit Systems") are its listing, as `quote` reads them. A list read
2523
+ // from a file or standard input, or past the lookups, is tickers: no word in it costs a quote to read as a name.
2524
+ const typedList = file === undefined && !args.includes("-") && !exchange;
2525
+ const read = await mapWithConcurrency(symbols, HISTORY_LIST_CONCURRENCY, async (symbol) => {
2193
2526
  try {
2194
- const listing = await resolveCliListing(symbol, exchange, market, { ownExchangeWins: true });
2195
- return { symbol, history: await loadListingHistory(listing, market, ctx, ask, { lookups }) };
2527
+ const listing = await resolveCliListing(symbol, exchange, market, { ownExchangeWins: true, companyWord: lookups && typedList });
2528
+ return { typed: symbol, listing };
2529
+ } catch (error) {
2530
+ return { typed: symbol, listing: null, error };
2531
+ }
2532
+ });
2533
+ const entries = typedList ? await joinCompanyNameWords(read, market) : read;
2534
+ const listed = await mapWithConcurrency(entries, HISTORY_LIST_CONCURRENCY, async (entry): Promise<ListedHistory> => {
2535
+ const symbol = entry.typed;
2536
+ try {
2537
+ if (!("joined" in entry) && !entry.listing) throw entry.error;
2538
+ const listing = "joined" in entry ? await resolveNamedListing(entry.joined, market) : entry.listing!;
2539
+ const loaded = await loadListingHistory(listing, market, ctx, ask, { lookups });
2540
+ return { symbol, history: currency ? await convertListingHistory(loaded, currency, market, ctx) : loaded };
2196
2541
  } catch (error) {
2197
2542
  const message = errorMessage(error) ?? `No history for ${symbol}`;
2198
2543
  return { symbol, error: isCliFailure(error) ? oneLineFailure(message, error.details) : message };
2199
2544
  }
2200
2545
  });
2546
+ // A word typed on the command line that is no ticker (`history GC=F banana`) is a mistake, refused as an unknown option is;
2547
+ // a list read from a file or standard input keeps a row for it, so one bad line does not lose the rest.
2548
+ if (file === undefined && !args.includes("-")) {
2549
+ const typo = refused[0]?.message ?? listed.flatMap((entry) => "error" in entry && notATickerSymbol(entry.error) ? [entry.error] : [])[0];
2550
+ if (typo) ctx.fail(typo, usage);
2551
+ }
2201
2552
  const served = listed.flatMap((entry) => "history" in entry && entry.history.data.length > 0 ? [entry.history] : []);
2202
2553
  // A symbol with no bars, whether its request failed or came back empty, is one row with the reason.
2203
2554
  const rows: HistoryListRow[] = listed.flatMap((entry) => "history" in entry
@@ -2360,7 +2711,7 @@ async function runFinancials(rawArgs: string[], ctx: Parameters<CliCommandDef["e
2360
2711
  if (sectionFlag && !tabular) ctx.fail("--section picks one table of --csv or --ndjson output.");
2361
2712
  if (sectionFlag && !section?.trim()) ctx.fail("--section needs a section title or number.");
2362
2713
  // Several symbols are a comparison, which RV draws side by side.
2363
- const compared = view === "valuation" ? comparedSymbols(args) : null;
2714
+ const compared = view === "valuation" && !typedCompanyName(args) ? comparedSymbols(args) : null;
2364
2715
  if (compared) {
2365
2716
  ctx.fail(`valuation takes one symbol; got ${compared.join(" ")}.`,
2366
2717
  `To compare their valuations side by side: gloom fn RV ${compared.join(",")}\nUsage: gloom valuation <symbol>`);
@@ -2380,8 +2731,9 @@ async function runFinancials(rawArgs: string[], ctx: Parameters<CliCommandDef["e
2380
2731
  listing.request.symbol, listing.request.exchange, { cacheMode: ctx.cliOptions.refresh ? "refresh" : "default" },
2381
2732
  ), undefined, { command: commandName, noun: commandName === "valuation" ? "valuation data" : commandName });
2382
2733
  // A converted TTM block at the rate `fx` reports, as `ticker` shows it; only the US dollar legs are read.
2734
+ // A withdrawn EV's bridge converts a balance sheet in another currency at our close on its date (withBalanceSheetRate).
2383
2735
  const financials = view === "statements" ? loaded
2384
- : await atReportTtmRate(loaded, createBaseConverter(market.dataProvider, "USD"));
2736
+ : await withBalanceSheetRate(await atReportTtmRate(loaded, createBaseConverter(market.dataProvider, "USD")), market.fxHistory ?? apiClient);
2385
2737
  // A trailing yield is measured from the cash history as DVD measures it, a forward yield dated ahead names the
2386
2738
  // declared distribution it annualizes (not in JSON), and one whose dividend stopped says so; read beside the listing notes.
2387
2739
  const distributions = view === "statements" ? null : loadDividendDistributions(
@@ -2793,7 +3145,7 @@ async function registrantUsExchange(market: MarketContext, symbol: string, regis
2793
3145
  return (venues.find((venue) => isUsListingExchange(venue.exchange)) ?? venues[0])?.exchange ?? null;
2794
3146
  }
2795
3147
 
2796
- /** ASX announcements as `filings` lists them for a listing that files nothing with the SEC. */
3148
+ /** ASX and HKEX announcements as `filings` lists them for a listing that files nothing with the SEC. */
2797
3149
  const ANNOUNCEMENT_COLUMNS = [
2798
3150
  { key: "date", header: "Released", format: (value: unknown) => typeof value === "string" ? `${value.slice(0, 16).replace("T", " ")} UTC` : "" },
2799
3151
  { key: "headline", header: "Headline", maxWidth: 60 },
@@ -2802,10 +3154,14 @@ const ANNOUNCEMENT_COLUMNS = [
2802
3154
  { key: "url", header: "URL", optional: true },
2803
3155
  ];
2804
3156
 
2805
- const ASX_ANNOUNCEMENTS = { source: "ASX company announcements", status: "not-a-feed", basis: "exchange announcements", oldest: null } as const;
3157
+ /** The source line of an exchange's announcements: "ASX company announcements", "HKEXnews announcements". */
3158
+ const exchangeAnnouncementsFreshness = (publisher: string) => ({
3159
+ source: publisher === "ASX" ? "ASX company announcements" : `${publisher} announcements`,
3160
+ status: "not-a-feed", basis: "exchange announcements", oldest: null,
3161
+ } as const);
2806
3162
 
2807
- function announcementRows(payload: ExchangeAnnouncementsPayload) {
2808
- return payload.announcements.map((item) => ({
3163
+ function announcementRows(payload: ExchangeAnnouncementsPayload, all: boolean) {
3164
+ return payload.announcements.filter((item) => all || !isRoutineReturn(item)).map((item) => ({
2809
3165
  date: item.date,
2810
3166
  headline: item.headline,
2811
3167
  type: item.types.join("; "),
@@ -2854,7 +3210,7 @@ async function runFilings(rawArgs: string[], ctx: Parameters<CliCommandDef["exec
2854
3210
  const choice = await listingChoiceNotes(listing, market, quote, venues);
2855
3211
  // A company on ASX that files nothing with the SEC lists its ASX announcements instead.
2856
3212
  if (identity && filings.length === 0 && !form && listsExchangeAnnouncements(identity.exchange)) {
2857
- await printExchangeAnnouncements(ctx, { resolved, count, choice, page: page! });
3213
+ await printExchangeAnnouncements(ctx, { resolved, count, choice, page: page!, all });
2858
3214
  return;
2859
3215
  }
2860
3216
  ctx.printResult({
@@ -2929,40 +3285,54 @@ function filingsFootnote(
2929
3285
  */
2930
3286
  async function printExchangeAnnouncements(
2931
3287
  ctx: Parameters<CliCommandDef["execute"]>[1],
2932
- input: { resolved: ListingIdentity; count: number; choice: string[]; page: ExchangeAnnouncementsPage },
3288
+ input: { resolved: ListingIdentity; count: number; choice: string[]; page: ExchangeAnnouncementsPage; all: boolean },
2933
3289
  ): Promise<void> {
2934
- const { resolved, count, choice, page } = input;
3290
+ const { resolved, count, choice, page, all } = input;
3291
+ const publisher = exchangeAnnouncementsPublisher(resolved.exchange) ?? resolved.exchange;
2935
3292
  const notice = noSecReportsNotice(resolved);
2936
- const pageLine = `${page.name}: ${page.url}`;
2937
3293
  let payload: ExchangeAnnouncementsPayload | null = null;
2938
3294
  let failure: string | null = null;
2939
3295
  try {
2940
- payload = await apiClient.getCloudExchangeAnnouncements({ symbol: resolved.symbol, exchange: resolved.exchange, limit: Math.min(count, 50) });
3296
+ // HKEX's routine returns are left out after the read, so its list is asked for whole: a buyback files one a day.
3297
+ const limit = all || publisher === "ASX" ? Math.min(count, 50) : 100;
3298
+ payload = await apiClient.getCloudExchangeAnnouncements({ symbol: resolved.symbol, exchange: resolved.exchange, limit });
2941
3299
  } catch (error) {
2942
- failure = `ASX announcements unavailable: ${error instanceof Error ? error.message : String(error)}`;
3300
+ failure = `${publisher} announcements unavailable: ${error instanceof Error ? error.message : String(error)}`;
2943
3301
  }
2944
- const rows = payload ? announcementRows(payload) : [];
3302
+ // The company's own page where Gloom Cloud has it (HKEXnews' search with the company filled in), else the venue's.
3303
+ const pageLine = `${page.name}: ${payload?.page || page.url}`;
3304
+ const listed = payload ? announcementRows(payload, all) : [];
3305
+ const rows = listed.slice(0, count);
3306
+ const routine = payload && !all ? payload.announcements.filter(isRoutineReturn).length : 0;
3307
+ const routineNote = routine > 0
3308
+ ? `Left out ${routine} routine ${routine === 1 ? "return" : "returns"} (next day disclosure and monthly returns) of the latest ${payload!.announcements.length}; --all lists them.`
3309
+ : null;
2945
3310
  const warnings = [
2946
3311
  ...choice,
2947
- ...payload?.stale ? ["ASX could not be reached; these are the announcements Gloom Cloud read last."] : [],
3312
+ ...payload?.stale ? [`${publisher} could not be reached; these are the announcements Gloom Cloud read last.`] : [],
2948
3313
  ...failure ? [failure] : [],
2949
3314
  ];
3315
+ // Only ASX flags price-sensitive announcements; the column is left out where the exchange flags none.
3316
+ const columns = rows.some((row) => typeof row.priceSensitive === "boolean")
3317
+ ? ANNOUNCEMENT_COLUMNS : ANNOUNCEMENT_COLUMNS.filter((column) => column.key !== "priceSensitive");
3318
+ const notes = [...routineNote ? [routineNote] : [], pageLine];
2950
3319
  ctx.printResult({
2951
3320
  data: rows,
2952
3321
  metadata: {
2953
- ...listingMetadata(resolved), secFilings: 0, announcementsPage: payload?.page ?? page.url,
3322
+ ...listingMetadata(resolved), secFilings: 0, announcementsPage: payload?.page || page.url,
2954
3323
  ...(payload ? { announcementsTotal: payload.total, announcementsRetrievedAt: payload.retrievedAt } : {}),
3324
+ ...(routine > 0 ? { routineReturnsHidden: routine } : {}),
2955
3325
  },
2956
- freshness: rowsFreshness(rows, { ...ASX_ANNOUNCEMENTS, observedKey: "date" }),
3326
+ freshness: rowsFreshness(rows, { ...exchangeAnnouncementsFreshness(publisher), observedKey: "date" }),
2957
3327
  ...(warnings.length > 0 ? { warnings } : {}),
2958
3328
  }, {
2959
3329
  heading: listingHeading(resolved),
2960
- ...(rows.length > 0 ? { summary: () => `${notice} Its latest ASX announcements:` } : {}),
3330
+ ...(rows.length > 0 ? { summary: () => `${notice} Its latest ${publisher} announcements:` } : {}),
2961
3331
  rows: () => rows,
2962
- columns: ANNOUNCEMENT_COLUMNS,
2963
- empty: `${failure ? notice : `${notice} ASX lists no announcements for it.`}\n${pageLine}`,
2964
- footnote: pageLine,
2965
- exportNotes: [notice, pageLine],
3332
+ columns,
3333
+ empty: `${failure ? notice : `${notice} ${publisher} lists no announcements for it.`}\n${notes.join("\n")}`,
3334
+ footnote: notes.join("\n"),
3335
+ exportNotes: [notice, ...notes],
2966
3336
  exportIdentity: { symbolOrSeries: `${resolved.symbol}:${resolved.exchange}` },
2967
3337
  });
2968
3338
  }
@@ -3146,9 +3516,10 @@ async function runHolders(
3146
3516
  (found) => found.holders.length === 0,
3147
3517
  { command: commandName, noun: "holder data" },
3148
3518
  ).catch(async (error: unknown) => {
3149
- // A fund has no ownership breakdown: say so, and what reads it, rather than the source's NO_DATA.
3150
- const fund = await fundHoldersAnswer(listing.symbol, error, await quoted, apiClient);
3151
- if (fund) fail(fund.message, fund.details.join("\n") || undefined, NO_DATA_CODE);
3519
+ // A fund has no ownership breakdown, and a listing may have no holders on record: say so
3520
+ // (and what reads a fund) rather than the source's NO_DATA.
3521
+ const none = await noHoldersAnswer(listing.key, listing.request.exchange, error, await quoted, apiClient);
3522
+ if (none) fail(none.message, none.details.join("\n") || undefined, NO_DATA_CODE);
3152
3523
  throw error;
3153
3524
  }),
3154
3525
  quoted,
@@ -3298,6 +3669,8 @@ async function runAnalyst(rawArgs: string[], ctx: Parameters<CliCommandDef["exec
3298
3669
  },
3299
3670
  freshness: rowsFreshness(analystRows(data), {
3300
3671
  ...REPORTED_DATA, basis: "analyst ratings", observedKey: "date", oldest: null,
3672
+ // When Gloom Cloud read the targets and the mix, which carry no date of their own.
3673
+ ...(data.fetchedAt ? { retrievedAt: data.fetchedAt } : {}),
3301
3674
  }, { stale: data.stale === true }),
3302
3675
  ...(choice.length > 0 ? { warnings: choice } : {}),
3303
3676
  }, {
@@ -3411,8 +3784,10 @@ async function runOptions(rawArgs: string[], ctx: Parameters<CliCommandDef["exec
3411
3784
  cacheMode: refresh ? "refresh" : "default", adjustedOptions: true,
3412
3785
  }) };
3413
3786
  }
3787
+ // A command answers once, so it asks the service as a quote does; the chain saved earlier stands in only when
3788
+ // the request fails, and the closing line then says when it was saved.
3414
3789
  const cached = await market.dataProvider.getCachedQuery?.("getOptionsChain", [symbol, exchange, expiry, undefined])
3415
- .load({ force: refresh });
3790
+ .load({ force: true });
3416
3791
  return {
3417
3792
  result: cached,
3418
3793
  chain: cached?.value ?? await market.dataProvider.getOptionsChain(symbol, exchange, expiry, {
@@ -3473,8 +3848,9 @@ async function runOptions(rawArgs: string[], ctx: Parameters<CliCommandDef["exec
3473
3848
  const basisFields = optionsBasisFields(basis);
3474
3849
  const currency = [...chain.calls, ...chain.puts].find((contract) => contract.currency?.trim())?.currency.trim().toUpperCase()
3475
3850
  ?? quote?.currency ?? null;
3476
- // A failed refresh falls back to the stored chain, which can be days old.
3477
- const refreshWarning = result?.refreshError == null ? null
3851
+ // A failed refresh falls back to the stored chain, which can be days old. One that could not get through
3852
+ // (offline, a timeout) is a saved copy the closing line dates; any other failure is said here.
3853
+ const refreshWarning = result?.refreshError == null || isTransientFailure(result.refreshError) ? null
3478
3854
  : `Options refresh failed; showing the chain stored ${new Date(result.fetchedAt).toISOString()}`
3479
3855
  + (chain.asOf ? ` (last trade ${chain.asOf})` : "");
3480
3856
  const sessionWarning = refreshWarning ? null : priorSessionChainWarning(chain, identity.exchange, Date.now());
@@ -3584,7 +3960,7 @@ async function runOptions(rawArgs: string[], ctx: Parameters<CliCommandDef["exec
3584
3960
  // The contract symbol already carries the date, so this goes first when the table is narrow.
3585
3961
  { key: "expiration", header: "Expiry", optional: true, dropPriority: 2 },
3586
3962
  { key: "strike", header: "Strike", align: "right" },
3587
- { key: "last", header: "Last", align: "right" },
3963
+ { key: "last", header: "Last", align: "right", format: formatOptionLastCell },
3588
3964
  { key: "bid", header: "Bid", align: "right", format: (_value, row) => formatOptionQuoteCell(row, "bid") },
3589
3965
  { key: "ask", header: "Ask", align: "right", format: (_value, row) => formatOptionQuoteCell(row, "ask") },
3590
3966
  { key: "iv", header: "IV", align: "right", format: (value, row) => formatOptionIvCell(value, row) },
@@ -3627,6 +4003,26 @@ function readFxDate(value: string, ctx: Parameters<CliCommandDef["execute"]>[1])
3627
4003
  return date;
3628
4004
  }
3629
4005
 
4006
+ /**
4007
+ * What the source line says of a day's FX closes: when they were taken, on
4008
+ * the UTC clock and New York's (`daily FX close at 21:00 UTC, 17:00 ET`),
4009
+ * when the service says, as for the days it sums from hourly bars. An older
4010
+ * day is its source's own day bar, whose cutoff the source does not state
4011
+ * and which moves with it (21:00 UTC one season, 20:00 UTC another), so the
4012
+ * line says that rather than a time.
4013
+ */
4014
+ function fxCloseBasis(closedAt: ReadonlyArray<string | undefined>): string {
4015
+ if (closedAt.length === 0) return "daily FX close";
4016
+ if (closedAt.some((at) => !at)) return "daily FX close: the source's day bar, no cutoff time published";
4017
+ const clock = (at: string) => {
4018
+ const time = Date.parse(at);
4019
+ const newYork = zonedDateTimeParts(time, "America/New_York");
4020
+ const pad = (value: number) => String(value).padStart(2, "0");
4021
+ return `${new Date(time).toISOString().slice(11, 16)} UTC, ${pad(newYork.hour)}:${pad(newYork.minute)} ET`;
4022
+ };
4023
+ return `daily FX close at ${[...new Set(closedAt.map((at) => clock(at!)))].join(" and ")}`;
4024
+ }
4025
+
3630
4026
  /**
3631
4027
  * `fx <pair> --date <day>`: the rate at that day's daily FX closes, read as
3632
4028
  * a position's purchase-date cost reads them (`fxCloseOnDate`): each
@@ -3643,7 +4039,6 @@ async function runFxOnDate(
3643
4039
  ) {
3644
4040
  const { request, amount, toUsdByDefault } = parsed;
3645
4041
  const { currency, baseCurrency } = request;
3646
- const pair = `${currency}/${baseCurrency}`;
3647
4042
  const history = market.fxHistory ?? apiClient;
3648
4043
  const codes = [...new Set([currency, baseCurrency].filter((code) => code !== "USD"))];
3649
4044
  const legs = new Map<string, FxCloseReading>([["USD", { rate: 1, date }]]);
@@ -3676,26 +4071,30 @@ async function runFxOnDate(
3676
4071
  : describeFxRate(request, rate, closes[0]);
3677
4072
  // A cross is as old as its older close; a weekend or holiday reads the trading day before it.
3678
4073
  const closeDate = [...legs.values()].map((leg) => leg.date).sort()[0]!;
3679
- const converted = amount == null ? null : amount * rate;
4074
+ // When the closes were taken (17:00 New York), or that the source does not say: a central bank's fixing is another time.
4075
+ const basis = fxCloseBasis(codes.map((code) => legs.get(code)?.closedAt));
4076
+ // A minor unit (ZAc) is converted at its fraction of the major currency's close; the row is in the unit typed.
4077
+ const unitRate = fxUnitRate(request, rate);
4078
+ const converted = amount == null ? null : amount * unitRate;
3680
4079
  const row = {
3681
- currency, baseCurrency, rate, asOf: closeDate, stale: false, pair, inverse: 1 / rate, date,
4080
+ ...fxRowSides(request, rate), rate: unitRate, asOf: closeDate, stale: false, inverse: 1 / unitRate, date,
3682
4081
  ...(amount == null ? {} : { amount, converted }),
3683
4082
  };
3684
4083
  const warnings = [
3685
4084
  ...request.readAs ?? [],
3686
4085
  ...closeDate < date ? [`No daily close on ${date}, a weekend or market holiday: this is the close of ${closeDate}, the trading day before it.`] : [],
3687
4086
  ...toUsdByDefault && amount != null
3688
- ? [`No target currency given, so ${currency} is converted to USD; for another, write fx ${args[0]!.trim()} ${currency}/<to> --date ${date}.`]
4087
+ ? [`No target currency given, so ${fxSideCode(request, "currency")} is converted to USD; for another, write fx ${args[0]!.trim()} ${fxSideCode(request, "currency")}/<to> --date ${date}.`]
3689
4088
  : [],
3690
4089
  ];
3691
4090
  ctx.printResult({
3692
4091
  data: [row],
3693
4092
  // A past close is what was asked for, never stale.
3694
- freshness: rowsFreshness([], { status: "not-a-feed", basis: "daily FX close", asOf: closeDate }),
4093
+ freshness: rowsFreshness([], { status: "not-a-feed", basis, asOf: closeDate }),
3695
4094
  warnings: warnings.length > 0 ? warnings : undefined,
3696
4095
  }, {
3697
- text: () => amount == null ? rateLine : `${describeFxConversion(request, amount, rate)}\n${rateLine}`,
3698
- exportIdentity: { symbolOrSeries: pair, currencyOrUnit: `${baseCurrency} per ${currency}`, interval: "1day" },
4096
+ text: () => amount == null && !request.units ? rateLine : `${describeFxConversion(request, amount ?? 1, rate)}\n${rateLine}`,
4097
+ exportIdentity: { symbolOrSeries: row.pair, currencyOrUnit: `${row.baseCurrency} per ${row.currency}`, interval: "1day" },
3699
4098
  columns: [
3700
4099
  { key: "currency", header: "Currency" },
3701
4100
  { key: "baseCurrency", header: "Base" },
@@ -3713,6 +4112,18 @@ async function runFxOnDate(
3713
4112
  });
3714
4113
  }
3715
4114
 
4115
+ /**
4116
+ * The sides of an `fx` row as typed: a minor unit's code (ZAc/USD) where one
4117
+ * was, with the major pair its rate is read from beside it.
4118
+ */
4119
+ function fxRowSides(request: FxRequest, majorRate: number) {
4120
+ const currency = fxSideCode(request, "currency"), baseCurrency = fxSideCode(request, "baseCurrency");
4121
+ return {
4122
+ currency, baseCurrency, pair: `${currency}/${baseCurrency}`,
4123
+ ...request.units ? { majorPair: `${request.currency}/${request.baseCurrency}`, majorRate } : {},
4124
+ };
4125
+ }
4126
+
3716
4127
  /**
3717
4128
  * What one unit of `quote` (a forward's quote currency) is worth in the
3718
4129
  * reader's currency at spot, to show a carry in it: 1 when they are the same,
@@ -3782,6 +4193,11 @@ async function runFx(rawArgs: string[], ctx: Parameters<CliCommandDef["execute"]
3782
4193
  const { request, amount, toUsdByDefault } = parsed;
3783
4194
  const { currency, baseCurrency } = request;
3784
4195
  const pair = `${currency}/${baseCurrency}`;
4196
+ // A forward is a pair of currencies; pence or cents have none of their own.
4197
+ if (tenor && request.units) {
4198
+ const typed = `${fxSideCode(request, "currency")}/${fxSideCode(request, "baseCurrency")}`;
4199
+ ctx.fail(`Forwards are on currencies, not their minor units: ${typed} is quoted as ${pair}.`, `gloom fx ${pair} --forward ${forwardOption}`);
4200
+ }
3785
4201
  if (tenor && currency === baseCurrency) ctx.fail(`${pair} has no forward: both sides are ${currency}.`, `Usage: gloom ${FX_FORWARD_USAGE}`);
3786
4202
  // A carry is on an amount held: zero or less holds nothing, and a sign would turn who earns it around.
3787
4203
  if (tenor && amount != null && !(amount > 0)) {
@@ -3821,11 +4237,13 @@ async function runFx(rawArgs: string[], ctx: Parameters<CliCommandDef["execute"]
3821
4237
  const asOf = observation && Number.isFinite(observation.updatedAt) ? new Date(observation.updatedAt).toISOString() : null;
3822
4238
  // A rate older than its feed's delay is stale, as `quote` says of the same quote.
3823
4239
  const stale = observation?.stale === true;
3824
- const converted = amount == null ? null : amount * rate;
4240
+ // A minor unit (ZAc) is converted at its fraction of the major currency's rate; the row is in the unit typed.
4241
+ const unitRate = fxUnitRate(request, rate);
4242
+ const converted = amount == null ? null : amount * unitRate;
3825
4243
  // The day's move, as `quote` gives the pair's: against the previous daily close.
3826
4244
  const move = quoted ? fxQuoteRateMove(quoted) : null;
3827
4245
  const row = {
3828
- currency, baseCurrency, rate, asOf, stale, pair, inverse: 1 / rate,
4246
+ ...fxRowSides(request, rate), rate: unitRate, asOf, stale, inverse: 1 / unitRate,
3829
4247
  ...(move ? { changePercent: move.percent, previousClose: move.previousRate } : {}),
3830
4248
  ...(quoted ? { quotes: quoted.quotes.map(({ symbol }) => symbol), ...(quoted.viaUsd ? { via: "USD" } : {}) } : {}),
3831
4249
  ...(quoted?.derivedFrom ? { derived: true, derivedFrom: quoted.derivedFrom } : {}),
@@ -3941,7 +4359,7 @@ async function runFx(rawArgs: string[], ctx: Parameters<CliCommandDef["execute"]
3941
4359
  // A currency typed as its name (yen) says which code it was read as.
3942
4360
  ...request.readAs ?? [],
3943
4361
  ...toUsdByDefault && amount != null
3944
- ? [`No target currency given, so ${currency} is converted to USD; for another, write fx ${args[0]!.trim()} ${currency}/<to>.`]
4362
+ ? [`No target currency given, so ${fxSideCode(request, "currency")} is converted to USD; for another, write fx ${args[0]!.trim()} ${fxSideCode(request, "currency")}/<to>.`]
3945
4363
  : [],
3946
4364
  ...rateNotes,
3947
4365
  ];
@@ -3966,12 +4384,13 @@ async function runFx(rawArgs: string[], ctx: Parameters<CliCommandDef["execute"]
3966
4384
  ctx.printResult({ data: [peso ? { ...row, ...pesoDollarRatesJson(peso) } : row], freshness, warnings: warnings.length > 0 ? warnings : undefined }, {
3967
4385
  // The conversion, then the rate it used; the source line under it dates that rate.
3968
4386
  text: () => [
3969
- ...amount == null ? [] : [describeFxConversion(request, amount, rate)],
4387
+ // A minor unit says what one of it is, the conversion's step to its major currency, without an amount too.
4388
+ ...amount == null && !request.units ? [] : [describeFxConversion(request, amount ?? 1, rate)],
3970
4389
  rateText,
3971
4390
  ...peso ? pesoDollarRateLines(peso) : [],
3972
4391
  ].join("\n"),
3973
4392
  // The rate is the base currency's price of one unit of the other, at the latest quote of each leg: USD per ZAR.
3974
- exportIdentity: { symbolOrSeries: pair, currencyOrUnit: `${baseCurrency} per ${currency}`, interval: quoted?.derivedFrom ? `derived from ${quoted.derivedFrom}` : "spot" },
4393
+ exportIdentity: { symbolOrSeries: row.pair, currencyOrUnit: `${row.baseCurrency} per ${row.currency}`, interval: quoted?.derivedFrom ? `derived from ${quoted.derivedFrom}` : "spot" },
3975
4394
  columns: [
3976
4395
  { key: "currency", header: "Currency" },
3977
4396
  { key: "baseCurrency", header: "Base" },
@@ -4001,7 +4420,7 @@ async function runEarnings(rawArgs: string[], ctx: Parameters<CliCommandDef["exe
4001
4420
  await withCliServices(ctx, async (services) => {
4002
4421
  const symbols = await readSymbols(entries, services.dataProvider);
4003
4422
  const listings = await Promise.all(symbols.map((symbol) => requireCliListing(
4004
- symbol, exchangeOption, services, ctx, { ownExchangeWins: symbols.length > 1 },
4423
+ symbol, exchangeOption, services, ctx, { ownExchangeWins: symbols.length > 1, companyWord: symbols.length <= MAX_CHOICE_LOOKUPS },
4005
4424
  )));
4006
4425
  const keys = listings.map((listing) => listing.key);
4007
4426
  // Each bare symbol's venues cost a search, so a long list (a portfolio check, not a lookup) names none.
@@ -4038,14 +4457,18 @@ async function runEarnings(rawArgs: string[], ctx: Parameters<CliCommandDef["exe
4038
4457
  return listed ? earningsChoiceNote(listing, eventOf(listing), await listed) : null;
4039
4458
  })),
4040
4459
  ]);
4041
- // A listing at home the calendar has no date for is named as well: a list never drops a symbol unsaid.
4042
- const undated = undatedListingsNote(listings.filter((listing) => !isListingAbroad(listing) && !eventOf(listing)));
4460
+ // A listing at home the calendar has no date for is named as well, with when it last reported: a list never
4461
+ // drops a symbol unsaid.
4462
+ const homeUndated = listings.filter((listing) => !isListingAbroad(listing) && !eventOf(listing));
4463
+ const lastReported = new Map(await Promise.all(homeUndated.slice(0, MAX_CHOICE_LOOKUPS)
4464
+ .map(async (listing) => [listing.key, await lastReportedDay(services.dataProvider, listing, today)] as const)));
4465
+ const undated = undatedListingsNote(homeUndated, lastReported);
4043
4466
  const noCalendar = [...abroadNotes, ...undated ? [undated] : []].join("\n");
4044
4467
  // Text prints the listings without a calendar under the table; other formats carry them as warnings.
4045
4468
  const warnings = [
4046
4469
  ...listings.flatMap(listingReadNotes),
4047
4470
  ...choiceNotes.filter((note): note is string => !!note),
4048
- ...ctx.cliOptions.format === "text" ? [] : [...abroadNotes, ...undated ? [undated] : []],
4471
+ ...ctx.cliOptions.format === "text" ? [] : [...abroadNotes, ...undated ? undated.split("\n") : []],
4049
4472
  ];
4050
4473
  ctx.printResult({
4051
4474
  data: events,
@@ -4101,18 +4524,20 @@ export const marketDataCliCommands: BuiltinCliCommandDef[] = [
4101
4524
  group: CLI_COMMAND_GROUPS.research,
4102
4525
  usage: [HISTORY_USAGE, "history --file <path> [--range <range> | --from <year|date> [--to <year|date>]]"],
4103
4526
  options: [
4104
- { flags: "--range <range>", description: `${HISTORY_RANGES.join(", ")} (default 1Y); ${HISTORY_YTD_RANGE}; ${HISTORY_ALL_RANGE}` },
4105
- { flags: "--from <year|date>, --start <year|date>", description: `${PRICE_WINDOW_FROM_HELP}. Up to five years come in daily bars, up to twenty weekly, longer monthly` },
4527
+ { flags: "--range <range>", description: `${HISTORY_RANGES.join(", ")} (default 1Y), or as other tools write them: ${HISTORY_RANGE_ALIASES}; ${HISTORY_YTD_RANGE}; ${HISTORY_ALL_RANGE}` },
4528
+ { flags: "--from <year|date>, --start <year|date>", description: `${PRICE_WINDOW_FROM_HELP}. Up to five years come in daily bars, up to twenty weekly, longer monthly, unless --interval picks the size` },
4529
+ { flags: "--interval <size>", description: "daily, weekly or monthly: the bar size for any range or window in place of the one it comes in, in text, CSV and JSON alike. --range ALL --interval daily is every daily bar kept, read in chunks" },
4106
4530
  { flags: "--to <year|date>, --end <year|date>", description: PRICE_WINDOW_TO_HELP },
4107
4531
  { flags: "--file <path>", description: "Read the symbols from a text or CSV file, one per line (- reads standard input), and write every symbol's bars in one table" },
4108
4532
  { flags: "--wide", description: "One row per date and one close column per symbol, its unit in the header, in place of one long table" },
4533
+ { flags: "--currency <code>", description: "Prices converted into that currency (USD) at each bar's date's daily FX close, the close before it on a day with none, the FX series named in a warning; each row keeps its rate, the close's date and its own close (fxRate, fxDate, localClose). Daily, weekly and monthly bars of a listing priced in a currency" },
4109
4534
  { flags: "--back-adjust [ratio]", description: "A continuous future (ES=F) stitched into one series at the rolls its bars name: every price before a roll moved by the gap between the two contracts that day (by difference, or scaled by their ratio with ratio), the rolls listed in a warning and in --json metadata.backAdjust. Daily bars, --range 5Y included; a roll whose contracts the source serves no bars of is left as traded and named. Raw front-month prices are the default" },
4110
4535
  EXCHANGE_OPTION,
4111
4536
  ],
4112
4537
  sections: [{
4113
4538
  title: "Bars",
4114
4539
  lines: [
4115
- `Each range comes in one bar size: ${historyIntervalsByRange()}. The line under the heading, and the --json metadata, give the currency, the bar size actually served, the first and last bar and the bar count. A warning says when the bars are coarser, or start later, than the range asked for, and for a coin, which trades every day, names each day it has no bar for.`,
4540
+ `Each range comes in one bar size, unless --interval picks one: ${historyIntervalsByRange()}. The line under the heading, and the --json metadata, give the currency, the bar size actually served, the first and last bar and the bar count. A warning says when the bars are coarser, or start later, than the range asked for, and for a coin, which trades every day, names each day it has no bar for.`,
4116
4541
  "A bar whose prices contradict each other (high below the open or close, or low above them) is left blank and flagged, such as high<open, with the count in a warning. A low under half the open and close, or a high over twice them, is left blank alone and flagged low<close/2 or high>2*open. --json rows carry currency, unit, interval and flag.",
4117
4542
  "A break in the series flags the bar after it, which keeps its prices: gap after more than three months with no bar (weeks for weekly, daily and intraday bars), jump when the close is over 100 times the one before or under a hundredth of it. A warning names each break, and the heading says the date the series runs unbroken from.",
4118
4543
  "The heading's last line is the max drawdown of the bars shown: the largest fall from a close to a later close, with the peak and the trough, their dates, and the date a close got back to the peak, if one did (maxDrawdown in --json). A yield (^TNX) reads it in bp, with its max run-up beside it: the largest rise from a close to a later close, found on its own (maxRunUp).",
@@ -4120,14 +4545,14 @@ export const marketDataCliCommands: BuiltinCliCommandDef[] = [
4120
4545
  }, {
4121
4546
  title: "CSV",
4122
4547
  lines: [
4123
- "Every --csv has one header, whatever the symbol, range or market state: Date, Open, High, Low, Close, Volume, Flag, Partial, Filled, Unsettled, Volume unit, Volume note, Venue volume, Volume venue, Volume basis, status, then symbol_or_series, currency_or_unit, interval, source and as_of. Prices are plain numbers in the unit currency_or_unit names: the currency, a pair's quote currency per base (JPY per USD for USDJPY=X) or index points. Partial, Filled and Unsettled are true or false, and status says why a row has no prices.",
4548
+ "Every --csv has one header, whatever the symbol, range or market state: Date, Open, High, Low, Close, Volume, Flag, Partial, Filled, Unsettled, Volume unit, Volume note, Venue volume, Volume venue, Volume basis, status, then symbol_or_series, currency_or_unit, interval, source, as_of and retrieved_at (when the export read the bars, an ISO time in UTC). Prices are plain numbers in the unit currency_or_unit names: the currency, a pair's quote currency per base (JPY per USD for USDJPY=X) or index points. Partial, Filled and Unsettled are true or false, and status says why a row has no prices.",
4124
4549
  "A continuous future whose bars name their contracts (NG=F) adds Contract, Roll and Thin before status: the contract per bar, and true or false for the bar it rolled at and a bar that traded far below those around it.",
4125
4550
  ],
4126
4551
  }, {
4127
4552
  title: "Several symbols",
4128
4553
  lines: [
4129
4554
  `history AAPL MSFT 000660.KS, or --file with one symbol a line (- reads standard input), writes every symbol's bars in one long table, ${HISTORY_LIST_CONCURRENCY} symbols loading at once. Each row names its symbol, its unit and the as-of of that symbol's bars in symbol_or_series, currency_or_unit and as_of.`,
4130
- "A symbol with no history is one row with its reason in status, and a warning names it; the command fails only when no symbol has any. --tail 5 keeps each symbol's newest five bars.",
4555
+ "A symbol with no history is one row with its reason in status, and a warning names it; the command fails only when no symbol has any. A word typed on the command line that is no ticker fails the command, and a bar size typed in a symbol's place (1s, 30s, 1m) says where the finest bars are; a list from --file keeps a row for a line that is no ticker. --tail 5 keeps each symbol's newest five bars.",
4131
4556
  "--wide sets the symbols side by side instead: one row per date, one close column per symbol headed with its unit (USDJPY=X close (JPY per USD)), a blank where a symbol has no bar that day. history USDJPY=X USDCHF=X EURCHF=X --csv --wide is a spreadsheet of the three closes; --tail 5 keeps the newest five dates.",
4132
4557
  ],
4133
4558
  }, {
@@ -4353,17 +4778,17 @@ export const marketDataCliCommands: BuiltinCliCommandDef[] = [
4353
4778
  },
4354
4779
  {
4355
4780
  name: "filings",
4356
- description: "Fetch recent SEC filings; a listing abroad gets its exchange's announcements page, and ASX's list",
4781
+ description: "Fetch recent SEC filings; a listing abroad gets its exchange's announcements page, and ASX's or HKEX's list",
4357
4782
  help: {
4358
4783
  group: CLI_COMMAND_GROUPS.companyData,
4359
4784
  usage: ["filings <symbol> [--count <n>] [--form <form>] [--all]"],
4360
4785
  options: [
4361
4786
  { flags: "--count <n>", description: "Number of filings (default 15)" },
4362
4787
  { flags: "--form <form>", description: "Only this form and its amendments, such as 10-K or 13D" },
4363
- { flags: "--all", description: "Also list what fn SEC leaves out by default: the pricing supplements and term sheets (424B2, FWP) a bank files for each structured note, and a fund trust's filings for its other funds" },
4788
+ { flags: "--all", description: "Also list what fn SEC leaves out by default: the pricing supplements and term sheets (424B2, FWP) a bank files for each structured note, and a fund trust's filings for its other funds; for an HKEX company, its next day disclosure and monthly returns" },
4364
4789
  EXCHANGE_OPTION,
4365
4790
  ],
4366
- examples: ["filings AAPL", "filings BHP:ASX", "filings NST.AX", "filings AAPL --count 40 --json", "filings CAR --form 13G"],
4791
+ examples: ["filings AAPL", "filings BHP:ASX", "filings NST.AX", "filings 9992:HKEX", "filings AAPL --count 40 --json", "filings CAR --form 13G"],
4367
4792
  },
4368
4793
  execute: runFilings,
4369
4794
  },