@gloom-sh/terminal 0.20.4 → 0.20.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 (217) hide show
  1. package/README.md +2 -0
  2. package/bin/gloom +9 -0
  3. package/bin/without-bun.cjs +98 -0
  4. package/package.json +3 -1
  5. package/src/api-client/data.ts +138 -35
  6. package/src/api-client/types/econ.ts +12 -0
  7. package/src/api-client/yield-curves.ts +1 -1
  8. package/src/app/global-shortcuts.ts +4 -1
  9. package/src/app/keybindings/actions.ts +6 -0
  10. package/src/app/keybindings/config.ts +2 -1
  11. package/src/app/keybindings/index.ts +1 -0
  12. package/src/app/keybindings/labels.ts +6 -1
  13. package/src/app/keybindings/resolve.ts +23 -4
  14. package/src/app/keybindings/terminal-keys.ts +35 -0
  15. package/src/app/pane-runtime/index.tsx +2 -2
  16. package/src/app/pane-runtime/ticker-open-runtime.ts +68 -40
  17. package/src/architecture/ui-literals-allowlist.json +1 -1
  18. package/src/capabilities/chart-series.ts +27 -1
  19. package/src/cli/commands/keybindings.ts +5 -5
  20. package/src/cli/commands/market.ts +78 -21
  21. package/src/cli/commands/news-search.ts +59 -7
  22. package/src/cli/commands/overview.ts +16 -1
  23. package/src/cli/commands/remote.ts +16 -17
  24. package/src/cli/commands/system.ts +1 -1
  25. package/src/cli/fx-forward.ts +25 -7
  26. package/src/cli/glossary.ts +19 -5
  27. package/src/cli/history-rows.ts +5 -3
  28. package/src/cli/known-gaps.ts +27 -1
  29. package/src/cli/listing-arg.ts +11 -1
  30. package/src/cli/name-entries.ts +5 -1
  31. package/src/cli/not-a-ticker.ts +4 -0
  32. package/src/cli/pane-functions/function-help.ts +2 -2
  33. package/src/components/command-bar/pane-settings.ts +2 -2
  34. package/src/components/command-bar/routes/root/results.ts +6 -2
  35. package/src/components/input-search-bar.tsx +9 -2
  36. package/src/components/layout/pane/header.tsx +2 -0
  37. package/src/components/layout/shell/pane/capture.ts +4 -1
  38. package/src/components/layout/status-bar.tsx +6 -1
  39. package/src/components/onboarding/first-run-workspace.ts +44 -2
  40. package/src/components/onboarding/onboarding-frame.tsx +11 -2
  41. package/src/components/onboarding/onboarding-keyboard.ts +16 -0
  42. package/src/components/onboarding/onboarding-wizard.tsx +8 -8
  43. package/src/components/onboarding/portfolio-step/positions-panel.tsx +62 -1
  44. package/src/components/onboarding/use-onboarding-progress.ts +12 -4
  45. package/src/components/pane-settings-dialog/desktop.tsx +2 -2
  46. package/src/components/pane-settings-dialog/tui.tsx +2 -2
  47. package/src/components/pane-settings-dialog/value.ts +6 -0
  48. package/src/components/pane-settings-dialog.tsx +3 -3
  49. package/src/components/reader/detail-reader.tsx +4 -0
  50. package/src/components/ui/index.ts +1 -1
  51. package/src/components/ui/page-stack-view.tsx +3 -0
  52. package/src/components/ui/pane-link-chip.tsx +269 -54
  53. package/src/components/ui/query-bar.tsx +2 -1
  54. package/src/components/ui/tabs.tsx +97 -19
  55. package/src/core/state/app/layout-reducer.ts +7 -0
  56. package/src/core/state/app/layout.ts +44 -7
  57. package/src/core/state/app/state.ts +1 -1
  58. package/src/core/state/app/types.ts +22 -2
  59. package/src/docs/snapshot.json +27 -10
  60. package/src/market-data/depositary-pair.ts +5 -3
  61. package/src/market-data/market/dated-previous-close.ts +94 -15
  62. package/src/market-data/market/status.ts +17 -1
  63. package/src/plugins/builtin/analytics/risk-client.ts +10 -4
  64. package/src/plugins/builtin/analytics/risk-episodes.ts +5 -4
  65. package/src/plugins/builtin/analytics/risk-headless.ts +4 -2
  66. package/src/plugins/builtin/analytics/risk-sectors.ts +91 -0
  67. package/src/plugins/builtin/awards/index.tsx +1 -1
  68. package/src/plugins/builtin/buildout/index.tsx +1 -0
  69. package/src/plugins/builtin/catalysts/index.tsx +2 -2
  70. package/src/plugins/builtin/cds/headless.ts +4 -0
  71. package/src/plugins/builtin/chart-composer/headless.ts +2 -1
  72. package/src/plugins/builtin/chart-composer/index.tsx +1 -0
  73. package/src/plugins/builtin/chat/content/composer.tsx +5 -4
  74. package/src/plugins/builtin/chat/content/index.tsx +12 -2
  75. package/src/plugins/builtin/chat/content/layout-metrics.ts +3 -3
  76. package/src/plugins/builtin/chat/content/open-targets.ts +3 -3
  77. package/src/plugins/builtin/chat/layout.ts +5 -2
  78. package/src/plugins/builtin/chat/message/pane-chip.tsx +61 -40
  79. package/src/plugins/builtin/chat/message/terminal.tsx +13 -15
  80. package/src/plugins/builtin/chat/pane-links/previews.ts +51 -5
  81. package/src/plugins/builtin/chat/pane-links/share-card.ts +36 -0
  82. package/src/plugins/builtin/cloud/askg/tool-display.ts +1 -0
  83. package/src/plugins/builtin/cloud/terminal-relay/redact.ts +5 -3
  84. package/src/plugins/builtin/commodity-balances/index.tsx +1 -0
  85. package/src/plugins/builtin/company-attention/index.tsx +1 -1
  86. package/src/plugins/builtin/company-kpis/headless.ts +3 -1
  87. package/src/plugins/builtin/company-kpis/index.tsx +2 -2
  88. package/src/plugins/builtin/cot/index.tsx +1 -1
  89. package/src/plugins/builtin/cpi/index.tsx +1 -1
  90. package/src/plugins/builtin/crypto-board/index.tsx +1 -0
  91. package/src/plugins/builtin/dividend-yield/index.tsx +1 -0
  92. package/src/plugins/builtin/doe/index.tsx +1 -1
  93. package/src/plugins/builtin/earnings-calls/headless.ts +5 -1
  94. package/src/plugins/builtin/earnings-calls/index.tsx +1 -0
  95. package/src/plugins/builtin/econ/calendar-model.ts +74 -1
  96. package/src/plugins/builtin/econ/fred-catalog.ts +3 -1
  97. package/src/plugins/builtin/econ/index.tsx +1 -0
  98. package/src/plugins/builtin/econ-statistics/index.tsx +1 -0
  99. package/src/plugins/builtin/econ-statistics/pane.tsx +6 -0
  100. package/src/plugins/builtin/estimate-revisions/index.tsx +1 -0
  101. package/src/plugins/builtin/executives/index.tsx +1 -0
  102. package/src/plugins/builtin/filing-events/index.tsx +1 -0
  103. package/src/plugins/builtin/fixed-income/index.tsx +1 -0
  104. package/src/plugins/builtin/futures-curve/headless.ts +3 -3
  105. package/src/plugins/builtin/futures-curve/index.tsx +1 -1
  106. package/src/plugins/builtin/futures-curve/model.ts +18 -0
  107. package/src/plugins/builtin/gpu/index.tsx +1 -1
  108. package/src/plugins/builtin/help/functions-table.tsx +1 -1
  109. package/src/plugins/builtin/help/index.tsx +11 -1
  110. package/src/plugins/builtin/help/keybindings-editor.tsx +1 -1
  111. package/src/plugins/builtin/holders/index.tsx +1 -0
  112. package/src/plugins/builtin/holders/report-header.ts +2 -2
  113. package/src/plugins/builtin/insider/index.tsx +1 -0
  114. package/src/plugins/builtin/iv-history/index.tsx +1 -1
  115. package/src/plugins/builtin/jobs/index.tsx +1 -0
  116. package/src/plugins/builtin/macro-day/headless.ts +27 -8
  117. package/src/plugins/builtin/macro-day/index.tsx +1 -1
  118. package/src/plugins/builtin/macro-day/model.ts +19 -3
  119. package/src/plugins/builtin/macro-day/pane.tsx +14 -9
  120. package/src/plugins/builtin/macro-day/releases.ts +25 -7
  121. package/src/plugins/builtin/market-valuation/index.tsx +1 -0
  122. package/src/plugins/builtin/market-valuation/pane.tsx +8 -0
  123. package/src/plugins/builtin/members/index.tsx +1 -1
  124. package/src/plugins/builtin/mna/index.tsx +1 -0
  125. package/src/plugins/builtin/news/index.tsx +1 -0
  126. package/src/plugins/builtin/news/wire/index.tsx +5 -1
  127. package/src/plugins/builtin/news/wire/news/detail-view.tsx +4 -0
  128. package/src/plugins/builtin/news/wire/news/list-search.ts +5 -2
  129. package/src/plugins/builtin/options/index.tsx +1 -0
  130. package/src/plugins/builtin/options-positioning/index.tsx +1 -0
  131. package/src/plugins/builtin/pe-band/index.tsx +1 -1
  132. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +25 -0
  133. package/src/plugins/builtin/portfolio-list/headless.ts +15 -6
  134. package/src/plugins/builtin/power/index.tsx +1 -1
  135. package/src/plugins/builtin/realized-vol/index.tsx +1 -1
  136. package/src/plugins/builtin/research/headless.ts +10 -4
  137. package/src/plugins/builtin/research/index.tsx +4 -0
  138. package/src/plugins/builtin/research-search/index.tsx +1 -0
  139. package/src/plugins/builtin/research-search/pane.tsx +8 -0
  140. package/src/plugins/builtin/revenue-breakdown/index.tsx +1 -0
  141. package/src/plugins/builtin/reverse-dcf/index.tsx +1 -1
  142. package/src/plugins/builtin/risk-factors/index.tsx +1 -0
  143. package/src/plugins/builtin/scanner/headless.ts +52 -13
  144. package/src/plugins/builtin/seasonality/index.tsx +1 -1
  145. package/src/plugins/builtin/sec/index.tsx +1 -0
  146. package/src/plugins/builtin/series-inventory.ts +1 -1
  147. package/src/plugins/builtin/shared/scanner-capture.ts +11 -3
  148. package/src/plugins/builtin/shared/series-list-detail.tsx +5 -0
  149. package/src/plugins/builtin/short-interest/index.tsx +1 -0
  150. package/src/plugins/builtin/social-mentions/index.tsx +1 -1
  151. package/src/plugins/builtin/supply-chain/index.tsx +1 -0
  152. package/src/plugins/builtin/thirteenf/data.ts +43 -10
  153. package/src/plugins/builtin/thirteenf/headless.ts +55 -11
  154. package/src/plugins/builtin/thirteenf/model.ts +25 -9
  155. package/src/plugins/builtin/thirteenf/report-notes.ts +27 -6
  156. package/src/plugins/builtin/thirteenf/types.ts +2 -0
  157. package/src/plugins/builtin/ticker-detail/adr-pair/model.ts +1 -1
  158. package/src/plugins/builtin/ticker-detail/financials/model.ts +12 -0
  159. package/src/plugins/builtin/ticker-detail/financials/ratio-table.tsx +3 -3
  160. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +5 -5
  161. package/src/plugins/builtin/ticker-detail/headless.ts +18 -13
  162. package/src/plugins/builtin/ticker-detail/index.tsx +4 -0
  163. package/src/plugins/builtin/ticker-detail/overview/model.ts +6 -4
  164. package/src/plugins/builtin/ticker-detail/overview-tab.tsx +6 -4
  165. package/src/plugins/builtin/time-sales/client.ts +9 -11
  166. package/src/plugins/builtin/time-sales/index.tsx +1 -1
  167. package/src/plugins/builtin/treasury-auctions/after.ts +267 -0
  168. package/src/plugins/builtin/treasury-auctions/cache.ts +18 -3
  169. package/src/plugins/builtin/treasury-auctions/client.ts +33 -2
  170. package/src/plugins/builtin/treasury-auctions/headless.ts +109 -19
  171. package/src/plugins/builtin/treasury-auctions/index.tsx +14 -4
  172. package/src/plugins/builtin/treasury-auctions/model.ts +256 -28
  173. package/src/plugins/builtin/treasury-auctions/pane.tsx +139 -28
  174. package/src/plugins/builtin/treasury-auctions/treasury-direct.ts +5 -2
  175. package/src/plugins/builtin/treasury-auctions/types.ts +7 -1
  176. package/src/plugins/builtin/vol-surface/index.tsx +1 -1
  177. package/src/plugins/builtin/world-venue-map/index.ts +1 -0
  178. package/src/plugins/builtin/yield-curve/curves.ts +10 -4
  179. package/src/plugins/builtin/yield-curve/headless.ts +6 -2
  180. package/src/plugins/builtin/yield-curve/index.tsx +3 -3
  181. package/src/plugins/builtin/yield-curve/series.ts +10 -0
  182. package/src/plugins/builtin/yield-curve/world.ts +3 -1
  183. package/src/portfolio/column-values.ts +2 -1
  184. package/src/public/__snapshots__/public-api.test.ts.snap +4 -0
  185. package/src/public/remote.ts +7 -1
  186. package/src/remote/client.ts +191 -11
  187. package/src/remote/controller-utils.ts +13 -1
  188. package/src/remote/controller.ts +88 -26
  189. package/src/remote/endpoint.ts +24 -0
  190. package/src/remote/form.ts +59 -4
  191. package/src/remote/resources.ts +44 -18
  192. package/src/remote/schema.ts +21 -9
  193. package/src/remote/secrets.ts +12 -0
  194. package/src/remote/semantic-tree.tsx +14 -2
  195. package/src/remote/server.ts +2 -1
  196. package/src/remote/surface.tsx +192 -0
  197. package/src/remote/types.ts +5 -0
  198. package/src/renderers/opentui/host.tsx +6 -0
  199. package/src/series/standalone.ts +2 -2
  200. package/src/shares/api.ts +21 -4
  201. package/src/shares/item.ts +73 -0
  202. package/src/shares/pane-item.ts +205 -0
  203. package/src/shares/pane.ts +4 -0
  204. package/src/shares/payload.ts +9 -5
  205. package/src/sources/gloomberb-cloud/news.ts +2 -0
  206. package/src/tickers/renamed-listings.ts +105 -0
  207. package/src/tickers/search/index.ts +103 -16
  208. package/src/time-series/resolve.ts +2 -2
  209. package/src/types/financials.ts +1 -0
  210. package/src/types/plugin-pane-settings.ts +2 -0
  211. package/src/types/plugin-panes.ts +22 -0
  212. package/src/utils/central-banks.ts +86 -1
  213. package/src/utils/datetime-format.ts +12 -3
  214. package/src/utils/depositary-receipt.ts +28 -3
  215. package/src/utils/fundamentals.ts +14 -0
  216. package/src/utils/max-drawdown.ts +97 -16
  217. package/src/utils/untrusted-text.ts +29 -0
@@ -0,0 +1,267 @@
1
+ import { apiClient } from "../../../api-client";
2
+ import type { CloudCurveHistory, CloudCurveId } from "../../../api-client/yield-curves";
3
+ import { createTtlCache } from "../../../data/ttl-cache";
4
+ import { toBasisPoints } from "../../../utils/basis-points";
5
+ import { AUCTION_HISTORY_ALL, type AuctionHistoryWindow } from "./client";
6
+ import { AUCTION_HISTORY_WINDOWS, auctionBenchmark, dealerPct, indirectPct, isPendingAuction, nextAuctionHistoryWindow } from "./model";
7
+ import type { TreasuryAuction } from "./types";
8
+
9
+ /**
10
+ * The after view (docs/research-data.md, Treasury auctions): how an auction
11
+ * ranked against its tenor's own recent history, and what the matching
12
+ * constant-maturity yield did after it.
13
+ *
14
+ * - B/C, indirect and dealer share are each a percentile against the tenor's
15
+ * previous 24 auctions with that figure: the share of them below it, half
16
+ * the ones equal. A tenor is the security type and the benchmark it was sold
17
+ * as (the 10-year note and its 9-Year 10-Month reopenings are one; a 10-year
18
+ * TIPS is another). Fewer than 12 earlier auctions rank nothing.
19
+ * - The yield change is the Treasury par (CMT) yield of the auction's tenor,
20
+ * or the TIPS real yield for a TIPS, from the auction day's close to the
21
+ * close 1, 5 and 20 sessions later, in basis points. An FRN floats and has
22
+ * none; a day the curve has no close for has none.
23
+ */
24
+
25
+ export type AuctionView = "results" | "after";
26
+ export const AUCTION_VIEWS: readonly AuctionView[] = ["results", "after"];
27
+
28
+ const PERCENTILE_LOOKBACK = 24;
29
+ const PERCENTILE_MIN = 12;
30
+
31
+ export interface AuctionAfter {
32
+ btcPercentile: number | null;
33
+ indirectPercentile: number | null;
34
+ dealerPercentile: number | null;
35
+ /** The CMT yield's change, bp, 1, 5 and 20 sessions after the auction day's close. */
36
+ after1d: number | null;
37
+ after5d: number | null;
38
+ after20d: number | null;
39
+ /** The yield read: "7Y", "10Y real"; null when none matches. */
40
+ cmt: string | null;
41
+ }
42
+
43
+ /**
44
+ * The window the after view reads first: two years more than it lists, which
45
+ * gives most tenors their 24 before the oldest row listed. A tenor sold a few
46
+ * times a year (the 30-year TIPS) needs more: widerAfterWindow.
47
+ */
48
+ export function afterLoadWindow(window: AuctionHistoryWindow): AuctionHistoryWindow {
49
+ if (window === AUCTION_HISTORY_ALL) return AUCTION_HISTORY_ALL;
50
+ return AUCTION_HISTORY_WINDOWS.find((next) => next === AUCTION_HISTORY_ALL || next >= window + 730) ?? AUCTION_HISTORY_ALL;
51
+ }
52
+
53
+ /** The first day the after view lists, for a window it read more than: undefined for ALL. */
54
+ export function afterWindowStart(window: AuctionHistoryWindow, now = Date.now()): string | undefined {
55
+ return window === AUCTION_HISTORY_ALL ? undefined : new Date(now - window * 86_400_000).toISOString().slice(0, 10);
56
+ }
57
+
58
+ const DAY_MS = 86_400_000;
59
+ /** A tenor's oldest auction read this close to the window's start may have older ones before it. */
60
+ const MIN_GAP_MS = 400 * DAY_MS;
61
+
62
+ /**
63
+ * The next window the after view should read, or null when the one read is
64
+ * enough: every listed tenor has its 24 auctions before the oldest one listed,
65
+ * or began inside the window (its oldest auction read is further from the
66
+ * window's start than its longest gap between auctions, and at least 400
67
+ * days), or the window is already ALL. Cash management bills are one-offs and
68
+ * never ask for more.
69
+ */
70
+ export function widerAfterWindow(
71
+ listed: readonly TreasuryAuction[],
72
+ loaded: readonly TreasuryAuction[],
73
+ window: AuctionHistoryWindow,
74
+ now = Date.now(),
75
+ ): AuctionHistoryWindow | null {
76
+ if (window === AUCTION_HISTORY_ALL) return null;
77
+ const start = now - window * DAY_MS;
78
+ const byTenor = new Map<string, number[]>();
79
+ for (const auction of loaded) {
80
+ const key = auctionTenorKey(auction);
81
+ if (key && !isPendingAuction(auction)) byTenor.set(key, [...byTenor.get(key) ?? [], Date.parse(auction.auctionDate)]);
82
+ }
83
+ const oldestListed = new Map<string, number>();
84
+ for (const auction of listed) {
85
+ const key = auctionTenorKey(auction);
86
+ if (!key || auction.secType === "CMB" || isPendingAuction(auction)) continue;
87
+ const date = Date.parse(auction.auctionDate);
88
+ oldestListed.set(key, Math.min(oldestListed.get(key) ?? date, date));
89
+ }
90
+ for (const [key, oldest] of oldestListed) {
91
+ const dates = (byTenor.get(key) ?? []).toSorted((left, right) => left - right);
92
+ if (dates.filter((date) => date < oldest).length >= PERCENTILE_LOOKBACK) continue;
93
+ let gap = MIN_GAP_MS;
94
+ for (let index = 1; index < dates.length; index++) gap = Math.max(gap, dates[index]! - dates[index - 1]!);
95
+ if (dates.length && dates[0]! - start <= gap) return nextAuctionHistoryWindow(window);
96
+ }
97
+ return null;
98
+ }
99
+
100
+ const NO_AFTER: AuctionAfter = {
101
+ btcPercentile: null, indirectPercentile: null, dealerPercentile: null, after1d: null, after5d: null, after20d: null, cmt: null,
102
+ };
103
+
104
+ /** The tenor an auction ranks within: its type and the benchmark it was sold as. */
105
+ function auctionTenorKey(auction: TreasuryAuction): string | null {
106
+ const benchmark = auctionBenchmark(auction.securityTerm);
107
+ return benchmark ? `${auction.secType}|${benchmark.count}${benchmark.unit}` : null;
108
+ }
109
+
110
+ /** 0 to 100: the share of `history` below `value`, half of those equal. */
111
+ function percentileOf(value: number, history: readonly number[]): number | null {
112
+ if (history.length < PERCENTILE_MIN) return null;
113
+ const below = history.filter((entry) => entry < value).length;
114
+ const equal = history.filter((entry) => entry === value).length;
115
+ return Math.round(((below + equal / 2) / history.length) * 100);
116
+ }
117
+
118
+ type Metric = (auction: TreasuryAuction) => number | null;
119
+ const METRICS: ReadonlyArray<[keyof Pick<AuctionAfter, "btcPercentile" | "indirectPercentile" | "dealerPercentile">, Metric]> = [
120
+ ["btcPercentile", (auction) => auction.bidToCoverRatio],
121
+ ["indirectPercentile", indirectPct],
122
+ ["dealerPercentile", dealerPct],
123
+ ];
124
+
125
+ /** Each completed auction's percentiles, by id, against the auctions of its tenor before it in `auctions`. */
126
+ export function auctionPercentiles(auctions: readonly TreasuryAuction[]): Map<string, Pick<AuctionAfter, "btcPercentile" | "indirectPercentile" | "dealerPercentile">> {
127
+ const byTenor = new Map<string, TreasuryAuction[]>();
128
+ for (const auction of auctions) {
129
+ const key = auctionTenorKey(auction);
130
+ if (!key || isPendingAuction(auction)) continue;
131
+ byTenor.set(key, [...byTenor.get(key) ?? [], auction]);
132
+ }
133
+ const ranked = new Map<string, Pick<AuctionAfter, "btcPercentile" | "indirectPercentile" | "dealerPercentile">>();
134
+ for (const group of byTenor.values()) {
135
+ group.sort((left, right) => left.auctionDate.localeCompare(right.auctionDate) || left.id.localeCompare(right.id));
136
+ group.forEach((auction, index) => {
137
+ const entry = { btcPercentile: null, indirectPercentile: null, dealerPercentile: null } as Record<string, number | null>;
138
+ for (const [key, metric] of METRICS) {
139
+ const value = metric(auction);
140
+ if (value == null) continue;
141
+ const history: number[] = [];
142
+ for (let earlier = index - 1; earlier >= 0 && history.length < PERCENTILE_LOOKBACK; earlier--) {
143
+ const past = metric(group[earlier]!);
144
+ if (past != null) history.push(past);
145
+ }
146
+ entry[key] = percentileOf(value, history);
147
+ }
148
+ ranked.set(auction.id, entry as Pick<AuctionAfter, "btcPercentile" | "indirectPercentile" | "dealerPercentile">);
149
+ });
150
+ }
151
+ return ranked;
152
+ }
153
+
154
+ /** A curve's tenor and its length in days, as Gloom Cloud stores the US curves. */
155
+ const NOMINAL_TENORS: ReadonlyArray<[string, number]> = [
156
+ ["1M", 30], ["6W", 42], ["2M", 61], ["3M", 91], ["4M", 122], ["6M", 183], ["1Y", 365], ["2Y", 730], ["3Y", 1095],
157
+ ["5Y", 1826], ["7Y", 2557], ["10Y", 3652], ["20Y", 7305], ["30Y", 10957],
158
+ ];
159
+ const REAL_TENORS: ReadonlyArray<[string, number]> = [["5Y", 1826], ["7Y", 2557], ["10Y", 3652], ["20Y", 7305], ["30Y", 10957]];
160
+ const UNIT_DAYS = { day: 1, week: 7, month: 30.44, year: 365.25 } as const;
161
+
162
+ /** The curve and tenor whose yield matches an auction's: the nearest stored tenor to its benchmark; null for an FRN. */
163
+ export function cmtFor(auction: TreasuryAuction): { curve: CloudCurveId; tenor: string } | null {
164
+ if (auction.secType === "FRN") return null;
165
+ const benchmark = auctionBenchmark(auction.securityTerm);
166
+ if (!benchmark) return null;
167
+ const days = benchmark.count * UNIT_DAYS[benchmark.unit];
168
+ const real = auction.secType === "TIPS";
169
+ const tenors = real ? REAL_TENORS : NOMINAL_TENORS;
170
+ const [tenor] = tenors.reduce((best, entry) => Math.abs(entry[1] - days) < Math.abs(best[1] - days) ? entry : best);
171
+ return { curve: real ? "us-real" : "us", tenor };
172
+ }
173
+
174
+ const cmtLabel = (cmt: { curve: CloudCurveId; tenor: string }) => cmt.curve === "us-real" ? `${cmt.tenor} real` : cmt.tenor;
175
+
176
+ /** A curve tenor's closes, oldest first, as `date` and `value` (percent). */
177
+ export type CurveCloses = ReadonlyArray<{ date: string; value: number }>;
178
+
179
+ /** The change from the auction day's close to the close `sessions` later, in bp; null when either is missing. */
180
+ export function yieldChangeAfter(closes: CurveCloses, date: string, sessions: number): number | null {
181
+ let low = 0, high = closes.length;
182
+ while (low < high) {
183
+ const middle = (low + high) >> 1;
184
+ if (closes[middle]!.date < date) low = middle + 1;
185
+ else high = middle;
186
+ }
187
+ const base = closes[low];
188
+ const later = closes[low + sessions];
189
+ if (!base || base.date !== date || !later) return null;
190
+ return toBasisPoints(later.value - base.value, 1);
191
+ }
192
+
193
+ /** The after view's figures for each auction shown, by id. */
194
+ export function projectAuctionAfter(
195
+ shown: readonly TreasuryAuction[],
196
+ history: readonly TreasuryAuction[],
197
+ curves: ReadonlyMap<string, CurveCloses>,
198
+ ): Map<string, AuctionAfter> {
199
+ const percentiles = auctionPercentiles(history);
200
+ return new Map(shown.map((auction) => {
201
+ const cmt = cmtFor(auction);
202
+ const closes = cmt ? curves.get(curveKey(cmt)) : undefined;
203
+ const change = (sessions: number) => closes && !isPendingAuction(auction) ? yieldChangeAfter(closes, auction.auctionDate, sessions) : null;
204
+ return [auction.id, {
205
+ ...NO_AFTER,
206
+ ...percentiles.get(auction.id),
207
+ after1d: change(1), after5d: change(5), after20d: change(20),
208
+ cmt: cmt ? cmtLabel(cmt) : null,
209
+ }];
210
+ }));
211
+ }
212
+
213
+ const curveKey = (cmt: { curve: CloudCurveId; tenor: string }) => `${cmt.curve}:${cmt.tenor}`;
214
+
215
+ /**
216
+ * A curve tenor's closes as read, from `from` (null: its whole history); ten
217
+ * minutes, since a session's close lands once a day. Keyed by curve and tenor
218
+ * alone, so a list that changes reads again only when it needs older closes.
219
+ */
220
+ const curveCache = createTtlCache<{ from: string | null; history: CloudCurveHistory }>({ ttlMs: 10 * 60_000, maxEntries: 64 });
221
+
222
+ export function resetAuctionCurvesForTests(): void {
223
+ curveCache.clear();
224
+ }
225
+
226
+ type CurveRead = (curve: CloudCurveId, tenor: string, from: string | null) => Promise<CloudCurveHistory>;
227
+
228
+ async function readCurve(curve: CloudCurveId, tenor: string, from: string | null, read: CurveRead): Promise<CloudCurveHistory> {
229
+ const key = curveKey({ curve, tenor });
230
+ const load = async () => ({ from, history: await read(curve, tenor, from) });
231
+ const held = await curveCache.load(key, load);
232
+ const covers = held.from == null || (from != null && held.from <= from);
233
+ return covers ? held.history : (await curveCache.load(key, load, { force: true })).history;
234
+ }
235
+
236
+ export interface AuctionCurveRead {
237
+ curves: Map<string, CurveCloses>;
238
+ /** Why a curve the view needs could not be read. */
239
+ errors: string[];
240
+ }
241
+
242
+ /**
243
+ * The closes of every curve tenor the shown auctions match, from `from`, the
244
+ * first day of the window listed (null for ALL: the whole curve).
245
+ */
246
+ export async function loadAuctionCurves(
247
+ shown: readonly TreasuryAuction[],
248
+ from: string | null,
249
+ read: CurveRead = (curve, tenor, start) => apiClient.getCloudCurveHistory(curve, tenor, start),
250
+ ): Promise<AuctionCurveRead> {
251
+ const needed = new Map<string, { curve: CloudCurveId; tenor: string }>();
252
+ for (const auction of shown) {
253
+ const cmt = cmtFor(auction);
254
+ if (cmt && !isPendingAuction(auction)) needed.set(curveKey(cmt), cmt);
255
+ }
256
+ const curves = new Map<string, CurveCloses>();
257
+ const errors: string[] = [];
258
+ await Promise.all([...needed].map(async ([key, { curve, tenor }]) => {
259
+ try {
260
+ const history = await readCurve(curve, tenor, from, read);
261
+ curves.set(key, history.points);
262
+ } catch (error) {
263
+ errors.push(`${cmtLabel({ curve, tenor })} Treasury yields unavailable: ${error instanceof Error ? error.message : String(error)}`);
264
+ }
265
+ }));
266
+ return { curves, errors };
267
+ }
@@ -16,8 +16,11 @@ const DIRECT_CACHE_SOURCE = "treasury-direct";
16
16
  /**
17
17
  * 3: every reported page was validated before this board was cached.
18
18
  * 4: boards carry direct takedown and bill discount rates, which a v3 board lacks.
19
+ * 5: boards carry the low yield and discount rate, and early rows with their high and low swapped are put right.
19
20
  */
20
- const CACHE_SCHEMA_VERSION = 4;
21
+ /** Raised when a board gains fields (5: the low yield; 6: early bills blank an investment rate their swapped discount rates contradict), so a saved board never lacks a column the pane shows. */
22
+ export const CACHE_SCHEMA_VERSION = 6;
23
+ export const DIRECT_CACHE_SCHEMA_VERSION = 2;
21
24
  export const TREASURY_FISCAL_DATA_CONNECTION_ID = "treasury-fiscal-data";
22
25
  export const TREASURY_DIRECT_CONNECTION_ID = "treasury-direct";
23
26
  /**
@@ -59,7 +62,7 @@ const archiveCache = createPluginCache<TreasuryAuction[]>({
59
62
  });
60
63
  /** TreasuryDirect's last weeks and announcements, refreshed as often as the board they are merged into. */
61
64
  const directCache = createPluginCache<TreasuryAuction[]>({
62
- kind: CACHE_KIND, source: DIRECT_CACHE_SOURCE, schemaVersion: 1, policy: CACHE_POLICY, decode,
65
+ kind: CACHE_KIND, source: DIRECT_CACHE_SOURCE, schemaVersion: DIRECT_CACHE_SCHEMA_VERSION, policy: CACHE_POLICY, decode,
63
66
  });
64
67
  let connectionHealth: ConnectionHealthRegistry | null = null;
65
68
 
@@ -167,6 +170,17 @@ function answered(result: TreasuryAuctionsResult): TreasuryAuctionsResult {
167
170
  return result.savedAt != null ? servedFromSavedCopy(result, result.savedAt) : result;
168
171
  }
169
172
 
173
+ /**
174
+ * The archive as saved, while it is still fresh: results that do not change,
175
+ * so a command reads the copy an earlier run saved (a command otherwise asks
176
+ * the source again: saved-copy-persistence.ts) and ALL answers in a second or
177
+ * two instead of walking 10,000 auctions again.
178
+ */
179
+ function savedArchive(key: string): Promise<PluginCacheResult<TreasuryAuction[]>> | null {
180
+ const saved = archiveCache.get(key, { allowExpired: true });
181
+ return saved && !saved.stale ? Promise.resolve(saved) : null;
182
+ }
183
+
170
184
  /**
171
185
  * ALL: the recent auctions since the archive boundary, refreshed hourly, and
172
186
  * the archive before it, from 1979-10-31, cached for weeks and never forced:
@@ -175,9 +189,10 @@ function answered(result: TreasuryAuctionsResult): TreasuryAuctionsResult {
175
189
  */
176
190
  async function loadAllTreasuryAuctions(force: boolean, loader: AuctionLoader, direct: DirectLoader | null): Promise<TreasuryAuctionsResult> {
177
191
  const boundary = auctionArchiveBoundary();
192
+ const key = `archive:${boundary}`;
178
193
  const [recent, archive] = await Promise.all([
179
194
  loadRecentBoard(force, `since:${boundary}`, () => loader({ from: boundary }), direct && { days: DIRECT_LOOKBACK_DAYS, load: direct }, () => boundary),
180
- archiveCache.load(`archive:${boundary}`, walk(FISCAL_DATA, () => loader({
195
+ savedArchive(key) ?? archiveCache.load(key, walk(FISCAL_DATA, () => loader({
181
196
  from: AUCTION_HISTORY_START, before: boundary, pageSize: AUCTION_ARCHIVE_PAGE_SIZE,
182
197
  }))).then(savedCopyForTransientFailure),
183
198
  ]);
@@ -14,6 +14,7 @@ const FIELDS = [
14
14
  "high_investment_rate",
15
15
  "high_yield",
16
16
  "avg_med_yield",
17
+ "low_yield",
17
18
  "high_price",
18
19
  "low_price",
19
20
  "avg_med_price",
@@ -29,6 +30,7 @@ const FIELDS = [
29
30
  "high_discnt_margin",
30
31
  "high_discnt_rate",
31
32
  "avg_med_discnt_rate",
33
+ "low_discnt_rate",
32
34
  ].join(",");
33
35
 
34
36
  export const AUCTION_HISTORY_DAYS = 120;
@@ -123,6 +125,33 @@ function toNumber(value: string | undefined | null): number | null {
123
125
  return Number.isFinite(parsed) ? parsed : null;
124
126
  }
125
127
 
128
+ /**
129
+ * A high and low in the order the auction cleared them. Fiscal Data has some
130
+ * early rows the other way round (the 30-year bond of 1982-02-04: high 14.47%,
131
+ * median 14.56%, low 14.61%; about 420 bills of 1979-83): a high below its low
132
+ * is read swapped when the median sits between them, and dropped when it does
133
+ * not, so neither reaches the stop-out as a negative spread. Prices follow a
134
+ * swapped pair. A bill's investment rate restates its high discount rate as
135
+ * the source had it, so once that pair is swapped or dropped the investment
136
+ * rate is blank rather than disagree with the discount rate beside it.
137
+ */
138
+ export function inClearingOrder(auction: TreasuryAuction): TreasuryAuction {
139
+ let next = auction;
140
+ for (const [high, median, low] of [["highYield", "avgMedYield", "lowYield"], ["highDiscountRate", "avgMedDiscountRate", "lowDiscountRate"]] as const) {
141
+ const top = next[high], bottom = next[low], middle = next[median];
142
+ if (top == null || bottom == null || top >= bottom) continue;
143
+ const investment = high === "highDiscountRate" ? { highInvestmentRate: null } : {};
144
+ if (middle != null && middle >= top && middle <= bottom) {
145
+ const prices = next.highPrice != null && next.lowPrice != null && next.highPrice > next.lowPrice
146
+ ? { highPrice: next.lowPrice, lowPrice: next.highPrice } : {};
147
+ next = { ...next, [high]: bottom, [low]: top, ...prices, ...investment };
148
+ } else {
149
+ next = { ...next, [high]: null, [low]: null, ...investment };
150
+ }
151
+ }
152
+ return next;
153
+ }
154
+
126
155
  export function normalizeAuction(raw: unknown): TreasuryAuction | null {
127
156
  if (!raw || typeof raw !== "object") return null;
128
157
  const record = raw as TreasuryAuctionRaw;
@@ -132,7 +161,7 @@ export function normalizeAuction(raw: unknown): TreasuryAuction | null {
132
161
  const cusip = (record.cusip ?? "").trim();
133
162
  if (!secType || !auctionDate) return null;
134
163
 
135
- return {
164
+ return inClearingOrder({
136
165
  // A reopening reuses its original CUSIP but is auctioned on its own date,
137
166
  // so CUSIP plus date is what keeps reopenings from collapsing into one row.
138
167
  id: cusip ? `${cusip}|${auctionDate}` : `${secType}|${auctionDate}|${securityTerm}`,
@@ -145,9 +174,11 @@ export function normalizeAuction(raw: unknown): TreasuryAuction | null {
145
174
  highInvestmentRate: toNumber(record.high_investment_rate),
146
175
  highDiscountRate: toNumber(record.high_discnt_rate),
147
176
  avgMedDiscountRate: toNumber(record.avg_med_discnt_rate),
177
+ lowDiscountRate: toNumber(record.low_discnt_rate),
148
178
  highDiscountMargin: toNumber(record.high_discnt_margin),
149
179
  highYield: toNumber(record.high_yield),
150
180
  avgMedYield: toNumber(record.avg_med_yield),
181
+ lowYield: toNumber(record.low_yield),
151
182
  highPrice: toNumber(record.high_price),
152
183
  lowPrice: toNumber(record.low_price),
153
184
  avgMedPrice: toNumber(record.avg_med_price),
@@ -158,7 +189,7 @@ export function normalizeAuction(raw: unknown): TreasuryAuction | null {
158
189
  primaryDealerAccepted: toNumber(record.primary_dealer_accepted),
159
190
  totalAccepted: toNumber(record.total_accepted),
160
191
  offeringAmount: toNumber(record.offering_amt),
161
- };
192
+ });
162
193
  }
163
194
 
164
195
  export function parseTreasuryAuctionsPayload(body: unknown): TreasuryAuction[] {
@@ -2,6 +2,10 @@ import type {
2
2
  HeadlessPaneDefinition,
3
3
  HeadlessPaneLoadArgs,
4
4
  } from "../../../types/plugin";
5
+ import type { HeadlessPaneColumn } from "../../../types/headless";
6
+ import {
7
+ afterLoadWindow, afterWindowStart, AUCTION_VIEWS, loadAuctionCurves, projectAuctionAfter, widerAfterWindow, type AuctionCurveRead, type AuctionView,
8
+ } from "./after";
5
9
  import { formatCompact } from "../../../utils/format";
6
10
  import { AUCTION_HISTORY_ALL, AUCTION_HISTORY_START, fetchTreasuryAuctions, type AuctionHistoryWindow } from "./client";
7
11
  import { loadTreasuryAuctions, type TreasuryAuctionsResult } from "./cache";
@@ -11,20 +15,29 @@ import { FIXED_INCOME_VIEW_STATE } from "../fixed-income/model";
11
15
  import {
12
16
  AUCTION_HISTORY_WINDOWS,
13
17
  AUCTION_SEARCH_FIELDS,
18
+ AUCTION_SORT_NAMES,
14
19
  auctionHistoryPhrase,
15
20
  auctionHistoryWindow,
16
21
  auctionSize,
22
+ auctionSortColumn,
17
23
  dealerPct,
18
24
  DEFAULT_AUCTION_SORT,
19
25
  directPct,
26
+ firstAuctionSortDirection,
20
27
  formatAuctionRate,
21
28
  indirectPct,
29
+ isAfterColumn,
30
+ isBill,
22
31
  isPendingAuction,
32
+ namesOtherMarket,
23
33
  nextAuctionHistoryWindow,
34
+ rateColumnLabel,
24
35
  rateQualifier,
25
36
  rateValue,
26
- stopOutVsAverageBp,
37
+ stopOutColumnLabel,
38
+ stopOutVsAvgBp,
27
39
  visibleAuctions,
40
+ widerWindowCouldAdd,
28
41
  type AuctionFilter,
29
42
  } from "./model";
30
43
 
@@ -40,7 +53,8 @@ const RESULTS_NOT_PUBLISHED = "results not published";
40
53
  const pending = (row: Record<string, unknown>) => isPendingAuction(row as unknown as TreasuryAuction);
41
54
 
42
55
  /** Why the stop-out column is not a tail; the docs page says the same at length. */
43
- const STOP_OUT_NOTE = "Stop-out vs avg is the high yield minus the average/median yield, in bp (bills: discount rates). "
56
+ const STOP_OUT_NOTE = "Stop-out vs median is the high yield minus the median yield, in bp (bills: discount rates); "
57
+ + "before November 1998, when most auctions were multiple-price, Treasury published the average, so older rows read against the average. "
44
58
  + "A true tail, the stop-out against the 1 pm when-issued yield, needs the when-issued yield, which the source does not carry.";
45
59
 
46
60
  const MISSING_METRICS_NOTE = "A blank B/C or bidder share is one the source does not have for that auction: "
@@ -61,7 +75,7 @@ const rateCell = (value: unknown, row: Record<string, unknown>) => {
61
75
  return qualifier ? `${text} ${qualifier}` : text;
62
76
  };
63
77
 
64
- const COLUMNS = [
78
+ const LEAD_COLUMNS: HeadlessPaneColumn[] = [
65
79
  { key: "auctionDate", header: "Date" },
66
80
  { key: "secType", header: "Type" },
67
81
  { key: "securityTerm", header: "Term" },
@@ -74,7 +88,17 @@ const COLUMNS = [
74
88
  ),
75
89
  textFormat: rateCell,
76
90
  },
91
+ ];
92
+
93
+ /** A bill's high discount rate, beside the investment rate its Rate is: the rate Treasury's announcement leads with. */
94
+ const DISCOUNT_RATE_COLUMN: HeadlessPaneColumn = {
95
+ key: "highDiscountRate", header: "Discount rate", align: "right" as const,
96
+ format: (value: unknown, row: Record<string, unknown>) => value == null ? pending(row) ? "" : "-" : `${Number(value).toFixed(3)}%`,
97
+ };
98
+
99
+ const RESULT_COLUMNS: HeadlessPaneColumn[] = [
77
100
  {
101
+ // Exports keep the name scripts read it by: the spread against the published average, or the median from November 1998.
78
102
  key: "stopOutVsAvgBp", header: "Stop-out vs avg (bp)", align: "right" as const,
79
103
  format: (value: unknown, row: Record<string, unknown>) => value == null ? pending(row) ? "" : "-" : Number(value).toFixed(1),
80
104
  },
@@ -86,22 +110,53 @@ const COLUMNS = [
86
110
  { key: "cusip", header: "CUSIP" },
87
111
  ];
88
112
 
113
+ const percentile = (value: unknown) => value == null ? "" : String(value);
114
+ const bpMove = (value: unknown) => value == null ? "" : `${Number(value) > 0 ? "+" : ""}${Number(value).toFixed(0)}`;
115
+
116
+ /** The after view: each auction against its tenor's last 24, and the matching Treasury yield's moves after it. */
117
+ const AFTER_COLUMNS: HeadlessPaneColumn[] = [
118
+ { key: "bidToCoverRatio", header: "B/C", align: "right" as const, format: (value: unknown) => value == null ? "" : Number(value).toFixed(2) },
119
+ { key: "btcPercentile", header: "B/C pctl", align: "right" as const, format: percentile },
120
+ { key: "indirectPercentile", header: "Indirect pctl", align: "right" as const, format: percentile },
121
+ { key: "dealerPercentile", header: "Dealer pctl", align: "right" as const, format: percentile },
122
+ { key: "cmt", header: "Yield", description: "The Treasury par yield the moves are read on: the auction's tenor, real for a TIPS." },
123
+ { key: "after1d", header: "+1d (bp)", align: "right" as const, format: bpMove },
124
+ { key: "after5d", header: "+5d (bp)", align: "right" as const, format: bpMove },
125
+ { key: "after20d", header: "+20d (bp)", align: "right" as const, format: bpMove },
126
+ { key: "cusip", header: "CUSIP" },
127
+ ];
128
+
129
+ /** The columns a board lists: a bill board heads its rate as the investment rate and puts the discount rate beside it. */
130
+ function columnsFor(view: AuctionView, auctions: readonly TreasuryAuction[]): HeadlessPaneColumn[] {
131
+ const rate = { ...LEAD_COLUMNS[3]!, textHeader: rateColumnLabel(auctions, "report") };
132
+ const discount = auctions.some(isBill) ? [DISCOUNT_RATE_COLUMN] : [];
133
+ // The spread is against the median from November 1998 and the average before: the heading says which the rows hold.
134
+ const results = RESULT_COLUMNS.map((column) => column.key === "stopOutVsAvgBp" ? { ...column, textHeader: stopOutColumnLabel(auctions, "report") } : column);
135
+ return [...LEAD_COLUMNS.slice(0, 3), rate, ...discount, ...view === "after" ? AFTER_COLUMNS : results];
136
+ }
137
+
138
+ const AFTER_NOTE = "Percentiles rank each auction against its tenor's previous 24 (at least 12); the moves are the Treasury par yield "
139
+ + "of its tenor (real for TIPS) from the auction day's close, in bp. Treasury par yields start in 1990, real yields in 2003.";
140
+
89
141
  interface TreasuryAuctionsHeadlessDependencies {
90
142
  load(args: HeadlessPaneLoadArgs, window: AuctionHistoryWindow): Promise<TreasuryAuctionsResult>;
143
+ curves(shown: readonly TreasuryAuction[], from: string | null): Promise<AuctionCurveRead>;
91
144
  }
92
145
 
93
146
  const defaultDependencies: TreasuryAuctionsHeadlessDependencies = {
94
147
  load: (_args, window) => loadTreasuryAuctions(false, fetchTreasuryAuctions, window),
148
+ curves: (shown, from) => loadAuctionCurves(shown, from),
95
149
  };
96
150
 
97
- /** An empty table says what was searched, in which window, and what the search understands. */
151
+ /** An empty table says what was searched, in which window, and what the search understands; another market's paper, what AUCT covers. */
98
152
  function emptyNote(query: string, filter: AuctionFilter, historyDays: AuctionHistoryWindow): string {
153
+ if (namesOtherMarket(query)) return `AUCT covers US Treasury auctions; "${query.trim()}" is not one. Search by ${AUCTION_SEARCH_FIELDS}.`;
99
154
  const searched = query.trim() ? `match "${query.trim()}"` : "found";
100
155
  const group = filter === "all" ? "" : ` in the ${filter} group`;
101
156
  return `No auctions ${searched}${group} in ${auctionHistoryPhrase(historyDays)}. Search by ${AUCTION_SEARCH_FIELDS}.`;
102
157
  }
103
158
 
104
- function createTreasuryAuctionsHeadless(
159
+ export function createTreasuryAuctionsHeadless(
105
160
  dependencies: TreasuryAuctionsHeadlessDependencies = defaultDependencies,
106
161
  ): HeadlessPaneDefinition<"rows"> {
107
162
  return {
@@ -119,6 +174,7 @@ function createTreasuryAuctionsHeadless(
119
174
  aliases: ["history"],
120
175
  settingKey: "historyDays",
121
176
  description: `Auction history window in days, up to 3650 (10 years), or all: every auction since ${AUCTION_HISTORY_START}.`,
177
+ example: "--history-days 3650",
122
178
  type: "enum",
123
179
  values: AUCTION_HISTORY_WINDOWS.map((days) => ({ value: String(days) })),
124
180
  defaultValue: "120",
@@ -131,8 +187,25 @@ function createTreasuryAuctionsHeadless(
131
187
  defaultValue: "all",
132
188
  pluginState: { pluginId: FIXED_INCOME_VIEW_STATE.treasuryAuctions, key: "activeTab" },
133
189
  },
190
+ {
191
+ key: "view",
192
+ description: "results: each auction's figures; after: its B/C, indirect and dealer percentiles against the tenor's last 24 auctions, and the matching Treasury yield's change 1, 5 and 20 sessions later (bp).",
193
+ type: "enum",
194
+ values: AUCTION_VIEWS.map((value) => ({ value })),
195
+ defaultValue: "results",
196
+ example: "--view after",
197
+ pluginState: { pluginId: FIXED_INCOME_VIEW_STATE.treasuryAuctions, key: "view" },
198
+ },
199
+ {
200
+ key: "sort",
201
+ description: "Row order, by a column: largest first for a figure, newest first for date, A to Z for type, term and CUSIP. An after-view column (btc-pctl, 1d...) shows the after view.",
202
+ type: "enum",
203
+ values: AUCTION_SORT_NAMES.map((entry) => ({ value: entry.value, ...(entry.aliases ? { aliases: entry.aliases } : {}) })),
204
+ example: "--sort btc-pctl",
205
+ pluginState: { pluginId: FIXED_INCOME_VIEW_STATE.treasuryAuctions, key: "sortColumn" },
206
+ },
134
207
  ],
135
- columns: COLUMNS,
208
+ columns: columnsFor("results", []),
136
209
  describe: (args) => {
137
210
  const window = auctionHistoryWindow({ historyDays: args.options.historyDays });
138
211
  return `Treasury Auctions | ${window === AUCTION_HISTORY_ALL ? "all" : `${window} days`} | ${String(args.options.filter)}`;
@@ -140,40 +213,57 @@ function createTreasuryAuctionsHeadless(
140
213
  async load(args) {
141
214
  const historyDays = auctionHistoryWindow({ historyDays: args.options.historyDays });
142
215
  const filter = args.options.filter as AuctionFilter;
143
- const result = await dependencies.load(args, historyDays);
216
+ const sortColumn = typeof args.options.sort === "string" ? auctionSortColumn(args.options.sort) : null;
217
+ // A sort by an after-view column is a request for that view.
218
+ const view: AuctionView = args.options.view === "after" || (sortColumn && isAfterColumn(sortColumn)) ? "after" : "results";
219
+ const sort = sortColumn ? { columnId: sortColumn, direction: firstAuctionSortDirection(sortColumn) } : DEFAULT_AUCTION_SORT;
144
220
  const query = typeof args.argument === "string" ? args.argument : "";
145
- const auctions = visibleAuctions(result.auctions, {
146
- filter,
147
- query,
148
- sort: DEFAULT_AUCTION_SORT,
149
- });
150
- const nextWindow = nextAuctionHistoryWindow(historyDays);
221
+ const from = view === "after" ? afterWindowStart(historyDays) : undefined;
222
+ // The after view reads more than it lists, until each listed tenor has its 24 before the oldest row (or ALL).
223
+ let window = view === "after" ? afterLoadWindow(historyDays) : historyDays;
224
+ let result = await dependencies.load(args, window);
225
+ let listed = visibleAuctions(result.auctions, { filter, query, sort: DEFAULT_AUCTION_SORT, from });
226
+ for (let wider = view === "after" ? widerAfterWindow(listed, result.auctions, window) : null; wider;
227
+ wider = widerAfterWindow(listed, result.auctions, window)) {
228
+ window = wider;
229
+ result = await dependencies.load(args, window);
230
+ listed = visibleAuctions(result.auctions, { filter, query, sort: DEFAULT_AUCTION_SORT, from });
231
+ }
232
+ const curves = view === "after" ? await dependencies.curves(listed, from ?? null) : null;
233
+ const after = curves ? projectAuctionAfter(listed, result.auctions, curves.curves) : null;
234
+ const auctions = sortColumn ? visibleAuctions(listed, { filter: "all", query: "", sort, ...(after ? { after } : {}) }) : listed;
151
235
  const notes = [
152
236
  ...(auctions.length === 0 ? [emptyNote(query, filter, historyDays)] : []),
153
- // ALL is the whole history: nothing older to point to.
154
- ...(nextWindow ? [`Older auctions: use --historyDays ${nextWindow}.`] : []),
155
- ...(auctions.length > 0 ? [STOP_OUT_NOTE] : []),
237
+ // Only where a longer window could list more: never past ALL, for another market, or for a CUSIP whose first auction is listed.
238
+ ...(nextAuctionHistoryWindow(historyDays) && widerWindowCouldAdd(query, auctions, historyDays)
239
+ ? [`Older auctions: use --history-days ${nextAuctionHistoryWindow(historyDays)}.`] : []),
240
+ ...(auctions.length > 0 && view === "results" ? [STOP_OUT_NOTE] : []),
241
+ ...(auctions.length > 0 && view === "after" ? [AFTER_NOTE] : []),
156
242
  ...(auctions.some(lacksMetrics) ? [MISSING_METRICS_NOTE] : []),
157
243
  ];
158
244
  return {
159
- complete: !result.refreshError,
245
+ complete: !result.refreshError && !curves?.errors.length,
160
246
  // A saved copy answering the failed refresh ends the report by saying when it was saved instead.
161
- errors: [unansweredRefreshError(result)].filter((error): error is string => !!error),
247
+ errors: [unansweredRefreshError(result), ...curves?.errors ?? []].filter((error): error is string => !!error),
162
248
  notes,
249
+ columns: columnsFor(view, auctions),
163
250
  rows: auctions.map((auction) => ({
164
251
  ...auction,
165
252
  rate: rateValue(auction),
166
- stopOutVsAvgBp: stopOutVsAverageBp(auction),
253
+ stopOutVsAvgBp: stopOutVsAvgBp(auction),
167
254
  indirectPercent: indirectPct(auction),
168
255
  directPercent: directPct(auction),
169
256
  dealerPercent: dealerPct(auction),
170
257
  size: auctionSize(auction),
258
+ ...(after ? after.get(auction.id) : {}),
171
259
  })),
172
260
  metadata: {
173
261
  fetchedAt: result.fetchedAt,
174
262
  stale: result.stale,
175
263
  historyDays,
176
264
  filter,
265
+ view,
266
+ ...(sortColumn ? { sort: args.options.sort } : {}),
177
267
  },
178
268
  };
179
269
  },