gloomberb 0.19.4 → 0.19.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/package.json +3 -1
  2. package/src/cli/commands/command-utils.ts +4 -0
  3. package/src/cli/commands/market.ts +119 -27
  4. package/src/cli/commands/search.ts +1 -1
  5. package/src/cli/commands/ticker.ts +10 -6
  6. package/src/cli/currency-name-hint.ts +60 -0
  7. package/src/cli/history-rows.ts +18 -1
  8. package/src/cli/known-gaps.ts +17 -2
  9. package/src/cli/not-a-ticker.ts +5 -3
  10. package/src/cli/pane-functions/catalog.ts +9 -1
  11. package/src/cli/pane-functions/headless.ts +7 -3
  12. package/src/cli/pane-functions/market-session.ts +6 -7
  13. package/src/cli/series-search.ts +4 -5
  14. package/src/components/chart/composite/panel-bitmap.ts +28 -2
  15. package/src/components/chart/composite/time-axis.ts +17 -2
  16. package/src/components/layout/shell/active-drag.ts +38 -7
  17. package/src/components/layout/shell/drag/magnets.ts +106 -0
  18. package/src/components/layout/window-controls.tsx +96 -35
  19. package/src/components/layout/window-fullscreen.ts +20 -0
  20. package/src/components/quote-flash.ts +36 -32
  21. package/src/market-data/coordinator/events.ts +17 -1
  22. package/src/market-data/frame-scheduler.ts +47 -10
  23. package/src/market-data/frame-wake.ts +74 -0
  24. package/src/market-data/futures-board.ts +7 -6
  25. package/src/market-data/hooks.tsx +12 -3
  26. package/src/market-data/performance.ts +78 -9
  27. package/src/market-data/request-types.ts +6 -3
  28. package/src/plugins/builtin/alerts/cli.ts +2 -1
  29. package/src/plugins/builtin/analytics/risk-evidence.ts +1 -0
  30. package/src/plugins/builtin/attention/evidence.ts +1 -1
  31. package/src/plugins/builtin/awards/client.ts +1 -1
  32. package/src/plugins/builtin/awards/evidence.ts +1 -1
  33. package/src/plugins/builtin/awards/pane.tsx +2 -1
  34. package/src/plugins/builtin/bond-calculator/math.ts +1 -1
  35. package/src/plugins/builtin/broker-manager/footer.ts +3 -2
  36. package/src/plugins/builtin/broker-manager/index.tsx +2 -1
  37. package/src/plugins/builtin/broker-manager/keyboard.ts +2 -1
  38. package/src/plugins/builtin/catalysts/evidence.ts +1 -1
  39. package/src/plugins/builtin/catalysts/pane.tsx +2 -1
  40. package/src/plugins/builtin/chart-composer/headless.ts +40 -1
  41. package/src/plugins/builtin/cloud-tweets/table.tsx +3 -2
  42. package/src/plugins/builtin/comment-letters/client.ts +2 -1
  43. package/src/plugins/builtin/company-kpis/client.ts +1 -1
  44. package/src/plugins/builtin/company-kpis/pane.tsx +2 -1
  45. package/src/plugins/builtin/company-kpis/screenshot-evidence.ts +3 -2
  46. package/src/plugins/builtin/cot/headless.ts +9 -3
  47. package/src/plugins/builtin/cot/model.ts +44 -3
  48. package/src/plugins/builtin/credit-documents/client.ts +1 -1
  49. package/src/plugins/builtin/credit-documents/evidence.ts +1 -1
  50. package/src/plugins/builtin/credit-documents/pane.tsx +2 -1
  51. package/src/plugins/builtin/earnings-calls/pane.tsx +1 -1
  52. package/src/plugins/builtin/earnings-ripple/index.tsx +6 -1
  53. package/src/plugins/builtin/econ/calendar-model.ts +2 -0
  54. package/src/plugins/builtin/econ/fred-catalog.ts +5 -5
  55. package/src/plugins/builtin/econ/print-watch.ts +3 -1
  56. package/src/plugins/builtin/futures/series.ts +16 -1
  57. package/src/plugins/builtin/fx-matrix/headless.ts +4 -2
  58. package/src/plugins/builtin/fx-matrix/index.tsx +37 -3
  59. package/src/plugins/builtin/fx-matrix/pairs.ts +15 -0
  60. package/src/plugins/builtin/gpu/headless.ts +2 -1
  61. package/src/plugins/builtin/help/function-card.tsx +2 -1
  62. package/src/plugins/builtin/help/index.tsx +2 -1
  63. package/src/plugins/builtin/insider/display.ts +45 -6
  64. package/src/plugins/builtin/ipo-calendar/model.ts +2 -0
  65. package/src/plugins/builtin/iv-history/client.ts +2 -1
  66. package/src/plugins/builtin/iv-history/headless.ts +2 -1
  67. package/src/plugins/builtin/jobs/pages.ts +4 -4
  68. package/src/plugins/builtin/kelly-sizer/headless.ts +2 -1
  69. package/src/plugins/builtin/market-heatmap/index.tsx +2 -1
  70. package/src/plugins/builtin/members/client.ts +1 -1
  71. package/src/plugins/builtin/mna/distress/client.ts +1 -0
  72. package/src/plugins/builtin/mna/pane.tsx +4 -1
  73. package/src/plugins/builtin/options/market-reference.ts +1 -1
  74. package/src/plugins/builtin/options/open-interest-as-of.ts +3 -1
  75. package/src/plugins/builtin/options/view.tsx +2 -1
  76. package/src/plugins/builtin/options-calculator/evidence.ts +1 -1
  77. package/src/plugins/builtin/options-scenario/csp-screen-pane.tsx +1 -1
  78. package/src/plugins/builtin/options-scenario/csp-screen.ts +8 -4
  79. package/src/plugins/builtin/options-scenario/csp.ts +28 -9
  80. package/src/plugins/builtin/options-scenario/evidence.ts +5 -4
  81. package/src/plugins/builtin/options-scenario/pane.tsx +2 -1
  82. package/src/plugins/builtin/perps/client.ts +1 -1
  83. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +2 -1
  84. package/src/plugins/builtin/portfolio-list/pane/index.tsx +7 -3
  85. package/src/plugins/builtin/portfolio-list/use-throttled-memo.ts +10 -19
  86. package/src/plugins/builtin/research/analyst-model.ts +1 -0
  87. package/src/plugins/builtin/research/equity-diagnostic-pane.tsx +2 -1
  88. package/src/plugins/builtin/research/index.tsx +1 -0
  89. package/src/plugins/builtin/research/relative-valuation-currency.ts +1 -1
  90. package/src/plugins/builtin/research/relative-valuation-peers.ts +2 -1
  91. package/src/plugins/builtin/research-search/command-bar-search.ts +3 -1
  92. package/src/plugins/builtin/research-search/snippet.ts +1 -0
  93. package/src/plugins/builtin/revenue-breakdown/client.ts +3 -2
  94. package/src/plugins/builtin/seasonality/headless.ts +2 -1
  95. package/src/plugins/builtin/sec/command-bar-search.ts +3 -2
  96. package/src/plugins/builtin/sec/index.tsx +7 -4
  97. package/src/plugins/builtin/sec/row-summaries.ts +28 -12
  98. package/src/plugins/builtin/short-interest/watch-client.ts +2 -1
  99. package/src/plugins/builtin/social-mentions/client.ts +2 -1
  100. package/src/plugins/builtin/supply-chain/client.ts +1 -1
  101. package/src/plugins/builtin/supply-chain/evidence.ts +1 -1
  102. package/src/plugins/builtin/supply-chain/graph-pane.tsx +2 -1
  103. package/src/plugins/builtin/supply-chain/pane.tsx +2 -1
  104. package/src/plugins/builtin/ticker-detail/adr-pair/headless.ts +1 -1
  105. package/src/plugins/builtin/ticker-detail/adr-pair/model.ts +24 -4
  106. package/src/plugins/builtin/ticker-detail/adr-pair/tab.tsx +1 -1
  107. package/src/plugins/builtin/time-sales/client.ts +1 -0
  108. package/src/plugins/builtin/vol-surface/client.ts +2 -1
  109. package/src/plugins/builtin/yield-curve/headless.ts +3 -1
  110. package/src/portfolio/column-values.ts +76 -10
  111. package/src/renderers/dom/host/box.tsx +204 -176
  112. package/src/renderers/dom/host/style.ts +49 -20
  113. package/src/renderers/dom/host/text.tsx +3 -2
  114. package/src/renderers/electrobun/bun/desktop/backend.ts +2 -0
  115. package/src/renderers/electrobun/bun/desktop/host-requests.ts +25 -1
  116. package/src/renderers/electrobun/bun/desktop/relaunch.ts +9 -1
  117. package/src/renderers/electrobun/bun/desktop/windows-script.ts +9 -6
  118. package/src/renderers/electrobun/bun/window/windows-native.ts +26 -1
  119. package/src/renderers/electrobun/shared/protocol.ts +6 -0
  120. package/src/renderers/electrobun/view/ui-host.tsx +7 -0
  121. package/src/renderers/electrobun/view/window-fullscreen.ts +10 -3
  122. package/src/sources/provider-router/index.ts +7 -1
  123. package/src/time-series/price-units.ts +11 -0
  124. package/src/ui/host.tsx +2 -0
  125. package/src/utils/currency-names.ts +20 -0
  126. package/src/utils/currency-pair.ts +6 -0
  127. package/src/utils/exchange-rate-snapshot.ts +20 -2
  128. package/src/utils/fx-market-hours.ts +43 -0
@@ -1,6 +1,22 @@
1
1
  import { measurePerf } from "../../utils/perf-marks";
2
2
  import { marketDataFrames, type DataFrameScheduler } from "../frame-scheduler";
3
3
 
4
+ const uniqueKeyLists = new WeakMap<readonly string[], readonly string[]>();
5
+
6
+ /**
7
+ * `keys` without repeats. React reads a hook's version on every store change
8
+ * and every render, always with the same memoized list, so its de-duplicated
9
+ * copy is kept with it rather than built each time.
10
+ */
11
+ function uniqueKeys(keys: readonly string[]): readonly string[] {
12
+ let unique = uniqueKeyLists.get(keys);
13
+ if (!unique) {
14
+ unique = [...new Set(keys)];
15
+ uniqueKeyLists.set(keys, unique);
16
+ }
17
+ return unique;
18
+ }
19
+
4
20
  /** Hears when a key gains its first listener and loses its last. */
5
21
  export interface KeyWatchHooks {
6
22
  watched?(key: string): void;
@@ -73,7 +89,7 @@ export class MarketDataCoordinatorEvents {
73
89
 
74
90
  getKeysVersion(keys: readonly string[]): number {
75
91
  let version = 0;
76
- for (const key of new Set(keys)) {
92
+ for (const key of uniqueKeys(keys)) {
77
93
  version += this.getKeyVersion(key);
78
94
  }
79
95
  return version;
@@ -54,6 +54,27 @@ export interface DataFrameRequest {
54
54
  phase?: DataFramePhase;
55
55
  /** Driver time before which the task must not run; background keys use it to wait out their interval. */
56
56
  notBefore?: number;
57
+ /**
58
+ * Lets the task wait to share a frame with other work: it runs in the first
59
+ * frame at or after `notBefore`, but only sets a frame off itself at this
60
+ * driver time. A frame that runs nothing else does not hold the next one
61
+ * back or count toward load pacing, so a quote arriving just after it is not
62
+ * kept waiting.
63
+ */
64
+ rideUntil?: number;
65
+ }
66
+
67
+ interface QueuedTask {
68
+ notBefore: number;
69
+ /** When the task sets a frame off by itself. */
70
+ wakeAt: number;
71
+ rides: boolean;
72
+ }
73
+
74
+ /** How many riding (rideUntil) and other tasks a frame ran. */
75
+ interface FrameTally {
76
+ riders: number;
77
+ others: number;
57
78
  }
58
79
 
59
80
  function monotonicNow(): number {
@@ -186,7 +207,7 @@ export function createManualFrameDriver(minIntervalMs: number): {
186
207
  }
187
208
 
188
209
  export class DataFrameScheduler {
189
- private readonly queues: Record<DataFramePhase, Map<DataFrameTask, number>> = {
210
+ private readonly queues: Record<DataFramePhase, Map<DataFrameTask, QueuedTask>> = {
190
211
  apply: new Map(),
191
212
  notify: new Map(),
192
213
  };
@@ -230,10 +251,18 @@ export class DataFrameScheduler {
230
251
  }
231
252
 
232
253
  /** Queues a task for the next frame. A task queued twice runs once. */
233
- request(task: DataFrameTask, { phase = "apply", notBefore = Number.NEGATIVE_INFINITY }: DataFrameRequest = {}): void {
254
+ request(task: DataFrameTask, { phase = "apply", notBefore = Number.NEGATIVE_INFINITY, rideUntil }: DataFrameRequest = {}): void {
234
255
  const queue = this.queues[phase];
235
256
  const existing = queue.get(task);
236
- queue.set(task, existing === undefined ? notBefore : Math.min(existing, notBefore));
257
+ const rides = rideUntil !== undefined;
258
+ const wakeAt = rides ? Math.max(notBefore, rideUntil) : notBefore;
259
+ if (existing === undefined) {
260
+ queue.set(task, { notBefore, wakeAt, rides });
261
+ } else {
262
+ existing.notBefore = Math.min(existing.notBefore, notBefore);
263
+ existing.wakeAt = Math.min(existing.wakeAt, wakeAt);
264
+ existing.rides &&= rides;
265
+ }
237
266
  if (!this.running) this.reschedule();
238
267
  }
239
268
 
@@ -252,7 +281,7 @@ export class DataFrameScheduler {
252
281
  private reschedule(): void {
253
282
  let earliest = Number.POSITIVE_INFINITY;
254
283
  for (const queue of Object.values(this.queues)) {
255
- for (const notBefore of queue.values()) earliest = Math.min(earliest, notBefore);
284
+ for (const queued of queue.values()) earliest = Math.min(earliest, queued.wakeAt);
256
285
  }
257
286
  if (earliest === Number.POSITIVE_INFINITY) {
258
287
  this.cancel();
@@ -269,10 +298,14 @@ export class DataFrameScheduler {
269
298
  }, at - this.driver.now());
270
299
  }
271
300
 
272
- private takeDue(phase: DataFramePhase, now: number): DataFrameTask[] {
301
+ /** The tasks due by `now`, counted into `frame` as riding (rideUntil) or not. */
302
+ private takeDue(phase: DataFramePhase, now: number, frame: FrameTally): DataFrameTask[] {
273
303
  const due: DataFrameTask[] = [];
274
- for (const [task, notBefore] of this.queues[phase]) {
275
- if (notBefore <= now) due.push(task);
304
+ for (const [task, queued] of this.queues[phase]) {
305
+ if (queued.notBefore > now) continue;
306
+ due.push(task);
307
+ if (queued.rides) frame.riders += 1;
308
+ else frame.others += 1;
276
309
  }
277
310
  for (const task of due) this.queues[phase].delete(task);
278
311
  return due;
@@ -283,21 +316,25 @@ export class DataFrameScheduler {
283
316
  this.running = true;
284
317
  const driver = this.driver;
285
318
  const now = driver.now();
319
+ const previousFrameAt = this.lastFrameAt;
286
320
  this.lastFrameAt = now;
321
+ const frame: FrameTally = { riders: 0, others: 0 };
287
322
  let notified = false;
288
323
  try {
289
324
  // Applying a batch may queue another applier (a flush feeding a
290
325
  // derived store); those still belong to this frame.
291
326
  for (let pass = 0; pass < MAX_APPLY_PASSES; pass += 1) {
292
- const due = this.takeDue("apply", now);
327
+ const due = this.takeDue("apply", now, frame);
293
328
  if (due.length === 0) break;
294
329
  runTasks(due);
295
330
  }
296
331
  // Listeners that write data while being notified are heard next frame.
297
- const listeners = this.takeDue("notify", now);
298
- notified = listeners.length > 0;
332
+ const listeners = this.takeDue("notify", now, frame);
333
+ notified = listeners.length > 0 && frame.others > 0;
299
334
  runTasks(listeners);
300
335
  } finally {
336
+ // Nothing but riders ran: the next frame is spaced from the last one that carried data.
337
+ if (frame.riders > 0 && frame.others === 0) this.lastFrameAt = previousFrameAt;
301
338
  this.running = false;
302
339
  // Only a frame that told readers something sets off renders worth timing.
303
340
  if (notified && driver.afterFrame) {
@@ -0,0 +1,74 @@
1
+ import { useRef, useSyncExternalStore } from "react";
2
+ import { marketDataFrames, type DataFrameScheduler, type DataFrameTask } from "./frame-scheduler";
3
+
4
+ export interface DataFrameWake {
5
+ /** The market data clock (monotonic, in ms). */
6
+ now(): number;
7
+ /**
8
+ * Renders the component again in the first market data frame at or after
9
+ * `time` on that clock, waiting up to one frame interval longer for a frame
10
+ * that brings quotes. Booked twice, the earlier time wins; a component that
11
+ * still needs one after it renders books again.
12
+ */
13
+ wakeAt(time: number): void;
14
+ /** Drops a booked render that is no longer needed. */
15
+ cancel(): void;
16
+ }
17
+
18
+ interface WakeStore extends DataFrameWake {
19
+ version: number;
20
+ booked: boolean;
21
+ listener: (() => void) | null;
22
+ task: DataFrameTask;
23
+ subscribe(listener: () => void): () => void;
24
+ getVersion(): number;
25
+ }
26
+
27
+ function createWakeStore(frames: DataFrameScheduler): WakeStore {
28
+ const store: WakeStore = {
29
+ version: 0,
30
+ booked: false,
31
+ listener: null,
32
+ task: () => {
33
+ store.booked = false;
34
+ store.version += 1;
35
+ store.listener?.();
36
+ },
37
+ subscribe(listener) {
38
+ store.listener = listener;
39
+ return () => {
40
+ store.listener = null;
41
+ store.cancel();
42
+ };
43
+ },
44
+ getVersion: () => store.version,
45
+ now: () => frames.now(),
46
+ wakeAt(time) {
47
+ store.booked = true;
48
+ // Due at `time`, it waits up to a frame for one that carries quotes.
49
+ frames.request(store.task, { phase: "notify", notBefore: time, rideUntil: time + frames.frameIntervalMs() });
50
+ },
51
+ cancel() {
52
+ if (!store.booked) return;
53
+ store.booked = false;
54
+ frames.remove(store.task);
55
+ },
56
+ };
57
+ return store;
58
+ }
59
+
60
+ /**
61
+ * A re-render booked on the market data clock, in the same React pass as the
62
+ * store updates that frame delivers. A flash ending or a throttled total
63
+ * catching up then rides along with the next quotes instead of costing a
64
+ * commit, and in the terminal a full redraw, of its own.
65
+ */
66
+ export function useDataFrameWake(frames: DataFrameScheduler = marketDataFrames): DataFrameWake {
67
+ const storeRef = useRef<{ frames: DataFrameScheduler; store: WakeStore } | null>(null);
68
+ if (storeRef.current?.frames !== frames) storeRef.current = { frames, store: createWakeStore(frames) };
69
+ const { store } = storeRef.current;
70
+ // A store notification is a sync-lane update, as every market data hook's is,
71
+ // so React folds it into the same render as the frame's other updates.
72
+ useSyncExternalStore(store.subscribe, store.getVersion, store.getVersion);
73
+ return store;
74
+ }
@@ -142,12 +142,13 @@ export const FUTURES_CONTRACTS: FuturesContract[] = [
142
142
  { symbol: "LE=F", code: "LE", name: "Live Cattle", sector: "livestock", venue: "CME", tick: 0.025, unit: "US cents / lb" },
143
143
  { symbol: "HE=F", code: "HE", name: "Lean Hogs", sector: "livestock", venue: "CME", tick: 0.025, unit: "US cents / lb" },
144
144
 
145
- { symbol: "6E=F", code: "6E", name: "Euro FX", sector: "currencies", venue: "CME", tick: 0.00005, bareCode: true },
146
- { symbol: "6J=F", code: "6J", name: "Japanese Yen", sector: "currencies", venue: "CME", tick: 0.0000005, bareCode: true },
147
- { symbol: "6B=F", code: "6B", name: "British Pound", sector: "currencies", venue: "CME", tick: 0.0001, bareCode: true },
148
- { symbol: "6A=F", code: "6A", name: "Australian Dollar", sector: "currencies", venue: "CME", tick: 0.00005, bareCode: true },
149
- { symbol: "6C=F", code: "6C", name: "Canadian Dollar", sector: "currencies", venue: "CME", tick: 0.00005, bareCode: true },
150
- { symbol: "6S=F", code: "6S", name: "Swiss Franc", sector: "currencies", venue: "CME", tick: 0.00005, bareCode: true },
145
+ // Quoted in US dollars per unit of the foreign currency, as the server's terms state for most of them.
146
+ { symbol: "6E=F", code: "6E", name: "Euro FX", sector: "currencies", venue: "CME", tick: 0.00005, unit: "USD / EUR", bareCode: true },
147
+ { symbol: "6J=F", code: "6J", name: "Japanese Yen", sector: "currencies", venue: "CME", tick: 0.0000005, unit: "USD / JPY", bareCode: true },
148
+ { symbol: "6B=F", code: "6B", name: "British Pound", sector: "currencies", venue: "CME", tick: 0.0001, unit: "USD / GBP", bareCode: true },
149
+ { symbol: "6A=F", code: "6A", name: "Australian Dollar", sector: "currencies", venue: "CME", tick: 0.00005, unit: "USD / AUD", bareCode: true },
150
+ { symbol: "6C=F", code: "6C", name: "Canadian Dollar", sector: "currencies", venue: "CME", tick: 0.00005, unit: "USD / CAD", bareCode: true },
151
+ { symbol: "6S=F", code: "6S", name: "Swiss Franc", sector: "currencies", venue: "CME", tick: 0.00005, unit: "USD / CHF", bareCode: true },
151
152
  ];
152
153
 
153
154
  export const FUTURES_SECTOR_LABELS: Record<FuturesSector, string> = {
@@ -219,6 +219,8 @@ interface PatchedMapSlot<K, V> {
219
219
  interface PatchedMapState<K, V> {
220
220
  signature: string;
221
221
  coordinator: SharedCoordinator | null;
222
+ /** The subscribed keys' summed version when the slots were last read. */
223
+ aggregateVersion: number;
222
224
  slots: Array<PatchedMapSlot<K, V>>;
223
225
  versions: number[];
224
226
  backing: Map<K, V>;
@@ -255,18 +257,22 @@ function usePatchedMap<K, V>(
255
257
  versions.push(slotVersion(slot, versionOf, aggregateVersion));
256
258
  }
257
259
  const view = new RetainedMapView(backing);
258
- state = { signature, coordinator, slots, versions, backing, view };
260
+ state = { signature, coordinator, slots, versions, backing, view, aggregateVersion };
259
261
  stateRef.current = state;
260
262
  return view;
261
263
  }
262
264
 
265
+ // Key versions only grow, so an unchanged sum means no slot moved: a render
266
+ // for any other reason skips reading every slot's versions. Both are kept
267
+ // only once read, so a read that throws is tried again on the next render.
268
+ if (aggregateVersion === state.aggregateVersion) return state.view;
263
269
  let changed = false;
264
270
  for (let index = 0; index < state.slots.length; index += 1) {
265
271
  const slot = state.slots[index]!;
266
272
  const version = slotVersion(slot, versionOf, aggregateVersion);
267
273
  if (version === state.versions[index]) continue;
268
- state.versions[index] = version;
269
274
  const value = slot.read();
275
+ state.versions[index] = version;
270
276
  if (value == null) {
271
277
  if (state.backing.delete(slot.key)) changed = true;
272
278
  } else if (state.backing.get(slot.key) !== value) {
@@ -274,6 +280,7 @@ function usePatchedMap<K, V>(
274
280
  changed = true;
275
281
  }
276
282
  }
283
+ state.aggregateVersion = aggregateVersion;
277
284
  if (!changed) return state.view;
278
285
  const view = new RetainedMapView(state.backing);
279
286
  state.view = view;
@@ -291,7 +298,9 @@ export function useTickerFinancialsMap(
291
298
  ): Map<string, TickerFinancials> {
292
299
  const coordinator = getSharedMarketDataCoordinator();
293
300
  const optionsKey = options.portfolioId ?? "";
294
- const tickerKey = buildTickerFinancialsMapKey(tickers, options);
301
+ // Per list, not per render: a quote tick re-renders the pane but leaves its
302
+ // rows (immutable records, replaced when they change) and portfolio alone.
303
+ const tickerKey = useMemo(() => buildTickerFinancialsMapKey(tickers, options), [optionsKey, tickers]);
295
304
  const subscriptionKeys = useMemo(() => buildTickerFinancialsKeys(tickers, options), [optionsKey, tickerKey]);
296
305
  const keysVersion = useCoordinatorKeysVersion(subscriptionKeys);
297
306
 
@@ -31,22 +31,76 @@ function coercePointDate(value: Date | string | number): Date | null {
31
31
  return Number.isFinite(date.getTime()) ? date : null;
32
32
  }
33
33
 
34
- function normalizePriceReturnHistory(points: readonly PricePoint[]): PricePoint[] {
34
+ interface NormalizedHistory {
35
+ /** The input's length and ends when it was read, so an array grown in place is read again. */
36
+ length: number;
37
+ first: PricePoint | undefined;
38
+ last: PricePoint | undefined;
39
+ history: readonly PricePoint[];
40
+ }
41
+
42
+ /**
43
+ * The normalized copy of each history read before. A ticker's bars stay the
44
+ * same array while its quote ticks, and every tick asks again with the quote
45
+ * appended, so the bars are sorted and copied once rather than per tick.
46
+ */
47
+ const normalizedCopies = new WeakMap<readonly PricePoint[], NormalizedHistory>();
48
+ /** Arrays built here already normalized (a copy, or one with the quote appended): read as they are. */
49
+ const normalizedArrays = new WeakSet<readonly PricePoint[]>();
50
+
51
+ function normalizePriceReturnHistory(points: readonly PricePoint[]): readonly PricePoint[] {
52
+ if (normalizedArrays.has(points)) return points;
53
+ const cached = normalizedCopies.get(points);
54
+ if (cached && cached.length === points.length && cached.first === points[0] && cached.last === points.at(-1)) return cached.history;
35
55
  const byTimestamp = new Map<number, PricePoint>();
36
56
  for (const point of points) {
37
57
  const date = coercePointDate(point.date as Date | string | number);
38
58
  if (!date || (!Number.isFinite(point.close) && !pricePointIntegrity(point))) continue;
39
59
  byTimestamp.set(date.getTime(), { ...point, date });
40
60
  }
41
- return [...byTimestamp.entries()]
61
+ const history = [...byTimestamp.entries()]
42
62
  .sort((left, right) => left[0] - right[0])
43
63
  .map(([, point]) => point);
64
+ normalizedArrays.add(history);
65
+ normalizedCopies.set(points, { length: points.length, first: points[0], last: points.at(-1), history });
66
+ return history;
67
+ }
68
+
69
+ /** Each normalized bar's session day by venue (barSessionDay), kept with the bar: the zone lookup is the slow part. */
70
+ const sessionDaysByVenue = new Map<string, WeakMap<PricePoint, string>>();
71
+ /** Whether each normalized bar's OHLC contradicts itself (pricePointIntegrity). */
72
+ const inconsistentPoints = new WeakMap<PricePoint, boolean>();
73
+
74
+ function sessionDays(history: readonly PricePoint[], venue: string | undefined): string[] {
75
+ const venueKey = venue ?? "";
76
+ let days = sessionDaysByVenue.get(venueKey);
77
+ if (!days) {
78
+ days = new WeakMap();
79
+ sessionDaysByVenue.set(venueKey, days);
80
+ }
81
+ return history.map((point) => {
82
+ let day = days.get(point);
83
+ if (day === undefined) {
84
+ day = barSessionDay(point.date.getTime(), venue);
85
+ days.set(point, day);
86
+ }
87
+ return day;
88
+ });
89
+ }
90
+
91
+ function isInconsistent(point: PricePoint): boolean {
92
+ let inconsistent = inconsistentPoints.get(point);
93
+ if (inconsistent === undefined) {
94
+ inconsistent = !!pricePointIntegrity(point);
95
+ inconsistentPoints.set(point, inconsistent);
96
+ }
97
+ return inconsistent;
44
98
  }
45
99
 
46
100
  export function appendQuoteToPriceReturnHistory(
47
101
  points: readonly PricePoint[],
48
102
  quote: Pick<Quote, "price" | "lastUpdated"> | null | undefined,
49
- ): PricePoint[] {
103
+ ): readonly PricePoint[] {
50
104
  const history = normalizePriceReturnHistory(points);
51
105
  if (!quote || !Number.isFinite(quote.price) || !Number.isFinite(quote.lastUpdated)) {
52
106
  return history;
@@ -58,13 +112,15 @@ export function appendQuoteToPriceReturnHistory(
58
112
  const latestHistoryTime = history.at(-1)?.date.getTime() ?? Number.NEGATIVE_INFINITY;
59
113
  if (quoteDate.getTime() <= latestHistoryTime) return history;
60
114
 
61
- return [
115
+ const withQuote = [
62
116
  ...history,
63
117
  {
64
118
  date: quoteDate,
65
119
  close: quote.price,
66
120
  },
67
121
  ];
122
+ normalizedArrays.add(withQuote);
123
+ return withQuote;
68
124
  }
69
125
 
70
126
  /** The calendar date a horizon ending on `day` is measured back to (periodBaseDay). */
@@ -89,23 +145,33 @@ function priceReturnForHorizon(
89
145
  venue: string | undefined,
90
146
  ): Pick<PriceReturnField, "value" | "unavailableReason"> {
91
147
  const history = normalizePriceReturnHistory(points);
148
+ return priceReturnFromHistory(history, sessionDays(history, venue), horizon);
149
+ }
150
+
151
+ /** `history` normalized, `days` its bars' session days. */
152
+ function priceReturnFromHistory(
153
+ history: readonly PricePoint[],
154
+ days: readonly string[],
155
+ horizon: PriceReturnHorizon,
156
+ ): Pick<PriceReturnField, "value" | "unavailableReason"> {
92
157
  if (history.length < 2) return {
93
158
  value: null,
94
- ...(history.some(pricePointIntegrity) ? { unavailableReason: "inconsistent-ohlc" as const } : {}),
159
+ ...(history.some(isInconsistent) ? { unavailableReason: "inconsistent-ohlc" as const } : {}),
95
160
  };
96
161
 
97
162
  const latest = history.at(-1)!;
98
163
  // The close on or before the same date a horizon earlier, as every period return is measured. No gap
99
164
  // limit: the overview's history can be sparse, and its base is whatever close it holds on or before then.
100
165
  // Each bar and the quote by its session day: a JPX bar stamped 00:00 JST, or a quote after a New York close, is not the UTC date's.
101
- const days = history.map((point) => barSessionDay(point.date.getTime(), venue));
102
166
  const baseDay = horizonBaseDay(days.at(-1)!, horizon);
103
167
  const baseIndex = periodBaseIndex(days, baseDay, Number.POSITIVE_INFINITY);
104
168
  const baseline = baseIndex < 0 ? null : history[baseIndex]!;
105
169
  const cutoff = new Date(`${baseDay}T00:00:00Z`);
106
170
 
107
- if (history.some((point) => point.date >= (baseline?.date ?? cutoff) && pricePointIntegrity(point))) {
108
- return { value: null, unavailableReason: "inconsistent-ohlc" };
171
+ // The bars from the baseline (or the cutoff) on: the history is in time order, one bar a timestamp.
172
+ const since = (baseline?.date ?? cutoff).getTime();
173
+ for (let index = history.length - 1; index >= 0 && history[index]!.date.getTime() >= since; index -= 1) {
174
+ if (isInconsistent(history[index]!)) return { value: null, unavailableReason: "inconsistent-ohlc" };
109
175
  }
110
176
  if (!baseline || !Number.isFinite(baseline.close) || baseline.close === 0) return { value: null };
111
177
  if (!Number.isFinite(latest.close)) return { value: null };
@@ -117,9 +183,12 @@ export function buildPriceReturnFields(
117
183
  venue?: string,
118
184
  horizons: readonly PriceReturnHorizon[] = PRICE_RETURN_HORIZONS,
119
185
  ): PriceReturnField[] {
186
+ // Normalized and dated once for every horizon.
187
+ const history = normalizePriceReturnHistory(points);
188
+ const days = sessionDays(history, venue);
120
189
  return horizons.map((horizon) => ({
121
190
  id: horizon.id,
122
191
  label: horizon.label,
123
- ...priceReturnForHorizon(points, horizon, venue),
192
+ ...priceReturnFromHistory(history, days, horizon),
124
193
  }));
125
194
  }
@@ -46,10 +46,11 @@ function brokerContractForTicker(
46
46
  const contracts = ticker?.metadata.broker_contracts ?? [];
47
47
  const portfolioId = options.portfolioId;
48
48
  if (portfolioId) {
49
- const positions = ticker?.metadata.positions.filter((position) => position.portfolio === portfolioId && position.shares !== 0) ?? [];
50
- const selected = new Map<string, BrokerContractRef>();
49
+ // Rows ask on every render of a list: nothing is allocated for a portfolio's lots until one names a contract.
50
+ let selected: Map<string, BrokerContractRef> | null = null;
51
51
  let hasPublicPosition = false;
52
- for (const position of positions) {
52
+ for (const position of ticker?.metadata.positions ?? []) {
53
+ if (position.portfolio !== portfolioId || position.shares === 0) continue;
53
54
  const hasExplicitId = position.brokerContractId != null;
54
55
  const hasExplicitIdentity = position.brokerContractIdentity != null;
55
56
  const hasLegacyScope = position.broker !== "manual" && !!position.broker && !!position.brokerInstanceId;
@@ -68,11 +69,13 @@ function brokerContractForTicker(
68
69
  hasPublicPosition = true;
69
70
  continue;
70
71
  }
72
+ selected ??= new Map();
71
73
  for (const contract of matches) {
72
74
  const key = scopedBrokerContractIdentityKey(contract);
73
75
  selected.set(key, contract);
74
76
  }
75
77
  }
78
+ if (!selected) return null;
76
79
  // One ticker quote must identify every selected lot. Never choose by array order.
77
80
  if (selected.size > 1 || (selected.size > 0 && hasPublicPosition)) return undefined;
78
81
  return selected.values().next().value ?? null;
@@ -1110,7 +1110,8 @@ export const alertsCliCommand: CliCommandDef = {
1110
1110
  });
1111
1111
  return;
1112
1112
  }
1113
- if (action === "delete" || action === "rm") {
1113
+ // `remove`, as the command's own description says it does, and `rm` delete as `delete` does.
1114
+ if (action === "delete" || action === "remove" || action === "rm") {
1114
1115
  const id = requireArg(args[1], "Usage: gloom alerts delete <id>", ctx);
1115
1116
  const level = alerts.find((alert) => alert.id === id) ?? null;
1116
1117
  const rule = level ? null : events.rules.find((entry) => entry.id === id) ?? null;
@@ -480,6 +480,7 @@ export function brokerPerformanceEvidence(
480
480
  performance: { flowTiming: "end-of-day", externalFlowsComplete: true, observations },
481
481
  }), now);
482
482
  } catch {
483
+ // Intentional ignore: account history that fails evidence validation does not qualify as evidence.
483
484
  return null;
484
485
  }
485
486
  }
@@ -19,7 +19,7 @@ export const attentionScreenshotEvidence: PaneScreenshotEvidenceHook<AttentionEv
19
19
  if (!isRecord(value) || value.kind !== "attention" || value.version !== 1 || value.complete !== true
20
20
  || !isRecord(value.payload) || attentionTab(value.tab) !== value.tab || typeof value.selectedSymbol !== "string"
21
21
  || !Number.isInteger(value.plottedValueCount) || Number(value.plottedValueCount) < 0) return null;
22
- try { validateAttention(value.payload as unknown as AttentionPayload); return value as unknown as AttentionEvidence; } catch { return null; }
22
+ try { validateAttention(value.payload as unknown as AttentionPayload); return value as unknown as AttentionEvidence; } catch { /* Intentional ignore: invalid captured observations are rejected as evidence by returning null. */ return null; }
23
23
  },
24
24
  mismatches(evidence, { resolved }) {
25
25
  return [evidence.payload.window !== attentionWindow(resolved.options.window) ? "Attention window does not match" : null,
@@ -14,7 +14,7 @@ const optionalText = (value: unknown) => value == null || text(value);
14
14
  const amount = (value: unknown) => value == null || text(value) && /^-?\d+(?:\.\d+)?$/.test(value) && Number.isFinite(Number(value));
15
15
  const date = (value: unknown) => text(value) && /^\d{4}-\d{2}-\d{2}$/.test(value) && Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value;
16
16
  const instant = (value: unknown) => text(value) && Number.isFinite(Date.parse(value));
17
- const url = (value: unknown) => { try { return text(value) && ["https:", "http:"].includes(new URL(value).protocol); } catch { return false; } };
17
+ const url = (value: unknown) => { try { return text(value) && ["https:", "http:"].includes(new URL(value).protocol); } catch { /* Intentional ignore: malformed URLs fail this web link field validator. */ return false; } };
18
18
  const confidence = (value: unknown) => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
19
19
  const count = (value: unknown) => Number.isSafeInteger(value) && Number(value) >= 0;
20
20
  const currency = (value: unknown) => text(value) && /^[A-Z]{3}$/.test(value);
@@ -24,7 +24,7 @@ export const awardsScreenshotEvidence: PaneScreenshotEvidenceHook<AwardsEvidence
24
24
  read(value) {
25
25
  if (!isRecord(value) || value.kind !== "government-awards" || value.version !== 1 || value.complete !== true || !Number.isSafeInteger(value.plottedValueCount)
26
26
  || Number(value.plottedValueCount) < 0 || awardTab(value.tab) !== value.tab || !isRecord(value.payload)) return null;
27
- try { validateAwards(value.payload as unknown as AwardsPayload); return value as unknown as AwardsEvidence; } catch { return null; }
27
+ try { validateAwards(value.payload as unknown as AwardsPayload); return value as unknown as AwardsEvidence; } catch { /* Intentional ignore: invalid captured observations are rejected as evidence by returning null. */ return null; }
28
28
  },
29
29
  mismatches(evidence, { resolved, payload }) {
30
30
  const snapshot = payload.config.layout.instances.find((entry) => entry.instanceId === payload.paneId)?.settings?.awardsSnapshot;
@@ -26,6 +26,7 @@ import { AWARDS_UNAVAILABLE, fetchAwards, loadAward, loadAwards, validateAwards
26
26
  import { useAwardsEvidence } from "./evidence";
27
27
  import { AWARD_TABS, aggregateId, awardHistorySeries, awardPercent, awardPeriod, awardScope, awardsCoverageNotes, awardsPreviewNote, awardTab, awardTypeLabel, futureAwardDatesNote, money,
28
28
  rankedAggregates } from "./model";
29
+ import { logFailure } from "../../../utils/log-failure";
29
30
 
30
31
  type Item = { kind: "award"; row: AwardRow } | { kind: "aggregate"; row: AwardAggregate } | { kind: "leader"; row: AwardCompanyLeader } | { kind: "locked"; id: string }
31
32
  | { kind: "section"; id: string; label: string; count: number } | { kind: "note"; id: string; text: string };
@@ -116,7 +117,7 @@ function AwardsView({ width, height, focused, symbol }: PaneProps & { symbol: st
116
117
  const [selectedId, setSelected] = usePluginPaneState<string | null>(`awards:selection:${tab}`, null);
117
118
  const search = useQueryBarSearch(), tickerSearch = useQueryBarSearch();
118
119
  const [snapshotSetting] = usePaneSettingValue<AwardsPayload | null>("awardsSnapshot", null);
119
- const snapshot = useMemo(() => { try { return snapshotSetting ? validateAwards(snapshotSetting) : null; } catch { return null; } }, [snapshotSetting]);
120
+ const snapshot = useMemo(() => { try { return snapshotSetting ? validateAwards(snapshotSetting) : null; } catch (error) { return logFailure("awards.pane", "Validate awards snapshot failed", null)(error); } }, [snapshotSetting]);
120
121
  const filter = useMemo<AwardFilter>(() => ({ ticker: ticker.trim().toUpperCase() || undefined, query: query.trim() || undefined,
121
122
  jurisdiction: jurisdiction || undefined, currency: currency || undefined, source: source || undefined, awardType, agency: agency || undefined, sector: sector || undefined, parentId: parentId || undefined,
122
123
  from: parentId ? undefined : range === "all" ? from || undefined : new Date(Date.now() - Number(range) * 86_400_000).toISOString().slice(0, 10), to: parentId ? undefined : to || undefined, limit: 100,
@@ -157,7 +157,7 @@ export function treasurySpread(terms: BondTerms, yieldPercent: number, curve: re
157
157
  const before = points.findLast((point) => point.maturityYears <= maturityYears);
158
158
  const after = points.find((point) => point.maturityYears >= maturityYears);
159
159
  if (!before || !after || !before.asOf || before.asOf !== after.asOf) return null;
160
- try { parseDate(before.asOf); } catch { return null; }
160
+ try { parseDate(before.asOf); } catch { /* Intentional ignore: a benchmark curve with an unreadable date gives no spread. */ return null; }
161
161
  const weight = before === after ? 0 : (maturityYears - before.maturityYears) / (after.maturityYears - before.maturityYears);
162
162
  const benchmarkPercent = before.yieldPercent! + weight * (after.yieldPercent! - before.yieldPercent!);
163
163
  return { benchmarkPercent, spreadBps: (yieldPercent - benchmarkPercent) * 100, asOf: before.asOf, maturityYears };
@@ -2,6 +2,7 @@ import { useMemo, useRef } from "react";
2
2
  import { usePaneFooter, type PaneFooterSegment, type PaneHint } from "../../../components";
3
3
  import { enableBrokerHint } from "../shared/broker-reconnect";
4
4
  import type { BrokerManagerMessage } from "./pane-actions";
5
+ import { logFailure } from "../../../utils/log-failure";
5
6
 
6
7
  interface BrokerManagerFooterActions {
7
8
  connectSelected: () => Promise<void>;
@@ -58,8 +59,8 @@ export function useBrokerManagerFooter({
58
59
  hints.push({ id: "edit", key: "e", label: "dit", onPress: () => actionsRef.current.startEdit() });
59
60
  if (disabledSelected === null) {
60
61
  hints.push(
61
- { id: "connect", key: "c", label: "onnect", onPress: () => actionsRef.current.connectSelected().catch(() => {}) },
62
- { id: "sync", key: "s", label: "ync", onPress: () => actionsRef.current.syncSelected().catch(() => {}) },
62
+ { id: "connect", key: "c", label: "onnect", onPress: () => actionsRef.current.connectSelected().catch(logFailure("broker-manager.footer", "Connect selected broker profile failed")) },
63
+ { id: "sync", key: "s", label: "ync", onPress: () => actionsRef.current.syncSelected().catch(logFailure("broker-manager.footer", "Sync selected broker profile failed")) },
63
64
  );
64
65
  }
65
66
  }
@@ -43,6 +43,7 @@ import {
43
43
  renderBrokerCell,
44
44
  type BrokerColumn,
45
45
  } from "./table";
46
+ import { logFailure } from "../../../utils/log-failure";
46
47
 
47
48
  export function BrokersPane({ focused, width, height }: PaneProps) {
48
49
  const language = useAppLanguage();
@@ -275,7 +276,7 @@ export function BrokersPane({ focused, width, height }: PaneProps) {
275
276
  }, []);
276
277
 
277
278
  const saveCurrentEdit = useCallback(() => {
278
- saveEdit().catch(() => {});
279
+ saveEdit().catch(logFailure("broker-manager", "Save broker profile edit failed"));
279
280
  }, [saveEdit]);
280
281
 
281
282
  // The detail insets one cell each side like the table cells.
@@ -1,6 +1,7 @@
1
1
  import { useShortcut, type KeyEventLike } from "../../../react/input";
2
2
  import { isPlainKey } from "../../../utils/keyboard";
3
3
  import type { BrokerEditKey } from "./detail";
4
+ import { logFailure } from "../../../utils/log-failure";
4
5
 
5
6
  /**
6
7
  * The edit form's keys beside its field ring (the detail's useFieldRing walks
@@ -48,7 +49,7 @@ export function useBrokerManagerKeyboard({
48
49
  }
49
50
  if (isPlainKey(event, "enter", "return")) {
50
51
  consume(event);
51
- saveEdit().catch(() => {});
52
+ saveEdit().catch(logFailure("broker-manager.keyboard", "Save broker form failed"));
52
53
  return;
53
54
  }
54
55
  if (onSelectRow && isPlainKey(event, "left", "h", "right", "l", "space")) {
@@ -32,7 +32,7 @@ function screenshotEvidence(paneId: string): PaneScreenshotEvidenceHook<Catalyst
32
32
  const payload = validateCatalysts(value.payload as unknown as CatalystResponse);
33
33
  if (value.rowIds.some((id) => !payload.events.some((event) => event.id === id)) || value.plottedValueCount !== value.rowIds.length) return null;
34
34
  return value as unknown as CatalystEvidence;
35
- } catch { return null; }
35
+ } catch { /* Intentional ignore: invalid captured observations are rejected as evidence by returning null. */ return null; }
36
36
  },
37
37
  mismatches(evidence, { resolved, payload }) {
38
38
  const snapshot = payload.config.layout.instances.find((pane) => pane.instanceId === payload.paneId)?.settings?.catalystSnapshot;
@@ -18,6 +18,7 @@ import { CLOUD_PLAN_KEY, useCloudUpgradeAction } from "../shared/cloud-upgrade";
18
18
  import { useOpenDescription } from "../shared/open-description";
19
19
  import { Blurred, LockedOverlay, UpgradeLabel } from "../shared/locked-rows";
20
20
  import { listingCell, toneColor } from "../shared/research-cells";
21
+ import { logFailure } from "../../../utils/log-failure";
21
22
  import { isCloudSessionRequired, useResearchCloudSession } from "../shared/research-cloud-session";
22
23
  import { loadCatalystDetail, loadCatalysts, validateCatalysts } from "./client";
23
24
  import { CatalystEventDetail } from "./detail";
@@ -65,7 +66,7 @@ export function CatalystView({ width, height, focused, symbol, litigation = fals
65
66
  const [selectedId, setSelectedId] = usePluginPaneState<string | null>("catalyst:selected", null);
66
67
  const [searchActive, setSearchActive] = useState(false);
67
68
  const [dateFieldActive, setDateFieldActive] = useState<string | null>(null);
68
- const snapshot = useMemo(() => { try { return snapshotSetting ? validateCatalysts(snapshotSetting) : null; } catch { return null; } }, [snapshotSetting]);
69
+ const snapshot = useMemo(() => { try { return snapshotSetting ? validateCatalysts(snapshotSetting) : null; } catch (error) { return logFailure("catalysts.pane", "Validate catalysts snapshot failed", null)(error); } }, [snapshotSetting]);
69
70
  const query = useMemo(() => catalystQuery({ ...filters, tab }, symbol ?? undefined, litigation), [filters, tab, symbol, litigation]);
70
71
  const loader = useCallback(async ({ offset, signal, force }: PageRequest) => {
71
72
  const result = snapshot ? { payload: snapshot, stale: false, refreshError: null } : await loadCatalysts({ ...query, limit: 100, offset }, accessKey, force, signal);