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
@@ -5,7 +5,10 @@ import { readFile, writeFile } from "fs/promises";
5
5
  * it runs: its own files are locked until it quits.
6
6
  */
7
7
 
8
- /** How long a script has to answer before the app stops waiting and keeps running. */
8
+ /**
9
+ * How long a script has, by default, to answer before the app stops waiting
10
+ * and keeps running. The app may still be opening: no window shows until then.
11
+ */
9
12
  const SCRIPT_START_TIMEOUT_MS = 20_000;
10
13
 
11
14
  /**
@@ -62,16 +65,16 @@ function schtasks(...args: string[]): void {
62
65
  * Runs `script` from the scheduled task `taskName`, which outlives the app (a
63
66
  * child of its process dies with it), and resolves to the answer it writes to
64
67
  * `log`: only on `started` may the app quit for it. The script removes the
65
- * task. When it does not answer in time, the app writes `cancel`, which keeps
66
- * a script that starts late from doing anything, and this throws with the
67
- * task gone, as it does when the task could not be made.
68
+ * task. When it does not answer within `timeoutMs`, the app writes `cancel`,
69
+ * which keeps a script that starts late from doing anything, and this throws
70
+ * with the task gone, as it does when the task could not be made.
68
71
  */
69
- export async function runScriptAfterExit(script: string, log: string, cancel: string, taskName: string): Promise<ScriptAnswer> {
72
+ export async function runScriptAfterExit(script: string, log: string, cancel: string, taskName: string, timeoutMs = SCRIPT_START_TIMEOUT_MS): Promise<ScriptAnswer> {
70
73
  const command = powershellCommand(script).map((part) => (part === script ? `"${part}"` : part)).join(" ");
71
74
  try {
72
75
  schtasks("/create", "/tn", taskName, "/tr", command, "/sc", "once", "/st", "00:00", "/f");
73
76
  schtasks("/run", "/tn", taskName);
74
- const deadline = Date.now() + SCRIPT_START_TIMEOUT_MS;
77
+ const deadline = Date.now() + timeoutMs;
75
78
  while (Date.now() < deadline) {
76
79
  const answer = scriptAnswer(await readFile(log, "utf8").catch(() => ""));
77
80
  if (answer) return answer;
@@ -1,4 +1,5 @@
1
1
  import { dlopen, FFIType, ptr, type Pointer } from "bun:ffi";
2
+ import type { DesktopWindowResizeEdge } from "../../shared/protocol";
2
3
 
3
4
  const WINDOWS_HANDLE_MAX_ATTEMPTS = 20;
4
5
  const WINDOWS_HANDLE_RETRY_DELAY_MS = 100;
@@ -57,6 +58,10 @@ function loadWin32() {
57
58
  args: [FFIType.u32, FFIType.ptr],
58
59
  returns: FFIType.bool,
59
60
  },
61
+ IsZoomed: {
62
+ args: [FFIType.ptr],
63
+ returns: FFIType.bool,
64
+ },
60
65
  });
61
66
  }
62
67
 
@@ -93,6 +98,8 @@ export function fitPageToClientArea(windowHandle: Pointer): boolean {
93
98
  const WM_NCLBUTTONDOWN = 0x00a1;
94
99
  const WM_CANCELMODE = 0x001f;
95
100
  const HTCAPTION = 2;
101
+ /** HTTOP, HTTOPLEFT, HTTOPRIGHT. */
102
+ const TOP_EDGE_HIT_TESTS: Record<DesktopWindowResizeEdge, number> = { top: 12, "top-left": 13, "top-right": 14 };
96
103
  /** GUITHREADINFO on 64-bit Windows: two DWORDs, six window handles, a RECT. */
97
104
  const GUI_THREAD_INFO_SIZE = 72;
98
105
  const GUI_THREAD_INFO_CAPTURE_OFFSET = 24;
@@ -126,12 +133,30 @@ function mouseCaptureOnThreadOf(win32: Win32, windowHandle: Pointer): Pointer |
126
133
  export function startSystemWindowMove(windowHandle: Pointer): boolean {
127
134
  const win32 = win32OrNull();
128
135
  if (!win32) return false;
136
+ return pressNonClientArea(win32, windowHandle, HTCAPTION);
137
+ }
138
+
139
+ /**
140
+ * Hands a press on the page's top edge to Windows as a press on the frame's
141
+ * top edge, which the page covers: its size loop then resizes the window until
142
+ * the button comes up. A maximized window has no edge to pull, so the press
143
+ * moves it, as one at the top of a maximized title bar does. False off Windows.
144
+ */
145
+ export function startSystemWindowResize(windowHandle: Pointer, edge: DesktopWindowResizeEdge): boolean {
146
+ const win32 = win32OrNull();
147
+ if (!win32) return false;
148
+ const hitTest = win32.symbols.IsZoomed(windowHandle) ? HTCAPTION : TOP_EDGE_HIT_TESTS[edge];
149
+ return pressNonClientArea(win32, windowHandle, hitTest);
150
+ }
151
+
152
+ /** Presses the window's frame at `hitTest` where the pointer is, after the page lets go of the mouse. */
153
+ function pressNonClientArea(win32: Win32, windowHandle: Pointer, hitTest: number): boolean {
129
154
  const point = new Int32Array(2);
130
155
  if (!win32.symbols.GetCursorPos(ptr(point))) return false;
131
156
  const capture = mouseCaptureOnThreadOf(win32, windowHandle);
132
157
  if (capture && capture !== windowHandle) win32.symbols.PostMessageW(capture, WM_CANCELMODE, 0n, 0n);
133
158
  const position = ((point[1]! & 0xffff) << 16) | (point[0]! & 0xffff);
134
- return win32.symbols.PostMessageW(windowHandle, WM_NCLBUTTONDOWN, BigInt(HTCAPTION), BigInt(position >>> 0));
159
+ return win32.symbols.PostMessageW(windowHandle, WM_NCLBUTTONDOWN, BigInt(hitTest), BigInt(position >>> 0));
135
160
  }
136
161
 
137
162
  export function wideString(value: string): Uint8Array {
@@ -60,6 +60,9 @@ export interface DesktopRestartMessage {
60
60
 
61
61
  export type DesktopWindowControlAction = "minimize" | "toggle-maximize" | "close";
62
62
 
63
+ /** The window edges the page pulls itself: the frame's own stop under its top. */
64
+ export type DesktopWindowResizeEdge = "top" | "top-left" | "top-right";
65
+
63
66
  export type DesktopContextMenuItem =
64
67
  | { type: "divider" }
65
68
  | {
@@ -212,8 +215,11 @@ interface DesktopBackendRequestMap {
212
215
  "host.exit": { request: null; response: null };
213
216
  "host.windowControl": { request: { action: DesktopWindowControlAction }; response: null };
214
217
  "host.windowFullscreen": { request: null; response: boolean };
218
+ "host.windowMaximized": { request: null; response: boolean };
215
219
  /** Windows: moves the window with the pointer through the system's own move loop. */
216
220
  "host.startWindowDrag": { request: null; response: null };
221
+ /** Windows: resizes the window from its top edge through the system's own size loop. */
222
+ "host.startWindowResize": { request: { edge: DesktopWindowResizeEdge }; response: null };
217
223
  "host.openExternal": { request: { url: string }; response: boolean };
218
224
  "host.copyText": { request: { text: string }; response: null };
219
225
  "host.focusWindow": { request: null; response: null };
@@ -47,6 +47,13 @@ export const webRendererHost: RendererHost = {
47
47
  if (action === "close") await flushUsageCounts({ timeoutMs: 1_000 });
48
48
  await backendRequest("host.windowControl", { action });
49
49
  },
50
+ startWindowResize(edge) {
51
+ // Windows resizes the window itself, as it does from a native frame's edge.
52
+ if (detectPlatform() !== "win32") return;
53
+ void backendRequest("host.startWindowResize", { edge }).catch((error: unknown) => {
54
+ console.error("[desktop] could not start resizing the window", error instanceof Error ? error.message : String(error));
55
+ });
56
+ },
50
57
  async openExternal(url) {
51
58
  return await backendRequest("host.openExternal", { url });
52
59
  },
@@ -1,4 +1,5 @@
1
- import { setWindowFullscreen } from "../../../components/layout/window-fullscreen";
1
+ import { setWindowFullscreen, setWindowMaximized } from "../../../components/layout/window-fullscreen";
2
+ import { detectPlatform } from "../../../utils/platform";
2
3
  import { backendRequest } from "./backend-rpc";
3
4
 
4
5
  /**
@@ -12,7 +13,8 @@ const RESIZE_SETTLE_MS = 120;
12
13
  * Keeps the view's idea of its window's fullscreen state current. Electrobun
13
14
  * emits no fullscreen event and a webview cannot see its window's style mask,
14
15
  * but entering and leaving fullscreen always resizes the window, so the host
15
- * is asked every time the size settles.
16
+ * is asked every time the size settles. On Windows, so is maximizing, which
17
+ * takes away the window's top edge.
16
18
  */
17
19
  export function installElectrobunWindowFullscreenTracking(): () => void {
18
20
  let settleTimer: ReturnType<typeof setTimeout> | null = null;
@@ -26,7 +28,12 @@ export function installElectrobunWindowFullscreenTracking(): () => void {
26
28
  }
27
29
  reading = true;
28
30
  try {
29
- setWindowFullscreen(await backendRequest("host.windowFullscreen") === true);
31
+ const [fullscreen, maximized] = await Promise.all([
32
+ backendRequest("host.windowFullscreen"),
33
+ detectPlatform() === "win32" ? backendRequest("host.windowMaximized") : false,
34
+ ]);
35
+ setWindowFullscreen(fullscreen === true);
36
+ setWindowMaximized(maximized === true);
30
37
  } catch {
31
38
  // A host too old to answer has the window chrome the header already
32
39
  // assumes, so leaving the last known state alone is the safe read.
@@ -33,6 +33,7 @@ import type { TimeRange } from "../../time-series/range";
33
33
  import type { ChartResolutionSupport, ManualChartResolution } from "../../time-series/resolution";
34
34
  import { debugLog } from "../../utils/debug-log";
35
35
  import { errorMessage } from "../../utils/errors";
36
+ import { isPastPreCloseRefetch } from "../../utils/exchange-rate-snapshot";
36
37
  import { ProviderRouterBatchRoutes } from "./batches";
37
38
  import { createSignedInRealtimeCloudAccess, type RealtimeCloudAccess } from "./realtime-access";
38
39
  import { mapListingTargets, publicListingExchange } from "../listing-target";
@@ -362,7 +363,12 @@ export class AssetDataRouter implements DataProvider {
362
363
  }
363
364
 
364
365
  async getExchangeRate(fromCurrency: string, context?: Pick<MarketDataRequestContext, "cacheMode">): Promise<number> {
365
- return (await this.getCachedQuery("getExchangeRate", [fromCurrency]).load({ force: context?.cacheMode === "refresh", background: this.revalidateInBackground })).value;
366
+ const query = this.getCachedQuery("getExchangeRate", [fromCurrency]);
367
+ // A rate read before the FX week closed is no close: once the close is out, wait for it instead of showing
368
+ // the old rate while it is read again, which the caller would then hold as read now.
369
+ const cached = query.getSnapshot().result;
370
+ const background = this.revalidateInBackground && !(cached && isPastPreCloseRefetch(cached));
371
+ return (await query.load({ force: context?.cacheMode === "refresh", background })).value;
366
372
  }
367
373
 
368
374
  async search(query: string, context?: SearchRequestContext): Promise<InstrumentSearchResult[]> {
@@ -125,6 +125,17 @@ export function perTonneUnit(unit: string): string {
125
125
  return isPerBarrelUnit(unit) ? unit.replace(/(\/\s*)\S.*$/, "$1tonne") : unit;
126
126
  }
127
127
 
128
+ /**
129
+ * A rate of one currency in another as reports and exports name it: `JPY /
130
+ * USD`, the chart's unit for USDJPY=X, is `JPY per USD`, as `history` says,
131
+ * and a currency future's `USD / CHF` is `USD per CHF`. Any other unit
132
+ * (`USD / barrel`, `USD`) is returned as it is.
133
+ */
134
+ export function currencyRateUnitText(unit: string): string {
135
+ const match = /^([A-Z]{3})\s*\/\s*([A-Z]{3})$/.exec(unit.trim());
136
+ return match ? `${match[1]} per ${match[2]}` : unit;
137
+ }
138
+
128
139
  /**
129
140
  * What a currency pair's price counts: the quote currency one unit of the
130
141
  * base buys, so EURUSD=X is USD / EUR and USDJPY=X JPY / USD. Null for a
package/src/ui/host.tsx CHANGED
@@ -727,6 +727,8 @@ export interface RendererHost {
727
727
  */
728
728
  startWindowDrag?(press?: { detail?: number }): Promise<void> | void;
729
729
  controlWindow?(action: "minimize" | "toggle-maximize" | "close"): Promise<void> | void;
730
+ /** From a press on the page's top edge, where its own window frame has none to pull. */
731
+ startWindowResize?(edge: "top" | "top-left" | "top-right"): Promise<void> | void;
730
732
  /**
731
733
  * Opens a link in the person's browser. Resolves false when no browser could
732
734
  * be shown from here (a terminal over SSH, or no opener installed), so the
@@ -126,3 +126,23 @@ export function currenciesNamed(text: string): readonly NamedCurrency[] {
126
126
  if (!key) return [];
127
127
  return names.get(key) ?? (key.endsWith("s") ? names.get(key.slice(0, -1)) : undefined) ?? [];
128
128
  }
129
+
130
+ /** Codes that are also English words, read as a currency only when typed in capitals: "try" is a verb before it is the lira. */
131
+ export const WORD_CURRENCY_CODES: ReadonlySet<string> = new Set(["TRY", "PEN", "COP", "MAD", "RUB", "CAD"]);
132
+
133
+ let namedCodes: ReadonlySet<string> | undefined;
134
+
135
+ /**
136
+ * The currency a three-letter code names, as a query types it: `jpy` and
137
+ * `JPY` are JPY, `TRY` the lira but `try` nothing (`WORD_CURRENCY_CODES`).
138
+ * Only the currencies named here count, so `all` is no Albanian lek. Null for
139
+ * any other text.
140
+ */
141
+ export function currencyCodeTyped(text: string): string | null {
142
+ const typed = text.trim();
143
+ if (!/^[A-Za-z]{3}$/.test(typed)) return null;
144
+ namedCodes ??= new Set(CURRENCY_NAMES.map(([code]) => code));
145
+ const code = typed.toUpperCase();
146
+ if (!namedCodes.has(code)) return null;
147
+ return typed === code || !WORD_CURRENCY_CODES.has(code) ? code : null;
148
+ }
@@ -98,6 +98,12 @@ function pairBaseRank(code: string): number {
98
98
  return code === "JPY" ? PAIR_BASE_ORDER.length + 1 : PAIR_BASE_ORDER.length;
99
99
  }
100
100
 
101
+ /** A currency's pair against the dollar, as markets quote it and as a listing: EURUSD=X for the euro, USDCHF=X for the franc. */
102
+ export function dollarPairListing(code: string): string {
103
+ const currency = code.trim().toUpperCase();
104
+ return pairBaseRank(currency) < pairBaseRank("USD") ? `${currency}USD=X` : `USD${currency}=X`;
105
+ }
106
+
101
107
  /**
102
108
  * A rate of `quote` per unit of `currency`, written the way markets quote
103
109
  * the pair, as `fx` reads a pair: 0.0067 USD per JPY is USD/JPY 149.25, and
@@ -2,10 +2,26 @@ import { readIntradayBar, readStaleReason } from "../market-data/quotes/intraday
2
2
  import type { QuoteIntradayBar } from "../types/financials";
3
3
  import type { ExchangeRateSnapshot } from "../types/exchange-rate";
4
4
  import { fixedUsdRate } from "./currency-units";
5
- import { fxFreshUntil } from "./fx-market-hours";
5
+ import { fxFreshUntil, fxPreCloseRefetchAt } from "./fx-market-hours";
6
6
 
7
7
  export const MAX_FX_OBSERVATION_AGE_MS = 7 * 24 * 60 * 60_000;
8
8
  const FX_FRESH_MS = 60 * 60_000;
9
+ /** The longest a source's FX runs behind the market, and what a rate that states no delay is taken to: Gloom Cloud's 15 minutes. */
10
+ const MAX_FX_DELAY_MINUTES = 15;
11
+
12
+ /** When a rate read at `fetchedAt` is read again for its week's close (fxPreCloseRefetchAt); a rate with no stated delay may be up to 15 minutes behind. */
13
+ function preCloseRefetchAt(fetchedAt: number | undefined, asOf: number | undefined, delayMinutes: number | undefined): number {
14
+ return fxPreCloseRefetchAt(fetchedAt, asOf, Math.min(delayMinutes ?? MAX_FX_DELAY_MINUTES, MAX_FX_DELAY_MINUTES) * 60_000);
15
+ }
16
+
17
+ /**
18
+ * Whether a cached rate is past the point it is read again for its FX week's
19
+ * close: shown while it is read again, it would stand in for a close it is
20
+ * not, so a caller that revalidates in the background waits for this one.
21
+ */
22
+ export function isPastPreCloseRefetch(result: { fetchedAt: number; asOf?: number; delayMinutes?: number }, now = Date.now()): boolean {
23
+ return preCloseRefetchAt(result.fetchedAt, result.asOf, result.delayMinutes) <= now;
24
+ }
9
25
 
10
26
  interface FxRateMetadata {
11
27
  fetchedAt?: number;
@@ -62,12 +78,14 @@ export function exchangeRateMetadata(value: unknown, currency: string, now = Dat
62
78
  if (expiresAt <= now) return fail();
63
79
  const delayMinutes = typeof data.delayMinutes === "number" && Number.isFinite(data.delayMinutes) && data.delayMinutes >= 0
64
80
  ? data.delayMinutes : undefined;
65
- const delay = Math.min(delayMinutes ?? 0, 15) * 60_000;
81
+ const delay = Math.min(delayMinutes ?? 0, MAX_FX_DELAY_MINUTES) * 60_000;
66
82
  const intradayBar = readIntradayBar(data.intradayBar);
67
83
  const staleReason = readStaleReason(data.staleReason);
68
84
  const staleAt = Math.min(declaredStaleAt ?? Infinity,
69
85
  fetchedAt === undefined ? Infinity : fxFreshUntil(fetchedAt, FX_FRESH_MS),
70
86
  asOf === undefined ? Infinity : fxFreshUntil(asOf, FX_FRESH_MS + delay),
87
+ // A rate this app read before the week closed is read again once the close is out: when it read it, not the source.
88
+ preCloseRefetchAt(fallbackFetchedAt ?? fetchedAt, asOf, delayMinutes),
71
89
  data.stale === true ? now : Infinity);
72
90
  return {
73
91
  ...(fetchedAt !== undefined ? { fetchedAt } : {}),
@@ -85,6 +85,49 @@ export function latestFxWeekOpen(time: number): number | null {
85
85
  return latestNewYorkFivePm(time, 0);
86
86
  }
87
87
 
88
+ /**
89
+ * How close to the FX week's close a print is its close: Gloom Cloud dates the
90
+ * week's close by its last minute (20:59Z, or 21:59Z in winter).
91
+ */
92
+ const FX_CLOSE_PRINT_MS = 60_000;
93
+
94
+ /** Whether a print made at `time` is the close of the FX week that closed at `weekClose`. */
95
+ export function isFxWeekClosePrint(time: number, weekClose: number): boolean {
96
+ return time <= weekClose && time >= weekClose - FX_CLOSE_PRINT_MS;
97
+ }
98
+
99
+ /**
100
+ * When a rate fetched at `fetchedAt` must be read again because it may stand
101
+ * in for a close it is not: once the close of its FX week is out (the
102
+ * week's close, `delayMs` later for a delayed feed). A rate fetched at 20:39Z
103
+ * on a Friday is no close, yet the hours the market is shut do not age it
104
+ * (fxFreshUntil), so until Sunday's open it stood in for Friday's close. The
105
+ * week is the one `fetchedAt` falls in, not the one it is now, so the time is
106
+ * the same whether it is asked on Friday or on Sunday. Infinity for a rate
107
+ * that is that close (isFxWeekClosePrint).
108
+ */
109
+ export function fxPreCloseRefetchAt(fetchedAt: number | undefined, observedAt: number | undefined, delayMs: number): number {
110
+ if (fetchedAt == null || !Number.isFinite(fetchedAt)) return Infinity;
111
+ const close = fxWeekCloseOf(fetchedAt, delayMs);
112
+ if (close == null || (observedAt != null && isFxWeekClosePrint(observedAt, close))) return Infinity;
113
+ return close + delayMs;
114
+ }
115
+
116
+ /**
117
+ * The close of the FX week a rate fetched at `time` belongs to: the latest
118
+ * one while its print may still be on its way (`delayMs`), else the next one.
119
+ * The next close is a week on, give or take the hour a clock change moves it.
120
+ */
121
+ function fxWeekCloseOf(time: number, delayMs: number): number | null {
122
+ const latest = latestFxWeekClose(time);
123
+ if (latest != null && time < latest + delayMs) return latest;
124
+ for (const ahead of [7 * DAY_MS, 7 * DAY_MS + 2 * HOUR_MS]) {
125
+ const close = latestFxWeekClose(time + ahead);
126
+ if (close != null && close > time) return close;
127
+ }
128
+ return null;
129
+ }
130
+
88
131
  /**
89
132
  * When the closure the market is in began (Friday 17:00 New York time); null
90
133
  * while it trades. That is `latestFxWeekClose` for every moment the week is