@gloom-sh/terminal 0.20.5 → 0.20.7

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 (185) hide show
  1. package/README.md +1 -1
  2. package/README.zh-CN.md +1 -1
  3. package/package.json +2 -1
  4. package/src/api-client/data.ts +10 -2
  5. package/src/api-client/fund-facts.ts +20 -4
  6. package/src/api-client/hk-tenders.ts +59 -0
  7. package/src/api-client/index.ts +1 -0
  8. package/src/api-client/socket.ts +4 -4
  9. package/src/api-client/types/econ.ts +20 -2
  10. package/src/app.tsx +18 -13
  11. package/src/architecture/floating-promise-allowlist.json +313 -0
  12. package/src/architecture/shortcut-labels-allowlist.json +1 -0
  13. package/src/cli/commands/market.ts +197 -57
  14. package/src/cli/commands/news-search.ts +22 -7
  15. package/src/cli/commands/overview.ts +12 -6
  16. package/src/cli/commands/search.ts +19 -3
  17. package/src/cli/commands/ticker.ts +3 -1
  18. package/src/cli/desktop-pane-shot.ts +61 -0
  19. package/src/cli/early-command.ts +2 -0
  20. package/src/cli/errors.ts +10 -1
  21. package/src/cli/fx-forward.ts +76 -12
  22. package/src/cli/fx-pair.ts +1 -1
  23. package/src/cli/fx-quote-rate.ts +23 -0
  24. package/src/cli/help.ts +1 -0
  25. package/src/cli/index-roots.ts +5 -4
  26. package/src/cli/index.ts +40 -3
  27. package/src/cli/known-gaps.ts +11 -8
  28. package/src/cli/listing-arg.ts +6 -4
  29. package/src/cli/options.ts +52 -3
  30. package/src/cli/output-file.ts +5 -3
  31. package/src/cli/pane-functions/catalog.ts +15 -0
  32. package/src/cli/pane-functions/dom.ts +4 -4
  33. package/src/cli/pane-functions/freshness.ts +38 -5
  34. package/src/cli/pane-functions/function-help.ts +4 -4
  35. package/src/cli/pane-functions/headless.ts +9 -4
  36. package/src/cli/pane-functions/index.ts +6 -4
  37. package/src/cli/pane-functions/resolver.ts +2 -2
  38. package/src/cli/pane-functions/screenshot-assessment.ts +16 -4
  39. package/src/cli/quote-answer.ts +57 -1
  40. package/src/cli/result.ts +38 -2
  41. package/src/cli/spreadsheet-hint.ts +7 -3
  42. package/src/cli/treasury-yields.ts +5 -3
  43. package/src/components/chart/composite/legend.tsx +40 -2
  44. package/src/components/command-bar/workflow/tickers.ts +2 -2
  45. package/src/components/data-table/view.tsx +9 -2
  46. package/src/components/ui/data-table/opentui/index.tsx +11 -4
  47. package/src/components/ui/data-table/opentui/model.ts +8 -6
  48. package/src/components/ui/data-table/types.ts +6 -1
  49. package/src/components/ui/table-layout.ts +38 -1
  50. package/src/docs/snapshot.json +58 -19
  51. package/src/i18n/es.ts +2 -0
  52. package/src/i18n/ja.ts +2 -0
  53. package/src/i18n/ko.ts +2 -0
  54. package/src/i18n/zh-cn.ts +2 -0
  55. package/src/i18n/zh-tw.ts +2 -0
  56. package/src/market-data/market/change-basis.ts +57 -12
  57. package/src/market-data/market/dated-previous-close.ts +184 -10
  58. package/src/market-data/market/freshness.ts +18 -6
  59. package/src/market-data/market/status.ts +9 -1
  60. package/src/market-data/published-nse-sessions.ts +16 -1
  61. package/src/market-data/quotes/contributions.ts +2 -0
  62. package/src/market-data/quotes/freshness.ts +15 -0
  63. package/src/market-data/quotes/listing-enterprise-value.ts +50 -0
  64. package/src/plugins/builtin/alerts/alert-engine.ts +15 -0
  65. package/src/plugins/builtin/alerts/cli.ts +22 -9
  66. package/src/plugins/builtin/alerts/headless.ts +1 -1
  67. package/src/plugins/builtin/alerts/index.tsx +5 -1
  68. package/src/plugins/builtin/alerts/metric-command.ts +1 -1
  69. package/src/plugins/builtin/alerts/metric-data.ts +15 -2
  70. package/src/plugins/builtin/backtest/headless.ts +1 -1
  71. package/src/plugins/builtin/cds/model.ts +0 -6
  72. package/src/plugins/builtin/chart-composer/formula.ts +16 -3
  73. package/src/plugins/builtin/chart-composer/headless-schema.ts +2 -0
  74. package/src/plugins/builtin/chart-composer/headless.ts +2 -1
  75. package/src/plugins/builtin/chart-composer/presets.ts +1 -0
  76. package/src/plugins/builtin/cloud/askg/pane.tsx +55 -13
  77. package/src/plugins/builtin/credit-boards/cdx-pane.tsx +20 -7
  78. package/src/plugins/builtin/credit-boards/client.ts +8 -0
  79. package/src/plugins/builtin/credit-boards/headless.ts +4 -1
  80. package/src/plugins/builtin/credit-boards/model.ts +58 -4
  81. package/src/plugins/builtin/credit-boards/series.ts +63 -6
  82. package/src/plugins/builtin/credit-boards/sovr-pane.tsx +3 -2
  83. package/src/plugins/builtin/credit-conditions/headless.ts +24 -6
  84. package/src/plugins/builtin/credit-conditions/index.tsx +1 -1
  85. package/src/plugins/builtin/credit-conditions/model.ts +12 -6
  86. package/src/plugins/builtin/credit-conditions/series.ts +2 -1
  87. package/src/plugins/builtin/econ/calendar-model.ts +41 -7
  88. package/src/plugins/builtin/econ/calendar-source.ts +7 -1
  89. package/src/plugins/builtin/econ/index.tsx +41 -8
  90. package/src/plugins/builtin/econ/types.ts +3 -0
  91. package/src/plugins/builtin/fixed-income/index.tsx +2 -0
  92. package/src/plugins/builtin/fx-matrix/index.tsx +44 -14
  93. package/src/plugins/builtin/help/keybindings-editor.tsx +6 -2
  94. package/src/plugins/builtin/holders/fund-holders.ts +22 -1
  95. package/src/plugins/builtin/holders/headless.ts +5 -4
  96. package/src/plugins/builtin/holders/pane.tsx +7 -3
  97. package/src/plugins/builtin/holders/report-header.ts +23 -0
  98. package/src/plugins/builtin/members/client.ts +1 -1
  99. package/src/plugins/builtin/members/headless.ts +2 -0
  100. package/src/plugins/builtin/members/model.ts +10 -8
  101. package/src/plugins/builtin/members/pane.tsx +4 -1
  102. package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +5 -2
  103. package/src/plugins/builtin/portfolio-list/cli/render.ts +86 -26
  104. package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +5 -1
  105. package/src/plugins/builtin/portfolio-list/headless.ts +2 -1
  106. package/src/plugins/builtin/portfolio-list/income.ts +46 -22
  107. package/src/plugins/builtin/portfolio-list/pane/data.ts +16 -6
  108. package/src/plugins/builtin/portfolio-list/pane/index.tsx +5 -4
  109. package/src/plugins/builtin/portfolio-list/use-throttled-ticker-order.ts +40 -3
  110. package/src/plugins/builtin/research/headless-schema.ts +4 -3
  111. package/src/plugins/builtin/research/relative-valuation-columns.ts +145 -47
  112. package/src/plugins/builtin/research/relative-valuation-currency.ts +31 -0
  113. package/src/plugins/builtin/research/relative-valuation-headless.ts +25 -8
  114. package/src/plugins/builtin/research/relative-valuation-model.ts +40 -9
  115. package/src/plugins/builtin/research/relative-valuation-pane.tsx +3 -2
  116. package/src/plugins/builtin/research/relative-valuation-peers.ts +2 -2
  117. package/src/plugins/builtin/sec/fund-facts.ts +25 -5
  118. package/src/plugins/builtin/shared/report-freshness.ts +15 -6
  119. package/src/plugins/builtin/supply-chain/model.ts +18 -6
  120. package/src/plugins/builtin/thirteenf/api.ts +47 -4
  121. package/src/plugins/builtin/ticker-detail/data-panes/historical-prices.tsx +8 -7
  122. package/src/plugins/builtin/ticker-detail/data-panes/history-bars.ts +8 -5
  123. package/src/plugins/builtin/ticker-detail/financials/model.ts +6 -2
  124. package/src/plugins/builtin/ticker-detail/financials/tab.tsx +1 -1
  125. package/src/plugins/builtin/ticker-detail/headless.ts +6 -4
  126. package/src/plugins/builtin/treasury-auctions/cache.ts +36 -2
  127. package/src/plugins/builtin/treasury-auctions/headless.ts +42 -4
  128. package/src/plugins/builtin/treasury-auctions/hk-headless.ts +126 -0
  129. package/src/plugins/builtin/treasury-auctions/hk-view.tsx +347 -0
  130. package/src/plugins/builtin/treasury-auctions/hk.ts +363 -0
  131. package/src/plugins/builtin/treasury-auctions/index.tsx +14 -1
  132. package/src/plugins/builtin/treasury-auctions/model.ts +16 -8
  133. package/src/plugins/builtin/treasury-auctions/pane.tsx +45 -21
  134. package/src/portfolio/collection-name.ts +22 -0
  135. package/src/portfolio/column-values.ts +3 -0
  136. package/src/portfolio/valuation-basis.ts +23 -1
  137. package/src/renderers/dom/data-table/frozen-column.ts +3 -1
  138. package/src/renderers/dom/data-table/index.tsx +27 -9
  139. package/src/renderers/dom/data-table/row.tsx +2 -0
  140. package/src/renderers/electrobun/bun/desktop/backend.ts +27 -24
  141. package/src/renderers/electrobun/bun/desktop/detached-windows.ts +3 -3
  142. package/src/renderers/electrobun/bun/desktop/snapshot-commit.ts +77 -0
  143. package/src/renderers/electrobun/shared/protocol.ts +4 -0
  144. package/src/renderers/electrobun/view/backend-rpc.ts +3 -0
  145. package/src/renderers/electrobun/view/desktop/window/bridge.ts +3 -0
  146. package/src/sources/gloomberb-cloud/normalizers.ts +9 -5
  147. package/src/sources/provider-router/cache.ts +3 -1
  148. package/src/state/hooks/quote-streaming.ts +14 -6
  149. package/src/sync/controller.ts +17 -2
  150. package/src/sync/other-window-tabs.ts +32 -1
  151. package/src/sync/react.ts +4 -4
  152. package/src/tickers/instrument-kind.ts +22 -1
  153. package/src/tickers/search/index.ts +5 -0
  154. package/src/tickers/terminal-codes.ts +17 -5
  155. package/src/time-series/bar-spacing.ts +33 -0
  156. package/src/time-series/base-series.ts +21 -3
  157. package/src/time-series/chart-bounds.ts +31 -0
  158. package/src/time-series/field-catalog.ts +17 -0
  159. package/src/time-series/fundamentals/current-valuation.ts +244 -0
  160. package/src/time-series/fundamentals/historical-valuation.ts +99 -0
  161. package/src/time-series/fundamentals/metric-ids.ts +61 -0
  162. package/src/time-series/fundamentals/period-points.ts +104 -0
  163. package/src/time-series/fundamentals/quarterly-ttm.ts +220 -0
  164. package/src/time-series/fundamentals/series.ts +164 -0
  165. package/src/time-series/fundamentals/source-statements.ts +177 -0
  166. package/src/time-series/fundamentals/statement-fields.ts +154 -0
  167. package/src/time-series/fundamentals/statement-merge.ts +124 -0
  168. package/src/time-series/fundamentals/statement.ts +114 -0
  169. package/src/time-series/fundamentals/valuation-multiples.ts +50 -0
  170. package/src/time-series/fundamentals.ts +18 -1275
  171. package/src/time-series/ice-credit.ts +32 -6
  172. package/src/time-series/resolve.ts +9 -5
  173. package/src/time-series/session-bar.ts +78 -9
  174. package/src/time-series/studies/formula.ts +53 -10
  175. package/src/time-series/studies/pair.ts +18 -7
  176. package/src/time-series/studies/units.ts +49 -2
  177. package/src/time-series/types.ts +12 -0
  178. package/src/types/desktop-window.ts +2 -0
  179. package/src/types/financials.ts +15 -0
  180. package/src/types/headless.ts +8 -0
  181. package/src/utils/cli-output.ts +6 -3
  182. package/src/utils/debug-log.ts +29 -0
  183. package/src/utils/ebitda.ts +128 -0
  184. package/src/utils/format.ts +1 -1
  185. package/src/utils/shell-word.ts +13 -0
@@ -1,10 +1,12 @@
1
1
  /**
2
2
  * The ICE BofA credit indexes FRED publishes and Gloom Cloud serves: option
3
- * adjusted spreads by rating and region, and effective yields (US investment
4
- * grade and high yield, investment grade by maturity and by rating), all in
5
- * percent. One list for the CRD board, the data catalog, `fred`'s basis point
6
- * text and FRED's coverage notice. FRED publishes no euro investment grade
7
- * (ICE BofA Euro Corporate) spread, so the euro row is high yield only.
3
+ * adjusted spreads by rating and region (US, euro, and the emerging markets
4
+ * corporate indexes by grade and by region), and effective yields (US
5
+ * investment grade and high yield, investment grade by maturity and by
6
+ * rating), all in percent. One list for the CRD board, the data catalog,
7
+ * `fred`'s basis point text and FRED's coverage notice. FRED publishes no euro
8
+ * investment grade (ICE BofA Euro Corporate) spread, so the euro row is high
9
+ * yield only.
8
10
  */
9
11
  export interface IceCreditSeries {
10
12
  seriesId: string;
@@ -13,7 +15,8 @@ export interface IceCreditSeries {
13
15
  /** The data catalog's name. */
14
16
  name: string;
15
17
  measure: "spread" | "yield";
16
- region: "us" | "euro";
18
+ /** Asia is an emerging markets region too, listed on its own so it can be read alone. */
19
+ region: "us" | "euro" | "em" | "asia";
17
20
  tags: readonly string[];
18
21
  }
19
22
 
@@ -21,6 +24,7 @@ export interface IceCreditSeries {
21
24
  export const ICE_HISTORY_LIMIT_NOTICE = "History limited to 3 years by the publisher.";
22
25
 
23
26
  const HIGH_YIELD = ["high yield", "junk"];
27
+ const EMERGING = ["EM", "emerging markets"];
24
28
 
25
29
  export const ICE_CREDIT_SERIES: readonly IceCreditSeries[] = [
26
30
  { seriesId: "BAMLC0A0CM", label: "US IG", name: "US investment grade corporate OAS", measure: "spread", region: "us", tags: ["IG", "investment grade"] },
@@ -33,6 +37,18 @@ export const ICE_CREDIT_SERIES: readonly IceCreditSeries[] = [
33
37
  { seriesId: "BAMLH0A2HYB", label: "B", name: "Single-B high yield OAS", measure: "spread", region: "us", tags: ["single B", "HY", ...HIGH_YIELD] },
34
38
  { seriesId: "BAMLH0A3HYC", label: "CCC", name: "CCC and lower high yield OAS", measure: "spread", region: "us", tags: ["CCC", "HY", "distressed", ...HIGH_YIELD] },
35
39
  { seriesId: "BAMLHE00EHYIOAS", label: "Euro HY", name: "Euro high yield OAS", measure: "spread", region: "euro", tags: ["euro", "EUR", "Europe", "HY", ...HIGH_YIELD] },
40
+ // ICE BofA's emerging markets Corporate Plus indexes: the whole, by grade, then by region.
41
+ { seriesId: "BAMLEMCBPIOAS", label: "EM Corp", name: "Emerging markets corporate OAS", measure: "spread", region: "em", tags: EMERGING },
42
+ { seriesId: "BAMLEMIBHGCRPIOAS", label: "EM IG", name: "Emerging markets investment grade corporate OAS", measure: "spread", region: "em",
43
+ tags: [...EMERGING, "IG", "investment grade", "high grade"] },
44
+ { seriesId: "BAMLEMHBHYCRPIOAS", label: "EM HY", name: "Emerging markets high yield corporate OAS", measure: "spread", region: "em",
45
+ tags: [...EMERGING, "HY", ...HIGH_YIELD] },
46
+ { seriesId: "BAMLEMRACRPIASIAOAS", label: "Asia EM", name: "Asia emerging markets corporate OAS", measure: "spread", region: "asia",
47
+ tags: [...EMERGING, "Asia", "Asian", "China", "Singapore", "SGD"] },
48
+ { seriesId: "BAMLEMRLCRPILAOAS", label: "LatAm EM", name: "Latin America emerging markets corporate OAS", measure: "spread", region: "em",
49
+ tags: [...EMERGING, "Latin America", "LatAm"] },
50
+ { seriesId: "BAMLEMRECRPIEMEAOAS", label: "EMEA EM", name: "EMEA emerging markets corporate OAS", measure: "spread", region: "em",
51
+ tags: [...EMERGING, "EMEA", "Europe, Middle East and Africa"] },
36
52
  { seriesId: "BAMLC0A0CMEY", label: "US IG yld", name: "US investment grade corporate effective yield", measure: "yield", region: "us", tags: ["IG", "investment grade"] },
37
53
  { seriesId: "BAMLH0A0HYM2EY", label: "US HY yld", name: "US high yield effective yield", measure: "yield", region: "us", tags: ["HY", ...HIGH_YIELD] },
38
54
  // Investment grade by maturity, to read a corporate against the Treasury of its tenor, then by rating.
@@ -55,3 +71,13 @@ export const ICE_CREDIT_SERIES_IDS: ReadonlySet<string> = new Set(ICE_CREDIT_SER
55
71
 
56
72
  /** The option-adjusted spreads, which FRED serves in percentage points. */
57
73
  export const ICE_SPREAD_SERIES: readonly IceCreditSeries[] = ICE_CREDIT_SERIES.filter((series) => series.measure === "spread");
74
+
75
+ const ICE_SPREAD_SERIES_IDS: ReadonlySet<string> = new Set(ICE_SPREAD_SERIES.map((series) => series.seriesId));
76
+
77
+ /**
78
+ * Whether a FRED series is an ICE option-adjusted spread, which every surface
79
+ * shows in basis points (FRED serves 0.93 for 93bp), as credit desks quote it.
80
+ */
81
+ export function isIceSpreadSeries(seriesId: string): boolean {
82
+ return ICE_SPREAD_SERIES_IDS.has(seriesId.trim().toUpperCase());
83
+ }
@@ -107,6 +107,7 @@ import {
107
107
  followLatestMarketObservation,
108
108
  capabilityRequestBounds,
109
109
  endAtNewestObservation,
110
+ startAtOldestObservation,
110
111
  latestSessionView,
111
112
  } from "./chart-bounds";
112
113
  import {
@@ -1067,11 +1068,14 @@ async function resolveChartSpecPass(
1067
1068
  : latestDaily - 7 * CHART_RESOLUTION_STEP_MS["1d"],
1068
1069
  end: latestDaily,
1069
1070
  };
1071
+ // A chart of published series alone (FRED, Gloom Cloud datasets) opens where they start, not on blank years.
1072
+ const publishedOnly = spec.series.length > 0 && spec.series.every(({ source }) => source.kind !== "security");
1073
+ const presetBounds = isDatasetChart(spec)
1074
+ ? endAtNewestObservation(initialVisibleBounds, rawSeries)
1075
+ : followLatestMarketObservation(initialVisibleBounds, rawSeries);
1070
1076
  const bounds = hasExplicitWindow
1071
1077
  ? requestVisibleBounds
1072
- : dailyBounds ?? sessionView?.bounds ?? (isDatasetChart(spec)
1073
- ? endAtNewestObservation(initialVisibleBounds, rawSeries)
1074
- : followLatestMarketObservation(initialVisibleBounds, rawSeries));
1078
+ : dailyBounds ?? sessionView?.bounds ?? (publishedOnly ? startAtOldestObservation(presetBounds, rawSeries) : presetBounds);
1075
1079
  if (sessionView?.priorClose != null && primaryRaw?.transform === "raw"
1076
1080
  && primaryRaw.unitGroup.startsWith("price") && primaryRaw.unitGroup !== "price:unknown") {
1077
1081
  const index = rawSeries.indexOf(primaryRaw);
@@ -1177,8 +1181,8 @@ async function resolveChartSpecPass(
1177
1181
  if (entry.warning) warnings.push(`${entry.label}: ${entry.warning}`);
1178
1182
  if (entry.points.length === 0 && entry.unreportedPeriod) {
1179
1183
  warnings.push(`${entry.label}: no ${entry.unreportedPeriod} figures are reported; annual figures are available.`);
1180
- } else if (entry.points.length === 0 && !entry.warning?.startsWith(VALUATION_CURRENCY_WARNING_PREFIX)) {
1181
- // A currency mismatch already explains an empty valuation series.
1184
+ } else if (entry.points.length === 0 && !entry.notMeaningful && !entry.warning?.startsWith(VALUATION_CURRENCY_WARNING_PREFIX)) {
1185
+ // A currency mismatch or an N/M already explains an empty valuation series.
1182
1186
  warnings.push(`${entry.label}: no observations in the selected date range.`);
1183
1187
  }
1184
1188
  }
@@ -1,11 +1,13 @@
1
1
  import type { PricePoint, Quote } from "../types/financials";
2
2
  import { classifyInstrumentType, kindFromListingSyntax } from "../tickers/instrument-kind";
3
- import { isAlwaysOpenExchange, isRegularSessionTime, sessionCalendarTimeZone } from "../market-data/market/freshness";
3
+ import { isAlwaysOpenExchange, isRegularSessionTime, latestRegularSessionClose, sessionCalendarTimeZone } from "../market-data/market/freshness";
4
+ import { DAILY_BAR_CLOSE_VENUES } from "../market-data/market/dated-previous-close";
4
5
  import { quoteTradingDay } from "../market-data/quotes/day-range";
6
+ import { canonicalExchange } from "../utils/exchanges";
5
7
  import { hasLikelyQuoteUnitMismatch } from "../utils/currency-units";
6
8
  import { pricePointIntegrity } from "../utils/price-history-integrity";
7
9
  import { zonedDateKey } from "../utils/zoned-date-time";
8
- import { barSizeFromGap, medianBarGap } from "./bar-spacing";
10
+ import { barSizeFromGap, medianBarGap, requestedBarSize } from "./bar-spacing";
9
11
  import { calendarBarStart, liveQuoteObservation } from "./chart-data";
10
12
 
11
13
  const DAY_MS = 24 * 60 * 60_000;
@@ -20,8 +22,41 @@ export interface SessionBarOptions {
20
22
  /** The listing's venue, when the caller knows it; otherwise the quote's. */
21
23
  venue?: string;
22
24
  assetCategory?: string;
25
+ /**
26
+ * The bar size the history was asked for or served in, when the caller
27
+ * knows it. Without it the size is read from the bars' spacing, which a
28
+ * thinly traded listing (a trade every week or two) makes look weekly.
29
+ */
30
+ barSize?: "1d" | "1wk" | "1mo";
23
31
  }
24
32
 
33
+ /** The `barSize` option for a history asked for in `resolution` bars: daily or longer ones only. */
34
+ export function dailyOrLongerBarSize(resolution: string | null | undefined): Pick<SessionBarOptions, "barSize"> {
35
+ return resolution === "1d" || resolution === "1wk" || resolution === "1mo" ? { barSize: resolution } : {};
36
+ }
37
+
38
+ /**
39
+ * The bar size withSessionBar is told for bars asked as `requested`: the
40
+ * request, unless the source stated another (`stated`) or the bars' spacing
41
+ * shows them finer, or coarser and starting their periods (requestedBarSize).
42
+ * A 5Y range asks for weekly bars; served daily, Thursday's bar is a day, and
43
+ * Friday's live price is a bar of its own, not Thursday's close.
44
+ */
45
+ export function requestedSessionBarSize(
46
+ points: readonly Pick<PricePoint, "date">[],
47
+ requested: string | null | undefined,
48
+ stated?: string | null,
49
+ ): Pick<SessionBarOptions, "barSize"> {
50
+ const asked = dailyOrLongerBarSize(requested).barSize;
51
+ return asked ? { barSize: requestedBarSize(points.map((point) => new Date(point.date).getTime()), asked, stated) } : {};
52
+ }
53
+
54
+ /**
55
+ * How long after its session closes a day's bar is final: a delayed quote
56
+ * runs up to twenty minutes behind, and a closing auction prints at the bell.
57
+ */
58
+ const SESSION_SETTLE_MS = 30 * 60_000;
59
+
25
60
  function barTime(point: Pick<PricePoint, "date">): number {
26
61
  const date = point.date as Date | string | number;
27
62
  return (date instanceof Date ? date : new Date(date)).getTime();
@@ -95,15 +130,18 @@ export function withSessionBar(
95
130
  options: SessionBarOptions,
96
131
  ): PricePoint[] {
97
132
  const last = points.at(-1);
98
- if (!last || points.length < 2) return points;
133
+ if (!last || (points.length < 2 && !options.barSize)) return points;
99
134
  const times = points.map(barTime);
100
135
  const lastTime = times.at(-1)!;
101
136
  const gap = medianBarGap(times);
102
- if (!Number.isFinite(lastTime) || gap === null || gap < DAILY_BAR_MIN_GAP_MS) return points;
103
- const size = barSizeFromGap(gap);
137
+ if (!Number.isFinite(lastTime) || (!options.barSize && (gap === null || gap < DAILY_BAR_MIN_GAP_MS))) return points;
138
+ // The size asked for, not the spacing: a listing that trades once a fortnight still has daily bars.
139
+ const size = options.barSize ?? barSizeFromGap(gap!);
104
140
  const venue = options.venue || quote?.listingExchangeName || quote?.exchangeName || undefined;
105
141
  if (venue && isAlwaysOpenExchange(venue)) return points;
106
142
  if (quote && !tradesInSessions(quote, venue)) return points;
143
+ const settled = quote ? settledSessionBar(points, last, lastTime, size, quote, venue, options.now) : null;
144
+ if (settled) return settled;
107
145
 
108
146
  // A quote that does not say its session is read by the venue's calendar.
109
147
  const trading = quote?.marketState === "REGULAR" || (quote?.marketState == null && isRegularSessionTime(venue, options.now) === true);
@@ -137,13 +175,44 @@ export function withSessionBar(
137
175
  return points;
138
176
  }
139
177
 
178
+ /**
179
+ * A day's bar the source still marks partial once its session has closed:
180
+ * the session's quote, read after the close, is that day's last price, so
181
+ * the bar takes it (with the day's extremes and volume, which only grow) and
182
+ * is final. A thin listing's Friday bar is no longer partial on Sunday.
183
+ * Null when the bar is not such a bar, or the quote is not from its session,
184
+ * and on a venue whose closed quote can end on a print after its closing call
185
+ * (B3): its official close is the source's bar, which is waited for.
186
+ */
187
+ function settledSessionBar(
188
+ points: PricePoint[],
189
+ last: PricePoint,
190
+ lastTime: number,
191
+ size: "1d" | "1wk" | "1mo",
192
+ quote: Quote,
193
+ venue: string | undefined,
194
+ now: number,
195
+ ): PricePoint[] | null {
196
+ if (size !== "1d" || !last.partial || quote.marketState === "REGULAR" || !positive(quote.price)) return null;
197
+ if (venue && DAILY_BAR_CLOSE_VENUES.has(canonicalExchange(venue))) return null;
198
+ const day = calendarBarStart(lastTime, "1d", venue);
199
+ const closed = latestRegularSessionClose(venue, now - SESSION_SETTLE_MS);
200
+ if (!closed || closed.date < day || quoteTradingDay(quote) !== day) return null;
201
+ if (hasLikelyQuoteUnitMismatch({ currency: quote.currency, price: last.close }, { currency: quote.currency, price: quote.price })) return null;
202
+ const { partial: _partial, ...bar } = sessionBar(last, last.date, quote, quote.price);
203
+ return [...points.slice(0, -1), bar];
204
+ }
205
+
140
206
  /**
141
207
  * The daily bars `history` shows as final, which alerts on a daily close read
142
208
  * too: the bars as served, less the bar of a session still trading
143
209
  * (withSessionBar, which `history` rebuilds from the quote and marks partial)
144
- * and any bar the source marks partial. A close `history` prints without
145
- * `partial` is final here, and one it prints with it is not.
210
+ * and any bar still partial. A bar the source marks partial after its session
211
+ * has settled takes that session's `quote` and is final, as `history` makes
212
+ * it (settledSessionBar); with no quote from its session it stays partial.
213
+ * A close `history` prints without `partial` is final here, and one it prints
214
+ * with it is not.
146
215
  */
147
- export function finalDailyBars(points: PricePoint[], options: SessionBarOptions): PricePoint[] {
148
- return withSessionBar(points, null, options).filter((point) => !point.partial);
216
+ export function finalDailyBars(points: PricePoint[], options: SessionBarOptions, quote?: Quote | null): PricePoint[] {
217
+ return withSessionBar(points, quote ?? null, options).filter((point) => !point.partial);
149
218
  }
@@ -10,6 +10,9 @@ import {
10
10
  isPriceGroup,
11
11
  knownUnitSignature,
12
12
  legName,
13
+ percentBasisPointRatioScale,
14
+ percentBasisPointUnit,
15
+ PLAIN_RATIO_UNIT,
13
16
  unitMismatchMessage,
14
17
  type SeriesUnit,
15
18
  } from "./units";
@@ -23,6 +26,8 @@ interface FormulaLeg {
23
26
  perBarrel: boolean;
24
27
  /** The barrels in a tonne the multiplier carries (7.45 for gasoil), making a per-barrel price per tonne. */
25
28
  perTonne: number | null;
29
+ /** The multiplier carries 100 (1), making a percent basis points, or 0.01 (-1), making basis points a percent. */
30
+ percentBp: 1 | -1 | null;
26
31
  }
27
32
 
28
33
  export interface FormulaTerms {
@@ -34,7 +39,7 @@ export interface FormulaTerms {
34
39
  }
35
40
 
36
41
  /**
37
- * A formula study's terms: `weight1`, `perBarrel1`, `perTonne1` ... per
42
+ * A formula study's terms: `weight1`, `perBarrel1`, `perTonne1`, `percentBp1` ... per
38
43
  * input it adds up, `power1` ... (1 or -1) per input it multiplies or divides
39
44
  * the sum by, and an optional `divisor`. A saved or hand-edited spec can carry
40
45
  * a multiplier or divisor no formula was written with (a value that is not a
@@ -55,11 +60,13 @@ export function formulaTerms(spec: ChartStudySpec, inputs: readonly ResolvedSeri
55
60
  if (!isFiniteNumber(weight)) return { error: `The multiplier of ${legName(input)} is missing or not a number; write the formula again.` };
56
61
  if (weight === 0) return { error: `${legName(input)} has a multiplier of 0, which removes it; leave it out of the formula instead.` };
57
62
  const perTonne = spec.parameters[`perTonne${index + 1}`];
63
+ const percentBp = spec.parameters[`percentBp${index + 1}`];
58
64
  legs.push({
59
65
  index,
60
66
  weight,
61
67
  perBarrel: spec.parameters[`perBarrel${index + 1}`] === 1,
62
68
  perTonne: isFiniteNumber(perTonne) && isBarrelsPerTonne(perTonne) ? perTonne : null,
69
+ percentBp: percentBp === 1 || percentBp === -1 ? percentBp : null,
63
70
  });
64
71
  }
65
72
  if (legs.length === 0) return { error: "The formula has no series to add up, only series it divides by; write the formula again." };
@@ -71,18 +78,32 @@ export function formulaTerms(spec: ChartStudySpec, inputs: readonly ResolvedSeri
71
78
 
72
79
  /**
73
80
  * A leg's unit once its multiplier is applied: 42 gallons of a per-gallon
74
- * price are a barrel's worth, and 7.45 barrels of gasoil a tonne's.
81
+ * price are a barrel's worth, 7.45 barrels of gasoil a tonne's, and 100 times
82
+ * a percent is basis points.
75
83
  */
76
- function formulaLegUnit(leg: FormulaLeg, input: ResolvedSeries): string {
84
+ function formulaLegUnit(leg: FormulaLeg, input: ResolvedSeries): SeriesUnit {
85
+ const converted = leg.percentBp ? percentBasisPointUnit(input.unit, leg.percentBp) : null;
86
+ if (converted) return converted;
77
87
  const unit = leg.perBarrel ? perBarrelUnit(input.unit) : input.unit;
78
- return leg.perTonne ? perTonneUnit(unit) : unit;
88
+ return { unit: leg.perTonne ? perTonneUnit(unit) : unit, unitGroup: input.unitGroup };
79
89
  }
80
90
 
81
91
  /** Why a formula's legs cannot be summed, or null when every leg counts the same known unit. */
82
92
  function formulaUnitMismatch(terms: FormulaTerms, inputs: readonly ResolvedSeries[]): string | null {
83
93
  if (terms.legs.length < 2) return null;
84
- const legs = terms.legs.map((leg) => ({ series: inputs[leg.index]!, unit: formulaLegUnit(leg, inputs[leg.index]!) }));
85
- const signatures = legs.map(({ series, unit }) => knownUnitSignature({ unit, unitGroup: series.unitGroup }));
94
+ // A 100 or 0.01 times the whole formula converts each leg it can: one it cannot convert beside one it does
95
+ // (a bp leg beside a % one, `(FRED:DGS5 - CAP:cdx:ig)*100`) would chart 100 times its basis points as basis points.
96
+ const scaled = terms.legs.filter((leg) => leg.percentBp !== null);
97
+ const converts = (leg: FormulaLeg) => percentBasisPointUnit(inputs[leg.index]!.unit, leg.percentBp!) !== null;
98
+ const converted = scaled.find(converts);
99
+ const unconverted = scaled.find((leg) => !converts(leg));
100
+ if (converted && unconverted) {
101
+ const [one, other] = [converted, unconverted].sort((left, right) => left.index - right.index);
102
+ return unitMismatchMessage("formula", { series: inputs[one!.index]!, unit: inputs[one!.index]!.unit },
103
+ { series: inputs[other!.index]!, unit: inputs[other!.index]!.unit });
104
+ }
105
+ const legs = terms.legs.map((leg) => ({ series: inputs[leg.index]!, ...formulaLegUnit(leg, inputs[leg.index]!) }));
106
+ const signatures = legs.map((leg) => knownUnitSignature(leg));
86
107
  const other = signatures.findIndex((signature, index) => index > 0 && (signature === null || signature !== signatures[0]));
87
108
  if (signatures[0] !== null && other < 0) return null;
88
109
  return unitMismatchMessage("formula", legs[0]!, legs[Math.max(1, other)]!);
@@ -149,9 +170,14 @@ export function formulaUnit(terms: FormulaTerms, inputs: readonly ResolvedSeries
149
170
  const mismatch = formulaUnitMismatch(terms, inputs);
150
171
  if (mismatch) return { error: mismatch };
151
172
  const first = inputs[terms.legs[0]!.index]!;
152
- let unit: SeriesUnit = { unit: formulaLegUnit(terms.legs[0]!, first), unitGroup: first.unitGroup };
173
+ let unit: SeriesUnit = formulaLegUnit(terms.legs[0]!, first);
153
174
  for (const factor of terms.factors) {
154
175
  const series = inputs[factor.index]!;
176
+ // A percent over basis points, or basis points over a percent, is a plain number (formulaFactorScale).
177
+ if (factor.power < 0 && percentBasisPointRatioScale(unit, series) !== null) {
178
+ unit = PLAIN_RATIO_UNIT;
179
+ continue;
180
+ }
155
181
  const next = combinedUnit(unit, series, factor.power);
156
182
  const issue = fxConversionIssue(unit, series, factor.power, next);
157
183
  if (issue) return { error: issue };
@@ -160,6 +186,21 @@ export function formulaUnit(terms: FormulaTerms, inputs: readonly ResolvedSeries
160
186
  return unit;
161
187
  }
162
188
 
189
+ /**
190
+ * What each series a formula divides by scales its value by besides itself:
191
+ * 100 over basis points when the formula is in %, 0.01 over a percent when it
192
+ * is in bp, so the two cancel to a plain number; 1 otherwise.
193
+ */
194
+ function formulaFactorScales(terms: FormulaTerms, inputs: readonly ResolvedSeries[]): number[] {
195
+ let unit: SeriesUnit = formulaLegUnit(terms.legs[0]!, inputs[terms.legs[0]!.index]!);
196
+ return terms.factors.map((factor) => {
197
+ const series = inputs[factor.index]!;
198
+ const scale = factor.power < 0 ? percentBasisPointRatioScale(unit, series) : null;
199
+ unit = scale !== null ? PLAIN_RATIO_UNIT : combinedUnit(unit, series, factor.power);
200
+ return scale ?? 1;
201
+ });
202
+ }
203
+
163
204
  export function resolveFormula(
164
205
  spec: ChartStudySpec,
165
206
  inputs: readonly ResolvedSeries[],
@@ -169,12 +210,14 @@ export function resolveFormula(
169
210
  ): ResolvedSeries[] {
170
211
  const first = inputs[terms.legs[0]!.index]!;
171
212
  // Rounded off the float's last digits: 42 × 4.6233 - 96.12 is 98.0586, not 98.05860000000001.
213
+ const factorScales = formulaFactorScales(terms, inputs);
172
214
  const points = alignedSamples(inputs).map(({ point, values }) => {
173
215
  let value: number | null = terms.legs.reduce((sum, leg) => sum + values[leg.index]! * leg.weight, 0) / terms.divisor;
174
- for (const factor of terms.factors) {
216
+ terms.factors.forEach((factor, position) => {
175
217
  const scale = values[factor.index]!;
176
- value = value === null || (factor.power < 0 && scale === 0) ? null : factor.power < 0 ? value / scale : value * scale;
177
- }
218
+ value = value === null || (factor.power < 0 && scale === 0) ? null
219
+ : (factor.power < 0 ? value / scale : value * scale) * factorScales[position]!;
220
+ });
178
221
  return derivedPoint({ point, value: 0 }, value === null ? null : Number(value.toPrecision(12)));
179
222
  });
180
223
  const frequencies = new Set(inputs.map((input) => input.nativeFrequency));
@@ -3,7 +3,7 @@ import type { ManualChartResolution } from "../resolution";
3
3
  import type { ChartStudySpec, ResolvedSeries, SeriesPeriod, TimeSeriesPoint } from "../types";
4
4
  import { isFiniteNumber } from "../../utils/guards";
5
5
  import { derivedPoint, outputSeries, studyPeriod } from "./shared";
6
- import { derivedValueDecimals, isPriceGroup, ratioUnit } from "./units";
6
+ import { derivedValueDecimals, isPriceGroup, PLAIN_RATIO_UNIT, percentBasisPointRatioScale, ratioUnit } from "./units";
7
7
 
8
8
  interface PairedSample {
9
9
  point: TimeSeriesPoint;
@@ -49,6 +49,11 @@ function pairedHistoryResolution(left: ResolvedSeries, right: ResolvedSeries): M
49
49
  return left.historyResolution === right.historyResolution ? left.historyResolution : null;
50
50
  }
51
51
 
52
+ /** A pair's leg as its formula names it: a published series as written, anything else by its label. */
53
+ function pairLegName(series: ResolvedSeries): string {
54
+ return series.expression ?? series.label;
55
+ }
56
+
52
57
  export function resolvePairStudy(
53
58
  spec: ChartStudySpec,
54
59
  left: ResolvedSeries,
@@ -58,15 +63,19 @@ export function resolvePairStudy(
58
63
  const paired = pairedSamples(left, right, spec.kind !== "correlation");
59
64
  if (spec.kind === "ratio" || spec.kind === "spread") {
60
65
  const multiplier = isFiniteNumber(spec.parameters.multiplier) ? spec.parameters.multiplier : 1;
66
+ const ratioStudy = spec.kind === "ratio";
67
+ // A percent over basis points cancels to a plain number, 100 times the quotient (4.1% over 61bp is 6.72),
68
+ // rounded off the float's last digits.
69
+ const percentScale = ratioStudy ? percentBasisPointRatioScale(left, right) : null;
61
70
  const points = paired.map((sample) => derivedPoint(
62
71
  { point: sample.point, value: sample.left },
63
- spec.kind === "ratio"
64
- ? sample.right === 0 ? null : sample.left / sample.right
72
+ ratioStudy
73
+ ? sample.right === 0 ? null : percentScale === null ? sample.left / sample.right
74
+ : Number((sample.left / sample.right * percentScale).toPrecision(12))
65
75
  : sample.left - sample.right * multiplier,
66
76
  ));
67
- const ratioStudy = spec.kind === "ratio";
68
77
  const outputUnit = ratioStudy
69
- ? ratioUnit(left, right)
78
+ ? percentScale === null ? ratioUnit(left, right) : PLAIN_RATIO_UNIT
70
79
  : { unit: left.unit, unitGroup: left.unitGroup };
71
80
  // A price over an FX rate is a price in the other currency (EUR / barrel),
72
81
  // stated as a future's unit is; a plain ratio keeps its own decimals.
@@ -75,9 +84,11 @@ export function resolvePairStudy(
75
84
  return [outputSeries(spec, left, {
76
85
  ...(convertedPrice ? { statedUnit: outputUnit.unit, priceAssetCategory: null } : {}),
77
86
  ...(valueDecimals !== undefined ? { valueDecimals } : {}),
87
+ // A published series reads as it is written (FRED:BAMLC0A0CM - CAP:cdx:ig): its long title would
88
+ // read like the leg's own line in a legend that has to shorten.
78
89
  label: ratioStudy
79
- ? `${left.label} / ${right.label}`
80
- : `${left.label} - ${multiplier === 1 ? "" : `${multiplier}×`}${right.label}`,
90
+ ? `${pairLegName(left)} / ${pairLegName(right)}`
91
+ : `${pairLegName(left)} - ${multiplier === 1 ? "" : `${multiplier}×`}${pairLegName(right)}`,
81
92
  points,
82
93
  color,
83
94
  unit: outputUnit.unit,
@@ -57,9 +57,9 @@ export function knownUnitSignature(series: Pick<ResolvedSeries, "unit" | "unitGr
57
57
  return `${basis ?? ""}|${parts.map(unitFactorIdentity).join("/")}`;
58
58
  }
59
59
 
60
- /** A leg as an error names it: its ticker (HO=F), else its label. */
60
+ /** A leg as a formula and an error name it: its ticker (HO=F), else as it is written (FRED:BAMLC0A0CM), else its label. */
61
61
  export function legName(series: ResolvedSeries): string {
62
- return series.listing?.symbol || series.label;
62
+ return series.listing?.symbol || series.expression || series.label;
63
63
  }
64
64
 
65
65
  /** What a leg's unit is, in words: "is USD / gallon", "is in %", "is in USD per an unknown quantity". */
@@ -97,6 +97,10 @@ export function unitMismatchMessage(
97
97
  if (gallons && leftCurrency === rightCurrency) {
98
98
  return `${named}: write ${GALLONS_PER_BARREL}*${gallons} to compare per barrel.`;
99
99
  }
100
+ // A percent beside basis points is 100 short of them, a known conversion as 42 gallons are a barrel.
101
+ const percent = isPercentUnit(left.unit) && isBasisPointUnit(right.unit) ? leftName
102
+ : isBasisPointUnit(left.unit) && isPercentUnit(right.unit) ? rightName : null;
103
+ if (percent) return `${named}: write ${BP_PER_PERCENT}*${percent} to compare in bp.`;
100
104
  const subject = kind === "spread" ? "a spread" : "a formula";
101
105
  if (leftCurrency && rightCurrency && leftCurrency !== rightCurrency) return `${named}: ${subject} does not convert currencies.`;
102
106
  const known = knownUnitSignature({ unit: left.unit, unitGroup: left.series.unitGroup }) !== null
@@ -122,6 +126,49 @@ export interface SeriesUnit {
122
126
  unitGroup: string;
123
127
  }
124
128
 
129
+ /**
130
+ * Basis points, in the group a catalog series in bp draws in (CDX IG), so a
131
+ * spread converted to bp shares its axis.
132
+ */
133
+ export const BASIS_POINT_UNIT: SeriesUnit = { unit: "bp", unitGroup: "series:bp" };
134
+ /** Percent, in the group FRED's percent series and a catalog series in % draw in. */
135
+ const PERCENT_UNIT: SeriesUnit = { unit: "%", unitGroup: "percent" };
136
+ /** Basis points in a percentage point: 0.93% is 93bp. */
137
+ export const BP_PER_PERCENT = 100;
138
+
139
+ function isPercentUnit(unit: string): boolean {
140
+ return unit.trim() === "%";
141
+ }
142
+
143
+ function isBasisPointUnit(unit: string): boolean {
144
+ return /^bps?$/i.test(unit.trim());
145
+ }
146
+
147
+ /**
148
+ * The unit a leg reads in once its multiplier converts it: times 100, a
149
+ * percent is basis points (0.93% is 93bp); times 0.01, basis points are a
150
+ * percent. Null when the conversion does not apply to the unit.
151
+ */
152
+ export function percentBasisPointUnit(unit: string, direction: 1 | -1): SeriesUnit | null {
153
+ if (direction === 1 && isPercentUnit(unit)) return BASIS_POINT_UNIT;
154
+ if (direction === -1 && isBasisPointUnit(unit)) return PERCENT_UNIT;
155
+ return null;
156
+ }
157
+
158
+ /**
159
+ * What a percent over basis points, or basis points over a percent, is
160
+ * multiplied by to cancel to a plain number: 100 for % over bp, 0.01 for bp
161
+ * over %. 4.1% over 61bp is 410bp over 61bp, 6.72. Null for any other pair.
162
+ */
163
+ export function percentBasisPointRatioScale(numerator: Pick<SeriesUnit, "unit">, denominator: Pick<SeriesUnit, "unit">): number | null {
164
+ if (isPercentUnit(numerator.unit) && isBasisPointUnit(denominator.unit)) return BP_PER_PERCENT;
165
+ if (isBasisPointUnit(numerator.unit) && isPercentUnit(denominator.unit)) return 1 / BP_PER_PERCENT;
166
+ return null;
167
+ }
168
+
169
+ /** A plain number: a ratio whose units cancel. */
170
+ export const PLAIN_RATIO_UNIT: SeriesUnit = { unit: "x", unitGroup: "ratio" };
171
+
125
172
  const UNKNOWN_UNIT: SeriesUnit = { unit: "unknown", unitGroup: "derived-unit:unknown" };
126
173
 
127
174
  export function isPriceGroup(unitGroup: string): boolean {
@@ -238,6 +238,12 @@ export interface ResolvedSeries {
238
238
  * figures of the period asked for, while its annual ones exist.
239
239
  */
240
240
  unreportedPeriod?: "quarterly";
241
+ /**
242
+ * Set where the series' current value is not meaningful (N/M): EV/EBITDA
243
+ * over EBITDA at or below zero, or a bank's or an insurer's, with why and
244
+ * the period it would end on (`valuationNotMeaningful`).
245
+ */
246
+ notMeaningful?: { reason: string; asOf: string };
241
247
  /** Acquired market-history cadence; null is explicitly unknown, undefined is legacy or nonmarket. */
242
248
  historyResolution?: ManualChartResolution | null;
243
249
  /**
@@ -265,6 +271,12 @@ export interface ResolvedSeries {
265
271
  * VWAP follow. Set even where no exchange time zone is known (futures).
266
272
  */
267
273
  listing?: { symbol: string; exchange: string };
274
+ /**
275
+ * A dataset series as a formula writes it (`FRED:BAMLC0A0CM`,
276
+ * `CAP:cdx:ig`): what a formula's label and its unit errors name it by,
277
+ * so they read as written rather than as the source's long title.
278
+ */
279
+ expression?: string;
268
280
  /** Price/volume observations and their derived studies, including 24/7
269
281
  * markets. Independent of whether the chart compresses exchange sessions.
270
282
  * `dataset`: a capability's published observations (vessel transits),
@@ -105,4 +105,6 @@ export interface DesktopWindowBridge {
105
105
  subscribeState(listener: (snapshot: DesktopSharedStateSnapshot) => void): () => void;
106
106
  subscribeDockPreview?(listener: (preview: DesktopDockPreviewState) => void): () => void;
107
107
  subscribeThemePreview?(listener: (preview: DesktopThemePreviewState) => void): () => void;
108
+ /** A window change the desktop app could not save (a window closed, a pane docked or moved), in the main window. */
109
+ subscribeSaveFailures?(listener: () => void): () => void;
108
110
  }
@@ -167,6 +167,21 @@ export interface Quote extends DepositaryReceiptFacts {
167
167
  * date the close (PreviousCloseDates); a source may set it too.
168
168
  */
169
169
  previousCloseDate?: string;
170
+ /**
171
+ * A thin listing that did not trade in the session its venue's calendar
172
+ * puts before the move's, and whose daily closes do not say which day its
173
+ * previousClose is from (PreviousCloseDates): its move names no day.
174
+ */
175
+ previousCloseUndated?: boolean;
176
+ /**
177
+ * A listing that did not trade in the session its price is from: the price
178
+ * and previous close are the venue's nominal prices (an HKEX counter's
179
+ * USD line, untraded for days), dated by its daily bars
180
+ * (PreviousCloseDates). `session` is the venue date whose nominal price it
181
+ * is; `lastTraded` the latest day its bars show a trade, null when they
182
+ * reach back to none. `lastUpdated` stays the last print.
183
+ */
184
+ nominalPrice?: { session: string; lastTraded: string | null };
170
185
  /** Official close of a completed regular session, in this quote's currency. */
171
186
  regularClose?: number;
172
187
  /** Exchange-local date of regularClose; separate from the daily previous-close reference. */
@@ -497,6 +497,12 @@ interface HeadlessPaneResultBase {
497
497
  */
498
498
  warnings?: string[];
499
499
  metadata?: Record<string, unknown>;
500
+ /**
501
+ * Options the load settled from what it was given rather than from a flag
502
+ * (AUCT's market, from a search naming Hong Kong's paper): the report's
503
+ * `options` show these, so they name what was used, not the default.
504
+ */
505
+ appliedOptions?: HeadlessPaneOptionValues;
500
506
  /** What this load knows about its data's source and age; overrides the definition's `freshness`. */
501
507
  freshness?: HeadlessPaneFreshness;
502
508
  }
@@ -692,6 +698,8 @@ export interface HeadlessSeries {
692
698
  textCompact?: boolean;
693
699
  /** Each point's `value` is its bar's close: `--csv` and `--ndjson` write Close alone, JSON keeps both. */
694
700
  valueIsClose?: boolean;
701
+ /** The series' current value is not meaningful: the report prints N/M dated by the period, and why. */
702
+ notMeaningful?: { reason: string; asOf: string };
695
703
  points: HeadlessSeriesPoint[];
696
704
  }
697
705
 
@@ -9,7 +9,7 @@ export interface CliTableColumn {
9
9
  maxWidth?: number;
10
10
  /** The narrowest a text column wraps to (MIN_WRAPPED_COLUMN_WIDTH unless set), or a `shrink: true` column is cut to; a narrower table moves columns under their rows. */
11
11
  minWidth?: number;
12
- /** Dropped, rightmost first, before any column is cut or moved to fit a terminal. */
12
+ /** Dropped, rightmost first, before any column is cut or moved to fit a terminal. Plain output keeps it, moved under its row. */
13
13
  optional?: boolean;
14
14
  /** Among optional columns, a higher priority is dropped sooner; equal ones go rightmost first. */
15
15
  dropPriority?: number;
@@ -711,12 +711,14 @@ function renderTableLayout(
711
711
  }) : [];
712
712
  const ownStacked = stacked.filter((entry) => !shared.includes(entry));
713
713
  // Columns moved under the rows print there as `Header value`, as many to a line as fit.
714
+ // Plain output keeps a moved column's empty cell as its dash, so every row reads the same columns.
715
+ const keepsEmpty = cliPlainEnabled();
714
716
  const renderStacked = (entries: readonly TableEntry[], cells: string[], rowIndex: number, lineIndent: string, width: number): string[] => {
715
717
  const lines: string[] = [];
716
718
  let line = "";
717
719
  for (const { column, index } of entries) {
718
720
  const value = cells[index] ?? "";
719
- if (rowIndex >= (column.stackRows ?? Infinity) || EMPTY_CELL.test(stripAnsi(value).trim())) continue;
721
+ if (rowIndex >= (column.stackRows ?? Infinity) || (!keepsEmpty && EMPTY_CELL.test(stripAnsi(value).trim()))) continue;
720
722
  const piece = `${cliStyles.muted(column.header)} ${value}`;
721
723
  if (line && visibleLength(line) + COLUMN_GAP + visibleLength(piece) <= width) {
722
724
  line += `${" ".repeat(COLUMN_GAP)}${piece}`;
@@ -774,7 +776,8 @@ export function renderTable(columns: CliTableColumn[], rows: string[][], options
774
776
  if (available == null || tableWidth(shown.map((entry) => entry.width)) <= available) {
775
777
  return renderTableLayout(columns, rows, options, shown, [], available, false);
776
778
  }
777
- while (tableWidth(shown.map((entry) => entry.width)) > available) {
779
+ // Plain output keeps every column (`--plain` promises it): an optional one moves under its row instead.
780
+ while (!cliPlainEnabled() && tableWidth(shown.map((entry) => entry.width)) > available) {
778
781
  const dropped = shown.reduce<(typeof shown)[number] | undefined>((pick, entry) => (
779
782
  entry.column.optional && (!pick || (entry.column.dropPriority ?? 0) >= (pick.column.dropPriority ?? 0)) ? entry : pick
780
783
  ), undefined);