@gloom-sh/terminal 0.20.18 → 0.20.19

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 (204) hide show
  1. package/package.json +1 -1
  2. package/src/api-client/cot.ts +5 -6
  3. package/src/api-client/data.ts +11 -1
  4. package/src/api-client/index.ts +1 -0
  5. package/src/api-client/request.ts +162 -40
  6. package/src/api-client/types/news.ts +45 -0
  7. package/src/api-client/types/world-venues.ts +9 -0
  8. package/src/app.tsx +4 -2
  9. package/src/architecture/floating-promise-allowlist.json +1 -1
  10. package/src/cli/commands/market.ts +53 -17
  11. package/src/cli/commands/ticker.ts +13 -6
  12. package/src/cli/context.ts +8 -0
  13. package/src/cli/desktop-pane-shot-browser.ts +3 -1
  14. package/src/cli/desktop-pane-shot-view.ts +0 -1
  15. package/src/cli/desktop-pane-shot.ts +204 -43
  16. package/src/cli/errors.ts +3 -9
  17. package/src/cli/exit-codes.ts +1 -1
  18. package/src/cli/glossary.ts +1 -1
  19. package/src/cli/help.ts +1 -1
  20. package/src/cli/history-rows.ts +2 -2
  21. package/src/cli/index.ts +1 -1
  22. package/src/cli/listing-arg.ts +87 -23
  23. package/src/cli/pane-functions/catalog-snapshot.json +17 -6
  24. package/src/cli/pane-functions/dom.ts +30 -2
  25. package/src/cli/pane-functions/freshness.ts +23 -4
  26. package/src/cli/pane-functions/function-help.ts +3 -3
  27. package/src/cli/pane-functions/headless.ts +9 -1
  28. package/src/cli/pane-functions/index.ts +77 -10
  29. package/src/cli/pane-functions/report-notices.ts +10 -0
  30. package/src/cli/pane-functions/resolver.ts +3 -2
  31. package/src/cli/pane-functions/screenshot-assessment.ts +10 -5
  32. package/src/cli/pane-functions/screenshot-data-evidence.ts +7 -15
  33. package/src/cli/pane-functions/screenshot-payload.ts +24 -10
  34. package/src/cli/pane-functions/screenshot-render.ts +21 -8
  35. package/src/cli/pane-functions/screenshot-types.ts +9 -0
  36. package/src/cli/quote-answer.ts +1 -1
  37. package/src/cli/result.ts +17 -0
  38. package/src/cli/scroll-truncation.ts +7 -2
  39. package/src/cli/ticker-resolution.ts +1 -1
  40. package/src/cli/unreachable.ts +21 -0
  41. package/src/components/chart/composite/drawing-store.ts +11 -7
  42. package/src/components/chart/composite/format.ts +1 -0
  43. package/src/components/chart/composite/legend.tsx +5 -2
  44. package/src/components/chart/composite/panel-surface/plot-gestures.ts +9 -2
  45. package/src/components/chart/composite/panel-surface.tsx +1 -1
  46. package/src/components/chart/composite/tools.ts +164 -39
  47. package/src/components/chart-table/header.tsx +2 -2
  48. package/src/components/chart-table/layout.ts +5 -6
  49. package/src/components/command-bar/routes/root/runtime.ts +11 -3
  50. package/src/components/command-bar/routes/ticker-search/results.ts +5 -0
  51. package/src/components/command-bar/selection-runtime.ts +29 -5
  52. package/src/components/command-bar/surface/index.tsx +4 -1
  53. package/src/components/command-bar/workflow/alert.ts +13 -5
  54. package/src/components/layout/pane/footer/model.ts +10 -2
  55. package/src/components/layout/pane/status-footer.ts +24 -0
  56. package/src/components/price-performance.tsx +26 -8
  57. package/src/components/reader/article-reader.tsx +12 -5
  58. package/src/components/ui/data-table/opentui/index.tsx +7 -0
  59. package/src/components/ui/table-layout.ts +32 -1
  60. package/src/market-data/ah-pair.ts +19 -0
  61. package/src/market-data/coordinator/entries.ts +6 -4
  62. package/src/market-data/coordinator/index.ts +14 -3
  63. package/src/market-data/futures-board.ts +36 -29
  64. package/src/market-data/futures-contract.ts +37 -1
  65. package/src/market-data/market/change-basis.ts +9 -0
  66. package/src/market-data/market/status.ts +40 -4
  67. package/src/market-data/performance.ts +127 -32
  68. package/src/market-data/quotes/time.ts +5 -2
  69. package/src/news/types.ts +28 -0
  70. package/src/notifications/app-badge.ts +2 -3
  71. package/src/notifications/app-notifier.ts +5 -0
  72. package/src/plugins/builtin/alerts/cli.ts +65 -18
  73. package/src/plugins/builtin/alerts/command.ts +39 -9
  74. package/src/plugins/builtin/alerts/event-rows.ts +9 -3
  75. package/src/plugins/builtin/alerts/events-pane.tsx +16 -10
  76. package/src/plugins/builtin/alerts/headless.ts +12 -6
  77. package/src/plugins/builtin/alerts/index.tsx +60 -8
  78. package/src/plugins/builtin/alerts/option-contract.ts +197 -0
  79. package/src/plugins/builtin/alerts/price.ts +30 -5
  80. package/src/plugins/builtin/alerts/pro-rules.ts +62 -0
  81. package/src/plugins/builtin/alerts/research-builder.ts +5 -10
  82. package/src/plugins/builtin/analytics/account-returns.ts +1 -1
  83. package/src/plugins/builtin/analytics/pane-model.ts +2 -2
  84. package/src/plugins/builtin/analytics/risk-client.ts +1 -1
  85. package/src/plugins/builtin/buildout/company/pane.tsx +4 -14
  86. package/src/plugins/builtin/catalysts/model.ts +2 -1
  87. package/src/plugins/builtin/chart-composer/chart-spec.ts +5 -0
  88. package/src/plugins/builtin/chart-composer/cli-options.ts +5 -3
  89. package/src/plugins/builtin/chart-composer/headless-schema.ts +14 -10
  90. package/src/plugins/builtin/chart-composer/headless.ts +2 -0
  91. package/src/plugins/builtin/chart-composer/index.tsx +17 -5
  92. package/src/plugins/builtin/chart-composer/pane.tsx +14 -4
  93. package/src/plugins/builtin/chart-composer/viewport-labels.ts +2 -17
  94. package/src/plugins/builtin/chat/controller/notifications.ts +1 -0
  95. package/src/plugins/builtin/chat/index.tsx +0 -1
  96. package/src/plugins/builtin/commodities-energy/index.tsx +1 -1
  97. package/src/plugins/builtin/company-kpis/headless.ts +1 -1
  98. package/src/plugins/builtin/company-kpis/model.ts +21 -9
  99. package/src/plugins/builtin/congress-trades/model.ts +9 -5
  100. package/src/plugins/builtin/cot/client.ts +2 -3
  101. package/src/plugins/builtin/cot/headless.ts +16 -16
  102. package/src/plugins/builtin/cot/index.tsx +6 -6
  103. package/src/plugins/builtin/cot/model.ts +25 -5
  104. package/src/plugins/builtin/cot/pane.tsx +11 -6
  105. package/src/plugins/builtin/cot/series.ts +11 -8
  106. package/src/plugins/builtin/cpi/model.ts +15 -4
  107. package/src/plugins/builtin/cpi/pane.tsx +29 -7
  108. package/src/plugins/builtin/doe/model.ts +30 -0
  109. package/src/plugins/builtin/doe/pane.tsx +8 -2
  110. package/src/plugins/builtin/earnings/board-table.ts +9 -4
  111. package/src/plugins/builtin/earnings/headless.ts +10 -3
  112. package/src/plugins/builtin/earnings/history-table.ts +4 -2
  113. package/src/plugins/builtin/earnings-calls/calendar.tsx +4 -3
  114. package/src/plugins/builtin/earnings-ripple/pane.tsx +2 -2
  115. package/src/plugins/builtin/econ/index.tsx +4 -2
  116. package/src/plugins/builtin/futures/model.ts +14 -1
  117. package/src/plugins/builtin/futures/series.ts +1 -8
  118. package/src/plugins/builtin/fx-matrix/index.tsx +2 -2
  119. package/src/plugins/builtin/insider/detail.tsx +36 -7
  120. package/src/plugins/builtin/insider/filing-stories.ts +110 -0
  121. package/src/plugins/builtin/insider/headless.ts +37 -2
  122. package/src/plugins/builtin/insider/index.tsx +79 -10
  123. package/src/plugins/builtin/insider/model.ts +43 -5
  124. package/src/plugins/builtin/ipo-calendar/client.ts +11 -1
  125. package/src/plugins/builtin/ipo-calendar/model.ts +3 -7
  126. package/src/plugins/builtin/jobs/headless.ts +2 -1
  127. package/src/plugins/builtin/jobs/model.ts +6 -0
  128. package/src/plugins/builtin/jobs/pane.tsx +8 -3
  129. package/src/plugins/builtin/news/wire/news/detail-view.tsx +118 -10
  130. package/src/plugins/builtin/news/wire/news/story-evidence.ts +178 -0
  131. package/src/plugins/builtin/options/analytics.ts +1 -1
  132. package/src/plugins/builtin/options/view.tsx +18 -11
  133. package/src/plugins/builtin/options-positioning/model.ts +11 -0
  134. package/src/plugins/builtin/options-positioning/pane.tsx +22 -1
  135. package/src/plugins/builtin/options-scenario/client.ts +49 -8
  136. package/src/plugins/builtin/options-scenario/headless.ts +7 -3
  137. package/src/plugins/builtin/options-scenario/model.ts +33 -2
  138. package/src/plugins/builtin/options-scenario/pane.tsx +3 -4
  139. package/src/plugins/builtin/perps/cascade.ts +4 -3
  140. package/src/plugins/builtin/perps/markets-section.tsx +5 -2
  141. package/src/plugins/builtin/perps/model.ts +4 -3
  142. package/src/plugins/builtin/portfolio-list/table.tsx +3 -2
  143. package/src/plugins/builtin/research/corporate-actions-pane.tsx +29 -14
  144. package/src/plugins/builtin/research/event-model.ts +12 -6
  145. package/src/plugins/builtin/research-search/index.tsx +3 -1
  146. package/src/plugins/builtin/scanner/denied.tsx +16 -4
  147. package/src/plugins/builtin/scanner/flow-pane.tsx +1 -1
  148. package/src/plugins/builtin/scanner/hilo-pane.tsx +1 -1
  149. package/src/plugins/builtin/sec/filing-display.tsx +14 -2
  150. package/src/plugins/builtin/sec/headless.ts +42 -4
  151. package/src/plugins/builtin/sec/index.tsx +21 -1
  152. package/src/plugins/builtin/sectors/sector-model.ts +1 -1
  153. package/src/plugins/builtin/shared/earnings-report.ts +32 -3
  154. package/src/plugins/builtin/shared/options-pro-copy.ts +34 -0
  155. package/src/plugins/builtin/shared/statement-currency.ts +23 -0
  156. package/src/plugins/builtin/shared/ticker-surface.ts +1 -1
  157. package/src/plugins/builtin/supply-chain/pane.tsx +4 -3
  158. package/src/plugins/builtin/themes/headless.ts +4 -4
  159. package/src/plugins/builtin/themes/model.ts +11 -8
  160. package/src/plugins/builtin/themes/pane.tsx +2 -2
  161. package/src/plugins/builtin/ticker-detail/financials/model.ts +22 -32
  162. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +7 -9
  163. package/src/plugins/builtin/ticker-detail/headless-schema.ts +2 -0
  164. package/src/plugins/builtin/ticker-detail/headless.ts +28 -12
  165. package/src/plugins/builtin/ticker-detail/overview/board-lot.ts +21 -0
  166. package/src/plugins/builtin/ticker-detail/overview/model.ts +11 -1
  167. package/src/plugins/builtin/ticker-detail/overview/pane.tsx +4 -0
  168. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +61 -13
  169. package/src/plugins/builtin/volatility/pane.tsx +3 -3
  170. package/src/plugins/builtin/world-venue-map/headless.ts +4 -2
  171. package/src/plugins/builtin/world-venue-map/model.ts +6 -1
  172. package/src/plugins/builtin/world-venue-map/venue-header.tsx +5 -3
  173. package/src/plugins/catalog-browser.ts +10 -1
  174. package/src/renderers/browser/activity.ts +16 -0
  175. package/src/renderers/browser/app-badge-host.ts +14 -0
  176. package/src/renderers/browser/main.tsx +5 -0
  177. package/src/renderers/browser/notifications.ts +103 -0
  178. package/src/renderers/browser/ui-host.tsx +4 -0
  179. package/src/renderers/dom/data-table/index.tsx +27 -4
  180. package/src/renderers/electrobun/view/http-fetch.ts +3 -2
  181. package/src/sources/gloomberb-cloud/index.ts +8 -6
  182. package/src/sources/gloomberb-cloud/news.ts +35 -0
  183. package/src/sources/provider-errors.ts +34 -7
  184. package/src/sources/provider-router/history.ts +32 -6
  185. package/src/time-series/base-series.ts +39 -6
  186. package/src/time-series/chart-seed.ts +2 -2
  187. package/src/time-series/history-quality.ts +4 -1
  188. package/src/time-series/hooks.ts +2 -0
  189. package/src/time-series/price-comparison.ts +17 -23
  190. package/src/time-series/reporting.ts +1 -1
  191. package/src/time-series/resolution.ts +13 -0
  192. package/src/time-series/resolve-context.ts +6 -0
  193. package/src/time-series/resolve.ts +39 -2
  194. package/src/time-series/types.ts +2 -1
  195. package/src/types/financials.ts +9 -1
  196. package/src/types/headless.ts +1 -0
  197. package/src/types/issuer-listings.ts +2 -0
  198. package/src/types/plugin-notifications.ts +3 -0
  199. package/src/types/price-history.ts +6 -4
  200. package/src/ui/host.tsx +2 -0
  201. package/src/utils/exchange-announcements.ts +7 -2
  202. package/src/utils/fundamentals.ts +40 -0
  203. package/src/utils/network-failure.ts +2 -0
  204. package/src/utils/price-history-integrity.ts +9 -1
@@ -4,7 +4,7 @@ import type { MarketNewsItem, NewsStoryItem } from "../../../../../types/news-so
4
4
  import { colors } from "../../../../../theme/colors";
5
5
  import { ArticleReader } from "../../../../../components/reader/article-reader";
6
6
  import type { ArticleBlock } from "../../../../../components/reader/article-text";
7
- import { ChoiceDialog, ExternalLinkText } from "../../../../../components/ui";
7
+ import { ActionRow, ChoiceDialog, ExternalLinkText } from "../../../../../components/ui";
8
8
  import { usePaneFooter } from "../../../../../components/layout/pane/footer";
9
9
  import { t } from "../../../../../i18n";
10
10
  import { useOptionalDialog, type PromptContext } from "../../../../../ui/dialog";
@@ -13,13 +13,25 @@ import { collectNewsDisplayTickers } from "../../../../../news/ticker-symbols";
13
13
  import { useInlineTickers } from "../../../../../state/hooks/inline-tickers";
14
14
  import { truncateToDisplayWidth } from "../../../../../utils/format";
15
15
  import { wrapTextLines } from "../../../../../utils/text-wrap";
16
- import { formatDetailDate, formatDetailTime } from "../../../../../utils/datetime-format";
16
+ import { formatDetailDate, formatDetailTime, formatShortDate } from "../../../../../utils/datetime-format";
17
17
  import { logFailure } from "../../../../../utils/log-failure";
18
18
  import { mergeNewsArticle, newsArticleRevision } from "../../../../../news/news-model";
19
- import { usePluginPaneState } from "../../../../runtime";
19
+ import { usePluginAppActions, usePluginPaneState } from "../../../../runtime";
20
20
  import { formatNewsCategory } from "../categories";
21
21
  import { shareItemExcerpt } from "../../../../../shares/item";
22
22
  import { usePaneShareItem } from "../../../../../shares/pane-item";
23
+ import type { NewsInsiderFiling } from "../../../../../news/types";
24
+ import {
25
+ groupInsiderFilings,
26
+ insiderFilingSummary,
27
+ insiderGroupHeading,
28
+ insiderGroupTotal,
29
+ rankStoryCoverage,
30
+ type InsiderFilingGroup,
31
+ } from "./story-evidence";
32
+
33
+ /** INS opens on one insider's lines of a company: the rows a story's filings are. */
34
+ const INSIDER_TEMPLATE_ID = "insider-pane";
23
35
 
24
36
  function hasStoryItems(article: MarketNewsItem | null): boolean {
25
37
  return (article?.items?.length ?? 0) > 0;
@@ -156,10 +168,9 @@ function storyItemDate(value: Date | string): Date {
156
168
  return Number.isNaN(date.getTime()) ? new Date(0) : date;
157
169
  }
158
170
 
159
- function sortStoryItems(items: readonly NewsStoryItem[] | undefined): NewsStoryItem[] {
160
- return [...(items ?? [])].sort((a, b) => (
161
- storyItemDate(b.publishedAt).getTime() - storyItemDate(a.publishedAt).getTime()
162
- ));
171
+ /** When the newest of a story's outlets published. */
172
+ function newestItemTime(items: readonly NewsStoryItem[]): number {
173
+ return items.reduce((newest, entry) => Math.max(newest, storyItemDate(entry.publishedAt).getTime()), 0);
163
174
  }
164
175
 
165
176
  const NATIVE_STRETCH_STYLE = { minWidth: 0 };
@@ -239,6 +250,56 @@ function NewsStoryTimelineItemView({
239
250
  );
240
251
  }
241
252
 
253
+ /**
254
+ * One filing a story reports: its accession, a link to the filing as filed,
255
+ * and what its lines add up to.
256
+ */
257
+ function StoryFilingView({ filing, width, nativePaneChrome }: { filing: NewsInsiderFiling; width: number; nativePaneChrome: boolean }) {
258
+ const filed = `filed ${formatShortDate(`${filing.filedOn}T00:00:00Z`, { utc: true })}`;
259
+ const label = `Form ${filing.form} ${filing.accession}`;
260
+ return (
261
+ <Box flexDirection="column" width={nativePaneChrome ? "100%" : width} style={nativePaneChrome ? NATIVE_STRETCH_STYLE : undefined}>
262
+ <Box height={nativePaneChrome ? undefined : 1} flexDirection="row" flexWrap={nativePaneChrome ? "wrap" : undefined} gap={nativePaneChrome ? 1 : undefined}>
263
+ {filing.url
264
+ ? <ExternalLinkText url={filing.url} label={label} color={colors.textBright} />
265
+ : <Text fg={colors.textBright}>{label}</Text>}
266
+ <Text fg={colors.textDim}>{nativePaneChrome ? filed : ` ${filed}`}</Text>
267
+ </Box>
268
+ <Box flexDirection="column" paddingLeft={2} width={nativePaneChrome ? "100%" : undefined} style={nativePaneChrome ? NATIVE_STRETCH_STYLE : undefined}>
269
+ <TextLines text={insiderFilingSummary(filing)} width={Math.max(10, width - 2)} color={colors.text} nativePaneChrome={nativePaneChrome} />
270
+ </Box>
271
+ </Box>
272
+ );
273
+ }
274
+
275
+ /**
276
+ * The Form 4s a story about insiders trading reports, each insider's together:
277
+ * who and where (a row that opens their lines in INS), what they add up to
278
+ * when there are several, then each filing.
279
+ */
280
+ function StoryFilingsView({ groups, width, nativePaneChrome, onOpen }: {
281
+ groups: readonly InsiderFilingGroup[];
282
+ width: number;
283
+ nativePaneChrome: boolean;
284
+ onOpen: (group: InsiderFilingGroup) => void;
285
+ }) {
286
+ return (
287
+ <Box flexDirection="column" gap={1} width={nativePaneChrome ? "100%" : width} style={nativePaneChrome ? NATIVE_STRETCH_STYLE : undefined}>
288
+ {groups.map((group) => (
289
+ <Box key={group.key} flexDirection="column">
290
+ <ActionRow label={insiderGroupHeading(group)} onPress={() => onOpen(group)} />
291
+ {group.filings.length > 1
292
+ ? <TextLines text={insiderGroupTotal(group)} width={width} color={colors.textDim} nativePaneChrome={nativePaneChrome} />
293
+ : null}
294
+ {group.filings.map((filing) => (
295
+ <StoryFilingView key={filing.accession} filing={filing} width={width} nativePaneChrome={nativePaneChrome} />
296
+ ))}
297
+ </Box>
298
+ ))}
299
+ </Box>
300
+ );
301
+ }
302
+
242
303
  export function NewsDetailView({ item, focused, width, showTitle = true }: {
243
304
  item: MarketNewsItem;
244
305
  focused: boolean;
@@ -255,14 +316,16 @@ export function NewsDetailView({ item, focused, width, showTitle = true }: {
255
316
  );
256
317
  const tickerTexts = useMemo(() => tickers.map((ticker) => `$${ticker}`), [tickers]);
257
318
  const { catalog } = useInlineTickers(tickerTexts, { badgeQuotes: true });
258
- const timelineItems = useMemo(() => sortStoryItems(item.items), [item.items]);
319
+ // The outlets that tell the story first, a wider post the story took in after them.
320
+ const timelineItems = useMemo(() => rankStoryCoverage(item.items, item), [item]);
321
+ const filingGroups = useMemo(() => groupInsiderFilings(item.insiderFilings ?? []), [item.insiderFilings]);
259
322
  const categoryLabels = useMemo(
260
323
  () => item.categories.map(formatNewsCategory).filter(Boolean).join(" \u00b7 "),
261
324
  [item.categories],
262
325
  );
263
326
  const lastUpdatedAt = new Date(Math.max(
264
327
  storyItemDate(item.publishedAt).getTime(),
265
- storyItemDate(timelineItems[0]?.publishedAt ?? item.publishedAt).getTime(),
328
+ newestItemTime(timelineItems),
266
329
  ));
267
330
 
268
331
  // The badges and outlet links, for the keyboard: [t]icker opens a mentioned
@@ -297,6 +360,37 @@ export function NewsDetailView({ item, focused, width, showTitle = true }: {
297
360
  if (url) void rendererHost.openExternal(url);
298
361
  }).catch(logFailure("news.detail-view", "Choose news coverage failed"));
299
362
  }, [coverage, dialog, rendererHost]);
363
+ // A filing's insider opens their lines in INS: the rows the story's numbers come from.
364
+ const { createPaneFromTemplate } = usePluginAppActions();
365
+ const openFilingRows = useCallback((group: InsiderFilingGroup) => {
366
+ if (!group.ticker) return;
367
+ createPaneFromTemplate(INSIDER_TEMPLATE_ID, { symbol: group.ticker, values: { insider: group.insider } });
368
+ }, [createPaneFromTemplate]);
369
+ const openableGroups = useMemo(() => filingGroups.filter((group) => group.ticker), [filingGroups]);
370
+ const chooseFilings = useCallback(() => {
371
+ if (openableGroups.length === 1) {
372
+ openFilingRows(openableGroups[0]!);
373
+ return;
374
+ }
375
+ if (!dialog || openableGroups.length === 0) return;
376
+ void dialog.prompt<string>({
377
+ closeOnClickOutside: true,
378
+ content: (ctx: PromptContext<string>) => (
379
+ <ChoiceDialog
380
+ {...ctx}
381
+ title={t("Filings")}
382
+ choices={openableGroups.map((group, index) => ({
383
+ id: String(index),
384
+ label: insiderGroupHeading(group),
385
+ description: insiderGroupTotal(group),
386
+ }))}
387
+ />
388
+ ),
389
+ }).then((choice) => {
390
+ const group = choice ? openableGroups[Number(choice)] : undefined;
391
+ if (group) openFilingRows(group);
392
+ }).catch(logFailure("news.detail-view", "Choose story filing failed"));
393
+ }, [dialog, openFilingRows, openableGroups]);
300
394
  usePaneFooter("news-detail:story", () => ({
301
395
  order: -1,
302
396
  hints: [
@@ -306,8 +400,11 @@ export function NewsDetailView({ item, focused, width, showTitle = true }: {
306
400
  ...(hasOtherCoverage && dialog
307
401
  ? [{ id: "sources", key: "s", label: "ources", onPress: chooseSource }]
308
402
  : []),
403
+ ...(openableGroups.length > 0
404
+ ? [{ id: "filings", key: "f", label: "ilings", title: "Open Filing Rows", onPress: chooseFilings }]
405
+ : []),
309
406
  ],
310
- }), [chooseSource, dialog, hasOtherCoverage, openTickerChoice, openableTickers]);
407
+ }), [chooseFilings, chooseSource, dialog, hasOtherCoverage, openTickerChoice, openableGroups.length, openableTickers]);
311
408
 
312
409
  // One outlet's own headline is the story's: the timeline is worth its rows
313
410
  // once a second outlet has written about it.
@@ -325,6 +422,17 @@ export function NewsDetailView({ item, focused, width, showTitle = true }: {
325
422
  focused={focused}
326
423
  width={width}
327
424
  height={0}
425
+ sections={filingGroups.length > 0 ? [{
426
+ label: "Filings",
427
+ content: (
428
+ <StoryFilingsView
429
+ groups={filingGroups}
430
+ width={coverageWidth}
431
+ nativePaneChrome={nativePaneChrome === true}
432
+ onOpen={openFilingRows}
433
+ />
434
+ ),
435
+ }] : undefined}
328
436
  childrenLabel={showTimeline ? "Coverage" : undefined}
329
437
  >
330
438
  {showTimeline && (
@@ -0,0 +1,178 @@
1
+ import type { NewsInsiderFiling, NewsStoryItem } from "../../../../../news/types";
2
+ import { formatCurrency, formatNumber } from "../../../../../utils/format";
3
+ import { formatShortDate } from "../../../../../utils/datetime-format";
4
+ import { formatInsiderName } from "../../../insider/display";
5
+
6
+ /*
7
+ * What a story's own page holds besides its text: the outlets that covered it,
8
+ * the most relevant to it first, and, for a story about insiders trading, the
9
+ * Form 4 filings it reports, each insider's filings together with their total.
10
+ */
11
+
12
+ /** Words that name nothing a story is about. */
13
+ const STOP_WORDS = new Set([
14
+ "a", "an", "and", "are", "as", "at", "be", "been", "but", "by", "for", "from", "had", "has", "have", "he", "her",
15
+ "his", "in", "into", "is", "it", "its", "of", "on", "or", "over", "said", "says", "she", "than", "that", "the",
16
+ "their", "them", "they", "this", "to", "was", "were", "which", "while", "who", "will", "with", "also", "after",
17
+ "about", "more", "most", "nearly", "new", "some", "such", "these", "those", "million", "billion", "percent",
18
+ ]);
19
+
20
+ /** A word as a story and its coverage share it: lower case, a plural's s left off. */
21
+ function stem(word: string): string {
22
+ return word.length > 4 && word.endsWith("s") && !word.endsWith("ss") ? word.slice(0, -1) : word;
23
+ }
24
+
25
+ function words(text: string): string[] {
26
+ return text.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase()
27
+ .split(/[^a-z0-9]+/).filter(Boolean);
28
+ }
29
+
30
+ /**
31
+ * The words a story is about, weighted: a name (a word its own text
32
+ * capitalises after the start of a sentence, Stevens, Nvidia, Q3) counts twice
33
+ * what any other word does.
34
+ */
35
+ function storyTerms(title: string, summary: string | undefined): Map<string, number> {
36
+ const text = `${title}. ${summary ?? ""}`;
37
+ const names = new Set<string>();
38
+ for (const sentence of text.split(/[.!?:]\s+/)) {
39
+ sentence.split(/\s+/).slice(1).forEach((raw) => {
40
+ const word = raw.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "");
41
+ if (/^\p{Lu}/u.test(word)) for (const part of words(word)) names.add(stem(part));
42
+ });
43
+ }
44
+ const terms = new Map<string, number>();
45
+ for (const word of words(text)) {
46
+ if (STOP_WORDS.has(word) || (word.length < 3 && !/\d/.test(word))) continue;
47
+ const term = stem(word);
48
+ terms.set(term, names.has(term) ? 2 : 1);
49
+ }
50
+ return terms;
51
+ }
52
+
53
+ /** The share of a story's weighted words an outlet's headline and summary also use, from 0 to 1. */
54
+ function coverageRelevance(item: Pick<NewsStoryItem, "title" | "summary">, terms: ReadonlyMap<string, number>): number {
55
+ let total = 0;
56
+ for (const weight of terms.values()) total += weight;
57
+ if (total === 0) return 0;
58
+ const used = new Set(words(`${item.title} ${item.summary ?? ""}`).map(stem));
59
+ let shared = 0;
60
+ for (const [term, weight] of terms) if (used.has(term)) shared += weight;
61
+ return shared / total;
62
+ }
63
+
64
+ function itemTime(item: NewsStoryItem): number {
65
+ const time = new Date(item.publishedAt).getTime();
66
+ return Number.isFinite(time) ? time : 0;
67
+ }
68
+
69
+ /**
70
+ * A story's coverage, the outlets that tell its story first: by the share of
71
+ * the story's words (its names counting double) each one's headline and summary
72
+ * use, the newest first among equals. A post the story took in that is about
73
+ * something wider (a sector's insider ratio under a story about one director's
74
+ * sales) goes after the reports of the story itself.
75
+ */
76
+ export function rankStoryCoverage(
77
+ items: readonly NewsStoryItem[] | undefined,
78
+ story: { title: string; summary?: string },
79
+ ): NewsStoryItem[] {
80
+ const terms = storyTerms(story.title, story.summary);
81
+ return [...(items ?? [])]
82
+ .map((item) => ({ item, relevance: Math.round(coverageRelevance(item, terms) * 100) }))
83
+ .sort((a, b) => b.relevance - a.relevance || itemTime(b.item) - itemTime(a.item))
84
+ .map(({ item }) => item);
85
+ }
86
+
87
+ /** One insider's filings a story reports, at one company, on one side. */
88
+ export interface InsiderFilingGroup {
89
+ key: string;
90
+ /** As filed (STEVENS MARK A): what INS filters by. */
91
+ insider: string;
92
+ /** As read (Mark A. Stevens). */
93
+ name: string;
94
+ title: string | null;
95
+ ticker: string | null;
96
+ issuerName: string | null;
97
+ side: NewsInsiderFiling["side"];
98
+ filings: NewsInsiderFiling[];
99
+ lines: number;
100
+ shares: number;
101
+ value: number;
102
+ firstTradeDate: string;
103
+ lastTradeDate: string;
104
+ }
105
+
106
+ /** The filings by insider, company and side, in the order the story's service ranks them (the largest first). */
107
+ export function groupInsiderFilings(filings: readonly NewsInsiderFiling[]): InsiderFilingGroup[] {
108
+ const groups = new Map<string, InsiderFilingGroup>();
109
+ for (const filing of filings) {
110
+ const key = `${filing.insider}\n${filing.ticker ?? filing.issuerName ?? ""}\n${filing.side}`;
111
+ const group = groups.get(key) ?? {
112
+ key,
113
+ insider: filing.insider,
114
+ name: formatInsiderName(filing.insider),
115
+ title: filing.title,
116
+ ticker: filing.ticker,
117
+ issuerName: filing.issuerName,
118
+ side: filing.side,
119
+ filings: [],
120
+ lines: 0,
121
+ shares: 0,
122
+ value: 0,
123
+ firstTradeDate: filing.firstTradeDate,
124
+ lastTradeDate: filing.lastTradeDate,
125
+ };
126
+ group.filings.push(filing);
127
+ group.lines += filing.lines;
128
+ group.shares += filing.shares;
129
+ group.value += filing.value;
130
+ if (filing.firstTradeDate < group.firstTradeDate) group.firstTradeDate = filing.firstTradeDate;
131
+ if (filing.lastTradeDate > group.lastTradeDate) group.lastTradeDate = filing.lastTradeDate;
132
+ groups.set(key, group);
133
+ }
134
+ return [...groups.values()];
135
+ }
136
+
137
+ /** `18 Sep 2026`; a span `31 Aug–2 Sep 2026`, the year once when both days share it. */
138
+ export function tradeDaySpan(first: string, last: string): string {
139
+ const day = (date: string, year: boolean) => formatShortDate(`${date}T00:00:00Z`, { utc: true, year: year ? "numeric" : false });
140
+ if (first === last) return day(first, true);
141
+ // The month once too when both days are in it: 3–4 Sep 2026.
142
+ if (first.slice(0, 7) === last.slice(0, 7)) return `${Number(first.slice(8, 10))}–${day(last, true)}`;
143
+ return `${day(first, first.slice(0, 4) !== last.slice(0, 4))}–${day(last, true)}`;
144
+ }
145
+
146
+ /** Whether the lines were traded under a Rule 10b5-1 plan, as the filing says, or that it does not say. */
147
+ function planText(rule10b51: boolean | null): string {
148
+ return rule10b51 === true ? "10b5-1 plan" : rule10b51 === false ? "no 10b5-1 plan" : "10b5-1 not stated";
149
+ }
150
+
151
+ const shareCount = (shares: number) => formatNumber(shares, Number.isInteger(shares) ? 0 : 4);
152
+ const dollars = (value: number) => formatCurrency(value, "USD", 2);
153
+ /** A weighted average to the four places Form 4 prices are filed to. */
154
+ const averagePrice = (price: number) => formatCurrency(price, "USD", 4);
155
+
156
+ /**
157
+ * One filing as its lines add up: `Sold 1,366,000 shares at avg $219.727,
158
+ * traded 18 Sep 2026, 2 lines, no 10b5-1 plan`.
159
+ */
160
+ export function insiderFilingSummary(filing: NewsInsiderFiling): string {
161
+ return [
162
+ `${filing.side === "sale" ? "Sold" : "Bought"} ${shareCount(filing.shares)} shares at avg ${averagePrice(filing.weightedPrice)}`,
163
+ `traded ${tradeDaySpan(filing.firstTradeDate, filing.lastTradeDate)}`,
164
+ `${filing.lines} ${filing.lines === 1 ? "line" : "lines"}`,
165
+ planText(filing.rule10b51),
166
+ ].join(", ");
167
+ }
168
+
169
+ /** An insider's filings in all: `4,236,740 shares for $946,627,633.48 in 3 Form 4s, traded 31 Aug–18 Sep 2026`. */
170
+ export function insiderGroupTotal(group: InsiderFilingGroup): string {
171
+ const count = group.filings.length;
172
+ return `${group.side === "sale" ? "Sold" : "Bought"} ${shareCount(group.shares)} shares for ${dollars(group.value)} in ${count} Form ${count === 1 ? "4" : "4s"}, traded ${tradeDaySpan(group.firstTradeDate, group.lastTradeDate)}`;
173
+ }
174
+
175
+ /** Who and where: `Mark A. Stevens · Director · NVDA`. */
176
+ export function insiderGroupHeading(group: InsiderFilingGroup): string {
177
+ return [group.name, group.title, group.ticker ?? group.issuerName].filter(Boolean).join(" · ");
178
+ }
@@ -184,7 +184,7 @@ function historicalVolatilityResult(points: readonly PricePoint[]): HistoricalVo
184
184
  if (cadenceIssue) return { value: null, unavailableReason: `HV30 unavailable: ${cadenceIssue}` };
185
185
  const result = realizedVolatilityResult(points, HISTORICAL_VOLATILITY_SESSIONS, "close-to-close");
186
186
  const reason = result.reason === "invalid-date" ? "invalid history date"
187
- : result.reason === "inconsistent-ohlc" ? "inconsistent OHLC history"
187
+ : result.reason === "inconsistent-ohlc" ? "contradictory prices in the history"
188
188
  : result.reason === "missing-close" ? "missing or nonpositive close"
189
189
  : result.reason && result.reason !== "insufficient-history" ? result.reason.replaceAll("-", " ") : null;
190
190
  return { value: result.value,
@@ -635,16 +635,17 @@ export function OptionsView({ width, height, focused, nestedInTabs = false, ivRa
635
635
  label: "Open interest as of",
636
636
  getMetadata: () => ({ text: openInterestAsOfLabel(openInterestAsOf), key: "openInterestAsOf", value: openInterestAsOf?.date ?? null }),
637
637
  } : null);
638
- // What IV and the Greeks are valued at, and the open interest's date. In a
639
- // crowded footer it shortens, then gives way to the contract under the cursor.
640
- // A stamped spot (a close, an extended print) is already the Spot figure's.
638
+ // What IV and the Greeks are valued at. In a crowded footer it shortens,
639
+ // then gives way to the contract under the cursor. A stamped spot (a close,
640
+ // an extended print) is already the Spot figure's.
641
641
  const footerSpot = modelSpot && !modelSpotStamp(modelSpot) ? modelSpot : null;
642
- const basisText = [footerSpot ? `spot ${formatModelSpotPrice(footerSpot.price)} ${modelSpotLabel(footerSpot)}` : null,
643
- strikeChain && !listedOpenInterest.loading ? openInterestAsOfLabel(openInterestAsOf) : null].filter(Boolean).join(" · ");
644
- const shortBasisText = [footerSpot ? `${formatModelSpotPrice(footerSpot.price)} last `
645
- + `${new Date(footerSpot.observedAt).toISOString().slice(11, 16)} UTC` : null,
646
- strikeChain && !listedOpenInterest.loading ? openInterestAsOf?.date ? `OI ${openInterestAsOf.date.slice(5)}` : "OI undated" : null]
647
- .filter(Boolean).join(" · ");
642
+ const basisText = footerSpot ? `spot ${formatModelSpotPrice(footerSpot.price)} ${modelSpotLabel(footerSpot)}` : "";
643
+ const shortBasisText = footerSpot ? `${formatModelSpotPrice(footerSpot.price)} last ${new Date(footerSpot.observedAt).toISOString().slice(11, 16)} UTC` : "";
644
+ // The open interest's date, which its counts cannot be read without: while the chain shows OI it shortens but
645
+ // stays, before the spot and the contract under the cursor give way, and a picture of the pane keeps it.
646
+ const openInterestShown = shownFieldIds.includes("openInterest");
647
+ const openInterestDateText = strikeChain && !listedOpenInterest.loading ? openInterestAsOfLabel(openInterestAsOf) : "";
648
+ const openInterestShortText = openInterestAsOf?.date ? `OI ${openInterestAsOf.date.slice(5)}` : "OI undated";
648
649
  // How IV was solved is said while the chain shows a figure that was not: a strike with no two-sided
649
650
  // out-of-the-money quote has its IV read off the neighbouring strikes, and its cell leads with "~".
650
651
  const ivFilledShown = shownFieldIds.includes("iv") && rows.some((row) => row.impliedVolatilityFilled && row.impliedVolatility != null);
@@ -654,6 +655,10 @@ export function OptionsView({ width, height, focused, nestedInTabs = false, ivRa
654
655
  label: "IV filled",
655
656
  getMetadata: () => ({ text: IV_FILLED_NOTE, key: "ivFilled", value: true }),
656
657
  } : null);
658
+ usePaneFooter("options-oi-date", () => ({ order: -1, info: openInterestDateText ? [{
659
+ id: "oi-as-of", capture: openInterestShown, holdsPlace: openInterestShown, parts: [{ text: openInterestDateText, tone: "muted" as const }],
660
+ variants: openInterestShown ? [[{ text: openInterestShortText, tone: "muted" as const }]] : [[{ text: openInterestShortText, tone: "muted" as const }], []],
661
+ }] : [] }), [openInterestDateText, openInterestShortText, openInterestShown]);
657
662
  usePaneFooter("options-basis", () => ({ info: [
658
663
  ...(basisText ? [{ id: "greeks-basis", parts: [{ text: basisText, tone: "muted" as const }],
659
664
  variants: [[{ text: shortBasisText, tone: "muted" as const }], []] }] : []),
@@ -661,8 +666,9 @@ export function OptionsView({ width, height, focused, nestedInTabs = false, ivRa
661
666
  title: IV_FILLED_DETAIL, variants: [[{ text: IV_FILLED_SHORT, tone: "muted" as const }]] }] : []),
662
667
  ] }), [basisText, shortBasisText, ivFilledShown]);
663
668
  // Fields the terminal chain gave up for width, counted so a narrow chain does
664
- // not read as all there is; hover names them. It leads the footer, so a
665
- // crowded row gives up the contract under the cursor before it.
669
+ // not read as all there is; hover names them. It leads the footer and holds
670
+ // its place beside the open interest's date, so a crowded row gives up the
671
+ // contract under the cursor before either.
666
672
  const hiddenFields = OPTION_FIELD_DEFS.filter((field) => optionFieldIds.includes(field.id) && !shownFieldIds.includes(field.id))
667
673
  .map((field) => field.label).join(", ");
668
674
  usePaneFooter("options-fit", () => {
@@ -670,6 +676,7 @@ export function OptionsView({ width, height, focused, nestedInTabs = false, ivRa
670
676
  return { order: -1, info: count ? [{
671
677
  id: "options-hidden-fields",
672
678
  capture: true,
679
+ holdsPlace: true,
673
680
  parts: [{ text: `${count} ${count === 1 ? "field" : "fields"} hidden`, tone: "muted" as const }],
674
681
  title: `Too narrow for ${hiddenFields}: a wider pane shows them, and Export CSV keeps them.`,
675
682
  variants: [[{ text: `${count} hidden`, tone: "muted" as const }]],
@@ -108,6 +108,17 @@ export function formatRatio(value: number | null | undefined): string {
108
108
  export function formatLevel(value: number | null | undefined): string {
109
109
  return value == null || !Number.isFinite(value) ? MISSING_VALUE : formatModelSpotPrice(value);
110
110
  }
111
+
112
+ /** The line Add Alert shows under Target Price when GEX fills it in: the level is fixed. */
113
+ const FLIP_ALERT_NOTE = "Fixed price: it does not follow the flip.";
114
+
115
+ /**
116
+ * Add Alert filled in for a price alert crossing the gamma flip as GEX shows it (the Flip figure's price, its
117
+ * grouping left out): a fixed level on the listing's quotes, which stays put when the flip moves, and says so.
118
+ */
119
+ export function flipAlertValues(symbol: string, flip: number): Record<string, string> {
120
+ return { kind: "price", symbol, condition: "crosses", price: formatLevel(flip).replaceAll(",", ""), priceNote: FLIP_ALERT_NOTE };
121
+ }
111
122
  /**
112
123
  * The spot of a positioning answer as the options panes stamp theirs: the
113
124
  * regular session's close when the server says so (a cash index outside its
@@ -19,10 +19,14 @@ import {
19
19
  type DataTableCell,
20
20
  type DataTableColumn,
21
21
  type PaneFooterSegment,
22
+ type PaneHint,
22
23
  type QueryBarFilter,
23
24
  type StatItem,
24
25
  } from "../../../components";
25
26
  import { savedCopyFooterSegment } from "../../../components/layout/pane/footer";
27
+ import { openFormModal } from "../../../components/form-modal";
28
+ import { getSharedRegistry } from "../../registry/shared";
29
+ import { usePluginAppActions } from "../../runtime";
26
30
  import type { CloudResource } from "../shared/cloud-resource";
27
31
  import { formatCompactAxis } from "../../../components/chart-table";
28
32
  import { usePaneRefreshKey } from "../../../components/data-table/table-pane";
@@ -66,6 +70,7 @@ import {
66
70
  formatDistance,
67
71
  formatGamma,
68
72
  formatLevel,
73
+ flipAlertValues,
69
74
  gammaTimesFigure,
70
75
  positioningSpotDetail,
71
76
  formatPayout,
@@ -318,12 +323,28 @@ function OptionsPositioningView({ width, height, focused, symbol }: PaneProps &
318
323
  const activeResource = tab === "gex" ? gamma : openInterest;
319
324
  // Expiries' Net GEX column loads beside the open interest it sits with.
320
325
  const columnGamma = tab === "expiries" && gammaReady ? gamma : null;
326
+ // Alert at this flip: Add Alert filled in with a price alert crossing the flip shown, a fixed price on the
327
+ // reader's quotes that the app checks, which stays put when dealer positioning moves the flip.
328
+ const { notify } = usePluginAppActions();
329
+ const flip = tab === "gex" ? gamma.data?.flip ?? null : null;
330
+ const alertsOn = getSharedRegistry()?.commands.has("set-alert") === true;
331
+ const flipHint = useMemo<PaneHint | null>(() => {
332
+ if (flip == null || !Number.isFinite(flip) || !alertsOn) return null;
333
+ const level = formatLevel(flip);
334
+ return {
335
+ id: "flip-alert", key: "a", label: "lert at flip",
336
+ title: `Alert at this flip: a price alert when your quote crosses ${level}, checked while Gloom runs. A fixed price; it stays at ${level} when dealer positioning moves the flip.`,
337
+ onPress: () => {
338
+ if (!openFormModal({ kind: "plugin-command", commandId: "set-alert", values: flipAlertValues(symbol, flip) })) notify({ body: "Open this from the main window.", type: "info" });
339
+ },
340
+ };
341
+ }, [alertsOn, flip, notify, symbol]);
321
342
  usePaneStatusFooter({
322
343
  registrationId: "options-positioning",
323
344
  loading: activeResource.loading || !!columnGamma?.loading,
324
345
  error: activeResource.data ? activeResource.error ?? columnGamma?.error ?? null : null,
325
346
  info,
326
- hints: upgradeHint ? [upgradeHint] : undefined,
347
+ hints: upgradeHint || flipHint ? [...upgradeHint ? [upgradeHint] : [], ...flipHint ? [flipHint] : []] : undefined,
327
348
  });
328
349
  const notices = useMemo(() => [
329
350
  ...(data?.warnings ?? []),
@@ -1,5 +1,5 @@
1
1
  import { apiClient } from "../../../api-client";
2
- import { getSharedMarketDataCoordinator, MarketDataCoordinator, resolveEntryValue } from "../../../market-data/coordinator";
2
+ import { entryFailedTransiently, getSharedMarketDataCoordinator, MarketDataCoordinator, resolveEntryValue } from "../../../market-data/coordinator";
3
3
  import type { InstrumentRef, OptionsRequest } from "../../../market-data/request-types";
4
4
  import type { QueryEntry } from "../../../market-data/result-types";
5
5
  import type { DataProvider } from "../../../types/data-provider";
@@ -18,6 +18,9 @@ import { loadModelDividendYield, type ModelDividendYield } from "../../../market
18
18
  import { abortable, abortError } from "../../../utils/async-deadline";
19
19
  import { extendedSession, modelSpotStamp, modelSpotStampVariants, type OptionModelSpot } from "../options/model-spot";
20
20
  import { errorMessage } from "../../../utils/errors";
21
+ import { isTransientFailure } from "../../../api-client/errors";
22
+ import { isTransientSourceFailure, serviceDidNotAnswerMessage } from "../../../sources/provider-errors";
23
+ import { DATA_SERVICE_UNREACHABLE_MESSAGE, isNetworkFailure } from "../../../utils/network-failure";
21
24
  import { dateOptionError, dateOptionFormatsOr, readCalendarDate } from "../../../utils/calendar-date";
22
25
 
23
26
  export interface ScenarioMarketSnapshot {
@@ -42,6 +45,11 @@ export interface ScenarioMarketSnapshot {
42
45
  warnings: string[];
43
46
  /** Why the requested expiry has no chain, naming the listed dates nearest it. */
44
47
  missingExpiry?: string;
48
+ /**
49
+ * Why the chain read failed: the data service did not answer, with when to
50
+ * ask again, or none is listed (`chainReadFailure`). Absent from older snapshots.
51
+ */
52
+ chainUnavailable?: string;
45
53
  }
46
54
 
47
55
  export interface ScenarioLoaderDependencies {
@@ -129,6 +137,7 @@ export async function loadScenarioMarket(
129
137
  });
130
138
  if (request.signal?.aborted) throw abortError(CANCELLED);
131
139
  if (!dividend) warnings.push("Dividend yield unavailable; supply an explicit assumption");
140
+ let chainRejection: unknown = chainResult.status === "rejected" ? chainResult.reason ?? new Error("Options chain read failed") : undefined;
132
141
  let chainEntry = entry(chainResult, "Options chain");
133
142
  let chain = chainEntry ? resolveEntryValue(chainEntry) : null;
134
143
  if (chain && !symbolMatches(chain.underlyingSymbol, symbol)) {
@@ -146,8 +155,9 @@ export async function loadScenarioMarket(
146
155
  && !chain.calls.length && !chain.puts.length ? listedExpiration : undefined);
147
156
  if (reload != null) {
148
157
  // Or a source that keys chains by its exact stamp answered the midnight request empty.
158
+ chainRejection = undefined;
149
159
  chainEntry = await abortable(dependencies.loadOptions({ instrument: request.instrument, expirationDate: reload }, options)
150
- .catch((error: unknown) => { warnings.push(`Options chain: ${errorMessage(error)}`); return null; }), request.signal, CANCELLED);
160
+ .catch((error: unknown) => { warnings.push(`Options chain: ${errorMessage(error)}`); chainRejection = error ?? new Error("Options chain read failed"); return null; }), request.signal, CANCELLED);
151
161
  if (request.signal?.aborted) throw abortError(CANCELLED);
152
162
  if (chainEntry?.error) warnings.push(`Options chain: ${chainEntry.error.message}`);
153
163
  chain = chainEntry ? resolveEntryValue(chainEntry) : null;
@@ -166,6 +176,14 @@ export async function loadScenarioMarket(
166
176
  } else if (chain && (listedExpiration ?? liveDefault) != null && !onExpiry(chain, (listedExpiration ?? liveDefault)!)) {
167
177
  warnings.push("Selected expiration unavailable in the returned options chain"); chain = null;
168
178
  }
179
+ // A read that failed says why: a service that did not answer is asked again, a chain none lists is not.
180
+ const chainUnavailable = !missingExpiry && (!chain || chainEntry?.error)
181
+ ? chainReadFailure(symbol, chainRejection, chainEntry, chain != null) : undefined;
182
+ if (chainUnavailable && chainUnavailable !== `No options chain is listed for ${symbol}.`) {
183
+ // The router's "No options provider available" of a read that timed out reads as no chain at all.
184
+ for (let index = warnings.length - 1; index >= 0; index -= 1) if (warnings[index]!.startsWith("Options chain: ")) warnings.splice(index, 1);
185
+ warnings.push(chainUnavailable);
186
+ }
169
187
  if (!chain) warnings.push("Options chain unavailable");
170
188
  else if (chainEntry?.error || (chainEntry?.staleAt != null && chainEntry.staleAt <= now)) warnings.push("Options chain is stale");
171
189
  const rateExpiration = request.rateExpiration ?? (expired ? undefined : request.expiration) ?? expirationDates[0];
@@ -186,9 +204,36 @@ export async function loadScenarioMarket(
186
204
  source: quoteCurrent ? quoteEntry?.source ?? quote!.providerId ?? null : null,
187
205
  underlyingQuote: quoteCurrent ? quote : null, rateAsOf: rate.asOf, warnings: [...new Set(warnings)],
188
206
  ...(missingExpiry ? { missingExpiry } : {}),
207
+ ...(chainUnavailable ? { chainUnavailable } : {}),
189
208
  };
190
209
  }
191
210
 
211
+ /**
212
+ * Why a chain read that failed left no current chain: the data service could
213
+ * not be reached or did not answer in time, which asking again may get past
214
+ * and is said with that advice, or it answered with none it lists. `kept` is
215
+ * a chain an earlier read left, which only a failure worth retrying explains.
216
+ * Undefined when the read did not fail.
217
+ */
218
+ function chainReadFailure(symbol: string, rejection: unknown, entry: QueryEntry<OptionsChain> | null, kept: boolean): string | undefined {
219
+ if (rejection === undefined && !entry?.error) return undefined;
220
+ const what = `the ${symbol} options chain`;
221
+ const message = rejection !== undefined ? errorMessage(rejection) : entry!.error!.message;
222
+ if (isNetworkFailure(rejection) || message === DATA_SERVICE_UNREACHABLE_MESSAGE || isNetworkFailure(message)) {
223
+ return `${DATA_SERVICE_UNREACHABLE_MESSAGE} for ${what}. Try again in a moment.`;
224
+ }
225
+ // A rate limit, or a read the service failed twice, already says when to ask again.
226
+ if (/\btry again\b/i.test(message)) return message;
227
+ const transient = rejection !== undefined ? isTransientFailure(rejection) || isTransientSourceFailure(rejection) : entryFailedTransiently(entry);
228
+ if (transient) return serviceDidNotAnswerMessage(what);
229
+ return kept ? undefined : `No options chain is listed for ${symbol}.`;
230
+ }
231
+
232
+ /** What a strategy seed says when the market holds no current chain to seed it from. */
233
+ function seedChainError(market: Pick<ScenarioMarketSnapshot, "missingExpiry" | "chainUnavailable"> | null | undefined): Error {
234
+ return new Error(market?.missingExpiry ?? market?.chainUnavailable ?? "A current options chain is required to seed a strategy");
235
+ }
236
+
192
237
  const sentence = (text: string) => text.charAt(0).toUpperCase() + text.slice(1);
193
238
 
194
239
  const cents = (value: number) => value.toFixed(2);
@@ -309,9 +354,7 @@ export function scenarioPositionFromSettings(
309
354
  let shareEntry: number | null | undefined;
310
355
  if (!legs.length && supplied(settings.strategy)) {
311
356
  if (!isScenarioStrategy(settings.strategy)) throw new Error("strategy must be vertical, straddle, put, csp or collar");
312
- if (!market?.chain || market.warnings.includes("Options chain is stale")) {
313
- throw new Error(market?.missingExpiry ?? "A current options chain is required to seed a strategy");
314
- }
357
+ if (!market?.chain || market.warnings.includes("Options chain is stale")) throw seedChainError(market);
315
358
  if (spot == null) throw new Error("A current underlying price or explicit --spot is required");
316
359
  // Leg IVs are solved at the market's own spot and time, never at a what-if override.
317
360
  const pricing = market.spot != null && rate != null ? { spot: market.spot, asOf: market.asOf, rate, dividendYield: dividendYield ?? 0 } : null;
@@ -583,9 +626,7 @@ export function seedScreenPosition(
583
626
  pick: (quoted: QuotedChain, pricing: StrategyPricing, unusable: UnusableChainText) => ScreenSeed,
584
627
  merged?: OptionsChain,
585
628
  ): ScenarioPosition {
586
- if (!market.chain || market.warnings.includes("Options chain is stale")) {
587
- throw new Error(market.missingExpiry ?? "A current options chain is required to seed a strategy");
588
- }
629
+ if (!market.chain || market.warnings.includes("Options chain is stale")) throw seedChainError(market);
589
630
  const chain = merged ?? market.chain;
590
631
  if (market.spot == null) throw new Error("A current underlying price is required");
591
632
  if (market.rate == null) throw new Error("Choosing legs by delta needs the Treasury rate");