gloomberb 0.18.1 → 0.18.2

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 (307) hide show
  1. package/package.json +1 -1
  2. package/src/api-client/commodity-balances.ts +6 -0
  3. package/src/api-client/company-kpis.ts +9 -0
  4. package/src/api-client/crypto-markets.ts +9 -0
  5. package/src/api-client/data.ts +6 -5
  6. package/src/api-client/equity-screener.ts +2 -0
  7. package/src/api-client/types.ts +5 -0
  8. package/src/app/pane-runtime/plugin-bindings.ts +3 -1
  9. package/src/app/pane-runtime/ticker-open-runtime.ts +17 -5
  10. package/src/app/runtime/plugin-bindings.ts +6 -2
  11. package/src/brokers/logos.ts +66 -0
  12. package/src/brokers/profile-form.ts +3 -0
  13. package/src/brokers/remote-broker-adapter.ts +13 -3
  14. package/src/capabilities/index.ts +1 -1
  15. package/src/capabilities/service-capabilities.ts +7 -1
  16. package/src/cli/base-converter.ts +60 -18
  17. package/src/cli/commands/market.ts +281 -154
  18. package/src/cli/commands/news-search.ts +35 -8
  19. package/src/cli/commands/system.ts +35 -1
  20. package/src/cli/commands/ticker.ts +100 -50
  21. package/src/cli/currency-hints.ts +27 -0
  22. package/src/cli/fx-pair.ts +41 -4
  23. package/src/cli/glossary.ts +57 -4
  24. package/src/cli/helpers.ts +36 -3
  25. package/src/cli/index.ts +4 -1
  26. package/src/cli/known-gaps.ts +37 -1
  27. package/src/cli/listing-arg.ts +37 -2
  28. package/src/cli/pane-functions/catalog.ts +3 -1
  29. package/src/cli/pane-functions/discovery.ts +15 -1
  30. package/src/cli/pane-functions/dom.ts +9 -4
  31. package/src/cli/pane-functions/freshness.ts +4 -4
  32. package/src/cli/pane-functions/function-help.ts +27 -3
  33. package/src/cli/pane-functions/headless.ts +6 -5
  34. package/src/cli/pane-functions/index.ts +3 -2
  35. package/src/cli/pane-functions/lock-note.ts +7 -4
  36. package/src/cli/pane-functions/resolver.ts +2 -1
  37. package/src/cli/quote-answer.ts +179 -0
  38. package/src/cli/series-search.ts +2 -1
  39. package/src/cli/types.ts +4 -0
  40. package/src/components/chart/composite/composite-chart.tsx +11 -2
  41. package/src/components/chart/composite/format.ts +13 -1
  42. package/src/components/chart/composite/level-labels.ts +30 -0
  43. package/src/components/chart/composite/levels.ts +17 -6
  44. package/src/components/chart/composite/panel-surface.tsx +58 -8
  45. package/src/components/command-bar/routes/ticker-search/actions.ts +6 -0
  46. package/src/components/index.ts +2 -0
  47. package/src/components/layout/pane/content.tsx +16 -14
  48. package/src/components/layout/pane/footer/index.tsx +22 -3
  49. package/src/components/layout/pane/footer/model.ts +99 -4
  50. package/src/components/layout/pane/header-tabs.tsx +15 -1
  51. package/src/components/onboarding/onboarding-frame.tsx +9 -11
  52. package/src/components/onboarding/use-onboarding-broker-form.ts +5 -2
  53. package/src/components/onboarding/wizard-model.ts +10 -3
  54. package/src/components/ui/button.tsx +11 -4
  55. package/src/components/ui/choice-dialog.tsx +8 -5
  56. package/src/components/ui/display.tsx +11 -6
  57. package/src/components/ui/fields.tsx +100 -20
  58. package/src/components/ui/icon.tsx +6 -1
  59. package/src/components/ui/list-row-lines.tsx +87 -0
  60. package/src/components/ui/list-view.tsx +14 -0
  61. package/src/components/ui/logo-mark.tsx +64 -0
  62. package/src/components/ui/number-step.ts +54 -0
  63. package/src/components/ui/select-button.tsx +5 -4
  64. package/src/components/ui/select-field.tsx +3 -3
  65. package/src/components/ui/status.tsx +17 -3
  66. package/src/components/ui/tabs.tsx +9 -1
  67. package/src/components/ui/toggle.tsx +17 -3
  68. package/src/core/state/app/instrument.ts +8 -3
  69. package/src/data/config/store/normalize.ts +4 -1
  70. package/src/data/plugin-cache.ts +32 -6
  71. package/src/docs/snapshot.json +5 -5
  72. package/src/i18n/es.ts +9 -3
  73. package/src/i18n/ja.ts +9 -3
  74. package/src/i18n/ko.ts +9 -3
  75. package/src/i18n/zh-cn.ts +10 -4
  76. package/src/i18n/zh-tw.ts +10 -4
  77. package/src/market-data/commodity-names.ts +80 -0
  78. package/src/market-data/coordinator/auxiliary.ts +3 -1
  79. package/src/market-data/coordinator/chart.ts +3 -1
  80. package/src/market-data/futures-board.ts +38 -1
  81. package/src/market-data/futures-contract.ts +91 -0
  82. package/src/market-data/fx-closes.ts +78 -1
  83. package/src/market-data/market/change-basis.ts +219 -0
  84. package/src/market-data/market/format.ts +28 -12
  85. package/src/market-data/market/freshness.ts +38 -0
  86. package/src/market-data/market/status.ts +55 -9
  87. package/src/market-data/market/year-to-date.ts +46 -0
  88. package/src/market-data/quotes/contributions.ts +12 -0
  89. package/src/market-data/quotes/delisting.ts +34 -0
  90. package/src/market-data/quotes/live-valuation.ts +23 -0
  91. package/src/market-data/quotes/resolution.ts +8 -2
  92. package/src/market-data/tax-equivalent.ts +10 -2
  93. package/src/notifications/app-notifier.ts +2 -2
  94. package/src/notifications/notification-log.ts +8 -6
  95. package/src/plugins/builtin/alerts/cli.ts +26 -18
  96. package/src/plugins/builtin/alerts/headless.ts +1 -1
  97. package/src/plugins/builtin/alerts/index.tsx +13 -4
  98. package/src/plugins/builtin/attention/trending.tsx +8 -6
  99. package/src/plugins/builtin/backtest/client.ts +5 -2
  100. package/src/plugins/builtin/backtest/window.ts +16 -3
  101. package/src/plugins/builtin/broker-manager/add-flow.tsx +40 -8
  102. package/src/plugins/builtin/broker-manager/detail.tsx +26 -1
  103. package/src/plugins/builtin/broker-manager/index.tsx +20 -9
  104. package/src/plugins/builtin/broker-manager/model.ts +5 -0
  105. package/src/plugins/builtin/broker-manager/pane-actions.tsx +8 -1
  106. package/src/plugins/builtin/broker-manager/table.ts +5 -1
  107. package/src/plugins/builtin/broker-trading/account-picker.tsx +91 -0
  108. package/src/plugins/builtin/broker-trading/chart-levels.ts +54 -0
  109. package/src/plugins/builtin/broker-trading/command.ts +103 -0
  110. package/src/plugins/builtin/broker-trading/controller.ts +688 -0
  111. package/src/plugins/builtin/broker-trading/dock.tsx +182 -0
  112. package/src/plugins/builtin/broker-trading/headless.ts +76 -0
  113. package/src/plugins/builtin/broker-trading/index.tsx +77 -0
  114. package/src/plugins/builtin/broker-trading/order-feed.ts +383 -0
  115. package/src/plugins/builtin/broker-trading/orders-data.ts +133 -0
  116. package/src/plugins/builtin/broker-trading/orders.tsx +437 -0
  117. package/src/plugins/builtin/broker-trading/overview-orders.tsx +121 -0
  118. package/src/plugins/builtin/broker-trading/pane-model.ts +207 -0
  119. package/src/plugins/builtin/broker-trading/pane.tsx +505 -0
  120. package/src/plugins/builtin/broker-trading/strategy.ts +153 -0
  121. package/src/plugins/builtin/broker-trading/ticket-parts.tsx +117 -0
  122. package/src/plugins/builtin/broker-trading/ticket.tsx +573 -0
  123. package/src/plugins/builtin/buildout/data-runtime.ts +1 -1
  124. package/src/plugins/builtin/buildout/format.ts +1 -0
  125. package/src/plugins/builtin/buildout/model/index.ts +16 -7
  126. package/src/plugins/builtin/buildout/pane/index.tsx +3 -2
  127. package/src/plugins/builtin/buildout/pane/status.tsx +3 -3
  128. package/src/plugins/builtin/chart-composer/cli-options.ts +19 -0
  129. package/src/plugins/builtin/chart-composer/data-catalog-pane.tsx +2 -1
  130. package/src/plugins/builtin/chart-composer/headless-schema.ts +3 -3
  131. package/src/plugins/builtin/chart-composer/headless.ts +2 -1
  132. package/src/plugins/builtin/chart-composer/option-range.ts +39 -0
  133. package/src/plugins/builtin/chart-composer/pane.tsx +31 -11
  134. package/src/plugins/builtin/chart-composer/presets.ts +2 -2
  135. package/src/plugins/builtin/chart-composer/series-catalog.ts +4 -2
  136. package/src/plugins/builtin/chart-composer/shortcuts.ts +3 -3
  137. package/src/plugins/builtin/chart-composer/viewport-labels.ts +5 -2
  138. package/src/plugins/builtin/chat/index.tsx +1 -1
  139. package/src/plugins/builtin/chat/status-widget.tsx +1 -1
  140. package/src/plugins/builtin/chat/unread-inbox-pane.tsx +6 -1
  141. package/src/plugins/builtin/chat/unread-inbox.ts +1 -1
  142. package/src/plugins/builtin/commodity-balances/client.ts +6 -4
  143. package/src/plugins/builtin/commodity-balances/headless.ts +41 -7
  144. package/src/plugins/builtin/commodity-balances/index.tsx +19 -4
  145. package/src/plugins/builtin/commodity-balances/model.ts +22 -0
  146. package/src/plugins/builtin/commodity-balances/pane.tsx +36 -5
  147. package/src/plugins/builtin/company-kpis/client.ts +3 -2
  148. package/src/plugins/builtin/company-kpis/headless.ts +5 -7
  149. package/src/plugins/builtin/company-kpis/model.ts +85 -2
  150. package/src/plugins/builtin/company-kpis/pane.tsx +26 -12
  151. package/src/plugins/builtin/composite-plugins.ts +3 -2
  152. package/src/plugins/builtin/cot/headless.ts +1 -1
  153. package/src/plugins/builtin/cot/index.tsx +1 -1
  154. package/src/plugins/builtin/cot/model.ts +35 -12
  155. package/src/plugins/builtin/credit-boards/cdx-pane.tsx +2 -1
  156. package/src/plugins/builtin/credit-boards/sovr-pane.tsx +2 -1
  157. package/src/plugins/builtin/credit-conditions/index.tsx +2 -1
  158. package/src/plugins/builtin/crypto-board/client.ts +33 -2
  159. package/src/plugins/builtin/crypto-board/headless.ts +5 -2
  160. package/src/plugins/builtin/crypto-board/model.ts +28 -8
  161. package/src/plugins/builtin/dividend-yield/headless.ts +30 -8
  162. package/src/plugins/builtin/dividend-yield/provider-client.ts +3 -1
  163. package/src/plugins/builtin/earnings-calls/headless.ts +4 -4
  164. package/src/plugins/builtin/earnings-calls/lock-note.ts +12 -3
  165. package/src/plugins/builtin/econ/calendar-model.ts +35 -0
  166. package/src/plugins/builtin/econ/index.tsx +31 -4
  167. package/src/plugins/builtin/econ/print-watch.ts +279 -0
  168. package/src/plugins/builtin/equity-screener/headless.ts +20 -5
  169. package/src/plugins/builtin/equity-screener/model.ts +40 -2
  170. package/src/plugins/builtin/equity-screener/pane.tsx +24 -21
  171. package/src/plugins/builtin/estimate-revisions/headless.ts +3 -2
  172. package/src/plugins/builtin/estimate-revisions/lock-note.ts +29 -7
  173. package/src/plugins/builtin/exposure/client.ts +4 -1
  174. package/src/plugins/builtin/exposure/editor.tsx +3 -3
  175. package/src/plugins/builtin/exposure/evidence.ts +4 -1
  176. package/src/plugins/builtin/exposure/holdings.ts +3 -1
  177. package/src/plugins/builtin/exposure/pane.tsx +37 -16
  178. package/src/plugins/builtin/filing-events/index.tsx +9 -3
  179. package/src/plugins/builtin/futures/table.tsx +6 -3
  180. package/src/plugins/builtin/futures-curve/pane.tsx +2 -2
  181. package/src/plugins/builtin/insider/base-values.ts +72 -0
  182. package/src/plugins/builtin/insider/headless.ts +29 -4
  183. package/src/plugins/builtin/jobs/headless.ts +2 -2
  184. package/src/plugins/builtin/jobs/lock-note.ts +14 -3
  185. package/src/plugins/builtin/market-halts/model.ts +31 -6
  186. package/src/plugins/builtin/market-halts/pane.tsx +3 -0
  187. package/src/plugins/builtin/market-valuation/pane.tsx +2 -1
  188. package/src/plugins/builtin/members/pane.tsx +8 -3
  189. package/src/plugins/builtin/news/wire/feed-config.ts +29 -12
  190. package/src/plugins/builtin/news/wire/index.tsx +7 -2
  191. package/src/plugins/builtin/news/wire/news/preset-pane.tsx +11 -3
  192. package/src/plugins/builtin/news/wire/rss/cli.ts +3 -2
  193. package/src/plugins/builtin/news/wire/rss/source.ts +13 -4
  194. package/src/plugins/builtin/options/footer.ts +25 -20
  195. package/src/plugins/builtin/options/live-quotes.ts +33 -18
  196. package/src/plugins/builtin/options/view.tsx +77 -22
  197. package/src/plugins/builtin/options-calculator/pane.tsx +4 -2
  198. package/src/plugins/builtin/options-scenario/pane.tsx +41 -6
  199. package/src/plugins/builtin/portfolio-list/account-metrics.ts +3 -0
  200. package/src/plugins/builtin/portfolio-list/cli/render.ts +34 -10
  201. package/src/plugins/builtin/portfolio-list/headless.ts +1 -1
  202. package/src/plugins/builtin/portfolio-list/pane/data.ts +23 -1
  203. package/src/plugins/builtin/portfolio-list/pane/index.tsx +33 -14
  204. package/src/plugins/builtin/portfolio-list/settings.ts +20 -2
  205. package/src/plugins/builtin/portfolio-list/summary/index.tsx +12 -0
  206. package/src/plugins/builtin/portfolio-list/summary/totals.ts +24 -3
  207. package/src/plugins/builtin/primary-dealers/client.ts +137 -62
  208. package/src/plugins/builtin/primary-dealers/headless.ts +30 -5
  209. package/src/plugins/builtin/primary-dealers/index.tsx +3 -2
  210. package/src/plugins/builtin/primary-dealers/model.ts +179 -129
  211. package/src/plugins/builtin/primary-dealers/pane.tsx +135 -15
  212. package/src/plugins/builtin/research/analyst-model.ts +5 -1
  213. package/src/plugins/builtin/risk-factors/index.tsx +12 -3
  214. package/src/plugins/builtin/scanner/feed.ts +6 -1
  215. package/src/plugins/builtin/scanner/headless.ts +1 -1
  216. package/src/plugins/builtin/scanner/lock-note.ts +3 -2
  217. package/src/plugins/builtin/series-inventory.ts +1 -0
  218. package/src/plugins/builtin/shared/cloud-denied.ts +7 -6
  219. package/src/plugins/builtin/shared/cloud-upgrade.ts +10 -11
  220. package/src/plugins/builtin/shared/free-routes.ts +24 -0
  221. package/src/plugins/builtin/shared/headless-options.ts +11 -0
  222. package/src/plugins/builtin/shared/pro-lock-note.ts +89 -7
  223. package/src/plugins/builtin/shared/research-trading.tsx +62 -0
  224. package/src/plugins/builtin/social-mentions/headless.ts +1 -1
  225. package/src/plugins/builtin/social-mentions/lock-note.ts +1 -1
  226. package/src/plugins/builtin/themes/headless.ts +8 -2
  227. package/src/plugins/builtin/themes/model.ts +43 -10
  228. package/src/plugins/builtin/themes/pane.tsx +8 -6
  229. package/src/plugins/builtin/ticker-detail/overview/model.ts +44 -10
  230. package/src/plugins/builtin/ticker-detail/overview/option-contract.ts +64 -0
  231. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +82 -21
  232. package/src/plugins/builtin/ticker-detail/pane.tsx +21 -14
  233. package/src/plugins/builtin/ticker-detail/quote-footer.ts +5 -1
  234. package/src/plugins/builtin/ticker-detail/quote-monitor/card.tsx +37 -8
  235. package/src/plugins/builtin/time-sales/pane.tsx +2 -2
  236. package/src/plugins/builtin/trace-bonds/client.ts +14 -3
  237. package/src/plugins/builtin/trace-bonds/headless.ts +1 -1
  238. package/src/plugins/builtin/vol-surface/pane.tsx +2 -2
  239. package/src/plugins/builtin-editorial.ts +1 -1
  240. package/src/plugins/compat.ts +3 -0
  241. package/src/plugins/external-runtime.ts +5 -0
  242. package/src/plugins/loader.ts +6 -0
  243. package/src/plugins/plugin-icon.ts +61 -0
  244. package/src/plugins/registry/host-actions.ts +2 -1
  245. package/src/plugins/registry/index.ts +9 -1
  246. package/src/plugins/runtime/context.tsx +5 -0
  247. package/src/plugins/runtime/index.tsx +3 -0
  248. package/src/portfolio/column-values.ts +13 -4
  249. package/src/portfolio/cost-fx.ts +5 -28
  250. package/src/public/__snapshots__/public-api.test.ts.snap +5 -0
  251. package/src/public/broker.ts +8 -0
  252. package/src/public/market-data.ts +5 -0
  253. package/src/renderers/dom/desktop/control-styles.ts +7 -1
  254. package/src/renderers/dom/desktop/controls.tsx +39 -7
  255. package/src/renderers/dom/desktop/icons.tsx +14 -0
  256. package/src/renderers/dom/desktop/list-view.tsx +51 -19
  257. package/src/renderers/dom/desktop/menu.tsx +10 -1
  258. package/src/renderers/dom/desktop/select-field.tsx +8 -6
  259. package/src/renderers/dom/host/style.ts +6 -1
  260. package/src/renderers/dom/host/tabs.tsx +6 -0
  261. package/src/renderers/dom/styles.css +12 -5
  262. package/src/renderers/electrobun/bun/core-capabilities.ts +12 -0
  263. package/src/renderers/electrobun/bun/external-plugins.ts +3 -0
  264. package/src/renderers/electrobun/shared/protocol.ts +2 -0
  265. package/src/renderers/electrobun/view/broker-remote-client.ts +16 -0
  266. package/src/renderers/electrobun/view/external-plugins.ts +1 -0
  267. package/src/series/validate.ts +2 -2
  268. package/src/sources/gloomberb-cloud/index.ts +50 -17
  269. package/src/sources/gloomberb-cloud/normalizers.ts +4 -0
  270. package/src/sources/history-result.ts +3 -0
  271. package/src/sources/provider-errors.ts +3 -1
  272. package/src/sources/provider-router/history.ts +49 -6
  273. package/src/sources/provider-router/index.ts +2 -1
  274. package/src/state/app/activity.ts +13 -0
  275. package/src/sync/controller.ts +4 -0
  276. package/src/sync/core-contributors.ts +62 -11
  277. package/src/sync/local-only.ts +121 -0
  278. package/src/sync/react.ts +6 -0
  279. package/src/sync/types.ts +3 -0
  280. package/src/tickers/listing-fate.ts +27 -8
  281. package/src/tickers/search/index.ts +24 -3
  282. package/src/time-series/price-comparison.ts +35 -0
  283. package/src/time-series/resolve.ts +52 -11
  284. package/src/time-series/spec.ts +1 -1
  285. package/src/time-series/types.ts +5 -0
  286. package/src/types/broker.ts +56 -1
  287. package/src/types/config.ts +6 -0
  288. package/src/types/data-provider.ts +5 -1
  289. package/src/types/financials.ts +23 -0
  290. package/src/types/headless.ts +12 -2
  291. package/src/types/instrument.ts +4 -0
  292. package/src/types/plugin.ts +24 -6
  293. package/src/types/price-history.ts +6 -1
  294. package/src/types/trading.ts +67 -0
  295. package/src/ui/host.tsx +4 -0
  296. package/src/utils/base-currency.ts +108 -0
  297. package/src/utils/currency-names.ts +128 -0
  298. package/src/utils/currency-pair.ts +2 -1
  299. package/src/utils/currency-units.ts +32 -1
  300. package/src/utils/dom-screenshot.ts +22 -9
  301. package/src/utils/exchange-notation.generated.ts +360 -0
  302. package/src/utils/exchanges.ts +15 -322
  303. package/src/utils/format.ts +31 -1
  304. package/src/utils/instrument-identity.ts +38 -1
  305. package/src/utils/options.ts +46 -1
  306. package/src/utils/price-history.ts +4 -0
  307. package/src/utils/reported-money.ts +8 -4
@@ -45,6 +45,7 @@ import { isRoundTheClockCoin } from "../../utils/crypto-pair";
45
45
  import { canonicalExchange, canonicalTickerKey, parsePublicTickerKey } from "../../utils/exchanges";
46
46
  import { normalizePriceHistory, priceHistoryIntervalMs, reachesLatestSettledSession } from "../../utils/price-history";
47
47
  import { createProviderMiss, ProviderBusyError, providerMissReason } from "../provider-errors";
48
+ import { parseListingDelisting } from "../../market-data/quotes/delisting";
48
49
  import { isRetryableApiError } from "../../api-client/errors";
49
50
  import { assertSecRegistrantMatches } from "../sec-registrant";
50
51
  import { nonUsSecListingVenue } from "../../utils/sec";
@@ -251,9 +252,11 @@ function mapCloudPriceHistory(
251
252
  }
252
253
  // Sessions of daily bars the answer left out for a close at or below zero.
253
254
  const nonPositiveCloseDates = resolution === "1d" ? cloudNonPositiveCloseDates(response.omittedSessions) : undefined;
255
+ const delisting = parseListingDelisting(response.delisting);
254
256
  return {
255
257
  points,
256
258
  resolution,
259
+ ...(delisting ? { delisting } : {}),
257
260
  ...(session && matchingSource && matchingIdentity ? { session } : {}),
258
261
  ...(nonPositiveCloseDates ? { nonPositiveCloseDates } : {}),
259
262
  ...(coverageStart ? { coverageStart } : {}),
@@ -262,6 +265,28 @@ function mapCloudPriceHistory(
262
265
  };
263
266
  }
264
267
 
268
+ const DAY_MS = 86_400_000;
269
+ /** Listings Gloom Cloud said no longer trade, by listing key: the day after each one's last session. */
270
+ const delistedHistoryEnds = new Map<string, Date>();
271
+
272
+ /**
273
+ * Where a trailing window ends for a listing that no longer trades: the day
274
+ * after its last session, as a window ending now ends the day after today's.
275
+ * A window ending now would hold none of its bars, or only the last few.
276
+ */
277
+ function delistedHistoryEnd(response: CloudMarketResponse<unknown>, key: string): Date | null {
278
+ const delisting = parseListingDelisting(response.delisting);
279
+ if (!delisting) {
280
+ // The symbol trades again (another issuer took it): its windows end now.
281
+ delistedHistoryEnds.delete(key);
282
+ return null;
283
+ }
284
+ const end = new Date(Date.parse(`${delisting.lastTradeDate}T00:00:00Z`) + DAY_MS);
285
+ if (delistedHistoryEnds.size >= 1024) delistedHistoryEnds.clear();
286
+ delistedHistoryEnds.set(key, end);
287
+ return end;
288
+ }
289
+
265
290
  function cloudHistoryResolution(interval: string): ManualChartResolution | null {
266
291
  const canonical = canonicalHistoryInterval(interval);
267
292
  return (["1m", "5m", "15m", "30m", "1h", "1d", "1wk", "1mo"] as const)
@@ -549,14 +574,14 @@ export class GloomberbCloudProvider implements AssetDataProvider {
549
574
  // A successful batch can contain an expired cache fallback for only
550
575
  // one listing. Match the single-quote freshness boundary and let the
551
576
  // normal router retry that item without discarding its healthy peers.
552
- if (item.stale === true) {
577
+ // A listing that no longer trades has only that last quote: kept, flagged stale.
578
+ const delisted = !!parseListingDelisting(item.data?.delisting);
579
+ if (item.stale === true && !delisted) {
553
580
  return { target, quote: null, error: createProviderMiss(`Cloud quotes are stale for ${target.symbol}`) };
554
581
  }
555
582
  if ((item.status === "success" || item.status === "partial") && item.data) {
556
- return {
557
- target,
558
- quote: retainRequestedQuoteSymbol(mapQuote(item.data), target.symbol),
559
- };
583
+ const quote = retainRequestedQuoteSymbol(mapQuote(item.data), target.symbol);
584
+ return { target, quote: item.stale === true ? { ...quote, stale: true } : quote };
560
585
  }
561
586
  return {
562
587
  target,
@@ -778,19 +803,27 @@ export class GloomberbCloudProvider implements AssetDataProvider {
778
803
  const target = cloudInstrumentTarget(ticker, exchange);
779
804
  exchange = target.exchange ?? "";
780
805
  const interval = toCloudInterval(resolution);
781
- const endDate = new Date();
782
- const startDate = subtractTimeRange(endDate, bufferRange);
783
806
  const includeTime = /^\d+(min|h)$/i.test(interval);
784
- const { response, extendedHours } = await withCloudFallback(
785
- () => loadCloudHistory(interval, (session) => apiClient.getCloudHistory(target.symbol, exchange, {
786
- interval,
787
- startDate: formatCloudDateTime(startDate, includeTime, exchange),
788
- endDate: formatCloudHistoryEnd(endDate, includeTime, exchange),
789
- ...(session ? { session } : {}),
790
- }), _context),
791
- `Cloud chart data is unavailable for ${ticker}`,
792
- );
793
- return mapCloudPriceHistory(response, target.symbol, exchange, interval, startDate, endDate, extendedHours);
807
+ const listingKey = canonicalTickerKey(target.symbol, exchange);
808
+ const load = (endDate: Date) => {
809
+ const startDate = subtractTimeRange(endDate, bufferRange);
810
+ return withCloudFallback(
811
+ () => loadCloudHistory(interval, (session) => apiClient.getCloudHistory(target.symbol, exchange, {
812
+ interval,
813
+ startDate: formatCloudDateTime(startDate, includeTime, exchange),
814
+ endDate: formatCloudHistoryEnd(endDate, includeTime, exchange),
815
+ ...(session ? { session } : {}),
816
+ }), _context),
817
+ `Cloud chart data is unavailable for ${ticker}`,
818
+ ).then((answer) => ({ ...answer, startDate, endDate }));
819
+ };
820
+ // A listing that no longer trades is read up to its last session, not up to now.
821
+ const knownEnd = delistedHistoryEnds.get(listingKey);
822
+ const now = new Date();
823
+ let answer = await load(knownEnd ?? now);
824
+ const delistedEnd = delistedHistoryEnd(answer.response, listingKey);
825
+ if (delistedEnd ? delistedEnd.getTime() < answer.endDate.getTime() : knownEnd) answer = await load(delistedEnd ?? now);
826
+ return mapCloudPriceHistory(answer.response, target.symbol, exchange, interval, answer.startDate, answer.endDate, answer.extendedHours);
794
827
  }
795
828
 
796
829
  async getDetailedPriceHistory(
@@ -27,6 +27,7 @@ import { createProviderMiss } from "../provider-errors";
27
27
  import { reconcileQuoteDayRange } from "../../market-data/quotes/day-range";
28
28
  import { redactUnavailableFundamentals } from "../../utils/fundamentals";
29
29
  import { readWithdrawnObservations } from "../../utils/statement-gaps";
30
+ import { parseListingDelisting } from "../../market-data/quotes/delisting";
30
31
 
31
32
  export const GLOOMBERB_CLOUD_PROVIDER_ID = "gloomberb-cloud" as const;
32
33
 
@@ -94,6 +95,7 @@ export function mapQuote(
94
95
  : futuresBasis ?? quote.priceBasis;
95
96
  return withoutUndefinedFields(reconcileQuoteDayRange({
96
97
  ...quote,
98
+ delisting: parseListingDelisting(quote.delisting),
97
99
  priceBasis,
98
100
  priceObservation,
99
101
  currency: currency || quote.currency,
@@ -130,6 +132,8 @@ export function mapQuote(
130
132
  divisor,
131
133
  ),
132
134
  extendedSessionPrint: typeof quote.extendedSessionPrint === "boolean" ? quote.extendedSessionPrint : undefined,
135
+ // A coin's move over 24 hours, or none, when its previous close is undatable.
136
+ changeBasis: quote.changeBasis === "24h" || quote.changeBasis === "none" ? quote.changeBasis : undefined,
133
137
  overnightPrice: normalizePriceValueByDivisor(quote.overnightPrice, divisor),
134
138
  overnightChange: normalizePriceValueByDivisor(quote.overnightChange, divisor),
135
139
  overnightPriceKind: quote.overnightPriceKind === "trade" || quote.overnightPriceKind === "mark"
@@ -6,6 +6,7 @@ import { parseHistorySession } from "../market-data/history-session";
6
6
  import { canonicalHistoryInterval } from "./history-retention";
7
7
  import { historyCoverageNoteText, isHistoryCoverageDate } from "./history-coverage";
8
8
  import { readNonPositiveCloseDates } from "./history-omitted";
9
+ import { parseListingDelisting } from "../market-data/quotes/delisting";
9
10
 
10
11
  export type HistoryResultRequest =
11
12
  | { kind: "range"; range: TimeRange }
@@ -38,6 +39,7 @@ export function normalizeHistoryResult(
38
39
  // A contradictory declaration cannot be laundered into unknown legacy data.
39
40
  if (result.session != null && (!session || result.resolution === null)) return null;
40
41
  const nonPositiveCloseDates = readNonPositiveCloseDates(result.nonPositiveCloseDates);
42
+ const delisting = parseListingDelisting(result.delisting);
41
43
  return { points: result.points, resolution: result.resolution,
42
44
  ...(session ? { session } : {}),
43
45
  ...(nonPositiveCloseDates ? { nonPositiveCloseDates } : {}),
@@ -47,6 +49,7 @@ export function normalizeHistoryResult(
47
49
  ? { coverageNote: historyCoverageNoteText(result.coverageNote) } : {}),
48
50
  ...(result.extendedHours === true ? { extendedHours: true } : {}),
49
51
  ...(result.savedCopyBehind === true ? { savedCopyBehind: true as const } : {}),
52
+ ...(delisting ? { delisting } : {}),
50
53
  };
51
54
  }
52
55
 
@@ -1,4 +1,6 @@
1
- const PROVIDER_MISS_BRAND = Symbol("provider-miss");
1
+ // Registered, so a miss raised by another copy of this module (a plugin that
2
+ // resolved `gloomberb/market-data` from the source tree) is still recognized.
3
+ const PROVIDER_MISS_BRAND = Symbol.for("gloomberb.provider-miss");
2
4
  const EXPECTED_PROVIDER_MISS = /No data found|symbol may be delisted|"code":"Not Found"|No history for /i;
3
5
 
4
6
  const MAX_REASON_LENGTH = 200;
@@ -4,6 +4,7 @@ import { canonicalHistoryInterval, HistoryRetentionError, isHistoryRetentionErro
4
4
  type HistoryRecoveryCandidate, type HistoryRetention, type HistorySourceOutcome } from "../history-retention";
5
5
  import type { BrokerCandidate } from "./brokers";
6
6
  import { withBrokerTimeout } from "./brokers";
7
+ import type { BrokerHistoryOptions } from "../../types/broker";
7
8
  import type { DataProvider, MarketDataRequestContext } from "../../types/data-provider";
8
9
  import type { PriceHistoryResult } from "../../types/price-history";
9
10
  import { fetchHistoryResult, historyResolutionForInterval, InvalidHistoryResultError, normalizeHistoryResult } from "../history-result";
@@ -244,6 +245,29 @@ function mergeRequestHistoryGaps(
244
245
  })));
245
246
  }
246
247
 
248
+ /** The extended session goes only to a broker that serves it, and only when the chart asked. */
249
+ function brokerHistoryOptions(candidate: BrokerCandidate, context?: MarketDataRequestContext): [BrokerHistoryOptions] | [] {
250
+ return context?.historySession === "extended" && candidate.broker.extendedHoursHistory === true ? [{ session: "extended" }] : [];
251
+ }
252
+
253
+ /**
254
+ * With Ext hours on, a broker that serves only the regular session answers
255
+ * after the market-data providers, which may hold the extended session; it is
256
+ * still the last resort before nothing. Otherwise the order is unchanged.
257
+ */
258
+ function brokersForSession(candidates: BrokerCandidate[], context?: MarketDataRequestContext): { first: BrokerCandidate[]; last: BrokerCandidate[] } {
259
+ if (context?.historySession !== "extended") return { first: candidates, last: [] };
260
+ return {
261
+ first: candidates.filter((candidate) => candidate.broker.extendedHoursHistory === true),
262
+ last: candidates.filter((candidate) => candidate.broker.extendedHoursHistory !== true),
263
+ };
264
+ }
265
+
266
+ function isIntradayInterval(interval: string | undefined): boolean {
267
+ const ms = interval ? priceHistoryIntervalMs(interval) : null;
268
+ return ms != null && ms < 24 * 60 * 60 * 1000;
269
+ }
270
+
247
271
  function normalizeRequestResult(value: PriceHistoryResult, request: HistoryRequestDescriptor): PriceHistoryResult {
248
272
  // Only this router says a copy is behind, when it answers: neither a source
249
273
  // nor a stored copy can carry that verdict in.
@@ -254,8 +278,12 @@ function normalizeRequestResult(value: PriceHistoryResult, request: HistoryReque
254
278
  };
255
279
  }
256
280
 
257
- /** A copy fetched at `fetchedAt`, now for a source's answer. */
281
+ /**
282
+ * A copy fetched at `fetchedAt`, now for a source's answer. A listing that no
283
+ * longer trades is never behind: its bars end on its last session for good.
284
+ */
258
285
  function resultIsStale(value: PriceHistoryResult, symbol: string, exchange: string, fetchedAt: number, intervalMs?: number | null): boolean {
286
+ if (value.delisting) return false;
259
287
  return isPriceHistoryStaleForCurrentWindow(value.points, Date.now(), {
260
288
  symbol, exchange, intervalMs: intervalMs ?? (value.resolution ? priceHistoryIntervalMs(value.resolution) : undefined), session: value.session,
261
289
  fetchedAt,
@@ -425,6 +453,7 @@ export class ProviderRouterHistoryRoutes {
425
453
  bufferRange,
426
454
  resolution,
427
455
  context?.instrument ?? null,
456
+ ...brokerHistoryOptions(candidate, context),
428
457
  )
429
458
  : null,
430
459
  fetchProvider: (provider) => fetchHistoryResult(provider, ticker, exchange, { kind: "resolution", range: bufferRange, resolution }, context),
@@ -543,6 +572,7 @@ export class ProviderRouterHistoryRoutes {
543
572
  endDate,
544
573
  barSize,
545
574
  context?.instrument ?? null,
575
+ ...brokerHistoryOptions(candidate, context),
546
576
  )
547
577
  : null,
548
578
  fetchProvider: (provider) => fetchHistoryResult(provider, ticker, exchange, { kind: "detail", start: startDate, end: endDate, interval: barSize }, context),
@@ -551,10 +581,13 @@ export class ProviderRouterHistoryRoutes {
551
581
 
552
582
  private async executeHistoryRequest(request: HistoryRequestDescriptor): Promise<PriceHistoryResult> {
553
583
  const recovery = this.validateRecovery(request);
554
- const brokerCandidates = recovery ? [] : this.deps.getBrokerCandidatesForContext(request.context, false);
584
+ const { first: brokerCandidates, last: regularSessionBrokers } = brokersForSession(
585
+ recovery ? [] : this.deps.getBrokerCandidatesForContext(request.context, false), request.context);
586
+ // Cached copies rank in the order the sources are asked.
555
587
  const sourceKeys = recovery ? [recovery.sourceKey] : [
556
588
  ...brokerCandidates.map((candidate) => this.deps.brokerSourceKey(candidate)),
557
589
  ...this.deps.getProviderSourceKeys(),
590
+ ...regularSessionBrokers.map((candidate) => this.deps.brokerSourceKey(candidate)),
558
591
  ];
559
592
  const cachedRecords = listCachedResources<unknown>(
560
593
  this.deps.resources,
@@ -584,6 +617,7 @@ export class ProviderRouterHistoryRoutes {
584
617
  const currentWindow = request.requestedEnd === undefined || isCurrentHistoryWindow(new Date(request.requestedEnd));
585
618
  const now = Date.now();
586
619
  const fetchState = (record: { fetchedAt: number; value: PriceHistoryResult }, checkedAt?: number): CalendarHistoryFetchState => currentWindow
620
+ && !record.value.delisting
587
621
  ? calendarHistoryFetchState(record.value.points, record.fetchedAt, now, {
588
622
  symbol: target.symbol,
589
623
  exchange: target.exchange || request.target.exchange,
@@ -661,6 +695,12 @@ export class ProviderRouterHistoryRoutes {
661
695
  });
662
696
  if (providerResult && hasUsablePriceHistory(providerResult.value.points)) return withReportedGaps(providerResult.value);
663
697
  if (providerResult) reportedGaps.push(providerResult.value);
698
+ if (regularSessionBrokers.length) {
699
+ const regularResult = await withBrokerTimeout(this.fetchBrokerHistory(request, regularSessionBrokers, onUnavailable, attempts));
700
+ for (const sourceKey of [...attempts.pending]) recordHistoryOutcome(attempts, sourceKey, "timeout");
701
+ if (regularResult && hasUsablePriceHistory(regularResult.value.points)) return withReportedGaps(regularResult.value);
702
+ if (regularResult) reportedGaps.push(regularResult.value);
703
+ }
664
704
  // A failed refetch falls back in the same order the cache hit used, so a
665
705
  // failing request answers what the next request will: a current copy
666
706
  // first, else a saved copy short of the latest session, which beats an
@@ -722,10 +762,12 @@ export class ProviderRouterHistoryRoutes {
722
762
  private async refreshHistory(request: HistoryRequestDescriptor): Promise<void> {
723
763
  try {
724
764
  const recovery = this.validateRecovery(request);
725
- const brokerCandidates = recovery ? [] : this.deps.getBrokerCandidatesForContext(request.context, false);
726
- const brokerResult = await withBrokerTimeout(this.fetchBrokerHistory(request, brokerCandidates));
765
+ const { first, last } = brokersForSession(recovery ? [] : this.deps.getBrokerCandidatesForContext(request.context, false), request.context);
766
+ const brokerResult = await withBrokerTimeout(this.fetchBrokerHistory(request, first));
727
767
  if (brokerResult && hasUsablePriceHistory(brokerResult.value.points)) return;
728
- await this.fetchProviderHistory(request);
768
+ const providerResult = await this.fetchProviderHistory(request);
769
+ if (providerResult && hasUsablePriceHistory(providerResult.value.points)) return;
770
+ if (last.length) await withBrokerTimeout(this.fetchBrokerHistory(request, last));
729
771
  } catch (error) {
730
772
  logFailure("sources.provider-router.history", "Refreshing background price history failed")(error);
731
773
  }
@@ -745,7 +787,8 @@ export class ProviderRouterHistoryRoutes {
745
787
  const fetched = await request.fetchBroker(candidate);
746
788
  if (fetched === null) { recordHistoryOutcome(attempts, sourceKey, "empty"); return null; }
747
789
  if (!Array.isArray(fetched)) { recordHistoryOutcome(attempts, sourceKey, "malformed"); return null; }
748
- const value = normalizeRequestResult({ points: fetched, resolution: historyResolutionForInterval(request.interval), sourceKey }, request);
790
+ const value = normalizeRequestResult({ points: fetched, resolution: historyResolutionForInterval(request.interval), sourceKey,
791
+ ...(brokerHistoryOptions(candidate, request.context).length && isIntradayInterval(request.interval) ? { extendedHours: true } : {}) }, request);
749
792
  if (hasUsablePriceHistory(value.points) && request.isFetchedValueStale(value)) { recordHistoryOutcome(attempts, sourceKey, "stale"); return null; }
750
793
  recordHistoryOutcome(attempts, sourceKey, hasUsablePriceHistory(value.points) ? "success" : value.points.length ? "reported-gaps" : "empty");
751
794
  onUnavailable?.(this.deps.brokerSourceKey(candidate), value);
@@ -412,7 +412,8 @@ export class AssetDataRouter implements DataProvider {
412
412
  }
413
413
 
414
414
  async getOptionsChain(ticker: string, exchange?: string, expirationDate?: number, context?: MarketDataRequestContext): Promise<OptionsChain> {
415
- return (await this.getCachedQuery("getOptionsChain", [ticker, exchange, expirationDate, context]).load({ force: context?.cacheMode === "refresh", background: this.revalidateInBackground })).value;
415
+ return (await this.getCachedQuery("getOptionsChain", [ticker, exchange, expirationDate, context])
416
+ .load({ force: context?.cacheMode === "refresh", background: this.revalidateInBackground && context?.cacheMode !== "current" })).value;
416
417
  }
417
418
 
418
419
  getCachedQuery<K extends CachedAssetMethod>(method: K, args: CachedAssetArgs<K>) {
@@ -190,6 +190,19 @@ export function usePaneInView(): boolean {
190
190
  return useContext(PaneInViewContext);
191
191
  }
192
192
 
193
+ /**
194
+ * Whether the pane around the caller is the focused one, as its frame draws
195
+ * it (a pane under the open command bar is not). Null outside a pane.
196
+ */
197
+ const PaneFocusedContext = createContext<boolean | null>(null);
198
+
199
+ export const PaneFocusedProvider = PaneFocusedContext.Provider;
200
+
201
+ /** For chrome a pane shows only while focused (a chart's drawing tools); null outside a pane. */
202
+ export function usePaneFocused(): boolean | null {
203
+ return useContext(PaneFocusedContext);
204
+ }
205
+
193
206
  /**
194
207
  * Gate a pane's market data (stream priority, polls, refresh clocks) on this:
195
208
  * the app can be seen and the pane is on screen. A covered pane should keep
@@ -13,6 +13,7 @@ import {
13
13
  type SyncSnapshot,
14
14
  type SyncTransport,
15
15
  } from "./types";
16
+ import type { LocalMarketDataLookup } from "./local-only";
16
17
 
17
18
  type CloudSyncPhase = "idle" | "disabled" | "syncing" | "synced" | "error";
18
19
 
@@ -32,6 +33,8 @@ interface SyncRuntime {
32
33
  getContributors: () => RegisteredSyncContributor[];
33
34
  getTransport: () => RegisteredSyncTransport | null;
34
35
  baselineStore?: SyncBaselineStore;
36
+ /** Sources whose quotes and bars never leave this device (`BrokerAdapter.localMarketData`); none when absent. */
37
+ isLocalMarketData?: LocalMarketDataLookup;
35
38
  }
36
39
 
37
40
  const CLIENT_ID_STORAGE_KEY = "gloomberb.sync.clientId";
@@ -357,6 +360,7 @@ export class CloudSyncController {
357
360
  state: runtime.getState(),
358
361
  baselinePayload: this.loadBaseline(runtime)?.[entry.contributor.id] ?? null,
359
362
  memo: this.memoFor(runtime, entry.contributor.id),
363
+ isLocalMarketData: runtime.isLocalMarketData,
360
364
  });
361
365
  payloads[entry.contributor.id] = {
362
366
  schemaVersion: entry.contributor.schemaVersion,
@@ -1,4 +1,5 @@
1
1
  import { scheduleConfigSave } from "../state/config-save-scheduler";
2
+ import { normalizeStoredBaseCurrency } from "../utils/base-currency";
2
3
  import { debugLog } from "../utils/debug-log";
3
4
  import { fnv1aHex, stableStringify } from "../utils/hash";
4
5
  import type { AppConfig, BrokerInstanceConfig, SavedLayout } from "../types/config";
@@ -39,6 +40,16 @@ import {
39
40
  knownBrokerHoldings,
40
41
  type KnownBrokerHoldings,
41
42
  } from "../brokers/broker-portfolio-sync";
43
+ import {
44
+ isLocalOnlyInstance,
45
+ isLocalOnlyPortfolio,
46
+ localOnlyScope,
47
+ publicConfig,
48
+ publicMarketData,
49
+ publicTickers,
50
+ withLocalOnlyEntries,
51
+ type LocalOnlyScope,
52
+ } from "./local-only";
42
53
 
43
54
  /**
44
55
  * What a saved layout mirrors from the live session rather than from the
@@ -612,9 +623,11 @@ function collectCoreCollectionsPayload(
612
623
  financials: Map<string, TickerFinancials>,
613
624
  exchangeRates: Map<string, number>,
614
625
  brokerAccounts: Record<string, BrokerAccount[]>,
626
+ /** The financials whose quotes may be uploaded: without those a source that keeps its market data local supplied. */
627
+ quoted: Map<string, TickerFinancials> = financials,
615
628
  ) {
616
629
  const records = [...tickers.values()]
617
- .map((ticker) => sanitizeTickerMetadata(ticker.metadata, financials.get(ticker.metadata.ticker)))
630
+ .map((ticker) => sanitizeTickerMetadata(ticker.metadata, quoted.get(ticker.metadata.ticker)))
618
631
  .filter(isSyncableTicker);
619
632
 
620
633
  // Only the USD anchor goes on the wire, as before: readers of the snapshot
@@ -873,14 +886,38 @@ interface LayoutMergeContext {
873
886
  pushedAt?: string;
874
887
  }
875
888
 
889
+ /** A pulled config without profiles and portfolios that are local-only here (an older build may have pushed them). */
890
+ function publicConfigPayload(payload: Record<string, unknown>, scope: LocalOnlyScope): Record<string, unknown> {
891
+ const without = (entries: unknown, isLocal: (entry: Record<string, unknown>) => boolean) => (
892
+ Array.isArray(entries) ? entries.filter((entry) => !isRecord(entry) || !isLocal(entry)) : entries
893
+ );
894
+ return {
895
+ ...payload,
896
+ ...("brokerInstances" in payload ? { brokerInstances: without(payload.brokerInstances, (entry) => isLocalOnlyInstance({ id: String(entry.id) }, scope)) } : {}),
897
+ ...("portfolios" in payload ? { portfolios: without(payload.portfolios, (entry) => isLocalOnlyPortfolio(entry as unknown as Portfolio, scope)) } : {}),
898
+ };
899
+ }
900
+
876
901
  function mergeConfigPayload(
877
902
  config: AppConfig,
878
903
  payload: unknown,
879
904
  baselineConfig: AppConfig = config,
880
905
  lastSyncedPayload?: unknown,
881
906
  layoutContext: LayoutMergeContext = {},
907
+ scope: LocalOnlyScope | null = null,
882
908
  ): AppConfig | null {
883
909
  if (!isRecord(payload)) return null;
910
+ if (scope) {
911
+ // Merged as if the local-only profiles and portfolios were not here, then put back as they were.
912
+ const local = publicConfig(config, scope);
913
+ const merged = mergeConfigPayload(local, publicConfigPayload(payload, scope), baselineConfig === config ? local : publicConfig(baselineConfig, scope),
914
+ lastSyncedPayload, layoutContext);
915
+ return merged && {
916
+ ...merged,
917
+ brokerInstances: withLocalOnlyEntries(merged.brokerInstances, config.brokerInstances, (instance) => isLocalOnlyInstance(instance, scope)),
918
+ portfolios: withLocalOnlyEntries(merged.portfolios, config.portfolios, (portfolio) => isLocalOnlyPortfolio(portfolio, scope)),
919
+ };
920
+ }
884
921
  const next: AppConfig = { ...config };
885
922
  // Two guards, both needed. baselineConfig catches edits made while this pull
886
923
  // was in flight; lastSyncedPayload catches edits made while the app was not
@@ -900,6 +937,8 @@ function mergeConfigPayload(
900
937
  };
901
938
 
902
939
  assign("baseCurrency");
940
+ // A device on an older version may still send a name or sign (Canadian dollar, CA$): it applies as its code, as a saved one loads.
941
+ if (typeof next.baseCurrency === "string" && next.baseCurrency.trim()) next.baseCurrency = normalizeStoredBaseCurrency(next.baseCurrency);
903
942
  assign("refreshIntervalMinutes");
904
943
  if ("portfolios" in payload && canApply("portfolios")) {
905
944
  const syncedPortfolios = payload.portfolios;
@@ -1148,6 +1187,8 @@ interface PulledTickersMerge {
1148
1187
  /** This device's live broker portfolios, each with the side holding its latest broker sync. */
1149
1188
  brokerPortfolios: ReadonlyMap<string, "local" | "pulled">;
1150
1189
  known: KnownBrokerHoldings;
1190
+ /** Connections kept on this device: their portfolios' holdings here outlast any pull. */
1191
+ localOnly: LocalOnlyScope | null;
1151
1192
  }
1152
1193
 
1153
1194
  /**
@@ -1224,7 +1265,7 @@ function mergePulledTicker(
1224
1265
  const portfolios: string[] = [];
1225
1266
  for (const portfolioId of portfolioIds) {
1226
1267
  const brokerSide = merge.brokerPortfolios.get(portfolioId);
1227
- const takePulled = brokerSide
1268
+ const takePulled = merge.localOnly?.portfolioIds.has(portfolioId) ? false : brokerSide
1228
1269
  ? brokerSide === "pulled"
1229
1270
  : !comparable || sameAsStored(
1230
1271
  holdingIn(localPositions, localLinks, portfolioId),
@@ -1269,7 +1310,7 @@ export const coreConfigSyncContributor: SyncContributor = {
1269
1310
  id: CORE_CONFIG_CONTRIBUTOR_ID,
1270
1311
  schemaVersion: 1,
1271
1312
  collect: ({ state, baselinePayload, memo }) => withLayoutProvenance(
1272
- collectCoreConfigPayload(state.config) as Record<string, unknown>,
1313
+ collectCoreConfigPayload(publicConfig(state.config, localOnlyScope(state.config))) as Record<string, unknown>,
1273
1314
  baselinePayload,
1274
1315
  memo?.get(),
1275
1316
  ),
@@ -1282,7 +1323,7 @@ export const coreConfigSyncContributor: SyncContributor = {
1282
1323
  const nextConfig = mergeConfigPayload(state.config, payload, baselineState.config, baselinePayload, {
1283
1324
  memo: memo?.get(),
1284
1325
  pushedAt,
1285
- });
1326
+ }, localOnlyScope(state.config));
1286
1327
  if (!nextConfig) return;
1287
1328
  const configChanged = !valuesEqual(nextConfig, state.config);
1288
1329
  if (configChanged) {
@@ -1328,15 +1369,24 @@ export const coreConfigSyncContributor: SyncContributor = {
1328
1369
  export const coreCollectionsSyncContributor: SyncContributor = {
1329
1370
  id: "core.collections",
1330
1371
  schemaVersion: 1,
1331
- collect: async ({ state }) => collectCoreCollectionsPayload(
1332
- state.config,
1333
- state.tickers,
1334
- state.financials,
1335
- await loadHoldingExchangeRates(state.config, state.tickers, state.financials),
1336
- state.brokerAccounts,
1337
- ),
1372
+ collect: async ({ state, isLocalMarketData }) => {
1373
+ // Connections the user keeps on this device stay here, with their portfolios, account values and
1374
+ // positions; so do the quotes and bars of a source that keeps its market data local.
1375
+ const scope = localOnlyScope(state.config);
1376
+ const config = publicConfig(state.config, scope);
1377
+ const tickers = publicTickers(state.tickers, scope);
1378
+ return collectCoreCollectionsPayload(
1379
+ config,
1380
+ tickers,
1381
+ state.financials,
1382
+ await loadHoldingExchangeRates(config, tickers, state.financials),
1383
+ state.brokerAccounts,
1384
+ publicMarketData(state.financials, isLocalMarketData),
1385
+ );
1386
+ },
1338
1387
  apply: async (payload, { snapshot, baselinePayload, baselineState, getState, isCurrent, dispatch, tickerRepository }) => {
1339
1388
  if (!isRecord(payload)) return;
1389
+ const scope = localOnlyScope(getState().config);
1340
1390
  hydrateProfileAnalytics(payload);
1341
1391
  if (!isCurrent()) return;
1342
1392
  // The config contributor applies first, so this is the config this pull left.
@@ -1356,6 +1406,7 @@ export const coreCollectionsSyncContributor: SyncContributor = {
1356
1406
  portfolios: [pulledPortfolios, pulledConfig?.portfolios].flatMap(idEntries),
1357
1407
  brokerInstances: idEntries(pulledConfig?.brokerInstances),
1358
1408
  }),
1409
+ localOnly: scope,
1359
1410
  };
1360
1411
  // Tickers here and pulled ones drop the ids of any watchlist that is gone
1361
1412
  // (removed elsewhere, or deleted by an older build that left its id on the
@@ -0,0 +1,121 @@
1
+ import type { AppConfig, BrokerInstanceConfig } from "../types/config";
2
+ import type { Quote, TickerFinancials } from "../types/financials";
3
+ import type { BrokerContractRef } from "../types/instrument";
4
+ import type { Portfolio, TickerPosition, TickerRecord } from "../types/ticker";
5
+
6
+ /**
7
+ * Broker connections the user keeps on this device (`BrokerInstanceConfig.localOnly`), and the
8
+ * portfolios of their accounts. Cloud sync leaves the connections, those portfolios with their
9
+ * account values, and the positions held in them out of every push, and keeps them through every
10
+ * pull, so nothing of them reaches Gloom Cloud and a pull never removes them here.
11
+ */
12
+ export interface LocalOnlyScope {
13
+ instanceIds: ReadonlySet<string>;
14
+ portfolioIds: ReadonlySet<string>;
15
+ }
16
+
17
+ /**
18
+ * Whether a source keeps the quotes and bars it supplies on this device (`BrokerAdapter.localMarketData`),
19
+ * by its provider id: a broker's is its broker id.
20
+ */
21
+ export type LocalMarketDataLookup = (providerId: string) => boolean;
22
+
23
+ /** The connections the user keeps on this device, or null when there are none. */
24
+ export function localOnlyScope(config: Pick<AppConfig, "brokerInstances" | "portfolios">): LocalOnlyScope | null {
25
+ const instanceIds = new Set(config.brokerInstances.flatMap((instance) => instance.localOnly === true ? [instance.id] : []));
26
+ if (instanceIds.size === 0) return null;
27
+ const scope = { instanceIds, portfolioIds: new Set<string>() };
28
+ return { instanceIds, portfolioIds: new Set(config.portfolios.flatMap((portfolio) => isLocalOnlyPortfolio(portfolio, scope) ? [portfolio.id] : [])) };
29
+ }
30
+
31
+ export function isLocalOnlyInstance(instance: Pick<BrokerInstanceConfig, "id">, scope: LocalOnlyScope): boolean {
32
+ return scope.instanceIds.has(instance.id);
33
+ }
34
+
35
+ export function isLocalOnlyPortfolio(portfolio: Pick<Portfolio, "id" | "brokerInstanceId">, scope: LocalOnlyScope): boolean {
36
+ return scope.portfolioIds.has(portfolio.id) || !!portfolio.brokerInstanceId && scope.instanceIds.has(portfolio.brokerInstanceId)
37
+ // A pulled portfolio has no profile id; its own id names the profile.
38
+ || [...scope.instanceIds].some((id) => portfolio.id.startsWith(`broker:${id}:`));
39
+ }
40
+
41
+ function isLocalOnlyPosition(position: Pick<TickerPosition, "portfolio" | "brokerInstanceId">, scope: LocalOnlyScope): boolean {
42
+ return scope.portfolioIds.has(position.portfolio) || !!position.brokerInstanceId && scope.instanceIds.has(position.brokerInstanceId);
43
+ }
44
+
45
+ function isLocalOnlyContract(contract: Pick<BrokerContractRef, "brokerInstanceId">, scope: LocalOnlyScope): boolean {
46
+ return !!contract.brokerInstanceId && scope.instanceIds.has(contract.brokerInstanceId);
47
+ }
48
+
49
+ /** The config as Cloud sync may see it: without the connections kept on this device and their portfolios. */
50
+ export function publicConfig<T extends Pick<AppConfig, "brokerInstances" | "portfolios">>(config: T, scope: LocalOnlyScope | null): T {
51
+ if (!scope) return config;
52
+ const brokerInstances = config.brokerInstances.filter((instance) => !isLocalOnlyInstance(instance, scope));
53
+ const portfolios = config.portfolios.filter((portfolio) => !isLocalOnlyPortfolio(portfolio, scope));
54
+ if (brokerInstances.length === config.brokerInstances.length && portfolios.length === config.portfolios.length) return config;
55
+ return { ...config, brokerInstances, portfolios };
56
+ }
57
+
58
+ /** The ticker as Cloud sync may see it: without positions, portfolios or contracts of connections kept on this device. */
59
+ function publicTicker(ticker: TickerRecord, scope: LocalOnlyScope | null): TickerRecord {
60
+ if (!scope) return ticker;
61
+ const { metadata } = ticker;
62
+ const positions = metadata.positions.filter((position) => !isLocalOnlyPosition(position, scope));
63
+ const portfolios = metadata.portfolios.filter((id) => !scope.portfolioIds.has(id));
64
+ const contracts = metadata.broker_contracts?.filter((contract) => !isLocalOnlyContract(contract, scope));
65
+ if (positions.length === metadata.positions.length && portfolios.length === metadata.portfolios.length
66
+ && contracts?.length === metadata.broker_contracts?.length) return ticker;
67
+ return { ...ticker, metadata: { ...metadata, positions, portfolios, ...(contracts ? { broker_contracts: contracts } : {}) } };
68
+ }
69
+
70
+ export function publicTickers(tickers: Map<string, TickerRecord>, scope: LocalOnlyScope | null): Map<string, TickerRecord> {
71
+ if (!scope) return tickers;
72
+ return new Map([...tickers].map(([symbol, ticker]) => [symbol, publicTicker(ticker, scope)]));
73
+ }
74
+
75
+ /** The quote fields sync uploads, any of which a source that keeps its market data local may have supplied. */
76
+ const SYNCED_QUOTE_FIELDS = ["price", "change", "changePercent", "previousClose"] as const;
77
+
78
+ function isLocalQuote(quote: Quote, isLocal: LocalMarketDataLookup): boolean {
79
+ const provenance = quote.provenance;
80
+ const providers = [quote.providerId, provenance?.price?.providerId, ...SYNCED_QUOTE_FIELDS.map((field) => provenance?.fields?.[field]?.providerId)];
81
+ return providers.some((providerId) => !!providerId && isLocal(providerId));
82
+ }
83
+
84
+ /** The provider of stored bars, from their source key: `provider:<id>` or `broker:<broker id>:<profile>`. */
85
+ function historyProvider(sourceKey: string | undefined): string | null {
86
+ const [kind, id] = sourceKey?.split(":") ?? [];
87
+ return (kind === "provider" || kind === "broker") && id ? id : null;
88
+ }
89
+
90
+ /**
91
+ * Financials as Cloud sync may upload them: without a quote or bars a source that keeps its market
92
+ * data local supplied. Sync reads only the quote and the week's move from them.
93
+ */
94
+ export function publicMarketData(financials: Map<string, TickerFinancials>, isLocal?: LocalMarketDataLookup): Map<string, TickerFinancials> {
95
+ if (!isLocal) return financials;
96
+ const output = new Map<string, TickerFinancials>();
97
+ for (const [symbol, entry] of financials) {
98
+ const localQuote = !!entry.quote && isLocalQuote(entry.quote, isLocal);
99
+ const provider = historyProvider(entry.priceHistorySourceKey);
100
+ const localBars = !!provider && isLocal(provider);
101
+ output.set(symbol, localQuote || localBars ? { ...entry, ...(localQuote ? { quote: undefined } : {}), ...(localBars ? { priceHistory: [] } : {}) } : entry);
102
+ }
103
+ return output;
104
+ }
105
+
106
+ /**
107
+ * `merged` (a list merged without the local-only entries) with this device's local-only entries
108
+ * of `local` back where they were: each stays at its place among the others, so an unchanged list
109
+ * comes back equal to `local`. An entry the pull brought that is local-only here is left out.
110
+ */
111
+ export function withLocalOnlyEntries<T>(merged: readonly T[], local: readonly T[], isLocalOnly: (entry: T) => boolean): T[] {
112
+ const incoming = merged.filter((entry) => !isLocalOnly(entry));
113
+ const output: T[] = [];
114
+ let next = 0;
115
+ for (const entry of local) {
116
+ if (isLocalOnly(entry)) output.push(entry);
117
+ else if (next < incoming.length) output.push(incoming[next++]!);
118
+ }
119
+ output.push(...incoming.slice(next));
120
+ return output;
121
+ }
package/src/sync/react.ts CHANGED
@@ -41,6 +41,12 @@ export function useCloudSyncRuntime({
41
41
  baselineStore,
42
42
  getContributors: () => pluginRegistry.getEnabledSyncContributors(),
43
43
  getTransport: () => pluginRegistry.getActiveSyncTransport(),
44
+ isLocalMarketData: (providerId) => {
45
+ const broker = pluginRegistry.brokers.get(providerId);
46
+ if (broker) return broker.localMarketData === true;
47
+ // A broker whose plugin is off may still have its quotes about from before; they stay here too.
48
+ return getState().config.brokerInstances.some((instance) => instance.brokerType === providerId);
49
+ },
44
50
  });
45
51
  }, [baselineStore, dispatch, getState, pluginRegistry, tickerRepository]);
46
52