gloomberb 0.19.5 → 0.19.6
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.
- package/package.json +1 -1
- package/patches/@opentui%2Fcore@0.3.2.patch +86 -25
- package/src/api-client/equity-screener.ts +23 -0
- package/src/app/pane-runtime/index.tsx +2 -0
- package/src/app/pane-runtime/plugin-bindings.ts +10 -1
- package/src/app.tsx +63 -16
- package/src/cli/commands/market.ts +149 -10
- package/src/cli/commands/search.ts +21 -3
- package/src/cli/commands/ticker.ts +74 -33
- package/src/cli/glossary.ts +3 -3
- package/src/cli/known-gaps.ts +8 -0
- package/src/cli/listing-arg.ts +12 -0
- package/src/cli/pane-functions/capabilities.ts +2 -0
- package/src/cli/pane-functions/catalog.ts +22 -4
- package/src/cli/pane-functions/function-help.ts +8 -5
- package/src/cli/pane-functions/headless.ts +4 -3
- package/src/cli/pane-functions/resolver.ts +75 -2
- package/src/cli/quote-answer.ts +9 -0
- package/src/cli/symbol-list.ts +54 -2
- package/src/cli/symbol-rows.ts +14 -2
- package/src/cli/ticker-resolution.ts +89 -20
- package/src/components/chart/composite/axis-overlays.tsx +60 -27
- package/src/components/chart/composite/composite-chart.tsx +118 -63
- package/src/components/chart/composite/cursor-source.ts +111 -0
- package/src/components/chart/composite/format.ts +168 -6
- package/src/components/chart/composite/legend.tsx +8 -4
- package/src/components/chart/composite/panel-labels.ts +20 -1
- package/src/components/chart/composite/panel-surface.tsx +201 -92
- package/src/components/chart/composite/price-axis-labels.tsx +92 -46
- package/src/components/chart/composite/price-series.ts +31 -8
- package/src/components/chart/composite/scene.ts +154 -59
- package/src/components/chart/composite/series-axis-tags.tsx +4 -2
- package/src/components/chart/composite/time-axis.ts +13 -5
- package/src/components/chart/composite/time-scale.ts +211 -56
- package/src/components/chart/composite/types.ts +11 -1
- package/src/components/chart/composite/use-composite-chart-keyboard.ts +32 -12
- package/src/components/chart/curve/curve-surface.tsx +5 -2
- package/src/components/chart/curve/model.ts +4 -1
- package/src/components/chart/native/use-bitmap-metrics.ts +81 -0
- package/src/components/chart/static/series.ts +3 -0
- package/src/components/command-bar/commands/collection-list.ts +81 -0
- package/src/components/command-bar/commands/direct/index.ts +6 -0
- package/src/components/command-bar/commands/registry.ts +8 -0
- package/src/components/command-bar/layout-items/current-layout.ts +22 -1
- package/src/components/command-bar/layout-items/focused-pane.ts +22 -1
- package/src/components/command-bar/pane-templates/items.ts +19 -3
- package/src/components/command-bar/pane-templates/workflow.ts +5 -0
- package/src/components/command-bar/routes/root/results.ts +23 -3
- package/src/components/command-bar/routes/root/selection.ts +4 -2
- package/src/components/command-bar/routes/root/shortcut-feedback.ts +1 -1
- package/src/components/command-bar/routes/root/shortcut-items.ts +3 -4
- package/src/components/command-bar/routes/root/shortcuts.ts +58 -14
- package/src/components/command-bar/routes/root/ticker-first.ts +32 -0
- package/src/components/command-bar/surface/environment.ts +2 -0
- package/src/components/command-bar/view-model.ts +7 -0
- package/src/components/command-bar/workflow/ops.ts +2 -1
- package/src/components/command-bar/workflow/tickers.ts +20 -0
- package/src/components/layout/shell/menu.ts +15 -1
- package/src/components/layout/shell/pane/actions.ts +4 -0
- package/src/components/layout/shell/ticker-link-menu.ts +12 -3
- package/src/components/layout/status-bar.tsx +20 -0
- package/src/components/onboarding/onboarding-keyboard.ts +5 -1
- package/src/components/onboarding/onboarding-wizard.tsx +15 -4
- package/src/components/onboarding/portfolio-step/positions-panel.tsx +8 -5
- package/src/components/onboarding/use-onboarding-progress.ts +20 -1
- package/src/components/price-sparkline/view.tsx +14 -6
- package/src/components/ticker/badge/index.tsx +8 -4
- package/src/components/ticker/badge/list.tsx +23 -7
- package/src/components/ui/column-grid.tsx +8 -2
- package/src/components/ui/data-table/opentui/model.ts +4 -1
- package/src/components/ui/tabs.tsx +5 -2
- package/src/core/state/app/layout.ts +18 -3
- package/src/core/state/app/state.ts +2 -0
- package/src/core/state/app/types.ts +5 -0
- package/src/data/config/layout.ts +3 -0
- package/src/data/config/store/normalize.ts +39 -4
- package/src/i18n/es.ts +10 -0
- package/src/i18n/ja.ts +10 -0
- package/src/i18n/ko.ts +10 -0
- package/src/i18n/zh-cn.ts +10 -0
- package/src/i18n/zh-tw.ts +10 -0
- package/src/layout/pane-manager/floating-placement.ts +7 -4
- package/src/layout/pane-manager/floating.ts +5 -2
- package/src/market-data/bond-funds.ts +19 -0
- package/src/market-data/futures-contract.ts +14 -3
- package/src/market-data/market/freshness.ts +18 -0
- package/src/market-data/market/status.ts +15 -2
- package/src/plugins/builtin/bond-calculator/headless.ts +2 -1
- package/src/plugins/builtin/bond-calculator/index.tsx +1 -1
- package/src/plugins/builtin/bond-calculator/model.ts +14 -5
- package/src/plugins/builtin/bond-calculator/pane.tsx +1 -1
- package/src/plugins/builtin/buildout/cells.tsx +25 -45
- package/src/plugins/builtin/buildout/detail/company.tsx +3 -3
- package/src/plugins/builtin/buildout/detail/index.tsx +1 -1
- package/src/plugins/builtin/buildout/detail/intel.tsx +4 -7
- package/src/plugins/builtin/buildout/detail/site.tsx +4 -4
- package/src/plugins/builtin/buildout/detail/ui.tsx +39 -38
- package/src/plugins/builtin/buildout/format.ts +23 -1
- package/src/plugins/builtin/buildout/model/types.ts +1 -0
- package/src/plugins/builtin/buildout/pane/index.tsx +2 -8
- package/src/plugins/builtin/buildout/table-model.ts +12 -4
- package/src/plugins/builtin/cds/headless.ts +1 -0
- package/src/plugins/builtin/cds/index.tsx +1 -1
- package/src/plugins/builtin/cloud/plugin.tsx +2 -0
- package/src/plugins/builtin/cloud/upgrade-status-widget.tsx +28 -3
- package/src/plugins/builtin/correlation/headless.ts +3 -2
- package/src/plugins/builtin/crypto-board/pane.tsx +5 -4
- package/src/plugins/builtin/debt-maturities/headless.ts +11 -2
- package/src/plugins/builtin/debt-maturities/model.ts +66 -0
- package/src/plugins/builtin/debt-maturities/pane.tsx +23 -4
- package/src/plugins/builtin/earnings-ripple/pane.tsx +1 -1
- package/src/plugins/builtin/econ/calendar-model.ts +28 -6
- package/src/plugins/builtin/equity-screener/client.ts +1 -1
- package/src/plugins/builtin/equity-screener/criterion-editor.tsx +4 -16
- package/src/plugins/builtin/equity-screener/headless.ts +4 -2
- package/src/plugins/builtin/equity-screener/ideas.ts +67 -3
- package/src/plugins/builtin/equity-screener/model.ts +180 -12
- package/src/plugins/builtin/equity-screener/pane.tsx +52 -12
- package/src/plugins/builtin/equity-screener/screen-check.ts +7 -4
- package/src/plugins/builtin/equity-screener/watchlist.ts +33 -0
- package/src/plugins/builtin/futures-curve/client.ts +19 -0
- package/src/plugins/builtin/futures-curve/headless.ts +52 -13
- package/src/plugins/builtin/futures-curve/index.tsx +1 -1
- package/src/plugins/builtin/futures-curve/model.ts +77 -6
- package/src/plugins/builtin/futures-curve/pane.tsx +19 -3
- package/src/plugins/builtin/macro-day/client.ts +41 -0
- package/src/plugins/builtin/macro-day/headless.ts +19 -9
- package/src/plugins/builtin/macro-day/model.ts +3 -1
- package/src/plugins/builtin/market-movers/index.tsx +4 -3
- package/src/plugins/builtin/mna/distress/headless.ts +1 -0
- package/src/plugins/builtin/perps/pane.tsx +3 -1
- package/src/plugins/builtin/portfolio-list/cli/bulk-symbols.ts +17 -0
- package/src/plugins/builtin/portfolio-list/cli/portfolio-command.ts +2 -1
- package/src/plugins/builtin/portfolio-list/cli/watchlist-command.ts +2 -1
- package/src/plugins/builtin/rate-path/headless.ts +24 -10
- package/src/plugins/builtin/research/event-model.ts +10 -3
- package/src/plugins/builtin/research/events-headless.ts +20 -2
- package/src/plugins/builtin/sec/fund-facts.ts +17 -1
- package/src/plugins/builtin/sec/index.tsx +1 -1
- package/src/plugins/builtin/shared/members-menu.tsx +103 -38
- package/src/plugins/builtin/short-interest/publications-model.ts +22 -1
- package/src/plugins/builtin/short-interest/publications-pane.tsx +13 -4
- package/src/plugins/builtin/short-interest/watch-model.ts +1 -1
- package/src/plugins/builtin/time-sales/pane.tsx +3 -2
- package/src/plugins/builtin/trace-bonds/client.ts +7 -4
- package/src/plugins/builtin/trace-bonds/index.tsx +1 -1
- package/src/plugins/builtin/volatility/client.ts +6 -1
- package/src/plugins/builtin/volatility/headless.ts +0 -1
- package/src/plugins/builtin/yield-curve/curves.ts +15 -0
- package/src/plugins/builtin/yield-curve/headless.ts +6 -1
- package/src/plugins/builtin/yield-curve/index.tsx +5 -8
- package/src/plugins/host-modules.ts +22 -3
- package/src/plugins/host-smoke.ts +6 -3
- package/src/portfolio/collection-name.ts +19 -0
- package/src/renderers/browser/http-proxy-transport.ts +78 -8
- package/src/renderers/cloudflare/http-proxy.ts +13 -2
- package/src/renderers/cloudflare/proxy-session.ts +47 -24
- package/src/renderers/cloudflare/worker.ts +15 -2
- package/src/renderers/desktop/geometry.ts +279 -0
- package/src/renderers/desktop/screen-setup.ts +246 -0
- package/src/renderers/desktop/sequential-window-host.ts +179 -0
- package/src/renderers/desktop/test-utils.ts +71 -0
- package/src/renderers/desktop/window-controller.ts +433 -0
- package/src/renderers/desktop/window-host.ts +70 -0
- package/src/renderers/desktop/window-layouts.ts +630 -0
- package/src/renderers/dom/data-frames.ts +15 -4
- package/src/renderers/electrobun/bun/application-menu/click.ts +1 -0
- package/src/renderers/electrobun/bun/application-menu/index.ts +4 -1
- package/src/renderers/electrobun/bun/desktop/backend-requests.ts +19 -8
- package/src/renderers/electrobun/bun/desktop/backend.ts +320 -19
- package/src/renderers/electrobun/bun/desktop/detached-windows.ts +83 -61
- package/src/renderers/electrobun/bun/desktop/host-requests.ts +4 -14
- package/src/renderers/electrobun/bun/desktop/initialization.ts +30 -11
- package/src/renderers/electrobun/bun/desktop/screen-setup-file.ts +55 -0
- package/src/renderers/electrobun/bun/desktop/state-broadcaster.ts +44 -8
- package/src/renderers/electrobun/bun/desktop/workspace/index.ts +298 -97
- package/src/renderers/electrobun/bun/desktop/workspace/requests.ts +44 -6
- package/src/renderers/electrobun/bun/index.ts +4 -97
- package/src/renderers/electrobun/bun/window/electrobun-window-host.ts +306 -0
- package/src/renderers/electrobun/bun/window/focus.ts +0 -25
- package/src/renderers/electrobun/bun/window/remembered-frame.ts +4 -82
- package/src/renderers/electrobun/shared/protocol.ts +44 -2
- package/src/renderers/electrobun/view/backend-rpc.ts +15 -0
- package/src/renderers/electrobun/view/desktop/window/bridge.ts +63 -3
- package/src/renderers/electrobun/view/main.tsx +13 -7
- package/src/series/fred-argument.ts +17 -0
- package/src/sources/provider-router/financial-routes.ts +7 -1
- package/src/state/app/context/index.tsx +16 -2
- package/src/state/desktop-windows.ts +63 -0
- package/src/sync/other-window-tabs.ts +62 -0
- package/src/tickers/company-name-listing.ts +23 -3
- package/src/tickers/listing-fate.ts +147 -1
- package/src/tickers/terminal-codes.ts +5 -0
- package/src/time-series/types.ts +6 -0
- package/src/types/config.ts +10 -1
- package/src/types/desktop-window.ts +71 -2
- package/src/types/financials.ts +4 -0
- package/src/types/headless.ts +19 -0
- package/src/types/plugin.ts +6 -0
- package/src/ui/index.tsx +14 -13
- package/src/ui/same-props.ts +58 -0
- package/src/utils/cli-output.ts +33 -4
- package/src/utils/format.ts +7 -2
- package/src/utils/futures-generic.ts +12 -0
- package/src/utils/http-proxy-upstream.ts +6 -2
- package/src/utils/plugin-proxy-hosts.json +0 -4
- package/src/utils/plugin-proxy-hosts.ts +22 -0
- package/src/utils/sec-filings.ts +7 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { logFailure } from "../../utils/log-failure";
|
|
2
2
|
import { commands as builtInCommands, getCommandPrefixes } from "../../components/command-bar/commands/registry";
|
|
3
|
-
import type { PaneDef, PaneTemplateCreateOptions, PaneTemplateDef } from "../../types/plugin";
|
|
3
|
+
import type { HeadlessPaneDefinition, PaneDef, PaneTemplateCreateOptions, PaneTemplateDef } from "../../types/plugin";
|
|
4
4
|
import type { MarketContext } from "../types";
|
|
5
5
|
import {
|
|
6
6
|
buildCreateOptions,
|
|
@@ -289,7 +289,7 @@ async function buildTemplateCatalogEntry(
|
|
|
289
289
|
aliases: [...(template.shortcut?.aliases ?? [])],
|
|
290
290
|
argKind: argument.kind,
|
|
291
291
|
argPlaceholder: argument.placeholder,
|
|
292
|
-
...(headless
|
|
292
|
+
...argExamples(headless, context),
|
|
293
293
|
...(headless?.argument.kind === "tickers" && template.shortcut?.argKind === "ticker"
|
|
294
294
|
? { shotArgument: argumentHint({ argKind: "ticker", argPlaceholder: template.shortcut.argPlaceholder }) } : {}),
|
|
295
295
|
keywords: template.keywords ?? [],
|
|
@@ -298,6 +298,20 @@ async function buildTemplateCatalogEntry(
|
|
|
298
298
|
};
|
|
299
299
|
}
|
|
300
300
|
|
|
301
|
+
/**
|
|
302
|
+
* The arguments a function's examples show past its placeholder: its own, and
|
|
303
|
+
* for a list of more than two symbols, a watchlist's name, which stands for
|
|
304
|
+
* its symbols (the reader's first watchlist).
|
|
305
|
+
*/
|
|
306
|
+
function argExamples(headless: HeadlessPaneDefinition | undefined, context: MarketContext): { argExamples: readonly string[] } | null {
|
|
307
|
+
const own = headless?.argument.examples ?? [];
|
|
308
|
+
const argument = headless?.argument;
|
|
309
|
+
const list = (argument?.kind === "symbol-list" || argument?.kind === "tickers") && (argument.maximum == null || argument.maximum > 2);
|
|
310
|
+
const name = context.config.watchlists[0]?.name ?? "Watchlist";
|
|
311
|
+
const examples = list ? [...own, /^[\w.-]+$/.test(name) ? name : `'${name.replace(/'/g, "'\\''")}'`] : own;
|
|
312
|
+
return examples.length > 0 ? { argExamples: examples } : null;
|
|
313
|
+
}
|
|
314
|
+
|
|
301
315
|
/**
|
|
302
316
|
* The functions `gloom catalog` and search list. An unlisted one (`listed:
|
|
303
317
|
* false`) is left out, and its pane is not listed in its place; `unlisted`
|
|
@@ -333,7 +347,7 @@ export async function buildPaneCatalogEntries(
|
|
|
333
347
|
aliases,
|
|
334
348
|
argKind: argument.kind,
|
|
335
349
|
argPlaceholder: argument.placeholder,
|
|
336
|
-
...(pane.headless
|
|
350
|
+
...argExamples(pane.headless, context),
|
|
337
351
|
keywords: [],
|
|
338
352
|
defaultSettings: {},
|
|
339
353
|
capability: getPaneFunctionCapability(undefined, pane),
|
|
@@ -403,6 +417,7 @@ function nameAndDescriptionFields(entry: PaneCatalogEntry): string[] {
|
|
|
403
417
|
...entry.keywords,
|
|
404
418
|
...entry.capability.aliases,
|
|
405
419
|
...entry.capability.intents,
|
|
420
|
+
...entry.capability.opens?.flatMap((opening) => opening.words) ?? [],
|
|
406
421
|
].filter((value): value is string => !!value).map((value) => value.toLowerCase());
|
|
407
422
|
}
|
|
408
423
|
|
|
@@ -450,6 +465,7 @@ function scorePaneCatalogEntry(entry: PaneCatalogEntry, query: string): CatalogM
|
|
|
450
465
|
entry.shortcut,
|
|
451
466
|
...entry.aliases,
|
|
452
467
|
...entry.capability.suggestFor ?? [],
|
|
468
|
+
...entry.capability.opens?.flatMap((opening) => opening.words) ?? [],
|
|
453
469
|
entry.templateId,
|
|
454
470
|
entry.paneId,
|
|
455
471
|
].filter((value): value is string => !!value).map((value) => normalizeLookupToken(value));
|
|
@@ -459,7 +475,9 @@ function scorePaneCatalogEntry(entry: PaneCatalogEntry, query: string): CatalogM
|
|
|
459
475
|
const flags = flagText(entry);
|
|
460
476
|
const wholeQuery = query.toLowerCase().trim().replace(/\s+/g, " ");
|
|
461
477
|
const called = identityFields(entry);
|
|
462
|
-
|
|
478
|
+
// A word that opens one case of the function (CTM's `VX`) is typed as its code is.
|
|
479
|
+
const codes = [entry.token, entry.shortcut, ...entry.aliases, ...entry.capability.opens?.flatMap((opening) => opening.words) ?? []]
|
|
480
|
+
.filter((value): value is string => !!value).map((value) => normalizeLookupToken(value));
|
|
463
481
|
|
|
464
482
|
let score = containsPhrase(`${named} ${flags}`, wholeQuery) ? 12 : 0;
|
|
465
483
|
// A query that is one of the function's own keywords ("hedge" for OSA) beats one found inside a
|
|
@@ -237,8 +237,11 @@ export const FUNCTION_HELP: Readonly<Record<string, FunctionHelp>> = {
|
|
|
237
237
|
summary: "Screen covered stocks on valuation, growth, margins, returns on capital, leverage, liquidity, volatility, technicals, float and ownership, short interest, insider activity and 13F holders, then rank the matches by any metric. "
|
|
238
238
|
+ "ATR% is the 14-session average true range as a percent of the last close. IV rank is a rank, not an IV percentile: 0 is the lowest 30-day implied volatility of the past 52 weeks and 100 the highest. IV percentile, IV30 change in vol points, HV20 and HV rank screen premium to sell. "
|
|
239
239
|
+ "Technical fields read the last completed session: RSI 14, price vs SMA 20, 50 and 200, trading days since a MACD or golden cross and since a new 20-day or 52-week high or low, and Bollinger width percentile (0 is a six-month squeeze). "
|
|
240
|
-
+ "ROIC, FCF yield, net debt / EBITDA, debt / equity and the revenue and EPS CAGRs read FA's bases, and forward growth EE's consensus; N/M where FA prints it.
|
|
241
|
-
|
|
240
|
+
+ "ROIC, FCF yield, net debt / EBITDA, debt / equity and the revenue and EPS CAGRs read FA's bases, and forward growth EE's consensus; N/M where FA prints it. "
|
|
241
|
+
+ "Classic scores: Piotroski F, Altman Z, the Graham number and Lynch fair value with their upside, Greenblatt's Magic Formula rank, the RS rating, years of profit, revenue and dividend growth, and S&P 500 and Dow membership. "
|
|
242
|
+
+ "Grades: Value, Growth, Profitability, Momentum and Revisions, F to A+, each ranked within the sector, and their equal-weighted 1-5 composite labelled Top, Strong, Neutral, Weak or Bottom. "
|
|
243
|
+
+ "Ideas holds ready technical screens, Value, Quality and GARP, screens on the classic scores and Top grades. The pane menu saves the matches to a watchlist.",
|
|
244
|
+
usage: ["EQS", "gloom fn EQS --preset golden-cross", "gloom fn EQS --preset quality", "gloom fn EQS --preset magic-formula", "gloom fn EQS --preset top-grades"],
|
|
242
245
|
keys: [key("a", "dd criterion"), key("m", "etric"), key("t", "check ticker"), key("s", "ave screen"), key("o", "pen research")],
|
|
243
246
|
data: same("Daily snapshot, statements as filed"),
|
|
244
247
|
bloomberg: ["EQS"],
|
|
@@ -353,8 +356,8 @@ export const FUNCTION_HELP: Readonly<Record<string, FunctionHelp>> = {
|
|
|
353
356
|
bloomberg: [],
|
|
354
357
|
},
|
|
355
358
|
MDAY: {
|
|
356
|
-
summary: "Does this name care about CPI day? Its average move on CPI, jobs report and FOMC days against a normal day, the average signed move and share of up days, and the move on every release day.",
|
|
357
|
-
usage: ["MDAY SPY"],
|
|
359
|
+
summary: "Does this name care about CPI day? Its average move on CPI, jobs report and FOMC days against a normal day, the average signed move and share of up days, and the move on every release day. Takes a FRED series too (FRED:T10Y2Y), whose moves in a rate or spread read in basis points.",
|
|
360
|
+
usage: ["MDAY SPY", "MDAY FRED:T10Y2Y"],
|
|
358
361
|
keys: [],
|
|
359
362
|
data: DAILY_CLOSES,
|
|
360
363
|
bloomberg: [],
|
|
@@ -1039,7 +1042,7 @@ export const FUNCTION_HELP: Readonly<Record<string, FunctionHelp>> = {
|
|
|
1039
1042
|
usage: ["CDS", "CDS F", "gloom fn CDS --sort 1m", "gloom fn CDS F --csv --section daily"],
|
|
1040
1043
|
keys: [OPEN, STEP],
|
|
1041
1044
|
data: same("Delayed, as trades are disseminated"),
|
|
1042
|
-
bloomberg: ["CDS"],
|
|
1045
|
+
bloomberg: ["CDS", "CDSW"],
|
|
1043
1046
|
},
|
|
1044
1047
|
CDX: {
|
|
1045
1048
|
summary: "CDX IG, HY and EM with iTraxx Main and Crossover on the run: the 5Y level, 1D, 1W and 1M moves, 1Y percentile and the day's print count. IG and iTraxx in spread, HY and EM in price. Naming an index opens the board on it, and `fn` adds its daily history. Sovereign CDS is the other tab.",
|
|
@@ -575,10 +575,10 @@ function statisticsEntries(stats: NonNullable<HeadlessSeriesResult["stats"]>): H
|
|
|
575
575
|
|
|
576
576
|
function renderBundle(
|
|
577
577
|
definition: HeadlessPaneDefinition,
|
|
578
|
-
|
|
578
|
+
sections: readonly HeadlessBundleSection[],
|
|
579
579
|
): string[] {
|
|
580
580
|
// A locked table is named once, on the Pro line, not under each heading.
|
|
581
|
-
return
|
|
581
|
+
return sections.filter((section) => !isLockedSection(section)).flatMap((section, index) => [
|
|
582
582
|
...(index > 0 ? [""] : []),
|
|
583
583
|
// A section with no title is its rows, or its empty message, alone.
|
|
584
584
|
...(section.title ? [renderSection(section.textTitle ?? section.title)] : []),
|
|
@@ -920,10 +920,11 @@ export function renderHeadlessPaneText(
|
|
|
920
920
|
case "rows": {
|
|
921
921
|
const rowsResult = result as HeadlessRowsResult;
|
|
922
922
|
lines.push(renderRows(rowsResult.textRows ?? rowsResult.rows, rowsResult.textColumns ?? rowsResult.columns, definition.columns, rowsResult.empty));
|
|
923
|
+
if (rowsResult.textSections?.length) lines.push("", ...renderBundle(definition, rowsResult.textSections));
|
|
923
924
|
break;
|
|
924
925
|
}
|
|
925
926
|
case "bundle":
|
|
926
|
-
lines.push(...renderBundle(definition, result as HeadlessBundleResult));
|
|
927
|
+
lines.push(...renderBundle(definition, (result as HeadlessBundleResult).sections));
|
|
927
928
|
break;
|
|
928
929
|
case "series":
|
|
929
930
|
lines.push(...renderSeries(result as HeadlessSeriesResult));
|
|
@@ -11,6 +11,7 @@ import { applyChartComposerCapabilityOptions } from "../../plugins/builtin/chart
|
|
|
11
11
|
import { parseChartSpec } from "../../plugins/builtin/chart-composer/chart-spec";
|
|
12
12
|
import { normalizeTickerInput } from "../../tickers/search";
|
|
13
13
|
import { slugifyName } from "../../utils/slugify";
|
|
14
|
+
import { fredSeriesArgument } from "../../series/fred-argument";
|
|
14
15
|
import { listCoinNotes, ListingArgError, listingInstrument, listingReadNotes, resolveCliListing, usListingsOnlyMessage } from "../listing-arg";
|
|
15
16
|
import { uncoveredInstrumentKind, uncoveredInstrumentMessage } from "../../tickers/instrument-coverage";
|
|
16
17
|
import { uncoveredInstrumentCommand } from "../uncovered-instrument";
|
|
@@ -22,6 +23,8 @@ import { readTerminalCodeArg } from "../../tickers/company-name-listing";
|
|
|
22
23
|
import { unknownBloombergMarket } from "../../tickers/terminal-codes";
|
|
23
24
|
import { notATickerWords } from "../company-name-hint";
|
|
24
25
|
import type { MarketContext } from "../types";
|
|
26
|
+
import { findWatchlist } from "../helpers";
|
|
27
|
+
import { readWatchlistArgument } from "../../portfolio/collection-name";
|
|
25
28
|
import {
|
|
26
29
|
buildPaneFunctionLookup,
|
|
27
30
|
buildTemplateContext,
|
|
@@ -141,13 +144,54 @@ export function parsePaneFunctionArgsFor(
|
|
|
141
144
|
args: string[],
|
|
142
145
|
globalOptions: { limit?: number; tail?: number } = {},
|
|
143
146
|
): ParsedPaneFunctionArgs {
|
|
144
|
-
const parsed = parsePaneFunctionArgs(args, globalOptions);
|
|
147
|
+
const parsed = withOpeningWord(registry, withKeywordNote(registry, parsePaneFunctionArgs(args, globalOptions)));
|
|
145
148
|
const found = parsed.target ? findPaneFunction(registry, parsed.target) : null;
|
|
146
149
|
if (!found?.pane) return parsed;
|
|
147
150
|
const capability = getPaneFunctionCapability(found.template, found.pane);
|
|
148
151
|
if (!capability.options.some((option) => (option.valueWords ?? 1) > 1 || option.list)) return parsed;
|
|
149
|
-
|
|
152
|
+
const reparsed = parsePaneFunctionArgs(args, globalOptions, (key) => findCapabilityOption(capability, key)?.valueWords ?? 1,
|
|
150
153
|
(key) => findCapabilityOption(capability, key)?.list === true);
|
|
154
|
+
return { ...reparsed, target: parsed.target, arg: reparsed.target === parsed.target ? reparsed.arg : parsed.arg,
|
|
155
|
+
...(parsed.listingNotes ? { listingNotes: parsed.listingNotes } : {}) };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* A word that opens no function by its code but names one case of a function
|
|
160
|
+
* (`discovery.opens`: `VX`, `vix futures`) runs that function on the case's
|
|
161
|
+
* argument, and says so: `fn VX` is `fn CTM VIX`. A word typed with an
|
|
162
|
+
* argument of its own keeps it.
|
|
163
|
+
*/
|
|
164
|
+
function withOpeningWord(registry: PaneFunctionCatalog, parsed: ParsedPaneFunctionArgs): ParsedPaneFunctionArgs {
|
|
165
|
+
if (!parsed.target || findPaneFunction(registry, parsed.target)) return parsed;
|
|
166
|
+
const wanted = normalizeLookupToken(parsed.target);
|
|
167
|
+
for (const template of registry.paneTemplates.values()) {
|
|
168
|
+
const pane = registry.panes.get(template.paneId);
|
|
169
|
+
const opens = pane ? getHeadlessPaneDefinition(template, pane)?.discovery?.opens : undefined;
|
|
170
|
+
const opening = opens?.find((entry) => entry.words.some((word) => normalizeLookupToken(word) === wanted));
|
|
171
|
+
if (!pane || !opening) continue;
|
|
172
|
+
const code = paneFunctionCode(template, pane);
|
|
173
|
+
const arg = parsed.arg.trim() || opening.argument;
|
|
174
|
+
return { ...parsed, target: code, arg, listingNotes: [...parsed.listingNotes ?? [], `${parsed.target} opened ${code} ${arg}, ${template.label}.`] };
|
|
175
|
+
}
|
|
176
|
+
return parsed;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* A word that opens a function as one of its keywords rather than its code or
|
|
181
|
+
* name (`fn VVIX` opens VIX, whose board lists VVIX) says which function it
|
|
182
|
+
* opened, so the report is never read as one of its own.
|
|
183
|
+
*/
|
|
184
|
+
function withKeywordNote(registry: PaneFunctionCatalog, parsed: ParsedPaneFunctionArgs): ParsedPaneFunctionArgs {
|
|
185
|
+
const found = parsed.target ? findPaneFunction(registry, parsed.target) : null;
|
|
186
|
+
if (!found?.pane || !found.template) return parsed;
|
|
187
|
+
const { template, pane } = found;
|
|
188
|
+
const wanted = normalizeLookupToken(parsed.target);
|
|
189
|
+
const headless = getHeadlessPaneDefinition(template, pane);
|
|
190
|
+
const names = [template.shortcut?.prefix, ...template.shortcut?.aliases ?? [], template.id, template.label, pane.id, pane.name,
|
|
191
|
+
headless?.discovery?.id, ...headless?.discovery?.aliases ?? []];
|
|
192
|
+
if (names.some((name) => name && normalizeLookupToken(name) === wanted)) return parsed;
|
|
193
|
+
const code = paneFunctionCode(template, pane);
|
|
194
|
+
return { ...parsed, listingNotes: [...parsed.listingNotes ?? [], `${parsed.target} opened ${code}, ${template.label}.`] };
|
|
151
195
|
}
|
|
152
196
|
|
|
153
197
|
/**
|
|
@@ -175,6 +219,12 @@ export async function applyListingArgument(
|
|
|
175
219
|
if (!(takesOneTicker || takesList) || getPaneFunctionCapability(found.template, found.pane).options.some((option) => option.key === "exchange")) {
|
|
176
220
|
return args;
|
|
177
221
|
}
|
|
222
|
+
// A watchlist's name stands for its symbols, as saved (`fn SIW HY3`).
|
|
223
|
+
const watchlist = takesList ? await watchlistArgument(args.arg, context, headless?.argument.maximum) : null;
|
|
224
|
+
if (watchlist) args = { ...args, arg: watchlist.symbols.join(", ") };
|
|
225
|
+
// A function that reads FRED series (MDAY) gets FRED:T10Y2Y as typed; any other is told it is no listing.
|
|
226
|
+
const fred = takesOneTicker && headless?.fredSeriesArgument && typeof args.options.exchange !== "string" ? fredSeriesArgument(args.arg) : null;
|
|
227
|
+
if (fred) return { ...args, arg: `FRED:${fred}` };
|
|
178
228
|
// A ticker with spaces is no listing, unless it is a terminal's code for one ("JPM US Equity"). A company's name
|
|
179
229
|
// typed there (`fn RDCF "Palantir Technologies"`) stops before a report of dashes is drawn, as `quote` words a
|
|
180
230
|
// name that is no ticker, with the company search finds for it.
|
|
@@ -254,6 +304,7 @@ export async function applyListingArgument(
|
|
|
254
304
|
}
|
|
255
305
|
notes.push(...answers.map((answer) => `${answer.message} ${answer.details.replaceAll("\n", " ")}`));
|
|
256
306
|
}
|
|
307
|
+
notes.unshift(...watchlist?.notes ?? []);
|
|
257
308
|
// One listing's notes come with its choice note; a list's are said here, with a coin's code read as a listing
|
|
258
309
|
// (CORR RIOT,BTC: BTC is the Grayscale fund) as `quote BTC` says it.
|
|
259
310
|
if (listings.length > 1) notes.unshift(...listings.flatMap(listingReadNotes), ...await listCoinNotes(listings, context));
|
|
@@ -266,6 +317,28 @@ export async function applyListingArgument(
|
|
|
266
317
|
};
|
|
267
318
|
}
|
|
268
319
|
|
|
320
|
+
/**
|
|
321
|
+
* The symbols of the watchlist a list argument names (case aside), as saved,
|
|
322
|
+
* at most the function's `maximum` of them, with the note that says the name
|
|
323
|
+
* was read as that watchlist (`readWatchlistArgument`). Null when the
|
|
324
|
+
* argument names no watchlist, or one with nothing in it.
|
|
325
|
+
*/
|
|
326
|
+
async function watchlistArgument(
|
|
327
|
+
arg: string,
|
|
328
|
+
context: MarketContext,
|
|
329
|
+
maximum: number | undefined,
|
|
330
|
+
): Promise<{ symbols: string[]; notes: string[] } | null> {
|
|
331
|
+
if (/[,;\t\n]/.test(arg)) return null;
|
|
332
|
+
const watchlist = findWatchlist(context.config, arg);
|
|
333
|
+
if (!watchlist) return null;
|
|
334
|
+
const symbols = (await context.store.loadAllTickers())
|
|
335
|
+
.filter((ticker) => ticker.metadata.watchlists.includes(watchlist.id))
|
|
336
|
+
.map((ticker) => ticker.metadata.ticker);
|
|
337
|
+
if (symbols.length === 0) return null;
|
|
338
|
+
const read = readWatchlistArgument(arg, watchlist, symbols, maximum);
|
|
339
|
+
return { symbols: read.symbols, notes: [read.note] };
|
|
340
|
+
}
|
|
341
|
+
|
|
269
342
|
/**
|
|
270
343
|
* `--section` picks one table of a report's `--csv` or `--ndjson` output. A
|
|
271
344
|
* function that has a `section` option of its own (CALLS: which part of a
|
package/src/cli/quote-answer.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { currencyCodeNote } from "./currency-hints";
|
|
|
10
10
|
import { describeSuggestion, suggestListing, suggestUsTicker, type ListingSuggestion } from "./listing-suggestion";
|
|
11
11
|
import { indexRootAlsoLine, indexRootTryLine } from "./index-roots";
|
|
12
12
|
import { indexRootFor } from "../tickers/index-roots";
|
|
13
|
+
import { serviceMarkedListing } from "../tickers/company-name-listing";
|
|
13
14
|
import { treasuryYieldLine, treasuryYieldTenor } from "./treasury-yields";
|
|
14
15
|
import { knownGapForTicker } from "./known-gaps";
|
|
15
16
|
import {
|
|
@@ -21,6 +22,7 @@ import {
|
|
|
21
22
|
loadBareVenues,
|
|
22
23
|
notTradedMessage,
|
|
23
24
|
oneWordCompanyName,
|
|
25
|
+
parseListingArg,
|
|
24
26
|
quoteBareListing,
|
|
25
27
|
serviceNamedCompany,
|
|
26
28
|
type ListingArg,
|
|
@@ -106,6 +108,13 @@ export async function answerQuote(
|
|
|
106
108
|
// HCI.L is HCI on LSE written with a vendor's suffix: one that does not trade there says so as HCI:LSE does.
|
|
107
109
|
const suffixed = await notTradedOnSuffixVenue(listing, market);
|
|
108
110
|
if (suffixed) return { result, listing, failure: { message: suffixed, oneLine: suffixed }, notes: [] };
|
|
111
|
+
// A bare index root the service marks its index with (VIX, ^VIX on CXI) is that index, read at once: the company
|
|
112
|
+
// name search below would quote it, read the crypto board and come to the same listing a second later.
|
|
113
|
+
const marked = root && !listing.exchange && listing.typed ? await serviceMarkedListing(market.dataProvider, listing.typed, root.symbol) : null;
|
|
114
|
+
const key = marked ? marked.exchange ? `${marked.symbol}:${marked.exchange}` : marked.symbol : null;
|
|
115
|
+
const index = key ? await answerNamedListing({ ...parseListingArg(key),
|
|
116
|
+
readAs: `Read "${listing.typed!.trim()}" as ${key} (${marked!.name}).`, readFromName: true }, market, request, refresh, datesChangeBasis) : null;
|
|
117
|
+
if (index) return index;
|
|
109
118
|
// A word the service marks as a company's name is that company, before the symbol is read on its listings abroad.
|
|
110
119
|
const named = !listing.exchange && listing.typed ? await serviceNamedCompany(listing.typed, market) : null;
|
|
111
120
|
const meant = named ? await answerNamedListing(named, market, request, refresh, datesChangeBasis) : null;
|
package/src/cli/symbol-list.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { fstatSync } from "fs";
|
|
|
3
3
|
import { splitSymbolArgLines, splitSymbolWords, stripStrayEdges, uniqueSymbols } from "./symbol-args";
|
|
4
4
|
import { foldTypedText } from "../utils/typed-text";
|
|
5
5
|
import { hasDecimalCommas, isFigure, isJunkCell, isNumberCell, protectFigureCommas, restoreFigureCommas } from "./symbol-cells";
|
|
6
|
+
import { endsInLegalForm, readTerminalListingCode, unknownBloombergMarket } from "../tickers/terminal-codes";
|
|
6
7
|
|
|
7
8
|
/** Header cells that name a spreadsheet's symbol column, compared without case, spaces or punctuation. */
|
|
8
9
|
const SYMBOL_HEADERS = new Set(["symbol", "symbols", "ticker", "tickers", "code", "stockcode", "securitycode", "instrument"]);
|
|
@@ -144,6 +145,54 @@ function looksLikeSymbol(cell: string): boolean {
|
|
|
144
145
|
return SYMBOL_TOKEN.test(cell) && !isNumberCell(cell);
|
|
145
146
|
}
|
|
146
147
|
|
|
148
|
+
/**
|
|
149
|
+
* A cell that is a terminal's code for one listing, spaces and all: `CZR US
|
|
150
|
+
* Equity`, `1128 HK Equity`, `VOD LN`. A company's name before its legal form
|
|
151
|
+
* (`SAP SE`, `SIEMENS AG`) is a name, though SE and AG are market codes too.
|
|
152
|
+
*/
|
|
153
|
+
function isTerminalCodeCell(cell: string): boolean {
|
|
154
|
+
return /\s/.test(cell.trim()) && !endsInLegalForm(cell)
|
|
155
|
+
&& (readTerminalListingCode(cell) != null || unknownBloombergMarket(cell) != null);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** A numeric exchange code as a grid holds one (`2007`, `0700`, `600519`): Hong Kong, Tokyo, Shanghai. Shorter is a quantity. */
|
|
159
|
+
const NUMERIC_CODE = /^\d{4,6}$/;
|
|
160
|
+
|
|
161
|
+
/** What a sheet holds beside its symbols that reads like one: a rating, a side, a flag. */
|
|
162
|
+
const VALUE_WORD = /^(?:buy|sell|hold|long|short|neutral|overweight|underweight|outperform|underperform|yes|no|true|false|none|total)$/i;
|
|
163
|
+
|
|
164
|
+
/** A cell a grid of symbols can hold: a symbol, never a rating or a side (`HOLD`, `BUY`). */
|
|
165
|
+
function isGridSymbol(cell: string): boolean {
|
|
166
|
+
return looksLikeSymbol(cell) && !VALUE_WORD.test(cell.trim());
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* The columns after the first that hold a symbol with a letter in it (or a
|
|
171
|
+
* terminal's code), and nothing that is a value: a whole number there is a
|
|
172
|
+
* numeric exchange code among tickers (`2007` beside `AAL`), not a value
|
|
173
|
+
* beside its symbol, whose column holds numbers alone (`ED 2582`) or values
|
|
174
|
+
* (`HOLD`, `100`).
|
|
175
|
+
*/
|
|
176
|
+
function symbolColumns(rows: readonly string[][]): Set<number> {
|
|
177
|
+
const columns = new Set<number>();
|
|
178
|
+
const values = new Set<number>();
|
|
179
|
+
for (const cells of rows) {
|
|
180
|
+
cells.forEach((cell, index) => {
|
|
181
|
+
if (index === 0 || !cell) return;
|
|
182
|
+
if (VALUE_WORD.test(cell.trim()) || (isFigure(cell) && !NUMERIC_CODE.test(cell.trim()))) values.add(index);
|
|
183
|
+
else if (isTerminalCodeCell(cell) || (looksLikeSymbol(cell) && /\p{L}/u.test(cell))) columns.add(index);
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
for (const index of values) columns.delete(index);
|
|
187
|
+
return columns;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** A grid of numeric exchange codes alone, two or more to a row (`0700 9988`): every cell is a listing. */
|
|
191
|
+
function numericCodeGrid(rows: readonly string[][]): boolean {
|
|
192
|
+
return rows.some((cells) => cells.filter(Boolean).length > 1)
|
|
193
|
+
&& rows.every((cells) => cells.every((cell) => !cell || NUMERIC_CODE.test(cell.trim())));
|
|
194
|
+
}
|
|
195
|
+
|
|
147
196
|
/** How many cells a table's ignored-cells note names before it counts the rest. */
|
|
148
197
|
const IGNORED_PREVIEW = 8;
|
|
149
198
|
|
|
@@ -198,8 +247,11 @@ export function parseSymbolText(text: string): SymbolText {
|
|
|
198
247
|
const figures = cleaned.some((cells) => cells.some((cell, index) => index > 0 && isFigure(cell)));
|
|
199
248
|
// Lines split by spaces alone are entries, unless figures sit beside the symbols.
|
|
200
249
|
if (!delimited && !figures) return { symbols: records.map((cells) => cells.join(" ")), ignored: [], entries: true };
|
|
201
|
-
|
|
202
|
-
|
|
250
|
+
// A grid of symbols: a terminal's code is one cell (`CZR US Equity`), and so is a numeric code among tickers (`2007`).
|
|
251
|
+
const codes = symbolColumns(cleaned);
|
|
252
|
+
const grid = numericCodeGrid(cleaned) || cleaned.every((cells) => cells.every((cell, index) => (
|
|
253
|
+
!cell || isJunkCell(cell) || isTerminalCodeCell(cell)
|
|
254
|
+
|| (isGridSymbol(cell) && (index === 0 || !isFigure(cell) || (NUMERIC_CODE.test(cell) && codes.has(index))))
|
|
203
255
|
)));
|
|
204
256
|
if (grid) return { symbols: records.flat().filter(Boolean), ignored: [] };
|
|
205
257
|
// Names split by semicolons or commas, with no figures: one pasted line, or one name a line with a separator left
|
package/src/cli/symbol-rows.ts
CHANGED
|
@@ -16,7 +16,7 @@ import {
|
|
|
16
16
|
type CliTickerOptions,
|
|
17
17
|
type CliTickerResolution,
|
|
18
18
|
} from "./ticker-resolution";
|
|
19
|
-
import { isUsSymbolVenue, LOOKUP_TIMEOUT_MS, tickerChangeLine, tickerChangeSymbol } from "../tickers/ticker-changes";
|
|
19
|
+
import { isUsSymbolVenue, LOOKUP_TIMEOUT_MS, movedAwayChange, tickerChangeLine, tickerChangeSymbol, type MovedTickerChange } from "../tickers/ticker-changes";
|
|
20
20
|
import { isVenueAbroad } from "../tickers/listing-fate";
|
|
21
21
|
import { sameCompany } from "../tickers/company-name";
|
|
22
22
|
import { tickerHasListingSuffix } from "../sources/listing-symbols";
|
|
@@ -283,9 +283,18 @@ function choiceNeeded(
|
|
|
283
283
|
: recent ? `${symbol} matched ${label}, ${sameCompany(resolution.ticker.metadata.name, history?.company) ? "that company's old line" : "another company's listing"}`
|
|
284
284
|
: null);
|
|
285
285
|
if (!found) return null;
|
|
286
|
+
// The line stopped trading as its company moved on (Rite Aid to RADCQ): one line says both.
|
|
287
|
+
const moved = resolution.ended ? movedAwayChange(resolution.change) : null;
|
|
288
|
+
if (moved) return { message: stoppedTradingLine(symbol, moved), successor: moved.tradesAs };
|
|
286
289
|
return { message: history ? `${history.note}; ${found}` : found, successor: history?.successor ?? null };
|
|
287
290
|
}
|
|
288
291
|
|
|
292
|
+
/** "RAD stopped trading 2023-10-17, now RADCQ", the company named first when known: a symbol whose line ended as its company moved. */
|
|
293
|
+
function stoppedTradingLine(symbol: string, moved: MovedTickerChange): string {
|
|
294
|
+
const who = moved.issuer ? `${moved.issuer} (${symbol})` : symbol;
|
|
295
|
+
return `${who} stopped trading ${moved.changes[0]!.date}, now ${moved.tradesAs}`;
|
|
296
|
+
}
|
|
297
|
+
|
|
289
298
|
/** The plain no-match answer, which a "Not found" line already says. */
|
|
290
299
|
export const NO_MATCH = /^No ticker match found for /;
|
|
291
300
|
|
|
@@ -404,6 +413,7 @@ export async function addSymbols({
|
|
|
404
413
|
reject,
|
|
405
414
|
add,
|
|
406
415
|
onRetry,
|
|
416
|
+
onProgress,
|
|
407
417
|
retry,
|
|
408
418
|
askWhenAmbiguous,
|
|
409
419
|
failure,
|
|
@@ -413,6 +423,8 @@ export async function addSymbols({
|
|
|
413
423
|
dataProvider: DataProvider;
|
|
414
424
|
/** Told when requests failed and the symbols that failed are about to be looked up again. */
|
|
415
425
|
onRetry?: (count: number, waitMs: number) => void;
|
|
426
|
+
/** Told as the symbols are looked up, with how many are and how many there are. */
|
|
427
|
+
onProgress?: (looked: number, total: number) => void;
|
|
416
428
|
/** The command that adds one listing, for the choices a failure names. */
|
|
417
429
|
retry?: (key: string) => string;
|
|
418
430
|
/** Why a symbol cannot be added before it is looked up, such as the cash line; null when it can. */
|
|
@@ -430,7 +442,7 @@ export async function addSymbols({
|
|
|
430
442
|
}): Promise<SymbolRow[]> {
|
|
431
443
|
const staged = new StagedTickerRepository(store);
|
|
432
444
|
const rejected = new Map(symbols.map((input) => [input, reject?.(input) ?? null] as const));
|
|
433
|
-
const resolutions = await resolveTickersForCli(symbols.filter((input) => !rejected.get(input)), staged, dataProvider, exchange, { onRetry, retry, askWhenAmbiguous });
|
|
445
|
+
const resolutions = await resolveTickersForCli(symbols.filter((input) => !rejected.get(input)), staged, dataProvider, exchange, { onRetry, onProgress, retry, askWhenAmbiguous });
|
|
434
446
|
const resolved = new Map(resolutions.map((resolution) => [resolution.input, resolution] as const));
|
|
435
447
|
const rows: SymbolRow[] = [];
|
|
436
448
|
// Listings a symbol of this list was added to, which a later symbol's choice must not drop.
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { logFailure } from "../utils/log-failure";
|
|
2
|
+
import { ApiRequestError, wasAskedTwice } from "../api-client/errors";
|
|
3
|
+
import { isNoSourceAnswer, isProviderBusy, SEARCH_BUSY_MESSAGE } from "../sources/provider-errors";
|
|
2
4
|
import type { DataProvider } from "../types/data-provider";
|
|
3
5
|
import type { Quote } from "../types/financials";
|
|
4
6
|
import type { InstrumentSearchResult } from "../types/instrument";
|
|
@@ -103,6 +105,13 @@ export interface CliTicker {
|
|
|
103
105
|
* still to be asked.
|
|
104
106
|
*/
|
|
105
107
|
otherVenues: string[] | null;
|
|
108
|
+
/**
|
|
109
|
+
* A bare US-style symbol whose quote could not be read (the service refused
|
|
110
|
+
* or failed it): whether the listing still trades is unknown, so an add
|
|
111
|
+
* cannot tell a live match from a dead one (`choiceNeeded`). A list looks
|
|
112
|
+
* it up again with the symbols that failed.
|
|
113
|
+
*/
|
|
114
|
+
unchecked?: true;
|
|
106
115
|
}
|
|
107
116
|
|
|
108
117
|
export interface CliTickerOptions {
|
|
@@ -226,7 +235,8 @@ export async function resolveCliTicker(
|
|
|
226
235
|
// A saved listing names what lists there; the issuer that left, if it is that one, is its old line.
|
|
227
236
|
if (listing.saved) {
|
|
228
237
|
const saved = options.refreshName === false ? { ticker: listing.saved, quote: null } : await nameFromListingQuote(listing.saved, store, dataProvider, null);
|
|
229
|
-
|
|
238
|
+
// A saved line that stopped trading is the old line, not something listed under the symbol now.
|
|
239
|
+
return withChange({ ...withEnded(saved, read), ...uncheckedIf(listing, saved) }, saved.quote ? tradingListing(saved.quote) : { name: saved.ticker.metadata.name });
|
|
230
240
|
}
|
|
231
241
|
// A listing its own quote names is found as `quote` finds it, the quote cache first, so a busy search never
|
|
232
242
|
// blocks a listing the quote knows. Search is asked after, for the venues a note names, and may fail.
|
|
@@ -287,11 +297,12 @@ export async function resolveCliTicker(
|
|
|
287
297
|
}
|
|
288
298
|
if (resolved.kind === "local") {
|
|
289
299
|
const local = options.refreshName === false ? { ticker: resolved.ticker, quote: null } : await nameFromListingQuote(resolved.ticker, store, dataProvider, bareQuote);
|
|
290
|
-
return withChange({ ...withEnded(local, [...read, ...bareNote ? [bareNote] : []]), otherVenues: bareNote ? bareVenues : null }, { name: local.ticker.metadata.name });
|
|
300
|
+
return withChange({ ...withEnded(local, [...read, ...bareNote ? [bareNote] : []]), otherVenues: bareNote ? bareVenues : null, ...uncheckedIf(listing, local) }, local.quote ? tradingListing(local.quote) : { name: local.ticker.metadata.name });
|
|
291
301
|
}
|
|
292
302
|
|
|
293
303
|
const { ticker, created } = await upsertTickerFromSearchResult(store, resolved.result);
|
|
294
|
-
|
|
304
|
+
// A listing saved before (by an earlier look at a list) is read again too: its quote says whether it still trades.
|
|
305
|
+
const named = created || !bareQuote ? await nameFromListingQuote(ticker, store, dataProvider, bareQuote) : { ticker, quote: bareQuote };
|
|
295
306
|
const saved = savedListingName(named.ticker);
|
|
296
307
|
const others = resolved.otherListings?.map((key) => parsePublicTickerKey(key).exchange ?? key) ?? [];
|
|
297
308
|
// Several companies' listings name the company it went to and theirs; one company's name its other venues.
|
|
@@ -307,9 +318,15 @@ export async function resolveCliTicker(
|
|
|
307
318
|
notes: [...read, venueNote, ended].filter((note): note is string => !!note),
|
|
308
319
|
ended,
|
|
309
320
|
otherVenues: bareNote ? bareVenues : others,
|
|
321
|
+
...uncheckedIf(listing, named),
|
|
310
322
|
}, current);
|
|
311
323
|
}
|
|
312
324
|
|
|
325
|
+
/** `unchecked` for a bare US-style symbol whose quote could not be read (`CliTicker.unchecked`). */
|
|
326
|
+
function uncheckedIf(listing: Pick<CliListing, "symbol" | "exchange">, read: { failed?: true }): { unchecked?: true } {
|
|
327
|
+
return read.failed && !listing.exchange && tickerChangeSymbol(listing.symbol) ? { unchecked: true } : {};
|
|
328
|
+
}
|
|
329
|
+
|
|
313
330
|
/**
|
|
314
331
|
* The listing a symbol's own quote names, asked as `quote` asks it (the quote
|
|
315
332
|
* cache first): a priced quote answering for that symbol, on the venue named
|
|
@@ -399,22 +416,49 @@ async function nameFromListingQuote(
|
|
|
399
416
|
store: AppTickerRepositoryPort,
|
|
400
417
|
dataProvider: DataProvider,
|
|
401
418
|
known: Quote | null,
|
|
402
|
-
): Promise<{ ticker: TickerRecord; quote: Quote | null }> {
|
|
419
|
+
): Promise<{ ticker: TickerRecord; quote: Quote | null; failed?: true }> {
|
|
403
420
|
const { metadata } = ticker;
|
|
404
421
|
try {
|
|
405
422
|
const quote = known ?? await dataProvider.getQuote(metadata.ticker, metadata.exchange);
|
|
406
423
|
const name = quote.name?.trim();
|
|
407
|
-
// A quote that names no listing may be another venue's line served from cache.
|
|
424
|
+
// A quote that names no listing may be another venue's line served from cache. A bare US row (RAD, no
|
|
425
|
+
// venue) is asked with none, and its own quote names none when the line stopped trading.
|
|
408
426
|
const quoteExchange = canonicalExchange(quote.listingExchangeName || quote.exchangeName);
|
|
409
|
-
|
|
427
|
+
const ownExchange = canonicalExchange(metadata.exchange);
|
|
428
|
+
if (quoteExchange !== ownExchange || (!quoteExchange && !quote.delisting)) return { ticker, quote: null };
|
|
410
429
|
if (!name || name === metadata.name) return { ticker, quote };
|
|
411
430
|
const named: TickerRecord = { ...ticker, metadata: { ...metadata, name } };
|
|
412
431
|
await store.saveTicker(named);
|
|
413
432
|
return { ticker: named, quote };
|
|
414
|
-
} catch {
|
|
415
|
-
// Without a quote the catalogue name stands.
|
|
416
|
-
|
|
433
|
+
} catch (error) {
|
|
434
|
+
// Without a quote the catalogue name stands. Refused, whether the listing still trades is unknown; answered
|
|
435
|
+
// with an error of the listing's own, a later look would answer the same, so the match stands as it is.
|
|
436
|
+
return { ticker, quote: null, ...quoteRefused(error) ? { failed: true as const } : {} };
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* Whether a quote failed as the service refusing or not reaching it (a rate
|
|
442
|
+
* limit, an overload, a timeout, no connection), which a later look may get
|
|
443
|
+
* past. A failure the service gave for the listing itself (no quote for it, a
|
|
444
|
+
* 4xx, a source that failed it twice) is the listing's own: a symbol whose
|
|
445
|
+
* quote always errors costs no wait. What cannot be told apart is taken for
|
|
446
|
+
* a refusal, so a busy service never lets a line that stopped trading pass as
|
|
447
|
+
* one that trades.
|
|
448
|
+
*/
|
|
449
|
+
function quoteRefused(error: unknown): boolean {
|
|
450
|
+
if (isNoSourceAnswer(error)) return false;
|
|
451
|
+
for (let current = error, depth = 0; current && typeof current === "object" && depth < 5; depth += 1) {
|
|
452
|
+
if (current instanceof ApiRequestError) {
|
|
453
|
+
const { status } = current;
|
|
454
|
+
if (status === 408 || status === 429 || status === 503) return true;
|
|
455
|
+
if (status !== undefined && status >= 400 && status < 500) return false;
|
|
456
|
+
return !wasAskedTwice(current);
|
|
457
|
+
}
|
|
458
|
+
if (wasAskedTwice(current)) return false;
|
|
459
|
+
current = (current as { failure?: unknown }).failure ?? (current as { cause?: unknown }).cause;
|
|
417
460
|
}
|
|
461
|
+
return true;
|
|
418
462
|
}
|
|
419
463
|
|
|
420
464
|
export type CliTickerResolution =
|
|
@@ -435,9 +479,10 @@ const MARKET_OPERATION = /^(?:GET|POST) \/market\//;
|
|
|
435
479
|
/**
|
|
436
480
|
* Waits before each new look at the symbols that failed while requests were
|
|
437
481
|
* failing. The first outlasts the five seconds the router keeps an empty
|
|
438
|
-
* search answer
|
|
482
|
+
* search answer. Two, so a long add is done within a minute: what is still
|
|
483
|
+
* refused after them is named with the command that adds it.
|
|
439
484
|
*/
|
|
440
|
-
const RETRY_WAITS_MS = [6_000, 15_000
|
|
485
|
+
const RETRY_WAITS_MS = [6_000, 15_000];
|
|
441
486
|
|
|
442
487
|
/**
|
|
443
488
|
* Counts the data service's market requests that fail while it watches. A
|
|
@@ -466,16 +511,33 @@ function lookUpTickers(
|
|
|
466
511
|
symbols: readonly string[],
|
|
467
512
|
concurrency: number,
|
|
468
513
|
resolve: (symbol: string) => Promise<CliTicker>,
|
|
514
|
+
looked?: () => void,
|
|
469
515
|
): Promise<CliTickerResolution[]> {
|
|
470
516
|
return mapWithConcurrency(symbols, concurrency, async (input): Promise<CliTickerResolution> => {
|
|
471
517
|
try {
|
|
472
518
|
return { input, ...await resolve(input) };
|
|
473
519
|
} catch (error) {
|
|
474
520
|
return { input, error: error instanceof Error ? error : new Error(String(error)) };
|
|
521
|
+
} finally {
|
|
522
|
+
looked?.();
|
|
475
523
|
}
|
|
476
524
|
});
|
|
477
525
|
}
|
|
478
526
|
|
|
527
|
+
/**
|
|
528
|
+
* Whether a lookup failed as busy: a search no source answered in time
|
|
529
|
+
* ("Search is busy"), which gives up before its request fails, so the
|
|
530
|
+
* requests the service failed do not count it.
|
|
531
|
+
*/
|
|
532
|
+
function busyLookup(entry: CliTickerResolution): boolean {
|
|
533
|
+
return !!entry.error && (entry.error.message === SEARCH_BUSY_MESSAGE || isProviderBusy(entry.error));
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/** Whether a lookup is to be made again while requests fail: one that failed as refused, or a match whose quote was refused. */
|
|
537
|
+
function lookAgain(entry: CliTickerResolution): boolean {
|
|
538
|
+
return entry.error ? mayBeRefusal(entry.error) : entry.unchecked === true;
|
|
539
|
+
}
|
|
540
|
+
|
|
479
541
|
/**
|
|
480
542
|
* What a symbol of a list asks the sources for, so the whole list's searches
|
|
481
543
|
* and change lookups go out in batches first: a bare symbol searches its
|
|
@@ -520,16 +582,21 @@ export async function resolveTickersForCli(
|
|
|
520
582
|
retry,
|
|
521
583
|
askWhenAmbiguous,
|
|
522
584
|
onRetry,
|
|
585
|
+
onProgress,
|
|
523
586
|
retryWaitsMs = RETRY_WAITS_MS,
|
|
524
587
|
}: Pick<CliTickerOptions, "retry" | "askWhenAmbiguous"> & {
|
|
525
588
|
/** Told before each new look, with how many symbols and how long it waits first. */
|
|
526
589
|
onRetry?: (count: number, waitMs: number) => void;
|
|
590
|
+
/** Told as each symbol of the first look is settled, with how many are and how many there are. */
|
|
591
|
+
onProgress?: (looked: number, total: number) => void;
|
|
527
592
|
retryWaitsMs?: readonly number[];
|
|
528
593
|
} = {},
|
|
529
594
|
): Promise<CliTickerResolution[]> {
|
|
530
595
|
const plans = new Map(symbols.map((input) => [input, listLookupPlan(input, exchange)] as const));
|
|
596
|
+
let settled = 0;
|
|
597
|
+
const progress = onProgress ? () => onProgress(++settled, symbols.length) : undefined;
|
|
531
598
|
// Each look asks for its symbols' searches and changes in batches first.
|
|
532
|
-
const look = async (inputs: readonly string[], concurrency: number): Promise<Map<string, CliTickerResolution>> => {
|
|
599
|
+
const look = async (inputs: readonly string[], concurrency: number, looked?: () => void): Promise<Map<string, CliTickerResolution>> => {
|
|
533
600
|
const batched = await batchedListLookups(dataProvider, inputs.map((input) => plans.get(input)!));
|
|
534
601
|
const resolve = (symbol: string) => resolveCliTicker(symbol, store, batched.dataProvider, exchange, {
|
|
535
602
|
retry, askWhenAmbiguous, ownExchangeWins: true, changeGraceMs: LOOKUP_TIMEOUT_MS,
|
|
@@ -537,28 +604,30 @@ export async function resolveTickersForCli(
|
|
|
537
604
|
// Symbols whose searches were answered ask only for quotes, which go out together; the rest ask as before.
|
|
538
605
|
const answered = (input: string) => batched.answered(plans.get(input)!);
|
|
539
606
|
return new Map((await Promise.all([
|
|
540
|
-
lookUpTickers(inputs.filter(answered), ANSWERED_CONCURRENCY, resolve),
|
|
541
|
-
lookUpTickers(inputs.filter((input) => !answered(input)), concurrency, resolve),
|
|
607
|
+
lookUpTickers(inputs.filter(answered), ANSWERED_CONCURRENCY, resolve, looked),
|
|
608
|
+
lookUpTickers(inputs.filter((input) => !answered(input)), concurrency, resolve, looked),
|
|
542
609
|
])).flat().map((entry) => [entry.input, entry] as const));
|
|
543
610
|
};
|
|
544
611
|
const failedRequests = watchFailedRequests();
|
|
545
612
|
try {
|
|
546
|
-
const looked = await look(symbols, RESOLVE_CONCURRENCY);
|
|
613
|
+
const looked = await look(symbols, RESOLVE_CONCURRENCY, progress);
|
|
547
614
|
let lookups = symbols.map((input) => looked.get(input)!);
|
|
548
|
-
let failing = failedRequests.count() > 0;
|
|
615
|
+
let failing = failedRequests.count() > 0 || lookups.some(busyLookup);
|
|
549
616
|
for (const waitMs of retryWaitsMs) {
|
|
550
|
-
|
|
617
|
+
// A match whose quote was refused is looked at again too, so it gets the check a first look gives.
|
|
618
|
+
const failed = lookups.filter(lookAgain).map((entry) => entry.input);
|
|
551
619
|
if (!failing || failed.length === 0) break;
|
|
552
620
|
onRetry?.(failed.length, waitMs);
|
|
553
621
|
await new Promise((resolveWait) => setTimeout(resolveWait, waitMs));
|
|
554
622
|
const before = failedRequests.count();
|
|
555
623
|
const again = await look(failed, RETRY_CONCURRENCY);
|
|
556
624
|
lookups = lookups.map((entry) => again.get(entry.input) ?? entry);
|
|
557
|
-
failing = failedRequests.count() > before;
|
|
625
|
+
failing = failedRequests.count() > before || [...again.values()].some(busyLookup);
|
|
558
626
|
}
|
|
559
627
|
if (!failing) return lookups;
|
|
560
|
-
// Still refused after the last wait: a failure may only be the refusal, so none is called not found
|
|
561
|
-
|
|
628
|
+
// Still refused after the last wait: a failure may only be the refusal, so none is called not found,
|
|
629
|
+
// and a match whose quote was refused is not taken as trading.
|
|
630
|
+
return lookups.map((entry) => lookAgain(entry)
|
|
562
631
|
? { input: entry.input, error: new LookupUnansweredError(entry.input) }
|
|
563
632
|
: entry);
|
|
564
633
|
} finally {
|