opencandle 0.11.1 → 0.12.0
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/README.md +20 -24
- package/dist/analysts/contracts.js +0 -1
- package/dist/analysts/orchestrator.js +0 -1
- package/dist/cli-main.js +13 -7
- package/dist/cli-options.d.ts +4 -0
- package/dist/cli-options.js +33 -0
- package/dist/cli.js +8 -3
- package/dist/config.js +0 -1
- package/dist/doctor/cli-command.js +2 -1
- package/dist/doctor/render.js +0 -1
- package/dist/doctor/report.js +40 -11
- package/dist/gui/server/ask-user-bridge.d.ts +19 -0
- package/dist/gui/server/ask-user-bridge.js +55 -0
- package/dist/gui/server/automation-heartbeat.d.ts +25 -0
- package/dist/gui/server/automation-heartbeat.js +61 -0
- package/dist/gui/server/background-quotes.d.ts +39 -0
- package/dist/gui/server/background-quotes.js +71 -0
- package/dist/gui/server/chat-event-adapter.d.ts +16 -0
- package/dist/gui/server/chat-event-adapter.js +263 -0
- package/dist/gui/server/gui-session-manager.d.ts +2 -0
- package/dist/gui/server/gui-session-manager.js +4 -0
- package/dist/gui/server/http-routes.d.ts +69 -0
- package/dist/gui/server/http-routes.js +1008 -0
- package/dist/gui/server/invoke-tool.d.ts +47 -0
- package/dist/gui/server/invoke-tool.js +373 -0
- package/dist/gui/server/live-chat-event-adapter.d.ts +19 -0
- package/dist/gui/server/live-chat-event-adapter.js +206 -0
- package/dist/gui/server/local-session-coordinator.d.ts +26 -0
- package/dist/gui/server/local-session-coordinator.js +53 -0
- package/dist/gui/server/market-state-api.d.ts +138 -0
- package/dist/gui/server/market-state-api.js +355 -0
- package/dist/gui/server/model-setup.d.ts +64 -0
- package/dist/gui/server/model-setup.js +150 -0
- package/dist/gui/server/private-api-access.d.ts +6 -0
- package/dist/gui/server/private-api-access.js +53 -0
- package/dist/gui/server/projector.d.ts +49 -0
- package/dist/gui/server/projector.js +296 -0
- package/dist/gui/server/prompt-observation.d.ts +8 -0
- package/dist/gui/server/prompt-observation.js +43 -0
- package/dist/gui/server/quote-snapshot-store.d.ts +14 -0
- package/dist/gui/server/quote-snapshot-store.js +49 -0
- package/dist/gui/server/server.d.ts +1 -0
- package/dist/gui/server/server.js +259 -0
- package/dist/gui/server/session-actions.d.ts +60 -0
- package/dist/gui/server/session-actions.js +218 -0
- package/dist/gui/server/session-entry-wait.d.ts +27 -0
- package/dist/gui/server/session-entry-wait.js +129 -0
- package/dist/gui/server/session-list.d.ts +2 -0
- package/dist/gui/server/session-list.js +11 -0
- package/dist/gui/server/shutdown.d.ts +10 -0
- package/dist/gui/server/shutdown.js +29 -0
- package/dist/gui/server/tool-invoke-ack.d.ts +17 -0
- package/dist/gui/server/tool-invoke-ack.js +26 -0
- package/dist/gui/server/tool-metadata.d.ts +93 -0
- package/dist/gui/server/tool-metadata.js +148 -0
- package/dist/gui/server/websocket.d.ts +9 -0
- package/dist/gui/server/websocket.js +124 -0
- package/dist/gui/server/writer-lock.d.ts +1 -0
- package/dist/gui/server/writer-lock.js +1 -0
- package/dist/gui/server/ws-hub.d.ts +50 -0
- package/dist/gui/server/ws-hub.js +284 -0
- package/dist/gui/shared/chat-events.d.ts +174 -0
- package/dist/gui/shared/chat-events.js +13 -0
- package/dist/gui/shared/event-reducer.d.ts +3 -0
- package/dist/gui/shared/event-reducer.js +187 -0
- package/dist/index.js +0 -1
- package/dist/infra/cache.js +0 -1
- package/dist/infra/freshness.js +0 -1
- package/dist/infra/http-client.js +1 -2
- package/dist/infra/index.js +0 -1
- package/dist/infra/market-calendar.js +0 -1
- package/dist/infra/native-dependencies.js +0 -1
- package/dist/infra/node-version.js +0 -1
- package/dist/infra/open-url.js +0 -1
- package/dist/infra/opencandle-paths.js +0 -1
- package/dist/infra/rate-limiter.js +0 -1
- package/dist/market-state/alert-conditions.js +0 -1
- package/dist/market-state/alert-runner.d.ts +1 -0
- package/dist/market-state/alert-runner.js +5 -4
- package/dist/market-state/daily-report.js +0 -1
- package/dist/market-state/local-automation-service.js +0 -1
- package/dist/market-state/notification-delivery.js +0 -1
- package/dist/market-state/resolve-for-mutation.js +0 -1
- package/dist/market-state/resolve.js +0 -1
- package/dist/market-state/service.d.ts +26 -21
- package/dist/market-state/service.js +175 -36
- package/dist/market-state/summaries.js +1 -13
- package/dist/memory/index.js +0 -1
- package/dist/memory/manager.js +0 -1
- package/dist/memory/preference-extractor.js +0 -1
- package/dist/memory/retrieval.js +0 -1
- package/dist/memory/sqlite.js +60 -11
- package/dist/memory/storage.js +0 -1
- package/dist/memory/tool-defaults.js +0 -1
- package/dist/memory/types.js +0 -1
- package/dist/monitor.js +0 -1
- package/dist/onboarding/connect.js +0 -1
- package/dist/onboarding/credential-interceptor.js +0 -1
- package/dist/onboarding/degradation-accumulator.js +0 -1
- package/dist/onboarding/prompt-user.d.ts +1 -1
- package/dist/onboarding/prompt-user.js +0 -1
- package/dist/onboarding/provider-status.js +0 -1
- package/dist/onboarding/providers.js +0 -1
- package/dist/onboarding/state.js +0 -1
- package/dist/onboarding/tool-helpers.js +0 -1
- package/dist/onboarding/tool-tags.js +0 -1
- package/dist/onboarding/validate-model-key.d.ts +17 -0
- package/dist/onboarding/validate-model-key.js +54 -0
- package/dist/onboarding/validation.js +0 -1
- package/dist/pi/opencandle-extension.js +2 -2
- package/dist/pi/session-action-dedupe.js +0 -1
- package/dist/pi/session-storage.js +0 -1
- package/dist/pi/session-writer-lock.js +0 -1
- package/dist/pi/session.js +0 -1
- package/dist/pi/setup.d.ts +2 -0
- package/dist/pi/setup.js +10 -3
- package/dist/pi/tool-adapter.js +0 -1
- package/dist/pi/tui-session-coordinator.js +0 -1
- package/dist/prompts/context-builder.js +1 -2
- package/dist/prompts/disclaimer.js +0 -1
- package/dist/prompts/policy-cards.js +0 -1
- package/dist/prompts/sections.js +0 -1
- package/dist/prompts/symbol-preflight.js +0 -1
- package/dist/prompts/workflow-prompts.js +0 -1
- package/dist/providers/alpha-vantage.js +2 -3
- package/dist/providers/coingecko.js +0 -1
- package/dist/providers/errors.js +0 -1
- package/dist/providers/exa-search.js +11 -10
- package/dist/providers/external-tool-command.js +0 -1
- package/dist/providers/external-tool-error.js +0 -1
- package/dist/providers/fear-greed.js +0 -1
- package/dist/providers/finnhub.js +0 -1
- package/dist/providers/fred.js +0 -1
- package/dist/providers/index.js +0 -1
- package/dist/providers/polymarket.js +0 -1
- package/dist/providers/provider-credential-error.js +0 -1
- package/dist/providers/reddit-cli.js +0 -1
- package/dist/providers/reddit.js +0 -1
- package/dist/providers/sec-edgar.js +0 -1
- package/dist/providers/tradingview.js +1 -2
- package/dist/providers/twitter-cli.js +0 -1
- package/dist/providers/twitter.js +0 -1
- package/dist/providers/web-search.js +15 -12
- package/dist/providers/with-fallback.js +0 -1
- package/dist/providers/wrap-provider.js +0 -1
- package/dist/providers/yahoo-finance.js +67 -4
- package/dist/routing/classify-intent.js +0 -1
- package/dist/routing/defaults.js +0 -1
- package/dist/routing/entity-extractor.js +2 -3
- package/dist/routing/fund-symbols.js +0 -1
- package/dist/routing/horizon.js +0 -1
- package/dist/routing/index.js +0 -1
- package/dist/routing/legacy-rule-router.js +0 -1
- package/dist/routing/planning.js +0 -1
- package/dist/routing/route-manifest.js +0 -1
- package/dist/routing/router-llm-client.d.ts +2 -2
- package/dist/routing/router-llm-client.js +0 -1
- package/dist/routing/router-prompt.js +0 -1
- package/dist/routing/router-types.js +0 -1
- package/dist/routing/router.js +1 -2
- package/dist/routing/slot-resolver.js +0 -1
- package/dist/routing/symbol-disambiguator.js +0 -1
- package/dist/routing/turn-context.js +0 -1
- package/dist/routing/types.js +0 -1
- package/dist/runtime/answer-contracts.js +0 -1
- package/dist/runtime/artifact-contracts.js +0 -1
- package/dist/runtime/evidence.js +0 -1
- package/dist/runtime/numeric-claims.js +0 -1
- package/dist/runtime/planning-evidence.js +0 -1
- package/dist/runtime/prompt-step.js +0 -1
- package/dist/runtime/provider-tracker.js +0 -1
- package/dist/runtime/run-context.js +0 -1
- package/dist/runtime/session-coordinator.js +0 -1
- package/dist/runtime/session-title.js +0 -1
- package/dist/runtime/tool-defaults-wrapper.js +0 -1
- package/dist/runtime/validation.js +0 -1
- package/dist/runtime/workflow-events.js +0 -1
- package/dist/runtime/workflow-runner.d.ts +1 -0
- package/dist/runtime/workflow-runner.js +8 -3
- package/dist/runtime/workflow-types.js +0 -1
- package/dist/sentiment/adapters/finnhub.js +0 -1
- package/dist/sentiment/adapters/reddit.js +0 -1
- package/dist/sentiment/adapters/twitter.js +0 -1
- package/dist/sentiment/adapters/web.js +0 -1
- package/dist/sentiment/index.js +4 -2
- package/dist/sentiment/insights.js +0 -1
- package/dist/sentiment/keywords.js +0 -1
- package/dist/sentiment/pipeline.js +0 -1
- package/dist/sentiment/scorer.js +0 -1
- package/dist/sentiment/store.js +0 -1
- package/dist/sentiment/trends.js +0 -1
- package/dist/sentiment/types.js +0 -1
- package/dist/system-prompt.js +0 -1
- package/dist/tool-kit.js +0 -1
- package/dist/tools/fundamentals/company-overview.d.ts +1 -1
- package/dist/tools/fundamentals/company-overview.js +2 -1
- package/dist/tools/fundamentals/comps.js +6 -4
- package/dist/tools/fundamentals/dcf.js +0 -1
- package/dist/tools/fundamentals/earnings.d.ts +1 -1
- package/dist/tools/fundamentals/earnings.js +2 -1
- package/dist/tools/fundamentals/financials.js +2 -1
- package/dist/tools/fundamentals/sec-filings.js +0 -1
- package/dist/tools/index.d.ts +116 -2
- package/dist/tools/index.js +0 -1
- package/dist/tools/interaction/ask-user.js +11 -1
- package/dist/tools/macro/event-probabilities.js +0 -1
- package/dist/tools/macro/fear-greed.d.ts +1 -1
- package/dist/tools/macro/fear-greed.js +0 -1
- package/dist/tools/macro/fred-data.d.ts +1 -1
- package/dist/tools/macro/fred-data.js +2 -1
- package/dist/tools/market/crypto-history.js +0 -1
- package/dist/tools/market/crypto-price.d.ts +2 -2
- package/dist/tools/market/crypto-price.js +0 -1
- package/dist/tools/market/screen-stocks.js +0 -1
- package/dist/tools/market/search-ticker.js +1 -2
- package/dist/tools/market/stock-history.js +0 -1
- package/dist/tools/market/stock-quote.d.ts +2 -2
- package/dist/tools/market/stock-quote.js +0 -1
- package/dist/tools/options/greeks.js +0 -1
- package/dist/tools/options/option-chain.d.ts +2 -2
- package/dist/tools/options/option-chain.js +0 -1
- package/dist/tools/portfolio/alerts.d.ts +2 -1
- package/dist/tools/portfolio/alerts.js +228 -2
- package/dist/tools/portfolio/correlation.js +23 -5
- package/dist/tools/portfolio/daily-report.js +0 -1
- package/dist/tools/portfolio/holdings-overlap.js +0 -1
- package/dist/tools/portfolio/notifications.js +0 -1
- package/dist/tools/portfolio/risk-analysis.d.ts +1 -1
- package/dist/tools/portfolio/risk-analysis.js +0 -1
- package/dist/tools/portfolio/tracker.d.ts +3 -1
- package/dist/tools/portfolio/tracker.js +57 -10
- package/dist/tools/portfolio/watchlist.d.ts +3 -6
- package/dist/tools/portfolio/watchlist.js +101 -110
- package/dist/tools/sentiment/insight-format.js +0 -1
- package/dist/tools/sentiment/query-match.js +0 -1
- package/dist/tools/sentiment/reddit-sentiment.js +0 -1
- package/dist/tools/sentiment/sentiment-summary.js +8 -4
- package/dist/tools/sentiment/sentiment-trend.d.ts +5 -1
- package/dist/tools/sentiment/sentiment-trend.js +6 -2
- package/dist/tools/sentiment/twitter-sentiment.js +0 -1
- package/dist/tools/sentiment/untrusted-text.js +0 -1
- package/dist/tools/sentiment/web-search.d.ts +1 -1
- package/dist/tools/sentiment/web-search.js +0 -1
- package/dist/tools/sentiment/web-sentiment.js +0 -1
- package/dist/tools/technical/backtest.js +0 -1
- package/dist/tools/technical/indicators.js +0 -1
- package/dist/types/fundamentals.js +0 -1
- package/dist/types/index.js +0 -1
- package/dist/types/macro.js +0 -1
- package/dist/types/market.d.ts +6 -0
- package/dist/types/market.js +0 -1
- package/dist/types/options.js +0 -1
- package/dist/types/portfolio.js +0 -1
- package/dist/types/prediction-markets.js +0 -1
- package/dist/types/sentiment.js +0 -1
- package/dist/workflows/compare-assets.js +0 -1
- package/dist/workflows/index.js +0 -1
- package/dist/workflows/options-screener.js +0 -1
- package/dist/workflows/portfolio-builder.js +0 -1
- package/gui/web/dist/assets/CatalogOverlay-CAc7e3Pf.js +1 -0
- package/gui/web/dist/assets/index-BOEKd9wT.css +2 -0
- package/gui/web/dist/assets/index-C-H05cQ2.js +65 -0
- package/gui/web/dist/index.html +2 -2
- package/package.json +11 -12
- package/dist/analysts/contracts.js.map +0 -1
- package/dist/analysts/orchestrator.js.map +0 -1
- package/dist/cli-main.js.map +0 -1
- package/dist/cli.js.map +0 -1
- package/dist/config.js.map +0 -1
- package/dist/doctor/cli-command.js.map +0 -1
- package/dist/doctor/render.js.map +0 -1
- package/dist/doctor/report.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/infra/cache.js.map +0 -1
- package/dist/infra/freshness.js.map +0 -1
- package/dist/infra/http-client.js.map +0 -1
- package/dist/infra/index.js.map +0 -1
- package/dist/infra/market-calendar.js.map +0 -1
- package/dist/infra/native-dependencies.js.map +0 -1
- package/dist/infra/node-version.js.map +0 -1
- package/dist/infra/open-url.js.map +0 -1
- package/dist/infra/opencandle-paths.js.map +0 -1
- package/dist/infra/rate-limiter.js.map +0 -1
- package/dist/market-state/alert-conditions.js.map +0 -1
- package/dist/market-state/alert-runner.js.map +0 -1
- package/dist/market-state/daily-report.js.map +0 -1
- package/dist/market-state/local-automation-service.js.map +0 -1
- package/dist/market-state/notification-delivery.js.map +0 -1
- package/dist/market-state/resolve-for-mutation.js.map +0 -1
- package/dist/market-state/resolve.js.map +0 -1
- package/dist/market-state/service.js.map +0 -1
- package/dist/market-state/summaries.js.map +0 -1
- package/dist/memory/index.js.map +0 -1
- package/dist/memory/manager.js.map +0 -1
- package/dist/memory/preference-extractor.js.map +0 -1
- package/dist/memory/retrieval.js.map +0 -1
- package/dist/memory/sqlite.js.map +0 -1
- package/dist/memory/storage.js.map +0 -1
- package/dist/memory/tool-defaults.js.map +0 -1
- package/dist/memory/types.js.map +0 -1
- package/dist/monitor.js.map +0 -1
- package/dist/onboarding/connect.js.map +0 -1
- package/dist/onboarding/credential-interceptor.js.map +0 -1
- package/dist/onboarding/degradation-accumulator.js.map +0 -1
- package/dist/onboarding/prompt-user.js.map +0 -1
- package/dist/onboarding/provider-status.js.map +0 -1
- package/dist/onboarding/providers.js.map +0 -1
- package/dist/onboarding/state.js.map +0 -1
- package/dist/onboarding/tool-helpers.js.map +0 -1
- package/dist/onboarding/tool-tags.js.map +0 -1
- package/dist/onboarding/validation.js.map +0 -1
- package/dist/pi/opencandle-extension.js.map +0 -1
- package/dist/pi/session-action-dedupe.js.map +0 -1
- package/dist/pi/session-storage.js.map +0 -1
- package/dist/pi/session-writer-lock.js.map +0 -1
- package/dist/pi/session.js.map +0 -1
- package/dist/pi/setup.js.map +0 -1
- package/dist/pi/tool-adapter.js.map +0 -1
- package/dist/pi/tui-session-coordinator.js.map +0 -1
- package/dist/prompts/context-builder.js.map +0 -1
- package/dist/prompts/disclaimer.js.map +0 -1
- package/dist/prompts/policy-cards.js.map +0 -1
- package/dist/prompts/sections.js.map +0 -1
- package/dist/prompts/symbol-preflight.js.map +0 -1
- package/dist/prompts/workflow-prompts.js.map +0 -1
- package/dist/providers/alpha-vantage.js.map +0 -1
- package/dist/providers/coingecko.js.map +0 -1
- package/dist/providers/errors.js.map +0 -1
- package/dist/providers/exa-search.js.map +0 -1
- package/dist/providers/external-tool-command.js.map +0 -1
- package/dist/providers/external-tool-error.js.map +0 -1
- package/dist/providers/fear-greed.js.map +0 -1
- package/dist/providers/finnhub.js.map +0 -1
- package/dist/providers/fred.js.map +0 -1
- package/dist/providers/index.js.map +0 -1
- package/dist/providers/polymarket.js.map +0 -1
- package/dist/providers/provider-credential-error.js.map +0 -1
- package/dist/providers/reddit-cli.js.map +0 -1
- package/dist/providers/reddit.js.map +0 -1
- package/dist/providers/sec-edgar.js.map +0 -1
- package/dist/providers/tradingview.js.map +0 -1
- package/dist/providers/twitter-cli.js.map +0 -1
- package/dist/providers/twitter.js.map +0 -1
- package/dist/providers/web-search.js.map +0 -1
- package/dist/providers/with-fallback.js.map +0 -1
- package/dist/providers/wrap-provider.js.map +0 -1
- package/dist/providers/yahoo-finance.js.map +0 -1
- package/dist/routing/classify-intent.js.map +0 -1
- package/dist/routing/defaults.js.map +0 -1
- package/dist/routing/entity-extractor.js.map +0 -1
- package/dist/routing/fund-symbols.js.map +0 -1
- package/dist/routing/horizon.js.map +0 -1
- package/dist/routing/index.js.map +0 -1
- package/dist/routing/legacy-rule-router.js.map +0 -1
- package/dist/routing/planning.js.map +0 -1
- package/dist/routing/route-manifest.js.map +0 -1
- package/dist/routing/router-llm-client.js.map +0 -1
- package/dist/routing/router-prompt.js.map +0 -1
- package/dist/routing/router-types.js.map +0 -1
- package/dist/routing/router.js.map +0 -1
- package/dist/routing/slot-resolver.js.map +0 -1
- package/dist/routing/symbol-disambiguator.js.map +0 -1
- package/dist/routing/turn-context.js.map +0 -1
- package/dist/routing/types.js.map +0 -1
- package/dist/runtime/answer-contracts.js.map +0 -1
- package/dist/runtime/artifact-contracts.js.map +0 -1
- package/dist/runtime/evidence.js.map +0 -1
- package/dist/runtime/numeric-claims.js.map +0 -1
- package/dist/runtime/planning-evidence.js.map +0 -1
- package/dist/runtime/prompt-step.js.map +0 -1
- package/dist/runtime/provider-tracker.js.map +0 -1
- package/dist/runtime/run-context.js.map +0 -1
- package/dist/runtime/session-coordinator.js.map +0 -1
- package/dist/runtime/session-title.js.map +0 -1
- package/dist/runtime/tool-defaults-wrapper.js.map +0 -1
- package/dist/runtime/validation.js.map +0 -1
- package/dist/runtime/workflow-events.js.map +0 -1
- package/dist/runtime/workflow-runner.js.map +0 -1
- package/dist/runtime/workflow-types.js.map +0 -1
- package/dist/sentiment/adapters/finnhub.js.map +0 -1
- package/dist/sentiment/adapters/reddit.js.map +0 -1
- package/dist/sentiment/adapters/twitter.js.map +0 -1
- package/dist/sentiment/adapters/web.js.map +0 -1
- package/dist/sentiment/index.js.map +0 -1
- package/dist/sentiment/insights.js.map +0 -1
- package/dist/sentiment/keywords.js.map +0 -1
- package/dist/sentiment/pipeline.js.map +0 -1
- package/dist/sentiment/scorer.js.map +0 -1
- package/dist/sentiment/store.js.map +0 -1
- package/dist/sentiment/trends.js.map +0 -1
- package/dist/sentiment/types.js.map +0 -1
- package/dist/system-prompt.js.map +0 -1
- package/dist/tool-kit.js.map +0 -1
- package/dist/tools/fundamentals/company-overview.js.map +0 -1
- package/dist/tools/fundamentals/comps.js.map +0 -1
- package/dist/tools/fundamentals/dcf.js.map +0 -1
- package/dist/tools/fundamentals/earnings.js.map +0 -1
- package/dist/tools/fundamentals/financials.js.map +0 -1
- package/dist/tools/fundamentals/sec-filings.js.map +0 -1
- package/dist/tools/index.js.map +0 -1
- package/dist/tools/interaction/ask-user.js.map +0 -1
- package/dist/tools/macro/event-probabilities.js.map +0 -1
- package/dist/tools/macro/fear-greed.js.map +0 -1
- package/dist/tools/macro/fred-data.js.map +0 -1
- package/dist/tools/market/crypto-history.js.map +0 -1
- package/dist/tools/market/crypto-price.js.map +0 -1
- package/dist/tools/market/screen-stocks.js.map +0 -1
- package/dist/tools/market/search-ticker.js.map +0 -1
- package/dist/tools/market/stock-history.js.map +0 -1
- package/dist/tools/market/stock-quote.js.map +0 -1
- package/dist/tools/options/greeks.js.map +0 -1
- package/dist/tools/options/option-chain.js.map +0 -1
- package/dist/tools/portfolio/alerts.js.map +0 -1
- package/dist/tools/portfolio/correlation.js.map +0 -1
- package/dist/tools/portfolio/daily-report.js.map +0 -1
- package/dist/tools/portfolio/holdings-overlap.js.map +0 -1
- package/dist/tools/portfolio/notifications.js.map +0 -1
- package/dist/tools/portfolio/risk-analysis.js.map +0 -1
- package/dist/tools/portfolio/tracker.js.map +0 -1
- package/dist/tools/portfolio/watchlist.js.map +0 -1
- package/dist/tools/sentiment/insight-format.js.map +0 -1
- package/dist/tools/sentiment/query-match.js.map +0 -1
- package/dist/tools/sentiment/reddit-sentiment.js.map +0 -1
- package/dist/tools/sentiment/sentiment-summary.js.map +0 -1
- package/dist/tools/sentiment/sentiment-trend.js.map +0 -1
- package/dist/tools/sentiment/twitter-sentiment.js.map +0 -1
- package/dist/tools/sentiment/untrusted-text.js.map +0 -1
- package/dist/tools/sentiment/web-search.js.map +0 -1
- package/dist/tools/sentiment/web-sentiment.js.map +0 -1
- package/dist/tools/technical/backtest.js.map +0 -1
- package/dist/tools/technical/indicators.js.map +0 -1
- package/dist/types/fundamentals.js.map +0 -1
- package/dist/types/index.js.map +0 -1
- package/dist/types/macro.js.map +0 -1
- package/dist/types/market.js.map +0 -1
- package/dist/types/options.js.map +0 -1
- package/dist/types/portfolio.js.map +0 -1
- package/dist/types/prediction-markets.js.map +0 -1
- package/dist/types/sentiment.js.map +0 -1
- package/dist/workflows/compare-assets.js.map +0 -1
- package/dist/workflows/index.js.map +0 -1
- package/dist/workflows/options-screener.js.map +0 -1
- package/dist/workflows/portfolio-builder.js.map +0 -1
- package/gui/server/ask-user-bridge.ts +0 -89
- package/gui/server/automation-heartbeat.ts +0 -97
- package/gui/server/background-quotes.ts +0 -127
- package/gui/server/chat-event-adapter.ts +0 -294
- package/gui/server/gui-session-manager.ts +0 -5
- package/gui/server/http-routes.ts +0 -1201
- package/gui/server/invoke-tool.ts +0 -490
- package/gui/server/live-chat-event-adapter.ts +0 -243
- package/gui/server/local-session-coordinator.ts +0 -97
- package/gui/server/market-state-api.ts +0 -331
- package/gui/server/model-setup.ts +0 -254
- package/gui/server/package.json +0 -5
- package/gui/server/private-api-access.ts +0 -62
- package/gui/server/projector.ts +0 -392
- package/gui/server/prompt-observation.ts +0 -58
- package/gui/server/quote-snapshot-store.ts +0 -50
- package/gui/server/server.ts +0 -289
- package/gui/server/session-actions.ts +0 -323
- package/gui/server/session-entry-wait.ts +0 -179
- package/gui/server/shutdown.ts +0 -47
- package/gui/server/tool-invoke-ack.ts +0 -49
- package/gui/server/tool-metadata.ts +0 -167
- package/gui/server/websocket.ts +0 -138
- package/gui/server/writer-lock.ts +0 -1
- package/gui/server/ws-hub.ts +0 -403
- package/gui/shared/chat-events.ts +0 -165
- package/gui/shared/event-reducer.ts +0 -220
- package/gui/web/dist/assets/CatalogOverlay-DZ1niyQm.js +0 -1
- package/gui/web/dist/assets/index-D4F9AJnn.css +0 -2
- package/gui/web/dist/assets/index-DtqMMBTr.js +0 -65
- package/src/analysts/contracts.ts +0 -176
- package/src/analysts/orchestrator.ts +0 -244
- package/src/cli-main.ts +0 -510
- package/src/cli.ts +0 -17
- package/src/config.ts +0 -272
- package/src/doctor/cli-command.ts +0 -83
- package/src/doctor/render.ts +0 -37
- package/src/doctor/report.ts +0 -638
- package/src/index.ts +0 -5
- package/src/infra/cache.ts +0 -127
- package/src/infra/freshness.ts +0 -165
- package/src/infra/http-client.ts +0 -134
- package/src/infra/index.ts +0 -14
- package/src/infra/market-calendar.ts +0 -193
- package/src/infra/native-dependencies.ts +0 -84
- package/src/infra/node-version.ts +0 -23
- package/src/infra/open-url.ts +0 -28
- package/src/infra/opencandle-paths.ts +0 -53
- package/src/infra/rate-limiter.ts +0 -77
- package/src/market-state/alert-conditions.ts +0 -82
- package/src/market-state/alert-runner.ts +0 -863
- package/src/market-state/daily-report.ts +0 -237
- package/src/market-state/local-automation-service.ts +0 -162
- package/src/market-state/notification-delivery.ts +0 -158
- package/src/market-state/resolve-for-mutation.ts +0 -24
- package/src/market-state/resolve.ts +0 -112
- package/src/market-state/service.ts +0 -2208
- package/src/market-state/summaries.ts +0 -75
- package/src/memory/index.ts +0 -10
- package/src/memory/manager.ts +0 -190
- package/src/memory/preference-extractor.ts +0 -106
- package/src/memory/retrieval.ts +0 -71
- package/src/memory/sqlite.ts +0 -577
- package/src/memory/storage.ts +0 -195
- package/src/memory/tool-defaults.ts +0 -108
- package/src/memory/types.ts +0 -71
- package/src/monitor.ts +0 -123
- package/src/onboarding/connect.ts +0 -177
- package/src/onboarding/credential-interceptor.ts +0 -122
- package/src/onboarding/degradation-accumulator.ts +0 -77
- package/src/onboarding/prompt-user.ts +0 -85
- package/src/onboarding/provider-status.ts +0 -382
- package/src/onboarding/providers.ts +0 -442
- package/src/onboarding/state.ts +0 -216
- package/src/onboarding/tool-helpers.ts +0 -104
- package/src/onboarding/tool-tags.ts +0 -244
- package/src/onboarding/validation.ts +0 -152
- package/src/pi/opencandle-extension.ts +0 -1294
- package/src/pi/session-action-dedupe.ts +0 -155
- package/src/pi/session-storage.ts +0 -5
- package/src/pi/session-writer-lock.ts +0 -426
- package/src/pi/session.ts +0 -84
- package/src/pi/setup.ts +0 -399
- package/src/pi/tool-adapter.ts +0 -49
- package/src/pi/tui-session-coordinator.ts +0 -351
- package/src/prompts/context-builder.ts +0 -326
- package/src/prompts/disclaimer.ts +0 -9
- package/src/prompts/policy-cards.ts +0 -228
- package/src/prompts/sections.ts +0 -46
- package/src/prompts/symbol-preflight.ts +0 -80
- package/src/prompts/workflow-prompts.ts +0 -504
- package/src/providers/alpha-vantage.ts +0 -340
- package/src/providers/coingecko.ts +0 -95
- package/src/providers/errors.ts +0 -9
- package/src/providers/exa-search.ts +0 -375
- package/src/providers/external-tool-command.ts +0 -164
- package/src/providers/external-tool-error.ts +0 -20
- package/src/providers/fear-greed.ts +0 -45
- package/src/providers/finnhub.ts +0 -125
- package/src/providers/fred.ts +0 -83
- package/src/providers/index.ts +0 -17
- package/src/providers/polymarket.ts +0 -214
- package/src/providers/provider-credential-error.ts +0 -23
- package/src/providers/reddit-cli.ts +0 -286
- package/src/providers/reddit.ts +0 -106
- package/src/providers/sec-edgar.ts +0 -326
- package/src/providers/tradingview.ts +0 -399
- package/src/providers/twitter-cli.ts +0 -202
- package/src/providers/twitter.ts +0 -102
- package/src/providers/web-search.ts +0 -303
- package/src/providers/with-fallback.ts +0 -42
- package/src/providers/wrap-provider.ts +0 -105
- package/src/providers/yahoo-finance.ts +0 -984
- package/src/routing/classify-intent.ts +0 -380
- package/src/routing/defaults.ts +0 -29
- package/src/routing/entity-extractor.ts +0 -557
- package/src/routing/fund-symbols.ts +0 -58
- package/src/routing/horizon.ts +0 -7
- package/src/routing/index.ts +0 -70
- package/src/routing/legacy-rule-router.ts +0 -13
- package/src/routing/planning.ts +0 -829
- package/src/routing/route-manifest.ts +0 -308
- package/src/routing/router-llm-client.ts +0 -64
- package/src/routing/router-prompt.ts +0 -159
- package/src/routing/router-types.ts +0 -84
- package/src/routing/router.ts +0 -1332
- package/src/routing/slot-resolver.ts +0 -213
- package/src/routing/symbol-disambiguator.ts +0 -72
- package/src/routing/turn-context.ts +0 -108
- package/src/routing/types.ts +0 -77
- package/src/runtime/answer-contracts.ts +0 -693
- package/src/runtime/artifact-contracts.ts +0 -77
- package/src/runtime/evidence.ts +0 -78
- package/src/runtime/numeric-claims.ts +0 -108
- package/src/runtime/planning-evidence.ts +0 -597
- package/src/runtime/prompt-step.ts +0 -185
- package/src/runtime/provider-tracker.ts +0 -40
- package/src/runtime/run-context.ts +0 -32
- package/src/runtime/session-coordinator.ts +0 -1037
- package/src/runtime/session-title.ts +0 -60
- package/src/runtime/tool-defaults-wrapper.ts +0 -43
- package/src/runtime/validation.ts +0 -211
- package/src/runtime/workflow-events.ts +0 -77
- package/src/runtime/workflow-runner.ts +0 -182
- package/src/runtime/workflow-types.ts +0 -105
- package/src/sentiment/adapters/finnhub.ts +0 -49
- package/src/sentiment/adapters/reddit.ts +0 -65
- package/src/sentiment/adapters/twitter.ts +0 -36
- package/src/sentiment/adapters/web.ts +0 -44
- package/src/sentiment/index.ts +0 -49
- package/src/sentiment/insights.ts +0 -269
- package/src/sentiment/keywords.ts +0 -31
- package/src/sentiment/pipeline.ts +0 -91
- package/src/sentiment/scorer.ts +0 -89
- package/src/sentiment/store.ts +0 -260
- package/src/sentiment/trends.ts +0 -96
- package/src/sentiment/types.ts +0 -112
- package/src/system-prompt.ts +0 -115
- package/src/tool-kit.ts +0 -69
- package/src/tools/AGENTS.md +0 -36
- package/src/tools/fundamentals/company-overview.ts +0 -64
- package/src/tools/fundamentals/comps.ts +0 -180
- package/src/tools/fundamentals/dcf.ts +0 -447
- package/src/tools/fundamentals/earnings.ts +0 -57
- package/src/tools/fundamentals/financials.ts +0 -63
- package/src/tools/fundamentals/sec-filings.ts +0 -105
- package/src/tools/index.ts +0 -104
- package/src/tools/interaction/ask-user.ts +0 -93
- package/src/tools/macro/event-probabilities.ts +0 -141
- package/src/tools/macro/fear-greed.ts +0 -41
- package/src/tools/macro/fred-data.ts +0 -92
- package/src/tools/market/crypto-history.ts +0 -72
- package/src/tools/market/crypto-price.ts +0 -65
- package/src/tools/market/screen-stocks.ts +0 -290
- package/src/tools/market/search-ticker.ts +0 -254
- package/src/tools/market/stock-history.ts +0 -104
- package/src/tools/market/stock-quote.ts +0 -73
- package/src/tools/options/greeks.ts +0 -81
- package/src/tools/options/option-chain.ts +0 -134
- package/src/tools/portfolio/alerts.ts +0 -457
- package/src/tools/portfolio/correlation.ts +0 -189
- package/src/tools/portfolio/daily-report.ts +0 -107
- package/src/tools/portfolio/holdings-overlap.ts +0 -139
- package/src/tools/portfolio/notifications.ts +0 -45
- package/src/tools/portfolio/risk-analysis.ts +0 -173
- package/src/tools/portfolio/tracker.ts +0 -308
- package/src/tools/portfolio/watchlist.ts +0 -288
- package/src/tools/sentiment/insight-format.ts +0 -50
- package/src/tools/sentiment/query-match.ts +0 -117
- package/src/tools/sentiment/reddit-sentiment.ts +0 -403
- package/src/tools/sentiment/sentiment-summary.ts +0 -383
- package/src/tools/sentiment/sentiment-trend.ts +0 -75
- package/src/tools/sentiment/twitter-sentiment.ts +0 -287
- package/src/tools/sentiment/untrusted-text.ts +0 -21
- package/src/tools/sentiment/web-search.ts +0 -186
- package/src/tools/sentiment/web-sentiment.ts +0 -96
- package/src/tools/technical/backtest.ts +0 -336
- package/src/tools/technical/indicators.ts +0 -281
- package/src/types/fundamentals.ts +0 -47
- package/src/types/index.ts +0 -26
- package/src/types/macro.ts +0 -27
- package/src/types/market.ts +0 -46
- package/src/types/options.ts +0 -53
- package/src/types/portfolio.ts +0 -83
- package/src/types/prediction-markets.ts +0 -13
- package/src/types/sentiment.ts +0 -129
- package/src/workflows/compare-assets.ts +0 -89
- package/src/workflows/index.ts +0 -3
- package/src/workflows/options-screener.ts +0 -125
- package/src/workflows/portfolio-builder.ts +0 -63
|
@@ -1,984 +0,0 @@
|
|
|
1
|
-
import YahooFinance from "yahoo-finance2";
|
|
2
|
-
import type { OptionsResult as YahooFinance2OptionsResult } from "yahoo-finance2/modules/options";
|
|
3
|
-
import { cache, STALE_LIMIT, TTL } from "../infra/cache.js";
|
|
4
|
-
import { HttpError, httpGet } from "../infra/http-client.js";
|
|
5
|
-
import { rateLimiter } from "../infra/rate-limiter.js";
|
|
6
|
-
import { computeGreeks } from "../tools/options/greeks.js";
|
|
7
|
-
import type { CompanyOverview, FinancialStatement } from "../types/fundamentals.js";
|
|
8
|
-
import type { OHLCV, StockQuote } from "../types/market.js";
|
|
9
|
-
import type {
|
|
10
|
-
OptionContract,
|
|
11
|
-
OptionsChain,
|
|
12
|
-
OptionsMarketSession,
|
|
13
|
-
OptionsQuoteStatus,
|
|
14
|
-
} from "../types/options.js";
|
|
15
|
-
import type { FundHoldings } from "../types/portfolio.js";
|
|
16
|
-
import { InvalidSymbolError } from "./errors.js";
|
|
17
|
-
|
|
18
|
-
const BASE_URL = "https://query1.finance.yahoo.com/v8/finance/chart";
|
|
19
|
-
const QUOTE_SUMMARY_URL = "https://query1.finance.yahoo.com/v10/finance/quoteSummary";
|
|
20
|
-
const STALE_QUOTE_MAX_RETRY_AFTER_MS = 1_000;
|
|
21
|
-
|
|
22
|
-
let yahooFinance2Client: InstanceType<typeof YahooFinance> | undefined;
|
|
23
|
-
|
|
24
|
-
function getYahooFinance2Client(): InstanceType<typeof YahooFinance> {
|
|
25
|
-
yahooFinance2Client ??= new YahooFinance({
|
|
26
|
-
suppressNotices: ["yahooSurvey", "ripHistorical"],
|
|
27
|
-
});
|
|
28
|
-
return yahooFinance2Client;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
type YahooNumber = number | { raw?: number; fmt?: string };
|
|
32
|
-
|
|
33
|
-
interface YahooChartResponse {
|
|
34
|
-
chart: {
|
|
35
|
-
result: Array<{
|
|
36
|
-
meta: Record<string, any>;
|
|
37
|
-
timestamp: number[];
|
|
38
|
-
indicators: {
|
|
39
|
-
quote: Array<{
|
|
40
|
-
open: number[];
|
|
41
|
-
high: number[];
|
|
42
|
-
low: number[];
|
|
43
|
-
close: number[];
|
|
44
|
-
volume: number[];
|
|
45
|
-
}>;
|
|
46
|
-
adjclose?: Array<{ adjclose: number[] }>;
|
|
47
|
-
};
|
|
48
|
-
}>;
|
|
49
|
-
error?: { code: string; description: string };
|
|
50
|
-
};
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
interface YahooQuoteSummaryResponse {
|
|
54
|
-
quoteSummary: {
|
|
55
|
-
result?: Array<YahooQuoteSummaryResult>;
|
|
56
|
-
error?: { code?: string; description?: string } | null;
|
|
57
|
-
};
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
interface YahooQuoteSummaryResult {
|
|
61
|
-
price?: {
|
|
62
|
-
symbol?: string;
|
|
63
|
-
shortName?: string;
|
|
64
|
-
longName?: string;
|
|
65
|
-
exchangeName?: string;
|
|
66
|
-
marketCap?: YahooNumber;
|
|
67
|
-
};
|
|
68
|
-
assetProfile?: {
|
|
69
|
-
longBusinessSummary?: string;
|
|
70
|
-
sector?: string;
|
|
71
|
-
industry?: string;
|
|
72
|
-
};
|
|
73
|
-
summaryProfile?: {
|
|
74
|
-
longBusinessSummary?: string;
|
|
75
|
-
sector?: string;
|
|
76
|
-
industry?: string;
|
|
77
|
-
};
|
|
78
|
-
summaryDetail?: {
|
|
79
|
-
trailingPE?: YahooNumber;
|
|
80
|
-
forwardPE?: YahooNumber;
|
|
81
|
-
dividendYield?: YahooNumber;
|
|
82
|
-
beta?: YahooNumber;
|
|
83
|
-
fiftyTwoWeekHigh?: YahooNumber;
|
|
84
|
-
fiftyTwoWeekLow?: YahooNumber;
|
|
85
|
-
averageVolume?: YahooNumber;
|
|
86
|
-
};
|
|
87
|
-
defaultKeyStatistics?: {
|
|
88
|
-
trailingEps?: YahooNumber;
|
|
89
|
-
forwardEps?: YahooNumber;
|
|
90
|
-
beta?: YahooNumber;
|
|
91
|
-
};
|
|
92
|
-
financialData?: {
|
|
93
|
-
profitMargins?: YahooNumber;
|
|
94
|
-
revenueGrowth?: YahooNumber;
|
|
95
|
-
totalRevenue?: YahooNumber;
|
|
96
|
-
};
|
|
97
|
-
topHoldings?: {
|
|
98
|
-
holdings?: Array<{
|
|
99
|
-
symbol?: string;
|
|
100
|
-
holdingName?: string;
|
|
101
|
-
holdingPercent?: YahooNumber;
|
|
102
|
-
}>;
|
|
103
|
-
equityHoldings?: {
|
|
104
|
-
sectorWeightings?: Array<Record<string, YahooNumber>>;
|
|
105
|
-
};
|
|
106
|
-
};
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
export async function getYahooCompanyOverview(symbol: string): Promise<CompanyOverview> {
|
|
110
|
-
const normalizedSymbol = symbol.toUpperCase();
|
|
111
|
-
const cacheKey = `yahoo:overview:${normalizedSymbol}`;
|
|
112
|
-
const cached = cache.get<CompanyOverview>(cacheKey);
|
|
113
|
-
if (cached) return cached;
|
|
114
|
-
|
|
115
|
-
try {
|
|
116
|
-
await rateLimiter.acquire("yahoo");
|
|
117
|
-
const result = await getYahooCompanySummary(normalizedSymbol);
|
|
118
|
-
if (!result?.price?.symbol) {
|
|
119
|
-
throw new Error(`Yahoo Finance: no company fundamentals returned for ${normalizedSymbol}`);
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
const profile = result.assetProfile ?? result.summaryProfile;
|
|
123
|
-
const overview: CompanyOverview = {
|
|
124
|
-
symbol: result.price.symbol.toUpperCase(),
|
|
125
|
-
name: result.price.longName ?? result.price.shortName ?? result.price.symbol,
|
|
126
|
-
description: profile?.longBusinessSummary ?? "",
|
|
127
|
-
exchange: result.price.exchangeName ?? "",
|
|
128
|
-
sector: profile?.sector ?? "",
|
|
129
|
-
industry: profile?.industry ?? "",
|
|
130
|
-
marketCap: yahooNumber(result.price.marketCap) ?? 0,
|
|
131
|
-
pe: yahooNullableNumber(result.summaryDetail?.trailingPE),
|
|
132
|
-
forwardPe: yahooNullableNumber(result.summaryDetail?.forwardPE),
|
|
133
|
-
eps:
|
|
134
|
-
yahooNullableNumber(result.defaultKeyStatistics?.trailingEps) ??
|
|
135
|
-
yahooNullableNumber(result.defaultKeyStatistics?.forwardEps),
|
|
136
|
-
dividendYield: yahooNullableNumber(result.summaryDetail?.dividendYield),
|
|
137
|
-
beta:
|
|
138
|
-
yahooNullableNumber(result.summaryDetail?.beta) ??
|
|
139
|
-
yahooNullableNumber(result.defaultKeyStatistics?.beta),
|
|
140
|
-
week52High: yahooNumber(result.summaryDetail?.fiftyTwoWeekHigh) ?? 0,
|
|
141
|
-
week52Low: yahooNumber(result.summaryDetail?.fiftyTwoWeekLow) ?? 0,
|
|
142
|
-
avgVolume: yahooNumber(result.summaryDetail?.averageVolume) ?? 0,
|
|
143
|
-
profitMargin: yahooNullableNumber(result.financialData?.profitMargins),
|
|
144
|
-
revenueGrowth: yahooNullableNumber(result.financialData?.revenueGrowth),
|
|
145
|
-
};
|
|
146
|
-
|
|
147
|
-
cache.set(cacheKey, overview, TTL.FUNDAMENTALS);
|
|
148
|
-
return overview;
|
|
149
|
-
} catch (error) {
|
|
150
|
-
const stale = cache.getStale<CompanyOverview>(cacheKey, STALE_LIMIT.FUNDAMENTALS);
|
|
151
|
-
if (stale) return stale.value;
|
|
152
|
-
throw error;
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
export async function getQuote(symbol: string): Promise<StockQuote> {
|
|
157
|
-
const cacheKey = `yahoo:quote:${symbol}`;
|
|
158
|
-
const cached = cache.get<StockQuote>(cacheKey);
|
|
159
|
-
if (cached) return cached;
|
|
160
|
-
|
|
161
|
-
try {
|
|
162
|
-
await rateLimiter.acquire("yahoo");
|
|
163
|
-
|
|
164
|
-
const url = `${BASE_URL}/${encodeURIComponent(symbol)}?interval=1d&range=1d`;
|
|
165
|
-
const data = await httpGet<YahooChartResponse>(url, {
|
|
166
|
-
headers: { "User-Agent": "OpenCandle/1.0" },
|
|
167
|
-
maxRetryAfterMs: STALE_QUOTE_MAX_RETRY_AFTER_MS,
|
|
168
|
-
});
|
|
169
|
-
|
|
170
|
-
if (data.chart.error) {
|
|
171
|
-
throw new Error(`Yahoo Finance: ${data.chart.error.description}`);
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
const result = data.chart.result[0];
|
|
175
|
-
const meta = result.meta;
|
|
176
|
-
const indicators = result.indicators.quote[0];
|
|
177
|
-
|
|
178
|
-
const price = meta.regularMarketPrice ?? 0;
|
|
179
|
-
const prevClose = meta.chartPreviousClose ?? meta.previousClose ?? price;
|
|
180
|
-
const change = price - prevClose;
|
|
181
|
-
const changePercent = prevClose !== 0 ? (change / prevClose) * 100 : 0;
|
|
182
|
-
|
|
183
|
-
// Open price: try meta first, fall back to indicators
|
|
184
|
-
const open = meta.regularMarketOpen ?? indicators?.open?.[0] ?? price;
|
|
185
|
-
|
|
186
|
-
const quote: StockQuote = {
|
|
187
|
-
symbol: meta.symbol,
|
|
188
|
-
price,
|
|
189
|
-
change,
|
|
190
|
-
changePercent,
|
|
191
|
-
open,
|
|
192
|
-
high: meta.regularMarketDayHigh ?? indicators?.high?.[0] ?? price,
|
|
193
|
-
low: meta.regularMarketDayLow ?? indicators?.low?.[0] ?? price,
|
|
194
|
-
previousClose: prevClose,
|
|
195
|
-
volume: meta.regularMarketVolume ?? 0,
|
|
196
|
-
marketCap: meta.marketCap ?? 0,
|
|
197
|
-
pe: null, // Not in chart endpoint
|
|
198
|
-
week52High: meta.fiftyTwoWeekHigh ?? 0,
|
|
199
|
-
week52Low: meta.fiftyTwoWeekLow ?? 0,
|
|
200
|
-
timestamp: Date.now(),
|
|
201
|
-
asOf: yahooMarketTimeToIso(meta.regularMarketTime),
|
|
202
|
-
currency:
|
|
203
|
-
typeof meta.currency === "string" && meta.currency.trim() !== ""
|
|
204
|
-
? meta.currency.trim().toUpperCase()
|
|
205
|
-
: null,
|
|
206
|
-
};
|
|
207
|
-
|
|
208
|
-
if (isZeroResultQuote(quote)) {
|
|
209
|
-
throw new InvalidSymbolError(symbol.toUpperCase(), "yahoo");
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
cache.set(cacheKey, quote, TTL.QUOTE);
|
|
213
|
-
return quote;
|
|
214
|
-
} catch (error) {
|
|
215
|
-
const stale = cache.getStale<StockQuote>(cacheKey, STALE_LIMIT.QUOTE);
|
|
216
|
-
if (stale) return stale.value;
|
|
217
|
-
throw error;
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
type YahooFundamentalsRow = {
|
|
222
|
-
date?: Date | string | number;
|
|
223
|
-
totalRevenue?: number;
|
|
224
|
-
annualTotalRevenue?: number;
|
|
225
|
-
grossProfit?: number;
|
|
226
|
-
annualGrossProfit?: number;
|
|
227
|
-
operatingIncome?: number;
|
|
228
|
-
annualOperatingIncome?: number;
|
|
229
|
-
netIncome?: number;
|
|
230
|
-
annualNetIncome?: number;
|
|
231
|
-
netIncomeCommonStockholders?: number;
|
|
232
|
-
annualNetIncomeCommonStockholders?: number;
|
|
233
|
-
basicEPS?: number;
|
|
234
|
-
annualBasicEPS?: number;
|
|
235
|
-
dilutedEPS?: number;
|
|
236
|
-
annualDilutedEPS?: number;
|
|
237
|
-
totalAssets?: number;
|
|
238
|
-
annualTotalAssets?: number;
|
|
239
|
-
totalLiabilitiesNetMinorityInterest?: number;
|
|
240
|
-
annualTotalLiabilitiesNetMinorityInterest?: number;
|
|
241
|
-
totalLiabilities?: number;
|
|
242
|
-
annualTotalLiabilities?: number;
|
|
243
|
-
stockholdersEquity?: number;
|
|
244
|
-
annualStockholdersEquity?: number;
|
|
245
|
-
commonStockEquity?: number;
|
|
246
|
-
annualCommonStockEquity?: number;
|
|
247
|
-
cashFlowFromContinuingOperatingActivities?: number;
|
|
248
|
-
annualCashFlowFromContinuingOperatingActivities?: number;
|
|
249
|
-
operatingCashFlow?: number;
|
|
250
|
-
annualOperatingCashFlow?: number;
|
|
251
|
-
freeCashFlow?: number;
|
|
252
|
-
annualFreeCashFlow?: number;
|
|
253
|
-
capitalExpenditure?: number;
|
|
254
|
-
annualCapitalExpenditure?: number;
|
|
255
|
-
capitalExpenditures?: number;
|
|
256
|
-
annualCapitalExpenditures?: number;
|
|
257
|
-
totalDebt?: number;
|
|
258
|
-
annualTotalDebt?: number;
|
|
259
|
-
cashAndCashEquivalents?: number;
|
|
260
|
-
annualCashAndCashEquivalents?: number;
|
|
261
|
-
ordinarySharesNumber?: number;
|
|
262
|
-
annualOrdinarySharesNumber?: number;
|
|
263
|
-
shareIssued?: number;
|
|
264
|
-
annualShareIssued?: number;
|
|
265
|
-
dilutedAverageShares?: number;
|
|
266
|
-
annualDilutedAverageShares?: number;
|
|
267
|
-
basicAverageShares?: number;
|
|
268
|
-
annualBasicAverageShares?: number;
|
|
269
|
-
};
|
|
270
|
-
|
|
271
|
-
export async function getYahooFinancials(symbol: string): Promise<FinancialStatement[]> {
|
|
272
|
-
const normalizedSymbol = symbol.toUpperCase();
|
|
273
|
-
const cacheKey = `yahoo:financials:${normalizedSymbol}`;
|
|
274
|
-
const cached = cache.get<FinancialStatement[]>(cacheKey);
|
|
275
|
-
if (cached) return cached;
|
|
276
|
-
|
|
277
|
-
try {
|
|
278
|
-
await rateLimiter.acquire("yahoo");
|
|
279
|
-
|
|
280
|
-
const period1 = new Date();
|
|
281
|
-
period1.setUTCFullYear(period1.getUTCFullYear() - 6);
|
|
282
|
-
const rows = (await getYahooFinance2Client().fundamentalsTimeSeries(
|
|
283
|
-
normalizedSymbol,
|
|
284
|
-
{
|
|
285
|
-
period1,
|
|
286
|
-
period2: new Date(),
|
|
287
|
-
type: "annual",
|
|
288
|
-
module: "all",
|
|
289
|
-
},
|
|
290
|
-
{ validateResult: false },
|
|
291
|
-
)) as YahooFundamentalsRow[];
|
|
292
|
-
|
|
293
|
-
const statements = rows
|
|
294
|
-
.map((row) => yahooFundamentalsRowToStatement(row))
|
|
295
|
-
.filter((statement): statement is FinancialStatement => statement !== null)
|
|
296
|
-
.sort((a, b) => b.fiscalDate.localeCompare(a.fiscalDate))
|
|
297
|
-
.slice(0, 4);
|
|
298
|
-
|
|
299
|
-
if (statements.length === 0) {
|
|
300
|
-
throw new Error(`Yahoo Finance: no financial statements returned for ${normalizedSymbol}`);
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
cache.set(cacheKey, statements, TTL.FUNDAMENTALS);
|
|
304
|
-
return statements;
|
|
305
|
-
} catch (error) {
|
|
306
|
-
const stale = cache.getStale<FinancialStatement[]>(cacheKey, STALE_LIMIT.FUNDAMENTALS);
|
|
307
|
-
if (stale) return stale.value;
|
|
308
|
-
throw error;
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
function yahooFundamentalsRowToStatement(row: YahooFundamentalsRow): FinancialStatement | null {
|
|
313
|
-
const fiscalDate = normalizeYahooDate(row.date);
|
|
314
|
-
if (!fiscalDate) return null;
|
|
315
|
-
|
|
316
|
-
const operatingCashFlowValue =
|
|
317
|
-
row.annualCashFlowFromContinuingOperatingActivities ??
|
|
318
|
-
row.cashFlowFromContinuingOperatingActivities ??
|
|
319
|
-
row.annualOperatingCashFlow ??
|
|
320
|
-
row.operatingCashFlow;
|
|
321
|
-
const capitalExpenditureValue =
|
|
322
|
-
row.annualCapitalExpenditure ??
|
|
323
|
-
row.capitalExpenditure ??
|
|
324
|
-
row.annualCapitalExpenditures ??
|
|
325
|
-
row.capitalExpenditures;
|
|
326
|
-
const operatingCashFlow = operatingCashFlowValue ?? 0;
|
|
327
|
-
const capitalExpenditure = capitalExpenditureValue ?? 0;
|
|
328
|
-
const freeCashFlow =
|
|
329
|
-
row.annualFreeCashFlow ??
|
|
330
|
-
row.freeCashFlow ??
|
|
331
|
-
(operatingCashFlowValue !== undefined && capitalExpenditureValue !== undefined
|
|
332
|
-
? operatingCashFlow + capitalExpenditure
|
|
333
|
-
: 0);
|
|
334
|
-
|
|
335
|
-
return {
|
|
336
|
-
fiscalDate,
|
|
337
|
-
revenue: row.annualTotalRevenue ?? row.totalRevenue ?? 0,
|
|
338
|
-
grossProfit: row.annualGrossProfit ?? row.grossProfit ?? 0,
|
|
339
|
-
operatingIncome: row.annualOperatingIncome ?? row.operatingIncome ?? 0,
|
|
340
|
-
netIncome:
|
|
341
|
-
row.annualNetIncome ??
|
|
342
|
-
row.netIncome ??
|
|
343
|
-
row.annualNetIncomeCommonStockholders ??
|
|
344
|
-
row.netIncomeCommonStockholders ??
|
|
345
|
-
0,
|
|
346
|
-
eps: row.annualDilutedEPS ?? row.dilutedEPS ?? row.annualBasicEPS ?? row.basicEPS ?? 0,
|
|
347
|
-
totalAssets: row.annualTotalAssets ?? row.totalAssets ?? 0,
|
|
348
|
-
totalLiabilities:
|
|
349
|
-
row.annualTotalLiabilitiesNetMinorityInterest ??
|
|
350
|
-
row.totalLiabilitiesNetMinorityInterest ??
|
|
351
|
-
row.annualTotalLiabilities ??
|
|
352
|
-
row.totalLiabilities ??
|
|
353
|
-
0,
|
|
354
|
-
totalEquity:
|
|
355
|
-
row.annualStockholdersEquity ??
|
|
356
|
-
row.stockholdersEquity ??
|
|
357
|
-
row.annualCommonStockEquity ??
|
|
358
|
-
row.commonStockEquity ??
|
|
359
|
-
0,
|
|
360
|
-
operatingCashFlow,
|
|
361
|
-
freeCashFlow,
|
|
362
|
-
totalDebt: row.annualTotalDebt ?? row.totalDebt,
|
|
363
|
-
cashAndEquivalents: row.annualCashAndCashEquivalents ?? row.cashAndCashEquivalents,
|
|
364
|
-
sharesOutstanding:
|
|
365
|
-
row.annualOrdinarySharesNumber ??
|
|
366
|
-
row.ordinarySharesNumber ??
|
|
367
|
-
row.annualShareIssued ??
|
|
368
|
-
row.shareIssued ??
|
|
369
|
-
row.annualDilutedAverageShares ??
|
|
370
|
-
row.dilutedAverageShares ??
|
|
371
|
-
row.annualBasicAverageShares ??
|
|
372
|
-
row.basicAverageShares,
|
|
373
|
-
};
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
function normalizeYahooDate(value: Date | string | number | undefined): string | null {
|
|
377
|
-
if (value instanceof Date) return value.toISOString().slice(0, 10);
|
|
378
|
-
if (typeof value === "number") {
|
|
379
|
-
if (!Number.isFinite(value)) return null;
|
|
380
|
-
const timestampMs = Math.abs(value) < 1_000_000_000_000 ? value * 1000 : value;
|
|
381
|
-
const date = new Date(timestampMs);
|
|
382
|
-
return Number.isNaN(date.getTime()) ? null : date.toISOString().slice(0, 10);
|
|
383
|
-
}
|
|
384
|
-
if (typeof value !== "string" || value.trim() === "") return null;
|
|
385
|
-
const date = new Date(value);
|
|
386
|
-
return Number.isNaN(date.getTime()) ? null : date.toISOString().slice(0, 10);
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
function isZeroResultQuote(quote: StockQuote): boolean {
|
|
390
|
-
return (
|
|
391
|
-
quote.price === 0 &&
|
|
392
|
-
quote.volume === 0 &&
|
|
393
|
-
quote.week52High === 0 &&
|
|
394
|
-
quote.week52Low === 0 &&
|
|
395
|
-
quote.marketCap === 0
|
|
396
|
-
);
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
export async function getHistory(
|
|
400
|
-
symbol: string,
|
|
401
|
-
range: string = "6mo",
|
|
402
|
-
interval: string = "1d",
|
|
403
|
-
): Promise<OHLCV[]> {
|
|
404
|
-
const cacheKey = `yahoo:history:${symbol}:${range}:${interval}`;
|
|
405
|
-
const cached = cache.get<OHLCV[]>(cacheKey);
|
|
406
|
-
if (cached) return cached;
|
|
407
|
-
|
|
408
|
-
try {
|
|
409
|
-
await rateLimiter.acquire("yahoo");
|
|
410
|
-
|
|
411
|
-
const url = `${BASE_URL}/${encodeURIComponent(symbol)}?interval=${interval}&range=${range}`;
|
|
412
|
-
const data = await httpGet<YahooChartResponse>(url, {
|
|
413
|
-
headers: { "User-Agent": "OpenCandle/1.0" },
|
|
414
|
-
});
|
|
415
|
-
|
|
416
|
-
if (data.chart.error) {
|
|
417
|
-
throw new Error(`Yahoo Finance: ${data.chart.error.description}`);
|
|
418
|
-
}
|
|
419
|
-
|
|
420
|
-
const result = data.chart.result[0];
|
|
421
|
-
const timestamps = result.timestamp;
|
|
422
|
-
const quotes = result.indicators.quote[0];
|
|
423
|
-
|
|
424
|
-
const ohlcv: OHLCV[] = timestamps
|
|
425
|
-
.map((ts, i) => ({
|
|
426
|
-
date: new Date(ts * 1000).toISOString().split("T")[0],
|
|
427
|
-
open: quotes.open[i],
|
|
428
|
-
high: quotes.high[i],
|
|
429
|
-
low: quotes.low[i],
|
|
430
|
-
close: quotes.close[i],
|
|
431
|
-
volume: quotes.volume[i],
|
|
432
|
-
}))
|
|
433
|
-
.filter((bar) => bar.open != null && bar.close != null);
|
|
434
|
-
|
|
435
|
-
cache.set(cacheKey, ohlcv, TTL.HISTORY);
|
|
436
|
-
return ohlcv;
|
|
437
|
-
} catch (error) {
|
|
438
|
-
const stale = cache.getStale<OHLCV[]>(cacheKey, STALE_LIMIT.HISTORY);
|
|
439
|
-
if (stale) return stale.value;
|
|
440
|
-
throw error;
|
|
441
|
-
}
|
|
442
|
-
}
|
|
443
|
-
|
|
444
|
-
export async function getFundHoldings(symbol: string): Promise<FundHoldings> {
|
|
445
|
-
const normalizedSymbol = symbol.toUpperCase();
|
|
446
|
-
const cacheKey = `yahoo:fund-holdings:${normalizedSymbol}`;
|
|
447
|
-
const cached = cache.get<FundHoldings>(cacheKey);
|
|
448
|
-
if (cached) return cached;
|
|
449
|
-
|
|
450
|
-
try {
|
|
451
|
-
await rateLimiter.acquire("yahoo");
|
|
452
|
-
|
|
453
|
-
const data = await getFundHoldingsSummary(normalizedSymbol);
|
|
454
|
-
const result = data.quoteSummary.result?.[0];
|
|
455
|
-
if (data.quoteSummary.error) {
|
|
456
|
-
throw new Error(
|
|
457
|
-
`Yahoo Finance: ${data.quoteSummary.error.description ?? data.quoteSummary.error.code ?? "quoteSummary error"}`,
|
|
458
|
-
);
|
|
459
|
-
}
|
|
460
|
-
if (!result?.topHoldings?.holdings?.length) {
|
|
461
|
-
throw new Error(`Yahoo Finance: no fund holdings returned for ${normalizedSymbol}`);
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
const holdings: FundHoldings = {
|
|
465
|
-
symbol: result.price?.symbol?.toUpperCase() ?? normalizedSymbol,
|
|
466
|
-
name: result.price?.shortName ?? result.price?.longName,
|
|
467
|
-
provider: "yahoo",
|
|
468
|
-
holdings: result.topHoldings.holdings.flatMap((holding) => {
|
|
469
|
-
const holdingSymbol = holding.symbol?.trim().toUpperCase();
|
|
470
|
-
const weight = normalizeHoldingWeight(holding.holdingPercent);
|
|
471
|
-
if (!holdingSymbol || weight === undefined) return [];
|
|
472
|
-
return [
|
|
473
|
-
{
|
|
474
|
-
symbol: holdingSymbol,
|
|
475
|
-
name: holding.holdingName?.trim() || holdingSymbol,
|
|
476
|
-
weight,
|
|
477
|
-
},
|
|
478
|
-
];
|
|
479
|
-
}),
|
|
480
|
-
sectorWeights: normalizeSectorWeights(result.topHoldings.equityHoldings?.sectorWeightings),
|
|
481
|
-
};
|
|
482
|
-
if (holdings.holdings.length === 0) {
|
|
483
|
-
throw new Error(`Yahoo Finance: no weighted fund holdings returned for ${normalizedSymbol}`);
|
|
484
|
-
}
|
|
485
|
-
|
|
486
|
-
cache.set(cacheKey, holdings, TTL.FUNDAMENTALS);
|
|
487
|
-
return holdings;
|
|
488
|
-
} catch (error) {
|
|
489
|
-
const stale = cache.getStale<FundHoldings>(cacheKey, STALE_LIMIT.FUNDAMENTALS);
|
|
490
|
-
if (stale) return stale.value;
|
|
491
|
-
throw error;
|
|
492
|
-
}
|
|
493
|
-
}
|
|
494
|
-
|
|
495
|
-
async function getFundHoldingsSummary(symbol: string): Promise<YahooQuoteSummaryResponse> {
|
|
496
|
-
return getYahooQuoteSummary(symbol, "price,topHoldings");
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
async function getYahooCompanySummary(symbol: string): Promise<YahooQuoteSummaryResult> {
|
|
500
|
-
const modules = [
|
|
501
|
-
"price",
|
|
502
|
-
"assetProfile",
|
|
503
|
-
"summaryProfile",
|
|
504
|
-
"summaryDetail",
|
|
505
|
-
"defaultKeyStatistics",
|
|
506
|
-
"financialData",
|
|
507
|
-
] as const;
|
|
508
|
-
try {
|
|
509
|
-
return (await getYahooFinance2Client().quoteSummary(
|
|
510
|
-
symbol,
|
|
511
|
-
{ modules: [...modules] },
|
|
512
|
-
{ validateResult: false },
|
|
513
|
-
)) as YahooQuoteSummaryResult;
|
|
514
|
-
} catch (error) {
|
|
515
|
-
const data = await getYahooQuoteSummary(symbol, modules.join(","));
|
|
516
|
-
if (data.quoteSummary.error) {
|
|
517
|
-
throw new Error(
|
|
518
|
-
`Yahoo Finance: ${data.quoteSummary.error.description ?? data.quoteSummary.error.code ?? "quoteSummary error"}`,
|
|
519
|
-
);
|
|
520
|
-
}
|
|
521
|
-
return data.quoteSummary.result?.[0] ?? {};
|
|
522
|
-
}
|
|
523
|
-
}
|
|
524
|
-
|
|
525
|
-
async function getYahooQuoteSummary(
|
|
526
|
-
symbol: string,
|
|
527
|
-
modules: string,
|
|
528
|
-
): Promise<YahooQuoteSummaryResponse> {
|
|
529
|
-
try {
|
|
530
|
-
return await fetchYahooQuoteSummary(symbol, modules);
|
|
531
|
-
} catch (error) {
|
|
532
|
-
if (!isYahooAuthError(error)) throw error;
|
|
533
|
-
return fetchYahooQuoteSummaryWithCrumb(symbol, modules);
|
|
534
|
-
}
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
async function fetchYahooQuoteSummary(
|
|
538
|
-
symbol: string,
|
|
539
|
-
modules: string,
|
|
540
|
-
): Promise<YahooQuoteSummaryResponse> {
|
|
541
|
-
const encodedModules = encodeURIComponent(modules);
|
|
542
|
-
const url = `${QUOTE_SUMMARY_URL}/${encodeURIComponent(symbol)}?modules=${encodedModules}`;
|
|
543
|
-
return httpGet<YahooQuoteSummaryResponse>(url, {
|
|
544
|
-
headers: { "User-Agent": "OpenCandle/1.0" },
|
|
545
|
-
});
|
|
546
|
-
}
|
|
547
|
-
|
|
548
|
-
async function fetchYahooQuoteSummaryWithCrumb(
|
|
549
|
-
symbol: string,
|
|
550
|
-
modules: string,
|
|
551
|
-
): Promise<YahooQuoteSummaryResponse> {
|
|
552
|
-
const encodedModules = encodeURIComponent(modules);
|
|
553
|
-
const { crumb, cookie } = await getYahooCrumb();
|
|
554
|
-
const url = `${QUOTE_SUMMARY_URL}/${encodeURIComponent(symbol)}?modules=${encodedModules}&crumb=${encodeURIComponent(crumb)}`;
|
|
555
|
-
try {
|
|
556
|
-
return await httpGet<YahooQuoteSummaryResponse>(url, {
|
|
557
|
-
headers: { "User-Agent": BROWSER_UA, Cookie: cookie },
|
|
558
|
-
});
|
|
559
|
-
} catch (error) {
|
|
560
|
-
if (!isYahooAuthError(error)) throw error;
|
|
561
|
-
clearCrumbCache();
|
|
562
|
-
const fresh = await getYahooCrumb();
|
|
563
|
-
const retryUrl = `${QUOTE_SUMMARY_URL}/${encodeURIComponent(symbol)}?modules=${encodedModules}&crumb=${encodeURIComponent(fresh.crumb)}`;
|
|
564
|
-
return httpGet<YahooQuoteSummaryResponse>(retryUrl, {
|
|
565
|
-
headers: { "User-Agent": BROWSER_UA, Cookie: fresh.cookie },
|
|
566
|
-
});
|
|
567
|
-
}
|
|
568
|
-
}
|
|
569
|
-
|
|
570
|
-
function isYahooAuthError(error: unknown): boolean {
|
|
571
|
-
return error instanceof HttpError && (error.status === 401 || error.status === 429);
|
|
572
|
-
}
|
|
573
|
-
|
|
574
|
-
function normalizeHoldingWeight(value: YahooNumber | undefined): number | undefined {
|
|
575
|
-
const numeric = yahooNumber(value);
|
|
576
|
-
if (numeric === undefined || !Number.isFinite(numeric) || numeric <= 0) return undefined;
|
|
577
|
-
return numeric > 1 ? roundWeight(numeric / 100) : roundWeight(numeric);
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
function yahooNumber(value: YahooNumber | undefined): number | undefined {
|
|
581
|
-
const numeric = typeof value === "number" ? value : value?.raw;
|
|
582
|
-
return numeric !== undefined && Number.isFinite(numeric) ? numeric : undefined;
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
function yahooNullableNumber(value: YahooNumber | undefined): number | null {
|
|
586
|
-
return yahooNumber(value) ?? null;
|
|
587
|
-
}
|
|
588
|
-
|
|
589
|
-
function normalizeSectorWeights(
|
|
590
|
-
sectors: Array<Record<string, YahooNumber>> | undefined,
|
|
591
|
-
): Record<string, number> | undefined {
|
|
592
|
-
if (!sectors?.length) return undefined;
|
|
593
|
-
const weights: Record<string, number> = {};
|
|
594
|
-
for (const sector of sectors) {
|
|
595
|
-
for (const [name, rawWeight] of Object.entries(sector)) {
|
|
596
|
-
const weight = normalizeHoldingWeight(rawWeight);
|
|
597
|
-
if (weight !== undefined) weights[name] = weight;
|
|
598
|
-
}
|
|
599
|
-
}
|
|
600
|
-
return Object.keys(weights).length > 0 ? weights : undefined;
|
|
601
|
-
}
|
|
602
|
-
|
|
603
|
-
function roundWeight(value: number): number {
|
|
604
|
-
return Math.round(value * 10_000) / 10_000;
|
|
605
|
-
}
|
|
606
|
-
|
|
607
|
-
// --- Options Chain (v7 API with crumb+cookie auth) ---
|
|
608
|
-
|
|
609
|
-
const BROWSER_UA =
|
|
610
|
-
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";
|
|
611
|
-
const YAHOO_RAW_FETCH_TIMEOUT_MS = 10_000;
|
|
612
|
-
|
|
613
|
-
let cachedCrumb: { crumb: string; cookie: string; expiresAt: number } | null = null;
|
|
614
|
-
|
|
615
|
-
export function clearCrumbCache(): void {
|
|
616
|
-
cachedCrumb = null;
|
|
617
|
-
}
|
|
618
|
-
|
|
619
|
-
export async function getYahooCrumb(): Promise<{ crumb: string; cookie: string }> {
|
|
620
|
-
if (cachedCrumb && Date.now() < cachedCrumb.expiresAt) {
|
|
621
|
-
return { crumb: cachedCrumb.crumb, cookie: cachedCrumb.cookie };
|
|
622
|
-
}
|
|
623
|
-
|
|
624
|
-
// Step 1: Hit fc.yahoo.com to get a session cookie
|
|
625
|
-
const cookieRes = await fetch("https://fc.yahoo.com/t", {
|
|
626
|
-
headers: { "User-Agent": BROWSER_UA },
|
|
627
|
-
signal: yahooRawFetchSignal(),
|
|
628
|
-
});
|
|
629
|
-
const setCookie = cookieRes.headers.get("set-cookie") ?? "";
|
|
630
|
-
const cookie = setCookie.split(";")[0]; // Extract just the cookie value
|
|
631
|
-
if (!cookie) {
|
|
632
|
-
if (!cookieRes.ok) {
|
|
633
|
-
throw new Error(
|
|
634
|
-
`Yahoo crumb cookie request failed: HTTP ${cookieRes.status} ${cookieRes.statusText}`.trim(),
|
|
635
|
-
);
|
|
636
|
-
}
|
|
637
|
-
throw new Error("Yahoo crumb cookie request did not return a session cookie");
|
|
638
|
-
}
|
|
639
|
-
|
|
640
|
-
// Step 2: Use the cookie to get a crumb
|
|
641
|
-
const crumbRes = await fetch("https://query2.finance.yahoo.com/v1/test/getcrumb", {
|
|
642
|
-
headers: { "User-Agent": BROWSER_UA, Cookie: cookie },
|
|
643
|
-
signal: yahooRawFetchSignal(),
|
|
644
|
-
});
|
|
645
|
-
if (!crumbRes.ok) {
|
|
646
|
-
throw new Error(
|
|
647
|
-
`Yahoo crumb request failed: HTTP ${crumbRes.status} ${crumbRes.statusText}`.trim(),
|
|
648
|
-
);
|
|
649
|
-
}
|
|
650
|
-
const crumb = (await crumbRes.text()).trim();
|
|
651
|
-
|
|
652
|
-
if (!crumb || crumb.includes("Unauthorized")) {
|
|
653
|
-
throw new Error("Failed to acquire Yahoo Finance crumb");
|
|
654
|
-
}
|
|
655
|
-
|
|
656
|
-
cachedCrumb = { crumb, cookie, expiresAt: Date.now() + TTL.CRUMB };
|
|
657
|
-
return { crumb, cookie };
|
|
658
|
-
}
|
|
659
|
-
|
|
660
|
-
interface YahooOptionsResponse {
|
|
661
|
-
optionChain: {
|
|
662
|
-
result: Array<{
|
|
663
|
-
underlyingSymbol: string;
|
|
664
|
-
expirationDates: number[];
|
|
665
|
-
strikes: number[];
|
|
666
|
-
quote: Record<string, any>;
|
|
667
|
-
options: Array<{
|
|
668
|
-
expirationDate: number;
|
|
669
|
-
calls: any[];
|
|
670
|
-
puts: any[];
|
|
671
|
-
}>;
|
|
672
|
-
}>;
|
|
673
|
-
error?: any;
|
|
674
|
-
};
|
|
675
|
-
}
|
|
676
|
-
|
|
677
|
-
export async function getOptionsChain(symbol: string, expiration?: number): Promise<OptionsChain> {
|
|
678
|
-
const cacheKey = `yahoo:options:${symbol}:${expiration ?? "nearest"}`;
|
|
679
|
-
const cached = cache.get<OptionsChain>(cacheKey);
|
|
680
|
-
if (cached) return cached;
|
|
681
|
-
|
|
682
|
-
await rateLimiter.acquire("yahoo");
|
|
683
|
-
|
|
684
|
-
const dateParam = expiration ? `&date=${expiration}` : "";
|
|
685
|
-
|
|
686
|
-
let res: Response | null = null;
|
|
687
|
-
let fetchError: unknown;
|
|
688
|
-
try {
|
|
689
|
-
const { crumb, cookie } = await getYahooCrumb();
|
|
690
|
-
const url = `https://query1.finance.yahoo.com/v7/finance/options/${encodeURIComponent(symbol)}?crumb=${encodeURIComponent(crumb)}${dateParam}`;
|
|
691
|
-
res = await fetch(url, {
|
|
692
|
-
headers: { "User-Agent": BROWSER_UA, Cookie: cookie },
|
|
693
|
-
signal: yahooRawFetchSignal(),
|
|
694
|
-
});
|
|
695
|
-
} catch (error) {
|
|
696
|
-
fetchError = error;
|
|
697
|
-
}
|
|
698
|
-
|
|
699
|
-
// On 401 or 429, refresh crumb and retry once
|
|
700
|
-
if (res?.status === 401 || res?.status === 429) {
|
|
701
|
-
try {
|
|
702
|
-
clearCrumbCache();
|
|
703
|
-
const fresh = await getYahooCrumb();
|
|
704
|
-
const retryUrl = `https://query1.finance.yahoo.com/v7/finance/options/${encodeURIComponent(symbol)}?crumb=${encodeURIComponent(fresh.crumb)}${dateParam}`;
|
|
705
|
-
res = await fetch(retryUrl, {
|
|
706
|
-
headers: { "User-Agent": BROWSER_UA, Cookie: fresh.cookie },
|
|
707
|
-
signal: yahooRawFetchSignal(),
|
|
708
|
-
});
|
|
709
|
-
} catch (error) {
|
|
710
|
-
fetchError = error;
|
|
711
|
-
res = null;
|
|
712
|
-
}
|
|
713
|
-
}
|
|
714
|
-
|
|
715
|
-
// If still failing, fall back to stealth browser (bypasses TLS fingerprinting)
|
|
716
|
-
if (!res?.ok) {
|
|
717
|
-
let browserError: unknown;
|
|
718
|
-
try {
|
|
719
|
-
const fallbackData = await fetchOptionsViaYahooFinance2(symbol, expiration);
|
|
720
|
-
if (fallbackData) {
|
|
721
|
-
const chain = parseOptionsResponse(fallbackData);
|
|
722
|
-
cache.set(cacheKey, chain, TTL.OPTIONS_CHAIN);
|
|
723
|
-
return chain;
|
|
724
|
-
}
|
|
725
|
-
} catch (error) {
|
|
726
|
-
browserError = error;
|
|
727
|
-
}
|
|
728
|
-
// All fetches failed — try stale cache before giving up
|
|
729
|
-
const stale = cache.getStale<OptionsChain>(cacheKey, STALE_LIMIT.OPTIONS_CHAIN);
|
|
730
|
-
if (stale) return stale.value;
|
|
731
|
-
if (res) {
|
|
732
|
-
const message = `Yahoo Finance options: HTTP ${res.status}`;
|
|
733
|
-
if (browserError instanceof Error) {
|
|
734
|
-
throw new Error(`${message}; yahoo-finance2 fallback failed: ${browserError.message}`);
|
|
735
|
-
}
|
|
736
|
-
throw new Error(message);
|
|
737
|
-
}
|
|
738
|
-
if (browserError instanceof Error) {
|
|
739
|
-
const message =
|
|
740
|
-
fetchError instanceof Error ? fetchError.message : "Yahoo Finance options: fetch failed";
|
|
741
|
-
throw new Error(`${message}; yahoo-finance2 fallback failed: ${browserError.message}`);
|
|
742
|
-
}
|
|
743
|
-
throw fetchError instanceof Error
|
|
744
|
-
? fetchError
|
|
745
|
-
: new Error("Yahoo Finance options: fetch failed");
|
|
746
|
-
}
|
|
747
|
-
|
|
748
|
-
const data: YahooOptionsResponse = await res.json();
|
|
749
|
-
const chain = parseOptionsResponse(data);
|
|
750
|
-
cache.set(cacheKey, chain, TTL.OPTIONS_CHAIN);
|
|
751
|
-
return chain;
|
|
752
|
-
}
|
|
753
|
-
|
|
754
|
-
function yahooRawFetchSignal(): AbortSignal {
|
|
755
|
-
return AbortSignal.timeout(YAHOO_RAW_FETCH_TIMEOUT_MS);
|
|
756
|
-
}
|
|
757
|
-
|
|
758
|
-
/**
|
|
759
|
-
* Compute time to expiry in years from a Yahoo expiration timestamp (midnight UTC).
|
|
760
|
-
* US equity options expire at 4:00 PM ET. During EDT that is 20:00 UTC.
|
|
761
|
-
* We use 21:00 UTC (4 PM EST / 5 PM EDT) as a conservative close offset
|
|
762
|
-
* and apply a floor of ~1 hour to prevent numerical instability near expiry.
|
|
763
|
-
*/
|
|
764
|
-
export function computeTimeToExpiry(expirationTs: number, nowMs: number = Date.now()): number {
|
|
765
|
-
const MARKET_CLOSE_OFFSET_S = 21 * 3600; // 21:00 UTC ≈ 4 PM ET
|
|
766
|
-
const MIN_TIME_YEARS = 1 / (365 * 24); // ~1 hour floor
|
|
767
|
-
const SECONDS_PER_YEAR = 365 * 24 * 3600;
|
|
768
|
-
|
|
769
|
-
const expiryCloseTs = expirationTs + MARKET_CLOSE_OFFSET_S;
|
|
770
|
-
const remainingS = expiryCloseTs - nowMs / 1000;
|
|
771
|
-
|
|
772
|
-
if (remainingS <= 0) return 0;
|
|
773
|
-
return Math.max(MIN_TIME_YEARS, remainingS / SECONDS_PER_YEAR);
|
|
774
|
-
}
|
|
775
|
-
|
|
776
|
-
function getUsOptionsMarketSession(now: Date = new Date()): OptionsMarketSession {
|
|
777
|
-
const parts = new Intl.DateTimeFormat("en-US", {
|
|
778
|
-
timeZone: "America/New_York",
|
|
779
|
-
weekday: "short",
|
|
780
|
-
hour: "2-digit",
|
|
781
|
-
minute: "2-digit",
|
|
782
|
-
hour12: false,
|
|
783
|
-
}).formatToParts(now);
|
|
784
|
-
const part = (type: string): string => parts.find((p) => p.type === type)?.value ?? "";
|
|
785
|
-
const weekday = part("weekday");
|
|
786
|
-
if (weekday === "Sat" || weekday === "Sun") return "closed";
|
|
787
|
-
|
|
788
|
-
const hour = Number(part("hour"));
|
|
789
|
-
const minute = Number(part("minute"));
|
|
790
|
-
const minutes = hour * 60 + minute;
|
|
791
|
-
if (minutes < 9 * 60 + 30) return "pre_market";
|
|
792
|
-
if (minutes < 16 * 60) return "regular";
|
|
793
|
-
return "after_hours";
|
|
794
|
-
}
|
|
795
|
-
|
|
796
|
-
function buildOptionsQuoteStatus(
|
|
797
|
-
contracts: OptionContract[],
|
|
798
|
-
now: Date = new Date(),
|
|
799
|
-
): OptionsQuoteStatus {
|
|
800
|
-
const marketSession = getUsOptionsMarketSession(now);
|
|
801
|
-
const totalContracts = contracts.length;
|
|
802
|
-
const zeroBidAskContracts = contracts.filter((c) => c.bid === 0 && c.ask === 0).length;
|
|
803
|
-
const allZeroBidAsk = totalContracts > 0 && zeroBidAskContracts === totalContracts;
|
|
804
|
-
const hasLiveBidAsk = contracts.some((c) => c.bid > 0 || c.ask > 0);
|
|
805
|
-
|
|
806
|
-
if (allZeroBidAsk && marketSession !== "regular") {
|
|
807
|
-
return {
|
|
808
|
-
marketSession,
|
|
809
|
-
bidAskState: "closed_market_or_stale_quotes",
|
|
810
|
-
zeroBidAskContracts,
|
|
811
|
-
totalContracts,
|
|
812
|
-
warning:
|
|
813
|
-
"All option contracts have $0.00/$0.00 bid/ask before regular options trading or outside market hours; treat bid/ask as closed-market or stale until the market opens.",
|
|
814
|
-
};
|
|
815
|
-
}
|
|
816
|
-
|
|
817
|
-
if (allZeroBidAsk) {
|
|
818
|
-
return {
|
|
819
|
-
marketSession,
|
|
820
|
-
bidAskState: "live_zero_bid_ask",
|
|
821
|
-
zeroBidAskContracts,
|
|
822
|
-
totalContracts,
|
|
823
|
-
warning:
|
|
824
|
-
"All option contracts have $0.00/$0.00 bid/ask during regular options trading hours; verify with a broker, but this may indicate live illiquidity.",
|
|
825
|
-
};
|
|
826
|
-
}
|
|
827
|
-
|
|
828
|
-
return {
|
|
829
|
-
marketSession,
|
|
830
|
-
bidAskState: hasLiveBidAsk ? "live_quotes" : "mixed_or_unknown",
|
|
831
|
-
zeroBidAskContracts,
|
|
832
|
-
totalContracts,
|
|
833
|
-
...(marketSession !== "regular"
|
|
834
|
-
? {
|
|
835
|
-
warning:
|
|
836
|
-
"Options bid/ask quotes may be stale outside regular options trading hours; verify live executable prices after the market opens.",
|
|
837
|
-
}
|
|
838
|
-
: {}),
|
|
839
|
-
};
|
|
840
|
-
}
|
|
841
|
-
|
|
842
|
-
function parseOptionsResponse(data: YahooOptionsResponse): OptionsChain {
|
|
843
|
-
if (data.optionChain.error) {
|
|
844
|
-
throw new Error(`Yahoo Finance options: ${JSON.stringify(data.optionChain.error)}`);
|
|
845
|
-
}
|
|
846
|
-
|
|
847
|
-
const result = data.optionChain.result[0];
|
|
848
|
-
const quote = result.quote;
|
|
849
|
-
const underlyingPrice = quote.regularMarketPrice ?? 0;
|
|
850
|
-
const opts = result.options[0];
|
|
851
|
-
if (!opts && underlyingPrice === 0) {
|
|
852
|
-
throw new InvalidSymbolError(result.underlyingSymbol, "yahoo");
|
|
853
|
-
}
|
|
854
|
-
const riskFreeRate = 0.05;
|
|
855
|
-
|
|
856
|
-
const expirationTs = opts.expirationDate;
|
|
857
|
-
const expirationDate = new Date(expirationTs * 1000).toISOString().split("T")[0];
|
|
858
|
-
const timeYears = computeTimeToExpiry(expirationTs);
|
|
859
|
-
|
|
860
|
-
const mapContract = (c: any, type: "call" | "put"): OptionContract => {
|
|
861
|
-
const strike = c.strike ?? c.strike?.raw ?? 0;
|
|
862
|
-
const iv = c.impliedVolatility ?? c.impliedVolatility?.raw ?? 0;
|
|
863
|
-
const greeks = computeGreeks({
|
|
864
|
-
type,
|
|
865
|
-
spot: underlyingPrice,
|
|
866
|
-
strike,
|
|
867
|
-
timeYears,
|
|
868
|
-
iv,
|
|
869
|
-
riskFreeRate,
|
|
870
|
-
});
|
|
871
|
-
return {
|
|
872
|
-
contractSymbol: c.contractSymbol ?? "",
|
|
873
|
-
type,
|
|
874
|
-
strike,
|
|
875
|
-
expiration: expirationDate,
|
|
876
|
-
bid: c.bid ?? c.bid?.raw ?? 0,
|
|
877
|
-
ask: c.ask ?? c.ask?.raw ?? 0,
|
|
878
|
-
lastPrice: c.lastPrice ?? c.lastPrice?.raw ?? 0,
|
|
879
|
-
volume: c.volume ?? c.volume?.raw ?? 0,
|
|
880
|
-
openInterest: c.openInterest ?? c.openInterest?.raw ?? 0,
|
|
881
|
-
impliedVolatility: iv,
|
|
882
|
-
inTheMoney: c.inTheMoney ?? false,
|
|
883
|
-
greeks,
|
|
884
|
-
};
|
|
885
|
-
};
|
|
886
|
-
|
|
887
|
-
const calls = (opts.calls ?? []).map((c: any) => mapContract(c, "call"));
|
|
888
|
-
const puts = (opts.puts ?? []).map((c: any) => mapContract(c, "put"));
|
|
889
|
-
const totalCallVolume = calls.reduce((s, c) => s + c.volume, 0);
|
|
890
|
-
const totalPutVolume = puts.reduce((s, c) => s + c.volume, 0);
|
|
891
|
-
const quoteStatus = buildOptionsQuoteStatus([...calls, ...puts]);
|
|
892
|
-
|
|
893
|
-
return {
|
|
894
|
-
symbol: result.underlyingSymbol,
|
|
895
|
-
underlyingPrice,
|
|
896
|
-
expirationDate,
|
|
897
|
-
expirationDates: result.expirationDates.map(
|
|
898
|
-
(ts) => new Date(ts * 1000).toISOString().split("T")[0],
|
|
899
|
-
),
|
|
900
|
-
calls,
|
|
901
|
-
puts,
|
|
902
|
-
totalCallVolume,
|
|
903
|
-
totalPutVolume,
|
|
904
|
-
putCallRatio: totalCallVolume > 0 ? totalPutVolume / totalCallVolume : 0,
|
|
905
|
-
quoteStatus,
|
|
906
|
-
fetchedAt: new Date().toISOString(),
|
|
907
|
-
asOf: yahooMarketTimeToIso(quote.regularMarketTime),
|
|
908
|
-
};
|
|
909
|
-
}
|
|
910
|
-
|
|
911
|
-
/**
|
|
912
|
-
* Fallback: fetch options data via yahoo-finance2 when the raw Yahoo path is blocked.
|
|
913
|
-
*/
|
|
914
|
-
async function fetchOptionsViaYahooFinance2(
|
|
915
|
-
symbol: string,
|
|
916
|
-
expiration?: number,
|
|
917
|
-
): Promise<YahooOptionsResponse | null> {
|
|
918
|
-
try {
|
|
919
|
-
const result = await getYahooFinance2Client().options(
|
|
920
|
-
symbol,
|
|
921
|
-
expiration ? { date: new Date(expiration * 1000) } : undefined,
|
|
922
|
-
);
|
|
923
|
-
return normalizeYahooFinance2OptionsResponse(result);
|
|
924
|
-
} catch (error) {
|
|
925
|
-
throw error instanceof Error ? error : new Error(String(error));
|
|
926
|
-
}
|
|
927
|
-
}
|
|
928
|
-
|
|
929
|
-
function normalizeYahooFinance2OptionsResponse(
|
|
930
|
-
data: YahooFinance2OptionsResult | YahooOptionsResponse,
|
|
931
|
-
): YahooOptionsResponse {
|
|
932
|
-
if ("optionChain" in data) return data as YahooOptionsResponse;
|
|
933
|
-
|
|
934
|
-
const options = data.options.map((option) => ({
|
|
935
|
-
expirationDate: toYahooUnixSeconds(option.expirationDate),
|
|
936
|
-
calls: option.calls,
|
|
937
|
-
puts: option.puts,
|
|
938
|
-
}));
|
|
939
|
-
const strikes = [
|
|
940
|
-
...new Set(
|
|
941
|
-
options
|
|
942
|
-
.flatMap((option) => [...option.calls, ...option.puts])
|
|
943
|
-
.map((contract) => Number((contract as { strike?: unknown }).strike))
|
|
944
|
-
.filter((strike) => Number.isFinite(strike)),
|
|
945
|
-
),
|
|
946
|
-
].sort((a, b) => a - b);
|
|
947
|
-
|
|
948
|
-
return {
|
|
949
|
-
optionChain: {
|
|
950
|
-
result: [
|
|
951
|
-
{
|
|
952
|
-
underlyingSymbol: data.underlyingSymbol,
|
|
953
|
-
expirationDates: data.expirationDates.map(toYahooUnixSeconds),
|
|
954
|
-
strikes,
|
|
955
|
-
quote: data.quote as Record<string, any>,
|
|
956
|
-
options,
|
|
957
|
-
},
|
|
958
|
-
],
|
|
959
|
-
},
|
|
960
|
-
};
|
|
961
|
-
}
|
|
962
|
-
|
|
963
|
-
function toYahooUnixSeconds(value: Date | number | string): number {
|
|
964
|
-
if (value instanceof Date) return Math.floor(value.getTime() / 1000);
|
|
965
|
-
if (typeof value === "number") {
|
|
966
|
-
return value > 1_000_000_000_000 ? Math.floor(value / 1000) : value;
|
|
967
|
-
}
|
|
968
|
-
return Math.floor(new Date(value).getTime() / 1000);
|
|
969
|
-
}
|
|
970
|
-
|
|
971
|
-
function yahooMarketTimeToIso(value: unknown): string | undefined {
|
|
972
|
-
let date: Date | undefined;
|
|
973
|
-
if (value instanceof Date) {
|
|
974
|
-
date = value;
|
|
975
|
-
} else if (typeof value === "number" && Number.isFinite(value)) {
|
|
976
|
-
date = new Date(value < 10_000_000_000 ? value * 1000 : value);
|
|
977
|
-
} else if (typeof value === "string" && value.trim() !== "") {
|
|
978
|
-
const numeric = Number(value);
|
|
979
|
-
date = Number.isFinite(numeric)
|
|
980
|
-
? new Date(numeric < 10_000_000_000 ? numeric * 1000 : numeric)
|
|
981
|
-
: new Date(value);
|
|
982
|
-
}
|
|
983
|
-
return date && Number.isFinite(date.getTime()) ? date.toISOString() : undefined;
|
|
984
|
-
}
|