gloomberb 0.20.9 → 0.20.11

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 (212) hide show
  1. package/package.json +1 -1
  2. package/patches/@opentui%2Fcore@0.3.2.patch +16 -0
  3. package/src/api-client/auth.ts +6 -0
  4. package/src/api-client/data.ts +1 -0
  5. package/src/api-client/earnings.ts +15 -0
  6. package/src/api-client/index.ts +14 -3
  7. package/src/api-client/socket-connection.ts +355 -0
  8. package/src/api-client/socket-features.ts +75 -0
  9. package/src/api-client/socket-frames.ts +161 -0
  10. package/src/api-client/socket-listeners.ts +207 -0
  11. package/src/api-client/socket-quotes.ts +332 -0
  12. package/src/api-client/socket.ts +150 -983
  13. package/src/api-client/types/account.ts +10 -0
  14. package/src/api-client/types/billing.ts +10 -0
  15. package/src/api-client/types/econ.ts +19 -7
  16. package/src/api-client/types/market.ts +7 -0
  17. package/src/api-client/types/screener.ts +2 -0
  18. package/src/brokers/signed-in/adapter.ts +19 -5
  19. package/src/brokers/signed-in/client.ts +13 -1
  20. package/src/brokers/signed-in/sign-in-dialog.tsx +33 -9
  21. package/src/cli/commands/market.ts +18 -8
  22. package/src/cli/commands/overview.ts +26 -7
  23. package/src/cli/commands/ticker.ts +40 -15
  24. package/src/cli/desktop-pane-shot.ts +39 -0
  25. package/src/cli/errors.ts +20 -3
  26. package/src/cli/fx-pair.ts +11 -2
  27. package/src/cli/history-rows.ts +34 -3
  28. package/src/cli/index.ts +1 -1
  29. package/src/cli/listing-arg.ts +51 -13
  30. package/src/cli/pane-functions/headless.ts +4 -2
  31. package/src/cli/pane-functions/index.ts +1 -0
  32. package/src/cli/pane-functions/resolver.ts +2 -1
  33. package/src/cli/pane-functions/screenshot-assessment.ts +73 -5
  34. package/src/cli/pane-functions/screenshot-types.ts +4 -0
  35. package/src/components/chart/composite/chart-layout.ts +7 -4
  36. package/src/components/chart/composite/composite-chart.tsx +6 -16
  37. package/src/components/chart/composite/toolbar.tsx +258 -82
  38. package/src/components/chart/composite/use-composite-chart-keyboard.ts +5 -6
  39. package/src/components/chart/native/kitty/manager.ts +2 -0
  40. package/src/components/chart/native/surface/manager.ts +211 -11
  41. package/src/components/command-bar/list/model.ts +13 -0
  42. package/src/components/command-bar/panel/index.tsx +2 -13
  43. package/src/components/command-bar/panel/layout.ts +1 -7
  44. package/src/components/command-bar/panel/runtime.ts +0 -1
  45. package/src/components/command-bar/panel/types.ts +0 -2
  46. package/src/components/command-bar/routes/ticker-search/actions.ts +2 -0
  47. package/src/components/command-bar/routes/ticker-search/results.ts +15 -8
  48. package/src/components/command-bar/surface/index.tsx +10 -5
  49. package/src/components/command-bar/workflow/alert.ts +21 -7
  50. package/src/components/data-table/column-menu.tsx +89 -0
  51. package/src/components/data-table/sort-menu.tsx +9 -2
  52. package/src/components/data-table/table-pane.ts +3 -1
  53. package/src/components/data-table/view.tsx +33 -6
  54. package/src/components/form-modal/content.tsx +10 -0
  55. package/src/components/index.ts +1 -1
  56. package/src/components/layout/pane/footer/index.tsx +25 -11
  57. package/src/components/layout/pane/footer/model.ts +88 -21
  58. package/src/components/layout/pane/sidebar.tsx +125 -15
  59. package/src/components/layout/shell/active-drag.ts +18 -13
  60. package/src/components/layout/shell/drag/magnets.ts +34 -18
  61. package/src/components/metric-treemap/heat-surface.tsx +2 -1
  62. package/src/components/metric-treemap/index.tsx +3 -2
  63. package/src/components/ticker/list-table-view.tsx +5 -0
  64. package/src/components/ui/confirm-dialog.tsx +253 -7
  65. package/src/components/ui/data-table/column-order.ts +180 -0
  66. package/src/components/ui/data-table/index.tsx +13 -2
  67. package/src/components/ui/data-table/opentui/index.tsx +267 -23
  68. package/src/components/ui/data-table/opentui/model.ts +43 -4
  69. package/src/components/ui/data-table/types.ts +56 -0
  70. package/src/components/ui/data-table/use-column-order.ts +135 -0
  71. package/src/components/ui/index.ts +1 -1
  72. package/src/components/ui/list-view.tsx +4 -3
  73. package/src/components/ui/status.tsx +9 -6
  74. package/src/components/ui/table-layout.ts +120 -0
  75. package/src/docs/snapshot.json +39 -2
  76. package/src/i18n/es.ts +14 -0
  77. package/src/i18n/ja.ts +14 -0
  78. package/src/i18n/ko.ts +14 -0
  79. package/src/i18n/zh-cn.ts +14 -0
  80. package/src/i18n/zh-tw.ts +14 -0
  81. package/src/market-data/coordinator/index.ts +4 -3
  82. package/src/market-data/coordinator/quotes.ts +12 -4
  83. package/src/market-data/fx-closes.ts +14 -2
  84. package/src/market-data/market/change-basis.ts +35 -1
  85. package/src/market-data/market/status.ts +37 -0
  86. package/src/market-data/performance.ts +4 -1
  87. package/src/market-data/quotes/freshness.ts +12 -0
  88. package/src/market-data/quotes/live-valuation.ts +26 -3
  89. package/src/market-data/quotes/regular-session-valuation.ts +1 -1
  90. package/src/market-data/realized-volatility.ts +3 -0
  91. package/src/market-data/us-bond-market.ts +115 -0
  92. package/src/plugins/builtin/account-management/invite-row.tsx +54 -0
  93. package/src/plugins/builtin/account-management/keyboard.ts +3 -0
  94. package/src/plugins/builtin/account-management/model.ts +1 -0
  95. package/src/plugins/builtin/account-management/pane.tsx +51 -5
  96. package/src/plugins/builtin/account-management/trial-cancel.ts +32 -7
  97. package/src/plugins/builtin/broker-manager/detail.tsx +5 -3
  98. package/src/plugins/builtin/broker-manager/index.tsx +6 -6
  99. package/src/plugins/builtin/broker-manager/model.ts +15 -6
  100. package/src/plugins/builtin/broker-manager/pane-actions.tsx +11 -4
  101. package/src/plugins/builtin/broker-manager/sign-in-end.ts +50 -19
  102. package/src/plugins/builtin/broker-manager/table.ts +10 -4
  103. package/src/plugins/builtin/chat/sidebar.tsx +33 -16
  104. package/src/plugins/builtin/cloud/askg/pane-session.ts +94 -0
  105. package/src/plugins/builtin/cloud/askg/pane.tsx +40 -83
  106. package/src/plugins/builtin/cloud/askg/tool-timeline.tsx +2 -0
  107. package/src/plugins/builtin/congress-trades/pane.tsx +8 -2
  108. package/src/plugins/builtin/correlation/compute.ts +4 -3
  109. package/src/plugins/builtin/earnings/board-model.ts +33 -0
  110. package/src/plugins/builtin/earnings/board-table.ts +50 -11
  111. package/src/plugins/builtin/earnings/board.tsx +29 -13
  112. package/src/plugins/builtin/earnings/calendar.tsx +15 -3
  113. package/src/plugins/builtin/earnings/client.ts +4 -1
  114. package/src/plugins/builtin/earnings/headless.ts +27 -14
  115. package/src/plugins/builtin/econ/calendar-source.ts +3 -0
  116. package/src/plugins/builtin/equity-screener/live.ts +74 -18
  117. package/src/plugins/builtin/equity-screener/model.ts +19 -4
  118. package/src/plugins/builtin/equity-screener/pane.tsx +19 -14
  119. package/src/plugins/builtin/equity-screener/refresh-anchor.ts +45 -0
  120. package/src/plugins/builtin/equity-screener/results.ts +22 -2
  121. package/src/plugins/builtin/equity-screener/screen-check.ts +9 -3
  122. package/src/plugins/builtin/futures/index.tsx +15 -1
  123. package/src/plugins/builtin/futures/table.tsx +1 -1
  124. package/src/plugins/builtin/fx-matrix/index.tsx +2 -0
  125. package/src/plugins/builtin/help/index.tsx +1 -1
  126. package/src/plugins/builtin/holders/pane.tsx +30 -20
  127. package/src/plugins/builtin/ipo-calendar/model.ts +3 -3
  128. package/src/plugins/builtin/iv-history/events.ts +5 -0
  129. package/src/plugins/builtin/iv-history/headless.ts +19 -12
  130. package/src/plugins/builtin/kelly-sizer/sections.tsx +2 -0
  131. package/src/plugins/builtin/macro-day/headless.ts +27 -8
  132. package/src/plugins/builtin/macro-day/model.ts +17 -4
  133. package/src/plugins/builtin/macro-day/releases.ts +36 -15
  134. package/src/plugins/builtin/market-halts/model.ts +3 -2
  135. package/src/plugins/builtin/market-movers/headless.ts +2 -1
  136. package/src/plugins/builtin/market-movers/index.tsx +3 -2
  137. package/src/plugins/builtin/market-movers/model.ts +75 -22
  138. package/src/plugins/builtin/market-movers/screener.ts +2 -1
  139. package/src/plugins/builtin/market-movers/table.ts +7 -5
  140. package/src/plugins/builtin/options/view.tsx +2 -0
  141. package/src/plugins/builtin/options-scenario/pane.tsx +2 -1
  142. package/src/plugins/builtin/pe-band/model.ts +4 -0
  143. package/src/plugins/builtin/perps/cascade-tabs.tsx +2 -1
  144. package/src/plugins/builtin/portfolio-list/cell-version.ts +4 -4
  145. package/src/plugins/builtin/portfolio-list/cli/render.ts +9 -4
  146. package/src/plugins/builtin/portfolio-list/pane/index.tsx +15 -1
  147. package/src/plugins/builtin/portfolio-list/summary/index.tsx +24 -7
  148. package/src/plugins/builtin/portfolio-list/summary/totals.ts +40 -11
  149. package/src/plugins/builtin/portfolio-list/table.tsx +18 -1
  150. package/src/plugins/builtin/rate-path/pane.tsx +2 -0
  151. package/src/plugins/builtin/research/analyst-headless.ts +9 -1
  152. package/src/plugins/builtin/research/analyst-pane.tsx +10 -4
  153. package/src/plugins/builtin/research/client.ts +25 -1
  154. package/src/plugins/builtin/research/corporate-actions-pane.tsx +2 -1
  155. package/src/plugins/builtin/research/event-model.ts +3 -13
  156. package/src/plugins/builtin/research/event-sources.ts +3 -1
  157. package/src/plugins/builtin/revenue-breakdown/pane.tsx +2 -0
  158. package/src/plugins/builtin/reverse-dcf/pane.tsx +2 -1
  159. package/src/plugins/builtin/seasonality/pane.tsx +2 -1
  160. package/src/plugins/builtin/short-interest/headless.ts +2 -0
  161. package/src/plugins/builtin/short-interest/publications-headless.ts +2 -0
  162. package/src/plugins/builtin/short-interest/watch-headless.ts +1 -0
  163. package/src/plugins/builtin/thirteenf/pane.tsx +2 -0
  164. package/src/plugins/builtin/ticker-detail/financials/model.ts +28 -6
  165. package/src/plugins/builtin/ticker-detail/financials/ratio-table.tsx +26 -9
  166. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +58 -35
  167. package/src/plugins/builtin/vol-surface/heat-grid.tsx +2 -1
  168. package/src/plugins/builtin/vol-surface/pane.tsx +2 -1
  169. package/src/plugins/builtin/world-indices/index.tsx +5 -1
  170. package/src/plugins/builtin/yield-curve/headless.ts +5 -1
  171. package/src/plugins/builtin/yield-curve/index.tsx +7 -1
  172. package/src/portfolio/column-values.ts +47 -14
  173. package/src/portfolio/return-metrics.ts +4 -2
  174. package/src/renderers/dom/data-table/column-drag.ts +147 -0
  175. package/src/renderers/dom/data-table/index.tsx +22 -0
  176. package/src/renderers/dom/data-table/row.tsx +27 -5
  177. package/src/renderers/dom/host/image-surface.tsx +19 -9
  178. package/src/renderers/dom/host/input.tsx +4 -0
  179. package/src/renderers/dom/styles.css +22 -0
  180. package/src/renderers/electrobun/view/cli-pane-shot-entry.tsx +23 -1
  181. package/src/renderers/opentui/chart-surface.tsx +1 -0
  182. package/src/renderers/opentui/frame-hits.ts +33 -0
  183. package/src/renderers/opentui/host.tsx +2 -0
  184. package/src/renderers/opentui/native-surface.ts +14 -21
  185. package/src/renderers/opentui/test-utils.tsx +3 -0
  186. package/src/sources/gloomberb-cloud/normalizers.ts +2 -0
  187. package/src/sources/provider-errors.ts +12 -0
  188. package/src/sources/provider-router/index.ts +12 -4
  189. package/src/state/app/context/index.tsx +22 -0
  190. package/src/state/pane-session.ts +145 -0
  191. package/src/test-support/app-store.ts +24 -1
  192. package/src/tickers/search/home-listing.ts +44 -1
  193. package/src/tickers/search/index.ts +5 -2
  194. package/src/tickers/search/ranking.ts +7 -7
  195. package/src/tickers/us-listing.ts +11 -5
  196. package/src/time-series/base-series.ts +7 -1
  197. package/src/time-series/fundamentals/current-valuation.ts +8 -0
  198. package/src/time-series/fundamentals/series.ts +6 -0
  199. package/src/time-series/live-quotes.ts +3 -9
  200. package/src/time-series/resolve.ts +1 -0
  201. package/src/types/financials.ts +20 -0
  202. package/src/types/headless.ts +9 -0
  203. package/src/ui/host.tsx +20 -0
  204. package/src/ui/pointer-drag.ts +11 -2
  205. package/src/utils/exchanges.ts +13 -8
  206. package/src/utils/fundamentals.ts +14 -3
  207. package/src/utils/price-earnings.ts +17 -10
  208. package/src/utils/price-history-integrity.ts +15 -0
  209. package/src/utils/reason-codes.ts +79 -0
  210. package/src/utils/share-multiples.cases.json +1667 -0
  211. package/src/utils/share-multiples.ts +384 -0
  212. package/src/utils/untrusted-text.ts +11 -0
@@ -0,0 +1,161 @@
1
+ import { logFailure } from "../utils/log-failure";
2
+ import { recordServerClockSample } from "../market-data/quotes/clock";
3
+ import type {
4
+ AuthUser,
5
+ ChatMessage,
6
+ ChatNotification,
7
+ ChatReactionsUpdate,
8
+ ScannerKind,
9
+ TeamNotification,
10
+ } from "./types";
11
+ import {
12
+ normalizeChatChannelStateFrame,
13
+ normalizeChatMessage,
14
+ normalizeChatNotification,
15
+ normalizeChatReactions,
16
+ normalizeTeamNotification,
17
+ } from "./normalizers";
18
+ import type { SocketListeners } from "./socket-listeners";
19
+
20
+ const SCANNER_MESSAGE_KINDS: Record<string, ScannerKind> = {
21
+ "scanner.hilo": "hilo",
22
+ "scanner.flow": "flow",
23
+ };
24
+
25
+ /** The server's hello on a connection. */
26
+ export type SocketReadyFrame = {
27
+ features?: unknown;
28
+ user?: Partial<AuthUser> | null;
29
+ };
30
+
31
+ /** Where a server frame goes: its listeners, or the socket itself for the frames that change the session. */
32
+ export type SocketFrameRoutes = {
33
+ listeners: SocketListeners;
34
+ /** "ready", once the server clock reading it carries is taken. */
35
+ ready: (frame: SocketReadyFrame) => void;
36
+ /** "auth.unverified": the server holds the session's user unverified. */
37
+ unverified: () => void;
38
+ /** One quote: a market.quote frame, or one item of a market.quotes batch. */
39
+ quote: (frame: unknown) => void;
40
+ };
41
+
42
+ /**
43
+ * Reads one server frame and hands it on, in one synchronous pass. A frame that does not parse is logged; a frame
44
+ * of a type nobody listens for is dropped.
45
+ */
46
+ export function dispatchSocketFrame(raw: string, routes: SocketFrameRoutes): void {
47
+ let parsed: any;
48
+ try {
49
+ parsed = JSON.parse(raw);
50
+ } catch (error) {
51
+ logFailure("cloud-socket", "WebSocket message decoding failed")(error);
52
+ return;
53
+ }
54
+ const { listeners } = routes;
55
+
56
+ if (parsed?.type === "ready") {
57
+ recordServerClockSample(parsed.serverTime);
58
+ routes.ready(parsed);
59
+ return;
60
+ }
61
+
62
+ if (parsed?.type === "auth.unverified") {
63
+ routes.unverified();
64
+ return;
65
+ }
66
+
67
+ if (
68
+ parsed?.type === "chat.message" &&
69
+ typeof parsed.channelId === "string" &&
70
+ parsed.data
71
+ ) {
72
+ listeners.chatChannels.emit(parsed.channelId, normalizeChatMessage(parsed.data as ChatMessage));
73
+ return;
74
+ }
75
+
76
+ if (
77
+ parsed?.type === "chat.reactions" &&
78
+ typeof parsed.channelId === "string" &&
79
+ typeof parsed.data?.messageId === "string"
80
+ ) {
81
+ const update: ChatReactionsUpdate = {
82
+ channelId: parsed.channelId,
83
+ messageId: parsed.data.messageId,
84
+ reactions: normalizeChatReactions(parsed.data.reactions),
85
+ };
86
+ listeners.chatReactions.emit(update);
87
+ return;
88
+ }
89
+
90
+ if (parsed?.type === "chat.notification" && parsed.data) {
91
+ listeners.chatNotifications.emit(normalizeChatNotification(parsed.data as ChatNotification));
92
+ return;
93
+ }
94
+
95
+ if (parsed?.type === "chat.mentions_changed") {
96
+ listeners.chatMentionCandidates.emit();
97
+ return;
98
+ }
99
+ if (parsed?.type === "chat.channel_state") {
100
+ const state = normalizeChatChannelStateFrame(parsed.data);
101
+ if (state) listeners.chatChannelState.emit(state);
102
+ return;
103
+ }
104
+
105
+ if (parsed?.type === "team.notification" && parsed.data) {
106
+ listeners.teamNotifications.emit(normalizeTeamNotification(parsed.data as TeamNotification));
107
+ return;
108
+ }
109
+
110
+ if (
111
+ parsed?.type === "chat.presence" &&
112
+ typeof parsed.onlineCount === "number"
113
+ ) {
114
+ listeners.chatPresence.emit(parsed.onlineCount);
115
+ return;
116
+ }
117
+
118
+ if (parsed?.type === "tape.snapshot" && parsed.data && typeof parsed.data.symbol === "string" && typeof parsed.data.exchange === "string") {
119
+ listeners.tape.emit(parsed.data.symbol, parsed.data.exchange, { type: "data", payload: parsed.data });
120
+ return;
121
+ }
122
+
123
+ const scannerKind =
124
+ typeof parsed?.type === "string"
125
+ ? SCANNER_MESSAGE_KINDS[parsed.type]
126
+ : undefined;
127
+ if (scannerKind) {
128
+ const { type: _type, ...payload } = parsed;
129
+ listeners.scanners.emit(scannerKind, { type: "data", payload });
130
+ return;
131
+ }
132
+
133
+ if (parsed?.type === "scanner.denied") {
134
+ const denied = SCANNER_MESSAGE_KINDS[`scanner.${parsed.scanner}`];
135
+ if (denied) {
136
+ listeners.scanners.emit(denied, {
137
+ type: "denied",
138
+ reason:
139
+ typeof parsed.reason === "string" ? parsed.reason : "pro_required",
140
+ });
141
+ }
142
+ return;
143
+ }
144
+
145
+ if (parsed?.type === "market.quote") {
146
+ routes.quote(parsed);
147
+ return;
148
+ }
149
+
150
+ if (parsed?.type === "market.quotes") {
151
+ recordServerClockSample(parsed.at);
152
+ if (!Array.isArray(parsed.quotes)) return;
153
+ // One synchronous pass: every item lands before the next data frame.
154
+ for (const item of parsed.quotes) routes.quote(item);
155
+ return;
156
+ }
157
+
158
+ if (typeof parsed?.type === "string") {
159
+ listeners.cloudEvents.emit(parsed.type, parsed.data);
160
+ }
161
+ }
@@ -0,0 +1,207 @@
1
+ import type { TapeFeedEvent } from "./tape";
2
+ import type {
3
+ ChatChannelState,
4
+ ChatMessage,
5
+ ChatNotification,
6
+ ChatReactionsUpdate,
7
+ ScannerFeedEvent,
8
+ ScannerKind,
9
+ TeamNotification,
10
+ } from "./types";
11
+ import { marketKey } from "./socket-quotes";
12
+
13
+ type Listener<Args extends unknown[]> = (...args: Args) => void;
14
+
15
+ /**
16
+ * What taking a listener off its key did: the key had no listeners, this one was not among them, it went and others
17
+ * remain, or it was the key's last and the key went with it.
18
+ */
19
+ type ListenerRemoval = "unknown-key" | "not-listening" | "removed" | "last";
20
+
21
+ /** Listeners to one kind of event, called in the order they subscribed. */
22
+ export class ListenerSet<Args extends unknown[] = []> {
23
+ private readonly listeners = new Set<Listener<Args>>();
24
+
25
+ get size(): number {
26
+ return this.listeners.size;
27
+ }
28
+
29
+ /** Adds a listener; the returned function removes it. */
30
+ add(listener: Listener<Args>): () => void {
31
+ this.listeners.add(listener);
32
+ return () => {
33
+ this.listeners.delete(listener);
34
+ };
35
+ }
36
+
37
+ emit(...args: Args): void {
38
+ for (const listener of this.listeners) listener(...args);
39
+ }
40
+
41
+ clear(): void {
42
+ this.listeners.clear();
43
+ }
44
+ }
45
+
46
+ /** Listeners grouped under a key (a chat channel, a frame type, a scanner); a key goes with its last listener. */
47
+ class KeyedListeners<K, Args extends unknown[]> {
48
+ private readonly groups = new Map<K, Set<Listener<Args>>>();
49
+
50
+ /** How many keys have listeners. */
51
+ get size(): number {
52
+ return this.groups.size;
53
+ }
54
+
55
+ keys(): IterableIterator<K> {
56
+ return this.groups.keys();
57
+ }
58
+
59
+ /** Adds a listener under its key; true when it is the key's first. */
60
+ add(key: K, listener: Listener<Args>): boolean {
61
+ const group = this.groups.get(key) ?? new Set<Listener<Args>>();
62
+ const first = group.size === 0;
63
+ group.add(listener);
64
+ this.groups.set(key, group);
65
+ return first;
66
+ }
67
+
68
+ remove(key: K, listener: Listener<Args>): ListenerRemoval {
69
+ const group = this.groups.get(key);
70
+ if (!group) return "unknown-key";
71
+ if (!group.delete(listener)) return "not-listening";
72
+ if (group.size > 0) return "removed";
73
+ this.groups.delete(key);
74
+ return "last";
75
+ }
76
+
77
+ emit(key: K, ...args: Args): void {
78
+ for (const listener of this.groups.get(key) ?? []) listener(...args);
79
+ }
80
+
81
+ clear(): void {
82
+ this.groups.clear();
83
+ }
84
+ }
85
+
86
+ /** A tape's market, as its subscribe frame names it. */
87
+ type TapeMarket = { symbol: string; exchange: string };
88
+
89
+ /** Tape listeners by market; each market keeps the symbol and exchange it was first subscribed with. */
90
+ class TapeListeners {
91
+ private readonly byMarket = new Map<string, TapeMarket & { listeners: Set<Listener<[TapeFeedEvent]>> }>();
92
+
93
+ /** How many markets have listeners. */
94
+ get size(): number {
95
+ return this.byMarket.size;
96
+ }
97
+
98
+ markets(): Iterable<TapeMarket> {
99
+ return this.byMarket.values();
100
+ }
101
+
102
+ /** Adds a listener to a normalized market; true when it is the market's first. */
103
+ add(market: TapeMarket, listener: Listener<[TapeFeedEvent]>): boolean {
104
+ const key = marketKey(market.symbol, market.exchange);
105
+ const existing = this.byMarket.get(key);
106
+ const entry = existing ?? { ...market, listeners: new Set<Listener<[TapeFeedEvent]>>() };
107
+ entry.listeners.add(listener);
108
+ this.byMarket.set(key, entry);
109
+ return !existing;
110
+ }
111
+
112
+ remove(market: TapeMarket, listener: Listener<[TapeFeedEvent]>): ListenerRemoval {
113
+ const key = marketKey(market.symbol, market.exchange);
114
+ const entry = this.byMarket.get(key);
115
+ if (!entry) return "unknown-key";
116
+ if (!entry.listeners.delete(listener)) return "not-listening";
117
+ if (entry.listeners.size) return "removed";
118
+ this.byMarket.delete(key);
119
+ return "last";
120
+ }
121
+
122
+ /** One market's event, keyed as the frame names it. */
123
+ emit(symbol: string, exchange: string, event: TapeFeedEvent): void {
124
+ for (const listener of this.byMarket.get(marketKey(symbol, exchange))?.listeners ?? []) listener(event);
125
+ }
126
+
127
+ /** A stream status every tape shares: a reset or a disconnect. */
128
+ emitAll(event: Exclude<TapeFeedEvent, { type: "data" }>): void {
129
+ for (const entry of this.byMarket.values()) for (const listener of entry.listeners) listener(event);
130
+ }
131
+
132
+ clear(): void {
133
+ this.byMarket.clear();
134
+ }
135
+ }
136
+
137
+ /** Scanner listeners by kind, with the latest payload of each so a pane opened mid-stream does not wait for the next tick. */
138
+ class ScannerListeners {
139
+ private readonly listeners = new KeyedListeners<ScannerKind, [ScannerFeedEvent]>();
140
+ private readonly snapshots = new Map<ScannerKind, ScannerFeedEvent>();
141
+
142
+ /** How many scanners have listeners. */
143
+ get size(): number {
144
+ return this.listeners.size;
145
+ }
146
+
147
+ keys(): IterableIterator<ScannerKind> {
148
+ return this.listeners.keys();
149
+ }
150
+
151
+ /** Adds a listener to a scanner; true when it is the scanner's first. */
152
+ add(scanner: ScannerKind, listener: Listener<[ScannerFeedEvent]>): boolean {
153
+ return this.listeners.add(scanner, listener);
154
+ }
155
+
156
+ snapshot(scanner: ScannerKind): ScannerFeedEvent | undefined {
157
+ return this.snapshots.get(scanner);
158
+ }
159
+
160
+ /** Removes a listener; the scanner's payload goes with its last one. */
161
+ remove(scanner: ScannerKind, listener: Listener<[ScannerFeedEvent]>): ListenerRemoval {
162
+ const removal = this.listeners.remove(scanner, listener);
163
+ if (removal === "last") this.snapshots.delete(scanner);
164
+ return removal;
165
+ }
166
+
167
+ emit(scanner: ScannerKind, event: ScannerFeedEvent): void {
168
+ this.snapshots.set(scanner, event);
169
+ this.listeners.emit(scanner, event);
170
+ }
171
+
172
+ clear(): void {
173
+ this.listeners.clear();
174
+ this.snapshots.clear();
175
+ }
176
+ }
177
+
178
+ /** Everyone the socket hands server frames to, by what they listen for. */
179
+ export class SocketListeners {
180
+ readonly chatChannels = new KeyedListeners<string, [ChatMessage]>();
181
+ readonly chatNotifications = new ListenerSet<[ChatNotification]>();
182
+ readonly chatMentionCandidates = new ListenerSet();
183
+ readonly chatChannelState = new ListenerSet<[ChatChannelState]>();
184
+ readonly chatReactions = new ListenerSet<[ChatReactionsUpdate]>();
185
+ readonly chatPresence = new ListenerSet<[number]>();
186
+ readonly teamNotifications = new ListenerSet<[TeamNotification]>();
187
+ /** Server push frames by type, e.g. a team layout update. */
188
+ readonly cloudEvents = new KeyedListeners<string, [unknown]>();
189
+ /** "ready" after each server hello, "closed" when that connection ends. */
190
+ readonly connection = new ListenerSet<["ready" | "closed"]>();
191
+ readonly tape = new TapeListeners();
192
+ readonly scanners = new ScannerListeners();
193
+
194
+ /** Drops the listeners a disposed socket no longer serves. Mention-candidate listeners stay subscribed across a dispose. */
195
+ clear(): void {
196
+ this.chatChannels.clear();
197
+ this.connection.clear();
198
+ this.chatNotifications.clear();
199
+ this.chatChannelState.clear();
200
+ this.chatPresence.clear();
201
+ this.chatReactions.clear();
202
+ this.teamNotifications.clear();
203
+ this.cloudEvents.clear();
204
+ this.tape.clear();
205
+ this.scanners.clear();
206
+ }
207
+ }
@@ -0,0 +1,332 @@
1
+ import type { CloudQuotePayload, QuoteStreamTarget } from "./types";
2
+ import { debugLog, previewList } from "../utils/debug-log";
3
+ import { canonicalExchange, normalizeSymbol } from "../utils/exchanges";
4
+ import { mergeQuoteSubscriptionTargets } from "../market-data/quote-subscription-target";
5
+ import { perpetualListing } from "../tickers/perpetual-listing";
6
+
7
+ /** How long subscription changes gather before they go out as one unsubscribe and one subscribe frame. */
8
+ export const QUOTE_SUBSCRIPTION_FLUSH_MS = 25;
9
+ /**
10
+ * The most perpetual listings the app streams at once, across every pane: on screen and selected first. The server
11
+ * takes up to 100 from one connection (fewer signed out); the rest keep their fetched readings.
12
+ */
13
+ const PERP_STREAM_BUDGET = 60;
14
+ /** On screen and selected first, then by weight; equal ones keep the order they were asked in. */
15
+ const perpStreamRank = (target: QuoteStreamTarget) => (target.selected ? 2 : 0) + (target.visible ? 1 : 0);
16
+ const isPerpTarget = (target: QuoteStreamTarget) => !!perpetualListing(target.symbol, target.exchange);
17
+ const cloudApiLog = debugLog.createLogger("cloud-api");
18
+
19
+ export type QuoteListener = (target: QuoteStreamTarget, quote: CloudQuotePayload) => void;
20
+ type QuoteSubscription = {
21
+ target: QuoteStreamTarget;
22
+ listener: QuoteListener;
23
+ };
24
+
25
+ /** What the quote stream needs from the connection. */
26
+ export type QuoteStreamLink = {
27
+ /** The connection while it is open, null otherwise. */
28
+ openSocket: () => WebSocket | null;
29
+ /** Sends a frame on the open connection; nothing happens when there is none. */
30
+ send: (payload: Record<string, unknown>) => void;
31
+ };
32
+
33
+ /** One listener's place in the quote stream. */
34
+ export type QuoteStreamSubscription = {
35
+ /** Queues what the subscription added or changed for the server. */
36
+ announce: () => void;
37
+ /** Takes the listener off its targets and queues what that changes. */
38
+ release: () => void;
39
+ };
40
+
41
+ /** One instrument's key across panes and frames: `AAPL:NASDAQ`, or the bare symbol without an exchange. */
42
+ export function marketKey(symbol: string, exchange?: string): string {
43
+ const normalizedSymbolValue = normalizeSymbol(symbol);
44
+ const normalizedExchangeValue = canonicalExchange(exchange);
45
+ return normalizedExchangeValue
46
+ ? `${normalizedSymbolValue}:${normalizedExchangeValue}`
47
+ : normalizedSymbolValue;
48
+ }
49
+
50
+ /** A target as market.subscribe sends it: an exchange always, and only the priority fields that are set. */
51
+ function serializeQuoteStreamTarget(target: QuoteStreamTarget): QuoteStreamTarget {
52
+ return {
53
+ symbol: target.symbol,
54
+ exchange: target.exchange ?? "",
55
+ ...(target.surface ? { surface: target.surface } : {}),
56
+ ...(target.visible ? { visible: true } : {}),
57
+ ...(target.selected ? { selected: true } : {}),
58
+ ...(Number.isFinite(target.weight) ? { weight: target.weight } : {}),
59
+ };
60
+ }
61
+
62
+ function sameQuoteStreamTarget(left: QuoteStreamTarget, right: QuoteStreamTarget): boolean {
63
+ return JSON.stringify(serializeQuoteStreamTarget(left)) === JSON.stringify(serializeQuoteStreamTarget(right));
64
+ }
65
+
66
+ function mergeQuoteStreamSubscriptions(subscriptions: Iterable<QuoteSubscription>): QuoteStreamTarget | null {
67
+ return mergeQuoteSubscriptionTargets([...subscriptions].map((subscription) => subscription.target));
68
+ }
69
+
70
+ /** The targets normalized, one per instrument (the last asked wins), without the ones that name no symbol. */
71
+ function uniqueQuoteStreamTargets(targets: QuoteStreamTarget[]): QuoteStreamTarget[] {
72
+ return [
73
+ ...new Map(
74
+ targets
75
+ .filter((target) => typeof target.symbol === "string" && target.symbol.trim().length > 0)
76
+ .map((target) => {
77
+ const normalized = {
78
+ symbol: normalizeSymbol(target.symbol),
79
+ exchange: canonicalExchange(target.exchange),
80
+ surface: target.surface,
81
+ visible: target.visible,
82
+ selected: target.selected,
83
+ weight: target.weight,
84
+ } satisfies QuoteStreamTarget;
85
+ return [marketKey(normalized.symbol, normalized.exchange), normalized] as const;
86
+ }),
87
+ ).values(),
88
+ ];
89
+ }
90
+
91
+ /**
92
+ * Every pane's quote listeners, merged per instrument, and what the server streams for them. Changes gather for
93
+ * QUOTE_SUBSCRIPTION_FLUSH_MS and go out together; a new connection gets the full set. Perpetual listings go out only
94
+ * on a connection whose server offers them, within PERP_STREAM_BUDGET.
95
+ */
96
+ export class QuoteStreamSubscriptions {
97
+ private nextSubscriptionId = 1;
98
+ private readonly subscriptions = new Map<string, Map<number, QuoteSubscription>>();
99
+ /** Each instrument's merged target: what the server was asked to stream. */
100
+ private readonly targets = new Map<string, QuoteStreamTarget>();
101
+ private readonly pendingSubscribes = new Map<string, QuoteStreamTarget>();
102
+ private readonly pendingUnsubscribes = new Map<string, QuoteStreamTarget>();
103
+ private flushTimer: ReturnType<typeof setTimeout> | null = null;
104
+ /**
105
+ * The connection whose server offered perpetual markets. Asked of every connection: a reconnect may reach an older
106
+ * server, which would read `BTC` on HYPERLIQUID as a stock symbol.
107
+ */
108
+ private perpsConnection: WebSocket | null = null;
109
+ /** The perpetual listings this connection streams, within PERP_STREAM_BUDGET. */
110
+ private streamedPerps = new Map<string, QuoteStreamTarget>();
111
+
112
+ constructor(private readonly link: QuoteStreamLink) {}
113
+
114
+ /** How many instruments are subscribed. */
115
+ get size(): number {
116
+ return this.targets.size;
117
+ }
118
+
119
+ /**
120
+ * Registers a listener on its targets. Nothing is queued for the server until `announce`, so the caller can open
121
+ * the connection in between.
122
+ */
123
+ subscribe(targets: QuoteStreamTarget[], listener: QuoteListener): QuoteStreamSubscription {
124
+ const subscriptionId = this.nextSubscriptionId++;
125
+ const uniqueTargets = uniqueQuoteStreamTargets(targets);
126
+
127
+ const newSubscriptions: QuoteStreamTarget[] = [];
128
+ const updatedSubscriptions: QuoteStreamTarget[] = [];
129
+ for (const target of uniqueTargets) {
130
+ const key = marketKey(target.symbol, target.exchange);
131
+ const subscriptions = this.subscriptions.get(key) ?? new Map<number, QuoteSubscription>();
132
+ const previousTarget = this.targets.get(key);
133
+ subscriptions.set(subscriptionId, { target, listener });
134
+ this.subscriptions.set(key, subscriptions);
135
+ const mergedTarget = mergeQuoteStreamSubscriptions(subscriptions.values()) ?? target;
136
+ if (!previousTarget) {
137
+ newSubscriptions.push(target);
138
+ } else if (!sameQuoteStreamTarget(previousTarget, mergedTarget)) {
139
+ updatedSubscriptions.push(mergedTarget);
140
+ }
141
+ this.targets.set(key, mergedTarget);
142
+ }
143
+
144
+ return {
145
+ announce: () => {
146
+ const subscriptionsToSend = [...newSubscriptions, ...updatedSubscriptions];
147
+ if (subscriptionsToSend.length === 0) return;
148
+ cloudApiLog.info("register quote listeners", {
149
+ count: subscriptionsToSend.length,
150
+ symbols: previewList(subscriptionsToSend, (target) => marketKey(target.symbol, target.exchange)),
151
+ });
152
+ this.queueSubscribes(subscriptionsToSend);
153
+ },
154
+ release: () => this.release(subscriptionId, uniqueTargets),
155
+ };
156
+ }
157
+
158
+ /** Delivers one market.quote frame, or one item of a market.quotes batch, to its listeners. */
159
+ deliver(frame: any): void {
160
+ if (!frame?.quote || typeof frame.symbol !== "string") return;
161
+ const subscriptions = this.subscriptions.get(marketKey(frame.symbol, frame.exchange));
162
+ if (!subscriptions) return;
163
+ const quote: CloudQuotePayload = {
164
+ ...(frame.quote as CloudQuotePayload),
165
+ ...(frame.delivery === "stream" || frame.delivery === "poll"
166
+ ? { delivery: frame.delivery }
167
+ : {}),
168
+ ...(typeof frame.stale === "boolean" ? { stale: frame.stale } : {}),
169
+ };
170
+ for (const subscription of subscriptions.values()) {
171
+ subscription.listener(subscription.target, quote);
172
+ }
173
+ }
174
+
175
+ /** A connection opened: what was queued before is part of the full set it is about to get. */
176
+ dropPending(): void {
177
+ this.pendingSubscribes.clear();
178
+ this.pendingUnsubscribes.clear();
179
+ }
180
+
181
+ /** Sends the full set on a connection that just opened; perpetual listings once its server offers them. */
182
+ replay(): void {
183
+ const targets = [...this.targets.values()].filter((target) => !isPerpTarget(target));
184
+ if (targets.length > 0) {
185
+ this.link.send({
186
+ type: "market.subscribe",
187
+ symbols: targets.map((target) => serializeQuoteStreamTarget(target)),
188
+ });
189
+ }
190
+ this.streamedPerps.clear();
191
+ this.syncPerpSubscriptions();
192
+ }
193
+
194
+ /**
195
+ * The connection whose server offers perpetual markets, null when the last hello did not. Perpetual listings held
196
+ * back since the socket opened go out once it is the open one.
197
+ */
198
+ setPerpsConnection(socket: WebSocket | null): void {
199
+ if (socket === this.perpsConnection) return;
200
+ this.perpsConnection = socket;
201
+ this.streamedPerps.clear();
202
+ this.syncPerpSubscriptions();
203
+ }
204
+
205
+ /** Drops every listener and queued change, and the flush waiting for them. */
206
+ clear(): void {
207
+ this.subscriptions.clear();
208
+ this.targets.clear();
209
+ this.pendingSubscribes.clear();
210
+ this.pendingUnsubscribes.clear();
211
+ if (this.flushTimer) {
212
+ clearTimeout(this.flushTimer);
213
+ this.flushTimer = null;
214
+ }
215
+ }
216
+
217
+ private release(subscriptionId: number, uniqueTargets: QuoteStreamTarget[]): void {
218
+ const removedTargets: QuoteStreamTarget[] = [];
219
+ const updatedTargets: QuoteStreamTarget[] = [];
220
+
221
+ for (const target of uniqueTargets) {
222
+ const key = marketKey(target.symbol, target.exchange);
223
+ const subscriptions = this.subscriptions.get(key);
224
+ if (!subscriptions || !subscriptions.delete(subscriptionId)) continue;
225
+ const previousTarget = this.targets.get(key);
226
+ if (subscriptions.size === 0) {
227
+ this.subscriptions.delete(key);
228
+ if (previousTarget) removedTargets.push(previousTarget);
229
+ this.targets.delete(key);
230
+ continue;
231
+ }
232
+ const mergedTarget = mergeQuoteStreamSubscriptions(subscriptions.values());
233
+ if (!mergedTarget) continue;
234
+ this.targets.set(key, mergedTarget);
235
+ if (previousTarget && !sameQuoteStreamTarget(previousTarget, mergedTarget)) {
236
+ updatedTargets.push(mergedTarget);
237
+ }
238
+ }
239
+
240
+ if (updatedTargets.length > 0) {
241
+ this.queueSubscribes(updatedTargets);
242
+ }
243
+
244
+ if (removedTargets.length > 0) {
245
+ cloudApiLog.info("remove quote listeners", {
246
+ count: removedTargets.length,
247
+ symbols: previewList(removedTargets, (target) => marketKey(target.symbol, target.exchange)),
248
+ });
249
+ this.queueUnsubscribes(removedTargets);
250
+ }
251
+ }
252
+
253
+ /**
254
+ * Streams the perpetual listings within the budget, once this connection's server offers them: the best ranked
255
+ * across every pane. One that falls out is unsubscribed; one whose target changed (`changed`) is sent again.
256
+ */
257
+ private syncPerpSubscriptions(changed: ReadonlySet<string> = new Set()): void {
258
+ const ws = this.link.openSocket();
259
+ if (!ws || this.perpsConnection !== ws) return;
260
+ const wanted = new Map(
261
+ [...this.targets]
262
+ .filter(([, target]) => isPerpTarget(target))
263
+ .sort(([, left], [, right]) => perpStreamRank(right) - perpStreamRank(left) || (right.weight ?? 0) - (left.weight ?? 0))
264
+ .slice(0, PERP_STREAM_BUDGET),
265
+ );
266
+ const unsubscribes = [...this.streamedPerps].filter(([key]) => !wanted.has(key)).map(([, target]) => target);
267
+ const subscribes = [...wanted].filter(([key]) => !this.streamedPerps.has(key) || changed.has(key)).map(([, target]) => target);
268
+ this.streamedPerps = wanted;
269
+ if (unsubscribes.length > 0) {
270
+ this.link.send({ type: "market.unsubscribe", symbols: unsubscribes.map((target) => serializeQuoteStreamTarget(target)) });
271
+ }
272
+ if (subscribes.length > 0) {
273
+ this.link.send({ type: "market.subscribe", symbols: subscribes.map((target) => serializeQuoteStreamTarget(target)) });
274
+ }
275
+ }
276
+
277
+ private scheduleFlush(): void {
278
+ if (this.flushTimer) return;
279
+ this.flushTimer = setTimeout(() => {
280
+ this.flushTimer = null;
281
+ this.flushQueued();
282
+ }, QUOTE_SUBSCRIPTION_FLUSH_MS);
283
+ }
284
+
285
+ private queueSubscribes(targets: QuoteStreamTarget[]): void {
286
+ for (const target of targets) {
287
+ const key = marketKey(target.symbol, target.exchange);
288
+ this.pendingUnsubscribes.delete(key);
289
+ this.pendingSubscribes.set(key, target);
290
+ }
291
+ this.scheduleFlush();
292
+ }
293
+
294
+ private queueUnsubscribes(targets: QuoteStreamTarget[]): void {
295
+ for (const target of targets) {
296
+ const key = marketKey(target.symbol, target.exchange);
297
+ this.pendingSubscribes.delete(key);
298
+ this.pendingUnsubscribes.set(key, target);
299
+ }
300
+ this.scheduleFlush();
301
+ }
302
+
303
+ /** Sends what gathered since the last flush; on a connection that is not open it is dropped, as the open replays all. */
304
+ private flushQueued(): void {
305
+ if (!this.link.openSocket()) {
306
+ this.pendingSubscribes.clear();
307
+ this.pendingUnsubscribes.clear();
308
+ return;
309
+ }
310
+ const subscribes = [...this.pendingSubscribes.values()].filter((target) => !isPerpTarget(target));
311
+ const unsubscribes = [...this.pendingUnsubscribes.values()].filter((target) => !isPerpTarget(target));
312
+ const perpsChanged = [...this.pendingSubscribes]
313
+ .filter(([, target]) => isPerpTarget(target))
314
+ .map(([key]) => key);
315
+ const perpsMoved = perpsChanged.length > 0 || [...this.pendingUnsubscribes.values()].some(isPerpTarget);
316
+ this.pendingSubscribes.clear();
317
+ this.pendingUnsubscribes.clear();
318
+ if (perpsMoved) this.syncPerpSubscriptions(new Set(perpsChanged));
319
+ if (unsubscribes.length > 0) {
320
+ this.link.send({
321
+ type: "market.unsubscribe",
322
+ symbols: unsubscribes.map((target) => serializeQuoteStreamTarget(target)),
323
+ });
324
+ }
325
+ if (subscribes.length > 0) {
326
+ this.link.send({
327
+ type: "market.subscribe",
328
+ symbols: subscribes.map((target) => serializeQuoteStreamTarget(target)),
329
+ });
330
+ }
331
+ }
332
+ }