gloomberb 0.2.0 → 0.3.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 (311) hide show
  1. package/README.md +20 -19
  2. package/bin/gloomberb +3 -0
  3. package/package.json +5 -4
  4. package/patches/@opentui%2Fcore@0.1.90.patch +356 -0
  5. package/src/app.tsx +1365 -0
  6. package/src/brokers/sync-broker-instance.test.ts +100 -0
  7. package/src/brokers/sync-broker-instance.ts +341 -0
  8. package/src/cli/commands/plugins.ts +173 -0
  9. package/src/cli/commands/portfolio.ts +210 -0
  10. package/src/cli/commands/search.ts +120 -0
  11. package/src/cli/commands/ticker.ts +375 -0
  12. package/src/cli/commands/watchlist.ts +210 -0
  13. package/src/cli/context.ts +62 -0
  14. package/src/cli/errors.ts +13 -0
  15. package/src/cli/helpers.ts +85 -0
  16. package/src/cli/index.ts +143 -0
  17. package/src/cli/ticker-resolution.ts +39 -0
  18. package/src/cli/types.ts +15 -0
  19. package/src/cli.test.ts +361 -0
  20. package/src/components/chart/chart-data.ts +239 -0
  21. package/src/components/chart/chart-renderer.ts +1199 -0
  22. package/src/components/chart/chart-types.ts +82 -0
  23. package/src/components/chart/chart-viewport.ts +21 -0
  24. package/src/components/chart/chart.test.ts +439 -0
  25. package/src/components/chart/comparison-chart-data.test.ts +109 -0
  26. package/src/components/chart/comparison-chart-data.ts +316 -0
  27. package/src/components/chart/comparison-chart-renderer.test.ts +84 -0
  28. package/src/components/chart/comparison-chart-renderer.ts +354 -0
  29. package/src/components/chart/comparison-stock-chart.tsx +1486 -0
  30. package/src/components/chart/cursor-motion.ts +48 -0
  31. package/src/components/chart/native/chart-rasterizer.ts +732 -0
  32. package/src/components/chart/native/kitty-adapter.ts +12 -0
  33. package/src/components/chart/native/kitty-manager.ts +142 -0
  34. package/src/components/chart/native/kitty-protocol.ts +110 -0
  35. package/src/components/chart/native/kitty-support.ts +71 -0
  36. package/src/components/chart/native/kitty.test.ts +620 -0
  37. package/src/components/chart/native/renderer-selection.ts +24 -0
  38. package/src/components/chart/native/surface-manager.ts +225 -0
  39. package/src/components/chart/native/surface-sync.ts +34 -0
  40. package/src/components/chart/stock-chart-renderer-switch.test.tsx +165 -0
  41. package/src/components/chart/stock-chart.test.ts +107 -0
  42. package/src/components/chart/stock-chart.tsx +1556 -0
  43. package/src/components/command-bar/__snapshots__/command-bar.test.tsx.snap +137 -0
  44. package/src/components/command-bar/command-bar.test.tsx +1546 -0
  45. package/src/components/command-bar/command-bar.tsx +4841 -0
  46. package/src/components/command-bar/command-registry.ts +269 -0
  47. package/src/components/command-bar/helpers.test.ts +224 -0
  48. package/src/components/command-bar/helpers.ts +371 -0
  49. package/src/components/command-bar/root-shortcuts.ts +158 -0
  50. package/src/components/command-bar/view-model.test.ts +152 -0
  51. package/src/components/command-bar/view-model.ts +185 -0
  52. package/src/components/command-bar/workflow-ops.test.ts +70 -0
  53. package/src/components/command-bar/workflow-ops.ts +433 -0
  54. package/src/components/command-bar/workflow-types.ts +127 -0
  55. package/src/components/detail-feed-view.test.tsx +105 -0
  56. package/src/components/detail-feed-view.tsx +295 -0
  57. package/src/components/index.ts +32 -0
  58. package/src/components/layout/floating-pane.tsx +49 -0
  59. package/src/components/layout/header.tsx +151 -0
  60. package/src/components/layout/pane-header.tsx +44 -0
  61. package/src/components/layout/pane.tsx +49 -0
  62. package/src/components/layout/pixel-mouse-mode.test.ts +122 -0
  63. package/src/components/layout/pixel-mouse.test.ts +40 -0
  64. package/src/components/layout/shell.test.tsx +651 -0
  65. package/src/components/layout/shell.tsx +1200 -0
  66. package/src/components/layout/status-bar.test.tsx +173 -0
  67. package/src/components/layout/status-bar.tsx +138 -0
  68. package/src/components/markdown-editor.tsx +134 -0
  69. package/src/components/markdown-text.tsx +218 -0
  70. package/src/components/onboarding/onboarding-wizard.test.tsx +184 -0
  71. package/src/components/onboarding/onboarding-wizard.tsx +1365 -0
  72. package/src/components/pane-settings-dialog.tsx +468 -0
  73. package/src/components/pane-template-wizard.test.tsx +52 -0
  74. package/src/components/pane-template-wizard.tsx +199 -0
  75. package/src/components/price-selector-dialog.tsx +195 -0
  76. package/src/components/spinner.tsx +2 -0
  77. package/src/components/tab-bar.tsx +17 -0
  78. package/src/components/ticker-badge-text.test.tsx +160 -0
  79. package/src/components/ticker-badge-text.tsx +58 -0
  80. package/src/components/ticker-badge.tsx +88 -0
  81. package/src/components/ticker-list-table.tsx +188 -0
  82. package/src/components/toggle-list.tsx +74 -0
  83. package/src/components/ui/button.tsx +77 -0
  84. package/src/components/ui/data-table.tsx +210 -0
  85. package/src/components/ui/external-link.tsx +22 -0
  86. package/src/components/ui/fields.tsx +187 -0
  87. package/src/components/ui/frame.tsx +73 -0
  88. package/src/components/ui/index.ts +53 -0
  89. package/src/components/ui/list-view.tsx +166 -0
  90. package/src/components/ui/loading.tsx +70 -0
  91. package/src/components/ui/status.tsx +83 -0
  92. package/src/components/ui/tabs.tsx +47 -0
  93. package/src/components/ui/toggle.tsx +164 -0
  94. package/src/components/ui/ui.test.tsx +134 -0
  95. package/src/data/app-persistence.ts +25 -0
  96. package/src/data/config-store.test.ts +347 -0
  97. package/src/data/config-store.ts +507 -0
  98. package/src/data/plugin-state-store.ts +102 -0
  99. package/src/data/resource-store.ts +323 -0
  100. package/src/data/session-store.ts +52 -0
  101. package/src/data/sqlite-cache.test.ts +103 -0
  102. package/src/data/sqlite-database.ts +62 -0
  103. package/src/data/sqlite-json.ts +19 -0
  104. package/src/data/ticker-repository.ts +45 -0
  105. package/src/data/ticker-store.ts +46 -0
  106. package/src/index.tsx +67 -0
  107. package/src/market-data/coordinator.test.ts +369 -0
  108. package/src/market-data/coordinator.ts +580 -0
  109. package/src/market-data/hooks.tsx +234 -0
  110. package/src/market-data/query-store.ts +28 -0
  111. package/src/market-data/request-types.test.ts +64 -0
  112. package/src/market-data/request-types.ts +70 -0
  113. package/src/market-data/result-types.ts +56 -0
  114. package/src/market-data/selectors.ts +166 -0
  115. package/src/market-data/trace.ts +7 -0
  116. package/src/pane-settings.test.ts +55 -0
  117. package/src/pane-settings.ts +73 -0
  118. package/src/plugins/builtin/ai/ask-ai-detail-tab.tsx +350 -0
  119. package/src/plugins/builtin/ai/gloomberb-cli.ts +70 -0
  120. package/src/plugins/builtin/ai/index.test.tsx +139 -0
  121. package/src/plugins/builtin/ai/index.tsx +86 -0
  122. package/src/plugins/builtin/ai/providers.ts +99 -0
  123. package/src/plugins/builtin/ai/runner.ts +82 -0
  124. package/src/plugins/builtin/ai/screener-contract.test.ts +117 -0
  125. package/src/plugins/builtin/ai/screener-contract.ts +174 -0
  126. package/src/plugins/builtin/ai/screener-pane.test.tsx +365 -0
  127. package/src/plugins/builtin/ai/screener-pane.tsx +1161 -0
  128. package/src/plugins/builtin/ai/settings.ts +79 -0
  129. package/src/plugins/builtin/ai/ticker-context.ts +64 -0
  130. package/src/plugins/builtin/ai/utils.ts +71 -0
  131. package/src/plugins/builtin/ask-ai.test.tsx +258 -0
  132. package/src/plugins/builtin/ask-ai.tsx +9 -0
  133. package/src/plugins/builtin/chat-controller.test.ts +217 -0
  134. package/src/plugins/builtin/chat-controller.ts +340 -0
  135. package/src/plugins/builtin/chat.test.tsx +451 -0
  136. package/src/plugins/builtin/chat.tsx +620 -0
  137. package/src/plugins/builtin/comparison-chart.test.tsx +277 -0
  138. package/src/plugins/builtin/comparison-chart.tsx +169 -0
  139. package/src/plugins/builtin/data-providers.ts +16 -0
  140. package/src/plugins/builtin/debug.tsx +351 -0
  141. package/src/plugins/builtin/help.test.tsx +110 -0
  142. package/src/plugins/builtin/help.tsx +281 -0
  143. package/src/plugins/builtin/layout-manager.tsx +264 -0
  144. package/src/plugins/builtin/manual-entry.tsx +25 -0
  145. package/src/plugins/builtin/news.tsx +143 -0
  146. package/src/plugins/builtin/notes-files.ts +58 -0
  147. package/src/plugins/builtin/notes.tsx +396 -0
  148. package/src/plugins/builtin/options-availability.test.tsx +179 -0
  149. package/src/plugins/builtin/options-availability.ts +158 -0
  150. package/src/plugins/builtin/options.tsx +364 -0
  151. package/src/plugins/builtin/portfolio-list/header.tsx +227 -0
  152. package/src/plugins/builtin/portfolio-list/index.tsx +99 -0
  153. package/src/plugins/builtin/portfolio-list/metrics.ts +460 -0
  154. package/src/plugins/builtin/portfolio-list/pane.tsx +533 -0
  155. package/src/plugins/builtin/portfolio-list/settings.ts +270 -0
  156. package/src/plugins/builtin/portfolio-list/summary.tsx +270 -0
  157. package/src/plugins/builtin/portfolio-list/table.tsx +64 -0
  158. package/src/plugins/builtin/portfolio-list.test.ts +74 -0
  159. package/src/plugins/builtin/portfolio-list.test.tsx +1164 -0
  160. package/src/plugins/builtin/portfolio-metrics.test.ts +224 -0
  161. package/src/plugins/builtin/quote-monitor.test.tsx +114 -0
  162. package/src/plugins/builtin/sec.tsx +250 -0
  163. package/src/plugins/builtin/ticker-detail/chart-tab.tsx +43 -0
  164. package/src/plugins/builtin/ticker-detail/financials-tab.tsx +390 -0
  165. package/src/plugins/builtin/ticker-detail/index.tsx +80 -0
  166. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +242 -0
  167. package/src/plugins/builtin/ticker-detail/pane.tsx +183 -0
  168. package/src/plugins/builtin/ticker-detail/quote-monitor.tsx +83 -0
  169. package/src/plugins/builtin/ticker-detail/settings.ts +132 -0
  170. package/src/plugins/builtin/ticker-detail-chart-tab-switch.test.tsx +193 -0
  171. package/src/plugins/builtin/ticker-detail.test.tsx +578 -0
  172. package/src/plugins/builtin/yahoo.ts +18 -0
  173. package/src/plugins/event-bus.ts +37 -0
  174. package/src/plugins/ibkr/__snapshots__/trade-tab.test.tsx.snap +35 -0
  175. package/src/plugins/ibkr/account-cache.test.ts +101 -0
  176. package/src/plugins/ibkr/account-cache.ts +137 -0
  177. package/src/plugins/ibkr/broker-adapter.ts +168 -0
  178. package/src/plugins/ibkr/config.test.ts +68 -0
  179. package/src/plugins/ibkr/config.ts +262 -0
  180. package/src/plugins/ibkr/dialogs.tsx +83 -0
  181. package/src/plugins/ibkr/flex.test.ts +107 -0
  182. package/src/plugins/ibkr/flex.ts +267 -0
  183. package/src/plugins/ibkr/fundamental-parser.ts +149 -0
  184. package/src/plugins/ibkr/gateway-helpers.ts +28 -0
  185. package/src/plugins/ibkr/gateway-selection.ts +51 -0
  186. package/src/plugins/ibkr/gateway-service.test.ts +450 -0
  187. package/src/plugins/ibkr/gateway-service.ts +2228 -0
  188. package/src/plugins/ibkr/index.test.tsx +183 -0
  189. package/src/plugins/ibkr/index.tsx +153 -0
  190. package/src/plugins/ibkr/instance-selection.test.ts +121 -0
  191. package/src/plugins/ibkr/instance-selection.ts +36 -0
  192. package/src/plugins/ibkr/price-normalization.test.ts +38 -0
  193. package/src/plugins/ibkr/price-normalization.ts +59 -0
  194. package/src/plugins/ibkr/trade-badge.tsx +27 -0
  195. package/src/plugins/ibkr/trade-tab.test.tsx +225 -0
  196. package/src/plugins/ibkr/trade-tab.tsx +1050 -0
  197. package/src/plugins/ibkr/trade-utils.test.ts +175 -0
  198. package/src/plugins/ibkr/trade-utils.ts +149 -0
  199. package/src/plugins/ibkr/trading-pane.tsx +438 -0
  200. package/src/plugins/ibkr/trading-state.test.ts +109 -0
  201. package/src/plugins/ibkr/trading-state.ts +339 -0
  202. package/src/plugins/loader.ts +71 -0
  203. package/src/plugins/pane-manager.test.ts +103 -0
  204. package/src/plugins/pane-manager.ts +974 -0
  205. package/src/plugins/plugin-persistence.ts +85 -0
  206. package/src/plugins/plugin-runtime.test.tsx +185 -0
  207. package/src/plugins/plugin-runtime.tsx +175 -0
  208. package/src/plugins/prediction-markets/cache.ts +114 -0
  209. package/src/plugins/prediction-markets/categories.ts +223 -0
  210. package/src/plugins/prediction-markets/chart.tsx +512 -0
  211. package/src/plugins/prediction-markets/columns.ts +133 -0
  212. package/src/plugins/prediction-markets/controller-data.ts +614 -0
  213. package/src/plugins/prediction-markets/controller.ts +725 -0
  214. package/src/plugins/prediction-markets/detail/book.tsx +118 -0
  215. package/src/plugins/prediction-markets/detail/outcomes.tsx +102 -0
  216. package/src/plugins/prediction-markets/detail/overview.tsx +73 -0
  217. package/src/plugins/prediction-markets/detail/pane.tsx +308 -0
  218. package/src/plugins/prediction-markets/detail/rules.tsx +16 -0
  219. package/src/plugins/prediction-markets/detail/shared.tsx +29 -0
  220. package/src/plugins/prediction-markets/detail/trades.tsx +30 -0
  221. package/src/plugins/prediction-markets/detail.test.tsx +47 -0
  222. package/src/plugins/prediction-markets/index.tsx +102 -0
  223. package/src/plugins/prediction-markets/keyboard.ts +64 -0
  224. package/src/plugins/prediction-markets/launch.test.ts +126 -0
  225. package/src/plugins/prediction-markets/launch.ts +240 -0
  226. package/src/plugins/prediction-markets/metrics.ts +311 -0
  227. package/src/plugins/prediction-markets/navigation.ts +90 -0
  228. package/src/plugins/prediction-markets/outcome-order.ts +19 -0
  229. package/src/plugins/prediction-markets/pane.test.tsx +425 -0
  230. package/src/plugins/prediction-markets/pane.tsx +294 -0
  231. package/src/plugins/prediction-markets/plugin.test.tsx +570 -0
  232. package/src/plugins/prediction-markets/rows.ts +229 -0
  233. package/src/plugins/prediction-markets/services/fetch.ts +97 -0
  234. package/src/plugins/prediction-markets/services/kalshi-adapter.ts +555 -0
  235. package/src/plugins/prediction-markets/services/polymarket-adapter.ts +660 -0
  236. package/src/plugins/prediction-markets/services/polymarket-ws.ts +108 -0
  237. package/src/plugins/prediction-markets/settings.ts +164 -0
  238. package/src/plugins/prediction-markets/status.ts +24 -0
  239. package/src/plugins/prediction-markets/table.tsx +84 -0
  240. package/src/plugins/prediction-markets/test-helpers.tsx +636 -0
  241. package/src/plugins/prediction-markets/types.ts +186 -0
  242. package/src/plugins/registry.ts +633 -0
  243. package/src/sources/exchange-rates.ts +18 -0
  244. package/src/sources/gloomberb-cloud.test.ts +199 -0
  245. package/src/sources/gloomberb-cloud.ts +326 -0
  246. package/src/sources/provider-errors.ts +19 -0
  247. package/src/sources/provider-router.test.ts +1476 -0
  248. package/src/sources/provider-router.ts +1405 -0
  249. package/src/sources/sec-edgar.test.ts +286 -0
  250. package/src/sources/sec-edgar.ts +526 -0
  251. package/src/sources/yahoo-finance.test.ts +14 -0
  252. package/src/sources/yahoo-finance.ts +1017 -0
  253. package/src/state/app-activity.test.ts +41 -0
  254. package/src/state/app-activity.ts +106 -0
  255. package/src/state/app-bootstrap.test.ts +471 -0
  256. package/src/state/app-bootstrap.ts +308 -0
  257. package/src/state/app-context.test.ts +406 -0
  258. package/src/state/app-context.test.tsx +162 -0
  259. package/src/state/app-context.tsx +981 -0
  260. package/src/state/selectors.ts +67 -0
  261. package/src/state/session-persistence.test.ts +128 -0
  262. package/src/state/session-persistence.ts +161 -0
  263. package/src/state/ticker-refresh-queue.test.ts +46 -0
  264. package/src/state/ticker-refresh-queue.ts +40 -0
  265. package/src/state/use-inline-tickers.ts +174 -0
  266. package/src/state/use-quote-streaming.test.ts +37 -0
  267. package/src/state/use-quote-streaming.test.tsx +70 -0
  268. package/src/state/use-quote-streaming.ts +80 -0
  269. package/src/state/use-session-snapshot.ts +84 -0
  270. package/src/test-support/data-provider.ts +22 -0
  271. package/src/theme/color-utils.ts +67 -0
  272. package/src/theme/colors.ts +128 -0
  273. package/src/theme/themes.test.ts +45 -0
  274. package/src/theme/themes.ts +491 -0
  275. package/src/types/broker.ts +105 -0
  276. package/src/types/config.ts +444 -0
  277. package/src/types/data-provider.ts +81 -0
  278. package/src/types/financials.ts +142 -0
  279. package/src/types/instrument.ts +29 -0
  280. package/src/types/persistence.ts +21 -0
  281. package/src/types/plugin.ts +354 -0
  282. package/src/types/ticker.ts +58 -0
  283. package/src/types/trading.ts +85 -0
  284. package/src/updater.test.ts +282 -0
  285. package/src/updater.ts +303 -0
  286. package/src/utils/api-client.ts +666 -0
  287. package/src/utils/ascii-chart.ts +172 -0
  288. package/src/utils/broker-instances.ts +47 -0
  289. package/src/utils/cli-output.ts +83 -0
  290. package/src/utils/currency-units.test.ts +49 -0
  291. package/src/utils/currency-units.ts +82 -0
  292. package/src/utils/debug-log.ts +133 -0
  293. package/src/utils/exchange-rate-map.ts +8 -0
  294. package/src/utils/format.ts +158 -0
  295. package/src/utils/fuzzy-search.ts +34 -0
  296. package/src/utils/market-status.ts +95 -0
  297. package/src/utils/options.ts +86 -0
  298. package/src/utils/price-history.ts +39 -0
  299. package/src/utils/quote-time.test.ts +22 -0
  300. package/src/utils/quote-time.ts +50 -0
  301. package/src/utils/sec.test.ts +55 -0
  302. package/src/utils/sec.ts +45 -0
  303. package/src/utils/ticker-list.test.ts +22 -0
  304. package/src/utils/ticker-list.ts +35 -0
  305. package/src/utils/ticker-metadata.ts +51 -0
  306. package/src/utils/ticker-search.test.ts +227 -0
  307. package/src/utils/ticker-search.ts +764 -0
  308. package/src/utils/ticker-tokenizer.test.ts +48 -0
  309. package/src/utils/ticker-tokenizer.ts +72 -0
  310. package/src/version.ts +1 -0
  311. package/install.mjs +0 -68
@@ -0,0 +1,460 @@
1
+ import type { CollectionSortPreference } from "../../../state/app-context";
2
+ import type { ColumnConfig } from "../../../types/config";
3
+ import type { TickerFinancials } from "../../../types/financials";
4
+ import type { TickerRecord } from "../../../types/ticker";
5
+ import { priceColor } from "../../../theme/colors";
6
+ import { clampQuoteTimestamp, formatQuoteAgeWithSource } from "../../../utils/quote-time";
7
+ import { convertCurrency, formatCompact, formatCurrency, formatNumber, formatPercentRaw, formatPrice } from "../../../utils/format";
8
+ import { getActiveQuoteDisplay, type ActiveQuoteDisplay } from "../../../utils/market-status";
9
+ import { formatOptionTicker } from "../../../utils/options";
10
+
11
+ export interface ColumnContext {
12
+ activeTab?: string;
13
+ baseCurrency: string;
14
+ exchangeRates: Map<string, number>;
15
+ now: number;
16
+ }
17
+
18
+ interface PortfolioPositionMetrics {
19
+ positionCurrency: string;
20
+ totalShares: number;
21
+ totalCost: number;
22
+ totalCostUnits: number;
23
+ totalPriceUnits: number;
24
+ brokerMktValue: number;
25
+ hasBrokerMktValue: boolean;
26
+ brokerPnl: number;
27
+ hasBrokerPnl: boolean;
28
+ brokerMarkPrice: number | undefined;
29
+ }
30
+
31
+ export interface PortfolioSummaryTotals {
32
+ totalMktValue: number;
33
+ dailyPnl: number;
34
+ dailyPnlPct: number;
35
+ totalCostBasis: number;
36
+ hasPositions: boolean;
37
+ unrealizedPnl: number;
38
+ unrealizedPnlPct: number;
39
+ avgWatchlistChange: number;
40
+ watchlistCount: number;
41
+ }
42
+
43
+ const EMPTY_SORT_PREFERENCE: CollectionSortPreference = {
44
+ columnId: null,
45
+ direction: "asc",
46
+ };
47
+
48
+ const DEFAULT_PORTFOLIO_SORT_PREFERENCE: CollectionSortPreference = {
49
+ columnId: "mkt_value",
50
+ direction: "desc",
51
+ };
52
+
53
+ function getPositionCurrency(
54
+ positions: TickerRecord["metadata"]["positions"],
55
+ fallbackCurrency: string,
56
+ ): string {
57
+ return positions.find((position) => position.currency)?.currency || fallbackCurrency;
58
+ }
59
+
60
+ function normalizePositionMultiplier(multiplier: number | undefined): number {
61
+ return typeof multiplier === "number" && Number.isFinite(multiplier) && multiplier > 0
62
+ ? multiplier
63
+ : 1;
64
+ }
65
+
66
+ function resolvePositionCostMultiplier(
67
+ position: TickerRecord["metadata"]["positions"][number],
68
+ ): number {
69
+ const priceMultiplier = normalizePositionMultiplier(position.multiplier);
70
+ if (priceMultiplier === 1) return 1;
71
+
72
+ if (position.marketValue == null || position.unrealizedPnl == null) {
73
+ return priceMultiplier;
74
+ }
75
+
76
+ const costWithoutMultiplier = position.shares * position.avgCost;
77
+ const costWithMultiplier = costWithoutMultiplier * priceMultiplier;
78
+ const withoutMultiplierError = Math.abs((position.marketValue - costWithoutMultiplier) - position.unrealizedPnl);
79
+ const withMultiplierError = Math.abs((position.marketValue - costWithMultiplier) - position.unrealizedPnl);
80
+
81
+ // IBKR gateway derivatives can report avgCost already scaled to the contract.
82
+ return withoutMultiplierError < withMultiplierError ? 1 : priceMultiplier;
83
+ }
84
+
85
+ function getPortfolioPositionMetrics(
86
+ ticker: TickerRecord,
87
+ activeTab: string | undefined,
88
+ fallbackCurrency: string,
89
+ ): PortfolioPositionMetrics {
90
+ const tabPositions = activeTab
91
+ ? ticker.metadata.positions.filter((position) => position.portfolio === activeTab)
92
+ : ticker.metadata.positions;
93
+ const positionCurrency = getPositionCurrency(tabPositions, fallbackCurrency);
94
+ let totalShares = 0;
95
+ let totalCost = 0;
96
+ let totalCostUnits = 0;
97
+ let totalPriceUnits = 0;
98
+ let brokerMktValue = 0;
99
+ let hasBrokerMktValue = false;
100
+ let brokerPnl = 0;
101
+ let hasBrokerPnl = false;
102
+ for (const position of tabPositions) {
103
+ const direction = position.side === "short" ? -1 : 1;
104
+ const priceMultiplier = normalizePositionMultiplier(position.multiplier);
105
+ const costMultiplier = resolvePositionCostMultiplier(position);
106
+
107
+ totalShares += position.shares * direction;
108
+ totalCost += position.shares * position.avgCost * costMultiplier;
109
+ totalCostUnits += position.shares * costMultiplier;
110
+ totalPriceUnits += position.shares * priceMultiplier * direction;
111
+
112
+ if (position.marketValue != null) {
113
+ brokerMktValue += position.marketValue;
114
+ hasBrokerMktValue = true;
115
+ }
116
+ if (position.unrealizedPnl != null) {
117
+ brokerPnl += position.unrealizedPnl;
118
+ hasBrokerPnl = true;
119
+ }
120
+ }
121
+
122
+ return {
123
+ positionCurrency,
124
+ totalShares,
125
+ totalCost,
126
+ totalCostUnits,
127
+ totalPriceUnits,
128
+ brokerMktValue,
129
+ hasBrokerMktValue,
130
+ brokerPnl,
131
+ hasBrokerPnl,
132
+ brokerMarkPrice: tabPositions.length === 1 ? tabPositions[0]?.markPrice : undefined,
133
+ };
134
+ }
135
+
136
+ function resolveBrokerFallbackMarketValue(metrics: PortfolioPositionMetrics): number | null {
137
+ if (metrics.hasBrokerMktValue) return metrics.brokerMktValue;
138
+ if (metrics.brokerMarkPrice != null && metrics.totalPriceUnits !== 0) {
139
+ return Math.abs(metrics.totalPriceUnits) * metrics.brokerMarkPrice;
140
+ }
141
+ if (metrics.hasBrokerPnl) {
142
+ return metrics.totalCost + metrics.brokerPnl;
143
+ }
144
+ return null;
145
+ }
146
+
147
+ function resolveBrokerFallbackPnl(metrics: PortfolioPositionMetrics, brokerMarketValue: number | null): number | null {
148
+ if (metrics.hasBrokerPnl) return metrics.brokerPnl;
149
+ if (brokerMarketValue != null && metrics.totalCost !== 0) {
150
+ return brokerMarketValue - metrics.totalCost;
151
+ }
152
+ return null;
153
+ }
154
+
155
+ export function resolvePortfolioPriceValue(
156
+ activeQuote: ActiveQuoteDisplay | null,
157
+ brokerMarkPrice: number | undefined,
158
+ ): { text: string; color?: string } {
159
+ if (activeQuote) {
160
+ return {
161
+ text: formatPrice(activeQuote.price),
162
+ color: priceColor(activeQuote.change),
163
+ };
164
+ }
165
+ if (brokerMarkPrice != null) {
166
+ return { text: formatPrice(brokerMarkPrice) };
167
+ }
168
+ return { text: "—" };
169
+ }
170
+
171
+ export function getColumnValue(
172
+ col: ColumnConfig,
173
+ ticker: TickerRecord,
174
+ financials: TickerFinancials | undefined,
175
+ ctx: ColumnContext,
176
+ ): { text: string; color?: string } {
177
+ const quote = financials?.quote;
178
+ const activeQuote = getActiveQuoteDisplay(quote);
179
+ const fundamentals = financials?.fundamentals;
180
+ const quoteCurrency = quote?.currency || ticker.metadata.currency || "USD";
181
+
182
+ const positionMetrics = getPortfolioPositionMetrics(ticker, ctx.activeTab, quoteCurrency);
183
+ const { positionCurrency, totalShares, totalCost, totalCostUnits, totalPriceUnits, brokerMarkPrice } = positionMetrics;
184
+ const brokerFallbackMktValue = resolveBrokerFallbackMarketValue(positionMetrics);
185
+ const brokerFallbackPnl = resolveBrokerFallbackPnl(positionMetrics, brokerFallbackMktValue);
186
+ const toBaseQuote = (value: number) =>
187
+ convertCurrency(value, quoteCurrency, ctx.baseCurrency, ctx.exchangeRates);
188
+ const toBasePosition = (value: number) =>
189
+ convertCurrency(value, positionCurrency, ctx.baseCurrency, ctx.exchangeRates);
190
+
191
+ switch (col.id) {
192
+ case "ticker": {
193
+ const marketState = quote?.marketState;
194
+ const statusDot = marketState === "REGULAR" ? "\u25CF" : "\u25CB";
195
+ const displayName = ticker.metadata.assetCategory === "OPT"
196
+ ? formatOptionTicker(ticker.metadata.ticker)
197
+ : ticker.metadata.ticker;
198
+ return { text: `${statusDot} ${displayName}` };
199
+ }
200
+ case "price":
201
+ return resolvePortfolioPriceValue(activeQuote, brokerMarkPrice);
202
+ case "change":
203
+ if (!activeQuote) return { text: "—" };
204
+ return {
205
+ text: (activeQuote.change >= 0 ? "+" : "") + activeQuote.change.toFixed(2),
206
+ color: priceColor(activeQuote.change),
207
+ };
208
+ case "bid":
209
+ return { text: quote?.bid != null ? formatPrice(quote.bid) : "—" };
210
+ case "ask":
211
+ return { text: quote?.ask != null ? formatPrice(quote.ask) : "—" };
212
+ case "spread":
213
+ return {
214
+ text: quote?.bid != null && quote?.ask != null
215
+ ? formatCurrency(quote.ask - quote.bid, quoteCurrency)
216
+ : "—",
217
+ };
218
+ case "change_pct":
219
+ return activeQuote
220
+ ? { text: formatPercentRaw(activeQuote.changePercent), color: priceColor(activeQuote.changePercent) }
221
+ : { text: quote ? formatPercentRaw(quote.changePercent) : "—", color: quote ? priceColor(quote.changePercent) : undefined };
222
+ case "market_cap":
223
+ if (!quote?.marketCap) return { text: "—" };
224
+ return { text: formatCompact(toBaseQuote(quote.marketCap)) };
225
+ case "pe":
226
+ return { text: fundamentals?.trailingPE ? formatNumber(fundamentals.trailingPE, 1) : "—" };
227
+ case "forward_pe":
228
+ return { text: fundamentals?.forwardPE ? formatNumber(fundamentals.forwardPE, 1) : "—" };
229
+ case "dividend_yield":
230
+ return {
231
+ text: fundamentals?.dividendYield != null ? `${(fundamentals.dividendYield * 100).toFixed(2)}%` : "—",
232
+ };
233
+ case "ext_hours":
234
+ if ((quote?.marketState === "PRE" || quote?.marketState === "PREPRE") && quote.preMarketPrice != null) {
235
+ const changePercent = activeQuote?.changePercent ?? quote.preMarketChangePercent ?? 0;
236
+ return { text: formatPercentRaw(changePercent), color: priceColor(changePercent) };
237
+ }
238
+ if ((quote?.marketState === "POST" || quote?.marketState === "POSTPOST") && quote.postMarketPrice != null) {
239
+ const changePercent = activeQuote?.changePercent ?? quote.postMarketChangePercent ?? 0;
240
+ return { text: formatPercentRaw(changePercent), color: priceColor(changePercent) };
241
+ }
242
+ return { text: "—" };
243
+ case "shares":
244
+ return { text: totalShares !== 0 ? formatCompact(totalShares) : "—" };
245
+ case "avg_cost":
246
+ if (totalCostUnits === 0) return { text: "—" };
247
+ return { text: formatPrice(totalCost / Math.abs(totalCostUnits)) };
248
+ case "cost_basis":
249
+ if (totalCost === 0) return { text: "—" };
250
+ return { text: formatCompact(toBasePosition(totalCost)) };
251
+ case "mkt_value":
252
+ if (activeQuote && totalPriceUnits !== 0) {
253
+ return { text: formatCompact(toBaseQuote(Math.abs(totalPriceUnits) * activeQuote.price)) };
254
+ }
255
+ if (brokerFallbackMktValue != null) {
256
+ return { text: formatCompact(toBasePosition(brokerFallbackMktValue)) };
257
+ }
258
+ return { text: "—" };
259
+ case "pnl":
260
+ if (activeQuote && totalPriceUnits !== 0) {
261
+ const pnl = toBaseQuote(Math.abs(totalPriceUnits) * activeQuote.price) - toBasePosition(totalCost);
262
+ return { text: `${pnl >= 0 ? "+" : ""}${formatCompact(pnl)}`, color: priceColor(pnl) };
263
+ }
264
+ if (brokerFallbackPnl != null) {
265
+ const pnl = toBasePosition(brokerFallbackPnl);
266
+ return { text: `${pnl >= 0 ? "+" : ""}${formatCompact(pnl)}`, color: priceColor(pnl) };
267
+ }
268
+ return { text: "—" };
269
+ case "pnl_pct":
270
+ if (activeQuote && totalCost !== 0) {
271
+ const marketValue = toBaseQuote(Math.abs(totalPriceUnits) * activeQuote.price);
272
+ const costBasis = toBasePosition(totalCost);
273
+ const percent = costBasis !== 0 ? ((marketValue - costBasis) / costBasis) * 100 : 0;
274
+ return { text: formatPercentRaw(percent), color: priceColor(percent) };
275
+ }
276
+ if (brokerFallbackPnl != null && totalCost !== 0) {
277
+ const costBasis = toBasePosition(totalCost);
278
+ const pnl = toBasePosition(brokerFallbackPnl);
279
+ const percent = costBasis !== 0 ? (pnl / costBasis) * 100 : 0;
280
+ return { text: formatPercentRaw(percent), color: priceColor(percent) };
281
+ }
282
+ return { text: "—" };
283
+ case "latency":
284
+ return { text: formatQuoteAgeWithSource(quote, ctx.now) };
285
+ default:
286
+ return { text: "—" };
287
+ }
288
+ }
289
+
290
+ export function getSortValue(
291
+ col: ColumnConfig,
292
+ ticker: TickerRecord,
293
+ financials: TickerFinancials | undefined,
294
+ ctx: ColumnContext,
295
+ ): number | string | null {
296
+ const quote = financials?.quote;
297
+ const activeQuote = getActiveQuoteDisplay(quote);
298
+ const fundamentals = financials?.fundamentals;
299
+ const quoteCurrency = quote?.currency || ticker.metadata.currency || "USD";
300
+
301
+ const positionMetrics = getPortfolioPositionMetrics(ticker, ctx.activeTab, quoteCurrency);
302
+ const { positionCurrency, totalShares, totalCost, totalCostUnits, totalPriceUnits, brokerMarkPrice } = positionMetrics;
303
+ const brokerFallbackMktValue = resolveBrokerFallbackMarketValue(positionMetrics);
304
+ const brokerFallbackPnl = resolveBrokerFallbackPnl(positionMetrics, brokerFallbackMktValue);
305
+ const toBaseQuote = (value: number) =>
306
+ convertCurrency(value, quoteCurrency, ctx.baseCurrency, ctx.exchangeRates);
307
+ const toBasePosition = (value: number) =>
308
+ convertCurrency(value, positionCurrency, ctx.baseCurrency, ctx.exchangeRates);
309
+
310
+ switch (col.id) {
311
+ case "ticker":
312
+ return ticker.metadata.ticker;
313
+ case "price":
314
+ if (activeQuote) return activeQuote.price;
315
+ if (brokerMarkPrice != null) return brokerMarkPrice;
316
+ return null;
317
+ case "bid":
318
+ return quote?.bid ?? null;
319
+ case "ask":
320
+ return quote?.ask ?? null;
321
+ case "spread":
322
+ return quote?.bid != null && quote?.ask != null ? quote.ask - quote.bid : null;
323
+ case "change":
324
+ return activeQuote ? activeQuote.change : null;
325
+ case "change_pct":
326
+ return activeQuote?.changePercent ?? null;
327
+ case "market_cap":
328
+ return quote?.marketCap ? toBaseQuote(quote.marketCap) : null;
329
+ case "pe":
330
+ return fundamentals?.trailingPE ?? null;
331
+ case "forward_pe":
332
+ return fundamentals?.forwardPE ?? null;
333
+ case "dividend_yield":
334
+ return fundamentals?.dividendYield ?? null;
335
+ case "ext_hours":
336
+ if ((quote?.marketState === "PRE" || quote?.marketState === "PREPRE") && quote.preMarketPrice != null) {
337
+ return activeQuote?.changePercent ?? quote.preMarketChangePercent ?? 0;
338
+ }
339
+ if ((quote?.marketState === "POST" || quote?.marketState === "POSTPOST") && quote.postMarketPrice != null) {
340
+ return activeQuote?.changePercent ?? quote.postMarketChangePercent ?? 0;
341
+ }
342
+ return null;
343
+ case "shares":
344
+ return totalShares !== 0 ? totalShares : null;
345
+ case "avg_cost":
346
+ return totalCostUnits !== 0 ? totalCost / Math.abs(totalCostUnits) : null;
347
+ case "cost_basis":
348
+ return totalCost !== 0 ? toBasePosition(totalCost) : null;
349
+ case "mkt_value":
350
+ if (activeQuote && totalPriceUnits !== 0) {
351
+ return toBaseQuote(Math.abs(totalPriceUnits) * activeQuote.price);
352
+ }
353
+ if (brokerFallbackMktValue != null) {
354
+ return toBasePosition(brokerFallbackMktValue);
355
+ }
356
+ return null;
357
+ case "pnl":
358
+ if (activeQuote && totalPriceUnits !== 0) {
359
+ return toBaseQuote(Math.abs(totalPriceUnits) * activeQuote.price) - toBasePosition(totalCost);
360
+ }
361
+ if (brokerFallbackPnl != null) {
362
+ return toBasePosition(brokerFallbackPnl);
363
+ }
364
+ return null;
365
+ case "pnl_pct":
366
+ if (activeQuote && totalCost !== 0) {
367
+ const marketValue = toBaseQuote(Math.abs(totalPriceUnits) * activeQuote.price);
368
+ const costBasis = toBasePosition(totalCost);
369
+ return costBasis !== 0 ? ((marketValue - costBasis) / costBasis) * 100 : null;
370
+ }
371
+ if (brokerFallbackPnl != null && totalCost !== 0) {
372
+ const costBasis = toBasePosition(totalCost);
373
+ const pnl = toBasePosition(brokerFallbackPnl);
374
+ return costBasis !== 0 ? (pnl / costBasis) * 100 : null;
375
+ }
376
+ return null;
377
+ case "latency":
378
+ return quote?.lastUpdated != null ? ctx.now - (clampQuoteTimestamp(quote.lastUpdated, ctx.now) ?? ctx.now) : null;
379
+ default:
380
+ return null;
381
+ }
382
+ }
383
+
384
+ export function resolveCollectionSortPreference(
385
+ collectionId: string | null,
386
+ isPortfolio: boolean,
387
+ collectionSorts: Record<string, CollectionSortPreference>,
388
+ ): CollectionSortPreference {
389
+ if (!collectionId) return EMPTY_SORT_PREFERENCE;
390
+ return collectionSorts[collectionId] ?? (isPortfolio ? DEFAULT_PORTFOLIO_SORT_PREFERENCE : EMPTY_SORT_PREFERENCE);
391
+ }
392
+
393
+ export function calculatePortfolioSummaryTotals(
394
+ tickers: TickerRecord[],
395
+ financialsMap: Map<string, TickerFinancials>,
396
+ baseCurrency: string,
397
+ exchangeRates: Map<string, number>,
398
+ isPortfolio: boolean,
399
+ collectionId: string | null,
400
+ ): PortfolioSummaryTotals {
401
+ let totalMktValue = 0;
402
+ let totalPrevValue = 0;
403
+ let totalCostBasis = 0;
404
+ let hasPositions = false;
405
+ let watchlistChangeSum = 0;
406
+ let watchlistCount = 0;
407
+
408
+ for (const ticker of tickers) {
409
+ const financials = financialsMap.get(ticker.metadata.ticker);
410
+ const quote = financials?.quote;
411
+ const activeQuote = getActiveQuoteDisplay(quote);
412
+ const quoteCurrency = quote?.currency || ticker.metadata.currency || "USD";
413
+
414
+ if (!isPortfolio) {
415
+ if (quote?.changePercent != null) {
416
+ watchlistChangeSum += quote.changePercent;
417
+ watchlistCount++;
418
+ }
419
+ continue;
420
+ }
421
+
422
+ const positionMetrics = getPortfolioPositionMetrics(ticker, collectionId ?? undefined, quoteCurrency);
423
+ const { positionCurrency, totalPriceUnits, totalCost } = positionMetrics;
424
+ const brokerFallbackMktValue = resolveBrokerFallbackMarketValue(positionMetrics);
425
+ const toBaseQuote = (value: number) => convertCurrency(value, quoteCurrency, baseCurrency, exchangeRates);
426
+ const toBasePosition = (value: number) => convertCurrency(value, positionCurrency, baseCurrency, exchangeRates);
427
+
428
+ if (quote && activeQuote && totalPriceUnits !== 0) {
429
+ hasPositions = true;
430
+ const marketValue = Math.abs(totalPriceUnits) * activeQuote.price;
431
+ totalMktValue += toBaseQuote(marketValue);
432
+ const previousClose = quote.previousClose || (activeQuote.price - activeQuote.change);
433
+ totalPrevValue += toBaseQuote(Math.abs(totalPriceUnits) * previousClose);
434
+ totalCostBasis += toBasePosition(totalCost);
435
+ } else if (brokerFallbackMktValue != null) {
436
+ hasPositions = true;
437
+ totalMktValue += toBasePosition(brokerFallbackMktValue);
438
+ totalCostBasis += toBasePosition(totalCost);
439
+ totalPrevValue += toBasePosition(brokerFallbackMktValue);
440
+ }
441
+ }
442
+
443
+ const dailyPnl = totalMktValue - totalPrevValue;
444
+ const dailyPnlPct = totalPrevValue !== 0 ? (dailyPnl / totalPrevValue) * 100 : 0;
445
+ const unrealizedPnl = totalMktValue - totalCostBasis;
446
+ const unrealizedPnlPct = totalCostBasis !== 0 ? (unrealizedPnl / totalCostBasis) * 100 : 0;
447
+ const avgWatchlistChange = watchlistCount > 0 ? watchlistChangeSum / watchlistCount : 0;
448
+
449
+ return {
450
+ totalMktValue,
451
+ dailyPnl,
452
+ dailyPnlPct,
453
+ totalCostBasis,
454
+ hasPositions,
455
+ unrealizedPnl,
456
+ unrealizedPnlPct,
457
+ avgWatchlistChange,
458
+ watchlistCount,
459
+ };
460
+ }