opencandle 0.5.0 → 0.7.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 +170 -186
- package/dist/analysts/contracts.d.ts +1 -3
- package/dist/analysts/contracts.js +1 -11
- package/dist/analysts/contracts.js.map +1 -1
- package/dist/analysts/orchestrator.d.ts +1 -3
- package/dist/analysts/orchestrator.js +1 -26
- package/dist/analysts/orchestrator.js.map +1 -1
- package/dist/cli.js +66 -7
- package/dist/cli.js.map +1 -1
- package/dist/config.d.ts +13 -3
- package/dist/config.js +25 -5
- package/dist/config.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/infra/cache.d.ts +8 -11
- package/dist/infra/cache.js +17 -15
- package/dist/infra/cache.js.map +1 -1
- package/dist/infra/http-client.d.ts +4 -1
- package/dist/infra/http-client.js +59 -6
- package/dist/infra/http-client.js.map +1 -1
- package/dist/infra/index.d.ts +2 -3
- package/dist/infra/index.js +2 -3
- package/dist/infra/index.js.map +1 -1
- package/dist/infra/native-dependencies.js +2 -2
- package/dist/infra/native-dependencies.js.map +1 -1
- package/dist/infra/node-version.js.map +1 -1
- package/dist/infra/opencandle-paths.d.ts +0 -3
- package/dist/infra/opencandle-paths.js +4 -11
- package/dist/infra/opencandle-paths.js.map +1 -1
- package/dist/infra/rate-limiter.js +12 -9
- package/dist/infra/rate-limiter.js.map +1 -1
- package/dist/market-state/alert-conditions.d.ts +34 -0
- package/dist/market-state/alert-conditions.js +23 -0
- package/dist/market-state/alert-conditions.js.map +1 -0
- package/dist/market-state/alert-runner.d.ts +55 -0
- package/dist/market-state/alert-runner.js +634 -0
- package/dist/market-state/alert-runner.js.map +1 -0
- package/dist/market-state/daily-report.d.ts +26 -0
- package/dist/market-state/daily-report.js +179 -0
- package/dist/market-state/daily-report.js.map +1 -0
- package/dist/market-state/local-automation-service.d.ts +25 -0
- package/dist/market-state/local-automation-service.js +119 -0
- package/dist/market-state/local-automation-service.js.map +1 -0
- package/dist/market-state/notification-delivery.d.ts +14 -0
- package/dist/market-state/notification-delivery.js +139 -0
- package/dist/market-state/notification-delivery.js.map +1 -0
- package/dist/market-state/resolve-for-mutation.d.ts +10 -0
- package/dist/market-state/resolve-for-mutation.js +15 -0
- package/dist/market-state/resolve-for-mutation.js.map +1 -0
- package/dist/market-state/resolve.d.ts +14 -0
- package/dist/market-state/resolve.js +89 -0
- package/dist/market-state/resolve.js.map +1 -0
- package/dist/market-state/service.d.ts +527 -0
- package/dist/market-state/service.js +1099 -0
- package/dist/market-state/service.js.map +1 -0
- package/dist/memory/index.d.ts +7 -7
- package/dist/memory/index.js +6 -6
- package/dist/memory/index.js.map +1 -1
- package/dist/memory/manager.js +11 -11
- package/dist/memory/manager.js.map +1 -1
- package/dist/memory/retrieval.js +7 -4
- package/dist/memory/retrieval.js.map +1 -1
- package/dist/memory/sqlite.js +385 -3
- package/dist/memory/sqlite.js.map +1 -1
- package/dist/memory/storage.js +1 -2
- package/dist/memory/storage.js.map +1 -1
- package/dist/memory/tool-defaults.js +64 -28
- package/dist/memory/tool-defaults.js.map +1 -1
- package/dist/memory/types.js.map +1 -1
- package/dist/monitor.d.ts +2 -0
- package/dist/monitor.js +104 -0
- package/dist/monitor.js.map +1 -0
- package/dist/onboarding/connect.d.ts +2 -2
- package/dist/onboarding/connect.js +13 -8
- package/dist/onboarding/connect.js.map +1 -1
- package/dist/onboarding/credential-interceptor.js +1 -1
- package/dist/onboarding/credential-interceptor.js.map +1 -1
- package/dist/onboarding/degradation-accumulator.js +1 -3
- package/dist/onboarding/degradation-accumulator.js.map +1 -1
- package/dist/onboarding/provider-status.d.ts +48 -0
- package/dist/onboarding/provider-status.js +285 -0
- package/dist/onboarding/provider-status.js.map +1 -0
- package/dist/onboarding/providers.d.ts +85 -8
- package/dist/onboarding/providers.js +83 -18
- package/dist/onboarding/providers.js.map +1 -1
- package/dist/onboarding/state.d.ts +1 -0
- package/dist/onboarding/state.js +5 -0
- package/dist/onboarding/state.js.map +1 -1
- package/dist/onboarding/tool-helpers.js +1 -1
- package/dist/onboarding/tool-helpers.js.map +1 -1
- package/dist/onboarding/tool-tags.d.ts +12 -1
- package/dist/onboarding/tool-tags.js +37 -5
- package/dist/onboarding/tool-tags.js.map +1 -1
- package/dist/onboarding/validation.d.ts +2 -2
- package/dist/onboarding/validation.js +1 -1
- package/dist/onboarding/validation.js.map +1 -1
- package/dist/pi/opencandle-extension.d.ts +8 -0
- package/dist/pi/opencandle-extension.js +502 -42
- package/dist/pi/opencandle-extension.js.map +1 -1
- package/dist/pi/session.d.ts +1 -1
- package/dist/pi/session.js +3 -1
- package/dist/pi/session.js.map +1 -1
- package/dist/pi/setup.js +8 -3
- package/dist/pi/setup.js.map +1 -1
- package/dist/pi/tool-adapter.d.ts +4 -1
- package/dist/pi/tool-adapter.js +10 -6
- package/dist/pi/tool-adapter.js.map +1 -1
- package/dist/prompts/context-builder.d.ts +1 -1
- package/dist/prompts/context-builder.js +20 -7
- package/dist/prompts/context-builder.js.map +1 -1
- package/dist/prompts/policy-cards.d.ts +1 -1
- package/dist/prompts/policy-cards.js +2 -2
- package/dist/prompts/policy-cards.js.map +1 -1
- package/dist/prompts/sections.d.ts +1 -1
- package/dist/prompts/symbol-preflight.d.ts +20 -0
- package/dist/prompts/symbol-preflight.js +49 -0
- package/dist/prompts/symbol-preflight.js.map +1 -0
- package/dist/prompts/workflow-prompts.d.ts +1 -1
- package/dist/prompts/workflow-prompts.js +54 -16
- package/dist/prompts/workflow-prompts.js.map +1 -1
- package/dist/providers/alpha-vantage.d.ts +1 -1
- package/dist/providers/alpha-vantage.js +26 -7
- package/dist/providers/alpha-vantage.js.map +1 -1
- package/dist/providers/coingecko.js +1 -1
- package/dist/providers/coingecko.js.map +1 -1
- package/dist/providers/errors.d.ts +5 -0
- package/dist/providers/errors.js +11 -0
- package/dist/providers/errors.js.map +1 -0
- package/dist/providers/exa-search.d.ts +2 -2
- package/dist/providers/exa-search.js +19 -11
- package/dist/providers/exa-search.js.map +1 -1
- package/dist/providers/external-tool-error.d.ts +10 -0
- package/dist/providers/external-tool-error.js +21 -0
- package/dist/providers/external-tool-error.js.map +1 -0
- package/dist/providers/fear-greed.js +1 -1
- package/dist/providers/fear-greed.js.map +1 -1
- package/dist/providers/finnhub.js +3 -5
- package/dist/providers/finnhub.js.map +1 -1
- package/dist/providers/fred.js +2 -2
- package/dist/providers/fred.js.map +1 -1
- package/dist/providers/index.d.ts +7 -6
- package/dist/providers/index.js +6 -5
- package/dist/providers/index.js.map +1 -1
- package/dist/providers/reddit-cli.d.ts +36 -0
- package/dist/providers/reddit-cli.js +201 -0
- package/dist/providers/reddit-cli.js.map +1 -0
- package/dist/providers/reddit.d.ts +1 -1
- package/dist/providers/reddit.js +9 -37
- package/dist/providers/reddit.js.map +1 -1
- package/dist/providers/sec-edgar.d.ts +1 -0
- package/dist/providers/sec-edgar.js +12 -4
- package/dist/providers/sec-edgar.js.map +1 -1
- package/dist/providers/tradingview.d.ts +47 -0
- package/dist/providers/tradingview.js +275 -0
- package/dist/providers/tradingview.js.map +1 -0
- package/dist/providers/twitter-cli.d.ts +40 -0
- package/dist/providers/twitter-cli.js +153 -0
- package/dist/providers/twitter-cli.js.map +1 -0
- package/dist/providers/twitter.d.ts +0 -8
- package/dist/providers/twitter.js +8 -60
- package/dist/providers/twitter.js.map +1 -1
- package/dist/providers/web-search.js +26 -12
- package/dist/providers/web-search.js.map +1 -1
- package/dist/providers/with-fallback.js +4 -2
- package/dist/providers/with-fallback.js.map +1 -1
- package/dist/providers/wrap-provider.d.ts +2 -3
- package/dist/providers/wrap-provider.js +44 -8
- package/dist/providers/wrap-provider.js.map +1 -1
- package/dist/providers/yahoo-finance.d.ts +1 -1
- package/dist/providers/yahoo-finance.js +153 -48
- package/dist/providers/yahoo-finance.js.map +1 -1
- package/dist/routing/classify-intent.d.ts +6 -0
- package/dist/routing/classify-intent.js +78 -7
- package/dist/routing/classify-intent.js.map +1 -1
- package/dist/routing/defaults.d.ts +1 -1
- package/dist/routing/entity-extractor.d.ts +1 -0
- package/dist/routing/entity-extractor.js +234 -29
- package/dist/routing/entity-extractor.js.map +1 -1
- package/dist/routing/fund-symbols.d.ts +2 -0
- package/dist/routing/fund-symbols.js +55 -0
- package/dist/routing/fund-symbols.js.map +1 -0
- package/dist/routing/horizon.d.ts +1 -0
- package/dist/routing/horizon.js +10 -0
- package/dist/routing/horizon.js.map +1 -0
- package/dist/routing/index.d.ts +10 -10
- package/dist/routing/index.js +6 -6
- package/dist/routing/index.js.map +1 -1
- package/dist/routing/planning.d.ts +2 -2
- package/dist/routing/planning.js +65 -34
- package/dist/routing/planning.js.map +1 -1
- package/dist/routing/route-manifest.d.ts +2 -2
- package/dist/routing/route-manifest.js +25 -4
- package/dist/routing/route-manifest.js.map +1 -1
- package/dist/routing/router-llm-client.js.map +1 -1
- package/dist/routing/router-prompt.js +7 -9
- package/dist/routing/router-prompt.js.map +1 -1
- package/dist/routing/router-types.d.ts +1 -0
- package/dist/routing/router.js +137 -22
- package/dist/routing/router.js.map +1 -1
- package/dist/routing/slot-resolver.d.ts +1 -1
- package/dist/routing/slot-resolver.js +2 -4
- package/dist/routing/slot-resolver.js.map +1 -1
- package/dist/routing/symbol-disambiguator.d.ts +11 -0
- package/dist/routing/symbol-disambiguator.js +52 -0
- package/dist/routing/symbol-disambiguator.js.map +1 -0
- package/dist/routing/turn-context.d.ts +1 -1
- package/dist/routing/turn-context.js +1 -1
- package/dist/routing/turn-context.js.map +1 -1
- package/dist/routing/types.d.ts +2 -0
- package/dist/runtime/answer-contracts.d.ts +1 -1
- package/dist/runtime/answer-contracts.js +48 -9
- package/dist/runtime/answer-contracts.js.map +1 -1
- package/dist/runtime/artifact-contracts.js.map +1 -1
- package/dist/runtime/planning-evidence.js +47 -26
- package/dist/runtime/planning-evidence.js.map +1 -1
- package/dist/runtime/prompt-step.d.ts +1 -9
- package/dist/runtime/prompt-step.js +0 -10
- package/dist/runtime/prompt-step.js.map +1 -1
- package/dist/runtime/run-context.d.ts +5 -2
- package/dist/runtime/run-context.js +8 -1
- package/dist/runtime/run-context.js.map +1 -1
- package/dist/runtime/session-coordinator.d.ts +13 -5
- package/dist/runtime/session-coordinator.js +160 -20
- package/dist/runtime/session-coordinator.js.map +1 -1
- package/dist/runtime/session-title.d.ts +14 -0
- package/dist/runtime/session-title.js +50 -0
- package/dist/runtime/session-title.js.map +1 -0
- package/dist/runtime/tool-defaults-wrapper.js +7 -5
- package/dist/runtime/tool-defaults-wrapper.js.map +1 -1
- package/dist/runtime/validation.js.map +1 -1
- package/dist/runtime/workflow-events.js.map +1 -1
- package/dist/runtime/workflow-runner.d.ts +3 -3
- package/dist/runtime/workflow-runner.js +1 -1
- package/dist/runtime/workflow-runner.js.map +1 -1
- package/dist/sentiment/adapters/finnhub.d.ts +1 -1
- package/dist/sentiment/adapters/finnhub.js +6 -1
- package/dist/sentiment/adapters/finnhub.js.map +1 -1
- package/dist/sentiment/adapters/reddit.d.ts +2 -2
- package/dist/sentiment/adapters/twitter.d.ts +1 -1
- package/dist/sentiment/adapters/web.d.ts +1 -1
- package/dist/sentiment/index.d.ts +10 -11
- package/dist/sentiment/index.js +10 -20
- package/dist/sentiment/index.js.map +1 -1
- package/dist/sentiment/insights.d.ts +17 -0
- package/dist/sentiment/insights.js +206 -0
- package/dist/sentiment/insights.js.map +1 -0
- package/dist/sentiment/keywords.js +26 -4
- package/dist/sentiment/keywords.js.map +1 -1
- package/dist/sentiment/pipeline.d.ts +2 -2
- package/dist/sentiment/pipeline.js +14 -2
- package/dist/sentiment/pipeline.js.map +1 -1
- package/dist/sentiment/scorer.d.ts +2 -0
- package/dist/sentiment/scorer.js +11 -2
- package/dist/sentiment/scorer.js.map +1 -1
- package/dist/sentiment/store.d.ts +1 -1
- package/dist/sentiment/store.js +1 -1
- package/dist/sentiment/store.js.map +1 -1
- package/dist/sentiment/trends.d.ts +1 -1
- package/dist/sentiment/trends.js.map +1 -1
- package/dist/sentiment/types.d.ts +2 -0
- package/dist/sentiment/types.js.map +1 -1
- package/dist/system-prompt.js +6 -9
- package/dist/system-prompt.js.map +1 -1
- package/dist/tool-kit.d.ts +7 -7
- package/dist/tool-kit.js +4 -4
- package/dist/tool-kit.js.map +1 -1
- package/dist/tools/fundamentals/company-overview.js +11 -6
- package/dist/tools/fundamentals/company-overview.js.map +1 -1
- package/dist/tools/fundamentals/comps.js +18 -9
- package/dist/tools/fundamentals/comps.js.map +1 -1
- package/dist/tools/fundamentals/dcf.js +23 -11
- package/dist/tools/fundamentals/dcf.js.map +1 -1
- package/dist/tools/fundamentals/earnings.js +8 -3
- package/dist/tools/fundamentals/earnings.js.map +1 -1
- package/dist/tools/fundamentals/financials.js +8 -3
- package/dist/tools/fundamentals/financials.js.map +1 -1
- package/dist/tools/fundamentals/sec-filings.js +21 -6
- package/dist/tools/fundamentals/sec-filings.js.map +1 -1
- package/dist/tools/index.d.ts +27 -20
- package/dist/tools/index.js +55 -43
- package/dist/tools/index.js.map +1 -1
- package/dist/tools/interaction/ask-user.js +15 -3
- package/dist/tools/interaction/ask-user.js.map +1 -1
- package/dist/tools/macro/fear-greed.js.map +1 -1
- package/dist/tools/macro/fred-data.d.ts +1 -1
- package/dist/tools/macro/fred-data.js +17 -6
- package/dist/tools/macro/fred-data.js.map +1 -1
- package/dist/tools/market/crypto-history.js +3 -1
- package/dist/tools/market/crypto-history.js.map +1 -1
- package/dist/tools/market/crypto-price.js +3 -1
- package/dist/tools/market/crypto-price.js.map +1 -1
- package/dist/tools/market/screen-stocks.d.ts +18 -0
- package/dist/tools/market/screen-stocks.js +252 -0
- package/dist/tools/market/screen-stocks.js.map +1 -0
- package/dist/tools/market/search-ticker.js +160 -8
- package/dist/tools/market/search-ticker.js.map +1 -1
- package/dist/tools/market/stock-history.d.ts +2 -2
- package/dist/tools/market/stock-history.js +26 -7
- package/dist/tools/market/stock-history.js.map +1 -1
- package/dist/tools/market/stock-quote.js +5 -3
- package/dist/tools/market/stock-quote.js.map +1 -1
- package/dist/tools/options/greeks.js +1 -1
- package/dist/tools/options/greeks.js.map +1 -1
- package/dist/tools/options/option-chain.js +19 -6
- package/dist/tools/options/option-chain.js.map +1 -1
- package/dist/tools/portfolio/alerts.d.ts +15 -0
- package/dist/tools/portfolio/alerts.js +357 -0
- package/dist/tools/portfolio/alerts.js.map +1 -0
- package/dist/tools/portfolio/correlation.d.ts +1 -1
- package/dist/tools/portfolio/correlation.js +33 -13
- package/dist/tools/portfolio/correlation.js.map +1 -1
- package/dist/tools/portfolio/daily-report.d.ts +8 -0
- package/dist/tools/portfolio/daily-report.js +83 -0
- package/dist/tools/portfolio/daily-report.js.map +1 -0
- package/dist/tools/portfolio/holdings-overlap.js +10 -3
- package/dist/tools/portfolio/holdings-overlap.js.map +1 -1
- package/dist/tools/portfolio/notifications.d.ts +7 -0
- package/dist/tools/portfolio/notifications.js +43 -0
- package/dist/tools/portfolio/notifications.js.map +1 -0
- package/dist/tools/portfolio/predictions.d.ts +12 -6
- package/dist/tools/portfolio/predictions.js +337 -87
- package/dist/tools/portfolio/predictions.js.map +1 -1
- package/dist/tools/portfolio/risk-analysis.d.ts +1 -1
- package/dist/tools/portfolio/risk-analysis.js +45 -6
- package/dist/tools/portfolio/risk-analysis.js.map +1 -1
- package/dist/tools/portfolio/tracker.d.ts +4 -3
- package/dist/tools/portfolio/tracker.js +246 -101
- package/dist/tools/portfolio/tracker.js.map +1 -1
- package/dist/tools/portfolio/watchlist.d.ts +6 -4
- package/dist/tools/portfolio/watchlist.js +208 -108
- package/dist/tools/portfolio/watchlist.js.map +1 -1
- package/dist/tools/sentiment/insight-format.d.ts +2 -0
- package/dist/tools/sentiment/insight-format.js +36 -0
- package/dist/tools/sentiment/insight-format.js.map +1 -0
- package/dist/tools/sentiment/query-match.d.ts +3 -0
- package/dist/tools/sentiment/query-match.js +113 -0
- package/dist/tools/sentiment/query-match.js.map +1 -0
- package/dist/tools/sentiment/reddit-sentiment.d.ts +12 -1
- package/dist/tools/sentiment/reddit-sentiment.js +266 -107
- package/dist/tools/sentiment/reddit-sentiment.js.map +1 -1
- package/dist/tools/sentiment/sentiment-summary.d.ts +9 -1
- package/dist/tools/sentiment/sentiment-summary.js +223 -205
- package/dist/tools/sentiment/sentiment-summary.js.map +1 -1
- package/dist/tools/sentiment/sentiment-trend.d.ts +1 -1
- package/dist/tools/sentiment/sentiment-trend.js +12 -2
- package/dist/tools/sentiment/sentiment-trend.js.map +1 -1
- package/dist/tools/sentiment/twitter-sentiment.d.ts +11 -1
- package/dist/tools/sentiment/twitter-sentiment.js +188 -58
- package/dist/tools/sentiment/twitter-sentiment.js.map +1 -1
- package/dist/tools/sentiment/untrusted-text.d.ts +2 -0
- package/dist/tools/sentiment/untrusted-text.js +17 -0
- package/dist/tools/sentiment/untrusted-text.js.map +1 -0
- package/dist/tools/sentiment/web-search.js +9 -13
- package/dist/tools/sentiment/web-search.js.map +1 -1
- package/dist/tools/sentiment/web-sentiment.js +19 -3
- package/dist/tools/sentiment/web-sentiment.js.map +1 -1
- package/dist/tools/technical/backtest.d.ts +1 -1
- package/dist/tools/technical/backtest.js +27 -20
- package/dist/tools/technical/backtest.js.map +1 -1
- package/dist/tools/technical/indicators.js +23 -5
- package/dist/tools/technical/indicators.js.map +1 -1
- package/dist/types/index.d.ts +3 -3
- package/dist/types/index.js.map +1 -1
- package/dist/types/market.d.ts +1 -0
- package/dist/types/portfolio.d.ts +14 -4
- package/dist/types/sentiment.d.ts +52 -0
- package/dist/workflows/compare-assets.d.ts +0 -3
- package/dist/workflows/compare-assets.js +20 -11
- package/dist/workflows/compare-assets.js.map +1 -1
- package/dist/workflows/index.d.ts +3 -4
- package/dist/workflows/index.js +3 -3
- package/dist/workflows/index.js.map +1 -1
- package/dist/workflows/options-screener.d.ts +0 -3
- package/dist/workflows/options-screener.js +4 -11
- package/dist/workflows/options-screener.js.map +1 -1
- package/dist/workflows/portfolio-builder.d.ts +0 -3
- package/dist/workflows/portfolio-builder.js +0 -8
- package/dist/workflows/portfolio-builder.js.map +1 -1
- package/gui/server/ask-user-bridge.ts +1 -1
- package/gui/server/automation-heartbeat.ts +97 -0
- package/gui/server/background-quotes.ts +97 -1
- package/gui/server/chat-event-adapter.ts +32 -10
- package/gui/server/chat-run-session.ts +16 -0
- package/gui/server/invoke-tool.ts +160 -3
- package/gui/server/live-chat-event-adapter.ts +21 -6
- package/gui/server/market-state-api.ts +315 -0
- package/gui/server/model-setup.ts +156 -2
- package/gui/server/private-api-access.ts +62 -0
- package/gui/server/projector.ts +18 -9
- package/gui/server/prompt-observation.ts +4 -7
- package/gui/server/quote-snapshot-store.ts +50 -0
- package/gui/server/server.ts +218 -451
- package/gui/server/session-actions.ts +186 -1
- package/gui/server/shutdown.ts +47 -0
- package/gui/server/tool-invoke-ack.ts +49 -0
- package/gui/server/tool-metadata.ts +101 -24
- package/gui/server/websocket.ts +13 -3
- package/gui/server/writer-lock.ts +6 -2
- package/gui/server/ws-hub.ts +311 -0
- package/gui/shared/chat-events.ts +16 -1
- package/gui/shared/event-reducer.ts +24 -6
- package/gui/web/dist/assets/CatalogOverlay-CgeY5Pkp.js +1 -0
- package/gui/web/dist/assets/index-C6W_2eAn.js +69 -0
- package/gui/web/dist/assets/index-hwbx24a5.css +1 -0
- package/gui/web/dist/index.html +2 -2
- package/package.json +9 -6
- package/src/analysts/contracts.ts +10 -23
- package/src/analysts/orchestrator.ts +8 -43
- package/src/cli.ts +76 -12
- package/src/config.ts +44 -9
- package/src/index.ts +1 -1
- package/src/infra/cache.ts +41 -30
- package/src/infra/http-client.ts +72 -6
- package/src/infra/index.ts +6 -10
- package/src/infra/native-dependencies.ts +8 -3
- package/src/infra/node-version.ts +3 -1
- package/src/infra/opencandle-paths.ts +3 -14
- package/src/infra/rate-limiter.ts +22 -19
- package/src/market-state/alert-conditions.ts +82 -0
- package/src/market-state/alert-runner.ts +863 -0
- package/src/market-state/daily-report.ts +247 -0
- package/src/market-state/local-automation-service.ts +162 -0
- package/src/market-state/notification-delivery.ts +158 -0
- package/src/market-state/resolve-for-mutation.ts +24 -0
- package/src/market-state/resolve.ts +112 -0
- package/src/market-state/service.ts +2344 -0
- package/src/memory/index.ts +7 -7
- package/src/memory/manager.ts +14 -16
- package/src/memory/retrieval.ts +8 -7
- package/src/memory/sqlite.ts +407 -6
- package/src/memory/storage.ts +5 -15
- package/src/memory/tool-defaults.ts +60 -39
- package/src/memory/types.ts +3 -3
- package/src/monitor.ts +121 -0
- package/src/onboarding/connect.ts +24 -31
- package/src/onboarding/credential-interceptor.ts +3 -15
- package/src/onboarding/degradation-accumulator.ts +1 -3
- package/src/onboarding/provider-status.ts +410 -0
- package/src/onboarding/providers.ts +144 -45
- package/src/onboarding/state.ts +13 -15
- package/src/onboarding/tool-helpers.ts +2 -9
- package/src/onboarding/tool-tags.ts +51 -8
- package/src/onboarding/validation.ts +16 -22
- package/src/pi/opencandle-extension.ts +643 -101
- package/src/pi/session.ts +7 -5
- package/src/pi/setup.ts +61 -43
- package/src/pi/tool-adapter.ts +19 -6
- package/src/prompts/context-builder.ts +24 -13
- package/src/prompts/policy-cards.ts +3 -3
- package/src/prompts/sections.ts +1 -1
- package/src/prompts/symbol-preflight.ts +80 -0
- package/src/prompts/workflow-prompts.ts +77 -28
- package/src/providers/alpha-vantage.ts +58 -39
- package/src/providers/coingecko.ts +2 -5
- package/src/providers/errors.ts +9 -0
- package/src/providers/exa-search.ts +24 -22
- package/src/providers/external-tool-error.ts +20 -0
- package/src/providers/fear-greed.ts +1 -1
- package/src/providers/finnhub.ts +7 -6
- package/src/providers/fred.ts +3 -3
- package/src/providers/index.ts +14 -6
- package/src/providers/reddit-cli.ts +317 -0
- package/src/providers/reddit.ts +14 -59
- package/src/providers/sec-edgar.ts +20 -6
- package/src/providers/tradingview.ts +399 -0
- package/src/providers/twitter-cli.ts +233 -0
- package/src/providers/twitter.ts +8 -79
- package/src/providers/web-search.ts +30 -20
- package/src/providers/with-fallback.ts +8 -7
- package/src/providers/wrap-provider.ts +49 -10
- package/src/providers/yahoo-finance.ts +204 -66
- package/src/routing/classify-intent.ts +101 -10
- package/src/routing/defaults.ts +1 -1
- package/src/routing/entity-extractor.ts +287 -38
- package/src/routing/fund-symbols.ts +58 -0
- package/src/routing/horizon.ts +7 -0
- package/src/routing/index.ts +48 -48
- package/src/routing/planning.ts +145 -53
- package/src/routing/route-manifest.ts +37 -15
- package/src/routing/router-llm-client.ts +4 -4
- package/src/routing/router-prompt.ts +15 -19
- package/src/routing/router-types.ts +2 -5
- package/src/routing/router.ts +251 -53
- package/src/routing/slot-resolver.ts +34 -11
- package/src/routing/symbol-disambiguator.ts +72 -0
- package/src/routing/turn-context.ts +6 -9
- package/src/routing/types.ts +2 -0
- package/src/runtime/answer-contracts.ts +105 -45
- package/src/runtime/artifact-contracts.ts +2 -1
- package/src/runtime/planning-evidence.ts +157 -66
- package/src/runtime/prompt-step.ts +1 -16
- package/src/runtime/run-context.ts +12 -2
- package/src/runtime/session-coordinator.ts +238 -63
- package/src/runtime/session-title.ts +60 -0
- package/src/runtime/tool-defaults-wrapper.ts +13 -5
- package/src/runtime/validation.ts +1 -4
- package/src/runtime/workflow-events.ts +7 -7
- package/src/runtime/workflow-runner.ts +5 -11
- package/src/sentiment/adapters/finnhub.ts +7 -2
- package/src/sentiment/adapters/reddit.ts +2 -2
- package/src/sentiment/adapters/twitter.ts +1 -1
- package/src/sentiment/adapters/web.ts +1 -1
- package/src/sentiment/index.ts +17 -26
- package/src/sentiment/insights.ts +269 -0
- package/src/sentiment/keywords.ts +26 -4
- package/src/sentiment/pipeline.ts +28 -5
- package/src/sentiment/scorer.ts +13 -2
- package/src/sentiment/store.ts +2 -2
- package/src/sentiment/trends.ts +9 -3
- package/src/sentiment/types.ts +8 -4
- package/src/system-prompt.ts +6 -9
- package/src/tool-kit.ts +10 -9
- package/src/tools/fundamentals/company-overview.ts +19 -9
- package/src/tools/fundamentals/comps.ts +68 -55
- package/src/tools/fundamentals/dcf.ts +145 -95
- package/src/tools/fundamentals/earnings.ts +16 -6
- package/src/tools/fundamentals/financials.ts +16 -7
- package/src/tools/fundamentals/sec-filings.ts +37 -16
- package/src/tools/index.ts +56 -43
- package/src/tools/interaction/ask-user.ts +22 -10
- package/src/tools/macro/fear-greed.ts +1 -1
- package/src/tools/macro/fred-data.ts +58 -46
- package/src/tools/market/crypto-history.ts +8 -3
- package/src/tools/market/crypto-price.ts +6 -6
- package/src/tools/market/screen-stocks.ts +279 -0
- package/src/tools/market/search-ticker.ts +218 -17
- package/src/tools/market/stock-history.ts +37 -12
- package/src/tools/market/stock-quote.ts +10 -7
- package/src/tools/options/greeks.ts +5 -5
- package/src/tools/options/option-chain.ts +41 -17
- package/src/tools/portfolio/alerts.ts +457 -0
- package/src/tools/portfolio/correlation.ts +47 -20
- package/src/tools/portfolio/daily-report.ts +101 -0
- package/src/tools/portfolio/holdings-overlap.ts +31 -15
- package/src/tools/portfolio/notifications.ts +45 -0
- package/src/tools/portfolio/predictions.ts +406 -106
- package/src/tools/portfolio/risk-analysis.ts +46 -7
- package/src/tools/portfolio/tracker.ts +270 -109
- package/src/tools/portfolio/watchlist.ts +250 -121
- package/src/tools/sentiment/insight-format.ts +50 -0
- package/src/tools/sentiment/query-match.ts +117 -0
- package/src/tools/sentiment/reddit-sentiment.ts +360 -121
- package/src/tools/sentiment/sentiment-summary.ts +302 -235
- package/src/tools/sentiment/sentiment-trend.ts +24 -7
- package/src/tools/sentiment/twitter-sentiment.ts +264 -73
- package/src/tools/sentiment/untrusted-text.ts +21 -0
- package/src/tools/sentiment/web-search.ts +21 -18
- package/src/tools/sentiment/web-sentiment.ts +30 -10
- package/src/tools/technical/backtest.ts +32 -22
- package/src/tools/technical/indicators.ts +39 -14
- package/src/types/index.ts +8 -3
- package/src/types/market.ts +1 -0
- package/src/types/portfolio.ts +14 -4
- package/src/types/sentiment.ts +61 -2
- package/src/workflows/compare-assets.ts +33 -21
- package/src/workflows/index.ts +3 -4
- package/src/workflows/options-screener.ts +27 -29
- package/src/workflows/portfolio-builder.ts +34 -27
- package/dist/infra/browser.d.ts +0 -35
- package/dist/infra/browser.js +0 -103
- package/dist/infra/browser.js.map +0 -1
- package/dist/tools/interaction/twitter-login.d.ts +0 -8
- package/dist/tools/interaction/twitter-login.js +0 -77
- package/dist/tools/interaction/twitter-login.js.map +0 -1
- package/dist/workflows/types.d.ts +0 -4
- package/dist/workflows/types.js +0 -2
- package/dist/workflows/types.js.map +0 -1
- package/gui/web/dist/assets/CatalogOverlay-Bmp6Knu7.js +0 -1
- package/gui/web/dist/assets/index-Bxt9QpLX.css +0 -1
- package/gui/web/dist/assets/index-CZ9DHZYy.js +0 -67
- package/src/infra/browser.ts +0 -111
- package/src/tools/interaction/twitter-login.ts +0 -93
- package/src/workflows/types.ts +0 -4
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { wrapProvider } from "../providers/wrap-provider.js";
|
|
2
|
+
import { getQuote } from "../providers/yahoo-finance.js";
|
|
3
|
+
import { isZeroFilledQuote } from "./resolve.js";
|
|
4
|
+
import type { MarketStateService, ReportRunRecord, ReportTemplateRecord } from "./service.js";
|
|
5
|
+
|
|
6
|
+
export interface DailyWatchlistReportSummary {
|
|
7
|
+
watchlistId: number;
|
|
8
|
+
symbols: string[];
|
|
9
|
+
quoteCount: number;
|
|
10
|
+
dataGapCount: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export interface DailyWatchlistReport {
|
|
14
|
+
generatedAt: string;
|
|
15
|
+
text: string;
|
|
16
|
+
summary: DailyWatchlistReportSummary;
|
|
17
|
+
dataGaps: string[];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function getOrCreateDefaultWatchlistReportTemplate(
|
|
21
|
+
service: MarketStateService,
|
|
22
|
+
): ReportTemplateRecord {
|
|
23
|
+
const existing = service
|
|
24
|
+
.listReportTemplates()
|
|
25
|
+
.find(
|
|
26
|
+
(template) =>
|
|
27
|
+
template.reportType === "watchlist_daily" && targetsDefaultWatchlist(template.configJson),
|
|
28
|
+
);
|
|
29
|
+
if (existing) return existing;
|
|
30
|
+
return service.createReportTemplate({
|
|
31
|
+
name: "Morning watchlist",
|
|
32
|
+
reportType: "watchlist_daily",
|
|
33
|
+
cadence: "daily",
|
|
34
|
+
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
35
|
+
localTime: "08:00",
|
|
36
|
+
config: { targets: { default_watchlist: true } },
|
|
37
|
+
enabled: true,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export async function recordDailyWatchlistReportRun(
|
|
42
|
+
service: MarketStateService,
|
|
43
|
+
params: {
|
|
44
|
+
templateId?: number | null;
|
|
45
|
+
triggerType: "manual" | "scheduled";
|
|
46
|
+
scheduledFor?: string | null;
|
|
47
|
+
ownerId?: string | null;
|
|
48
|
+
},
|
|
49
|
+
): Promise<{ report: DailyWatchlistReport; run: ReportRunRecord }> {
|
|
50
|
+
const report = await generateDailyWatchlistReport(service);
|
|
51
|
+
const run = service.recordReportRun({
|
|
52
|
+
templateId: params.templateId,
|
|
53
|
+
startedAt: report.generatedAt,
|
|
54
|
+
completedAt: new Date().toISOString(),
|
|
55
|
+
status: "completed",
|
|
56
|
+
triggerType: params.triggerType,
|
|
57
|
+
scheduledFor: params.scheduledFor,
|
|
58
|
+
ownerId: params.ownerId,
|
|
59
|
+
summary: { ...report.summary, text: report.text },
|
|
60
|
+
errors: report.dataGaps,
|
|
61
|
+
});
|
|
62
|
+
service.recordNotificationEvent({
|
|
63
|
+
sourceType: "report_run",
|
|
64
|
+
sourceId: run.id,
|
|
65
|
+
severity: report.dataGaps.length > 0 ? "warning" : "info",
|
|
66
|
+
title: "Daily watchlist report generated",
|
|
67
|
+
body: `Generated ${report.summary.quoteCount} quote(s) with ${report.dataGaps.length} data gap(s).`,
|
|
68
|
+
payload: report.summary,
|
|
69
|
+
createdAt: run.completedAt ?? report.generatedAt,
|
|
70
|
+
});
|
|
71
|
+
return { report, run };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export async function generateDailyWatchlistReport(
|
|
75
|
+
service: MarketStateService,
|
|
76
|
+
): Promise<DailyWatchlistReport> {
|
|
77
|
+
const generatedAt = new Date().toISOString();
|
|
78
|
+
const watchlist = service.getDefaultWatchlist();
|
|
79
|
+
const items = service.listWatchlistItems(watchlist.id);
|
|
80
|
+
const dataGaps: string[] = [];
|
|
81
|
+
|
|
82
|
+
const quotes = await Promise.all(
|
|
83
|
+
items.map(async (item) => {
|
|
84
|
+
const result = await wrapProvider("yahoo", () => getQuote(item.symbol));
|
|
85
|
+
if (result.status === "unavailable") {
|
|
86
|
+
dataGaps.push(`${item.symbol}: ${result.reason}`);
|
|
87
|
+
return null;
|
|
88
|
+
}
|
|
89
|
+
if (result.stale) {
|
|
90
|
+
dataGaps.push(`${item.symbol}: provider returned stale market data`);
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
if (isZeroFilledQuote(result.data)) {
|
|
94
|
+
dataGaps.push(`${item.symbol}: Yahoo returned no valid market data.`);
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
return { item, quote: result.data };
|
|
98
|
+
}),
|
|
99
|
+
);
|
|
100
|
+
|
|
101
|
+
const validQuotes = quotes.filter((q) => q != null);
|
|
102
|
+
const movers = [...validQuotes].sort(
|
|
103
|
+
(a, b) => Math.abs(b.quote.changePercent) - Math.abs(a.quote.changePercent),
|
|
104
|
+
);
|
|
105
|
+
const freshnessLines =
|
|
106
|
+
validQuotes.length === 0 ? [` No quote data available.`] : quoteFreshnessLines(validQuotes);
|
|
107
|
+
const moverLines =
|
|
108
|
+
movers.length === 0
|
|
109
|
+
? [` No movers available.`]
|
|
110
|
+
: movers
|
|
111
|
+
.slice(0, 5)
|
|
112
|
+
.map(
|
|
113
|
+
({ item, quote }) =>
|
|
114
|
+
` ${item.symbol}: ${formatSigned(quote.changePercent)}% to $${quote.price.toFixed(2)}`,
|
|
115
|
+
);
|
|
116
|
+
const dataGapLines = dataGaps.length === 0 ? [` None.`] : dataGaps.map((gap) => ` ${gap}`);
|
|
117
|
+
|
|
118
|
+
const lines = [
|
|
119
|
+
`**Daily Watchlist Report**`,
|
|
120
|
+
`Generated: ${generatedAt}`,
|
|
121
|
+
`Target watchlist: ${watchlist.name}`,
|
|
122
|
+
``,
|
|
123
|
+
`Quote freshness`,
|
|
124
|
+
...freshnessLines,
|
|
125
|
+
``,
|
|
126
|
+
`Major movers`,
|
|
127
|
+
...moverLines,
|
|
128
|
+
``,
|
|
129
|
+
`Recent alerts`,
|
|
130
|
+
` ${service.listAlertEvents().length} recorded alert event(s).`,
|
|
131
|
+
``,
|
|
132
|
+
`Technical snapshot`,
|
|
133
|
+
` Deferred unless quote/history data is available through a later section builder.`,
|
|
134
|
+
``,
|
|
135
|
+
`Data gaps`,
|
|
136
|
+
...dataGapLines,
|
|
137
|
+
];
|
|
138
|
+
|
|
139
|
+
return {
|
|
140
|
+
generatedAt,
|
|
141
|
+
text: lines.join("\n"),
|
|
142
|
+
summary: {
|
|
143
|
+
watchlistId: watchlist.id,
|
|
144
|
+
symbols: items.map((item) => item.symbol),
|
|
145
|
+
quoteCount: validQuotes.length,
|
|
146
|
+
dataGapCount: dataGaps.length,
|
|
147
|
+
},
|
|
148
|
+
dataGaps,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function nextDailyReportRunAt(
|
|
153
|
+
timezone: string,
|
|
154
|
+
localTime: string,
|
|
155
|
+
now = new Date(),
|
|
156
|
+
): string {
|
|
157
|
+
const [hourPart, minutePart] = localTime.split(":");
|
|
158
|
+
const hour = Number(hourPart);
|
|
159
|
+
const minute = Number(minutePart);
|
|
160
|
+
if (
|
|
161
|
+
!Number.isInteger(hour) ||
|
|
162
|
+
!Number.isInteger(minute) ||
|
|
163
|
+
hour < 0 ||
|
|
164
|
+
hour > 23 ||
|
|
165
|
+
minute < 0 ||
|
|
166
|
+
minute > 59
|
|
167
|
+
) {
|
|
168
|
+
throw new Error(`Invalid report local_time: ${localTime}`);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const today = zonedDateParts(now, timezone);
|
|
172
|
+
let candidate = zonedTimeToUtc(today, hour, minute, timezone);
|
|
173
|
+
if (candidate.getTime() <= now.getTime()) {
|
|
174
|
+
const tomorrow = new Date(Date.UTC(today.year, today.month - 1, today.day + 1, 12, 0, 0));
|
|
175
|
+
candidate = zonedTimeToUtc(zonedDateParts(tomorrow, timezone), hour, minute, timezone);
|
|
176
|
+
}
|
|
177
|
+
return candidate.toISOString();
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export function targetsDefaultWatchlist(config: unknown): boolean {
|
|
181
|
+
if (typeof config !== "object" || config === null) return false;
|
|
182
|
+
const targets = (config as { targets?: unknown }).targets;
|
|
183
|
+
if (typeof targets !== "object" || targets === null) return false;
|
|
184
|
+
return (targets as { default_watchlist?: unknown }).default_watchlist === true;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function quoteFreshnessLines(
|
|
188
|
+
quotes: Array<{ item: { symbol: string }; quote: { timestamp: number; price: number } }>,
|
|
189
|
+
): string[] {
|
|
190
|
+
return quotes.map(
|
|
191
|
+
({ item, quote }) =>
|
|
192
|
+
` ${item.symbol}: $${quote.price.toFixed(2)} as of ${new Date(quote.timestamp).toISOString()}`,
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function formatSigned(value: number): string {
|
|
197
|
+
return `${value >= 0 ? "+" : ""}${value.toFixed(2)}`;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function zonedDateParts(
|
|
201
|
+
date: Date,
|
|
202
|
+
timezone: string,
|
|
203
|
+
): { year: number; month: number; day: number } {
|
|
204
|
+
const parts = new Intl.DateTimeFormat("en-CA", {
|
|
205
|
+
timeZone: timezone,
|
|
206
|
+
year: "numeric",
|
|
207
|
+
month: "2-digit",
|
|
208
|
+
day: "2-digit",
|
|
209
|
+
}).formatToParts(date);
|
|
210
|
+
return {
|
|
211
|
+
year: numberPart(parts, "year"),
|
|
212
|
+
month: numberPart(parts, "month"),
|
|
213
|
+
day: numberPart(parts, "day"),
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function zonedTimeToUtc(
|
|
218
|
+
date: { year: number; month: number; day: number },
|
|
219
|
+
hour: number,
|
|
220
|
+
minute: number,
|
|
221
|
+
timezone: string,
|
|
222
|
+
): Date {
|
|
223
|
+
const naiveUtc = new Date(Date.UTC(date.year, date.month - 1, date.day, hour, minute, 0));
|
|
224
|
+
const offsetMs = timeZoneOffsetMs(naiveUtc, timezone);
|
|
225
|
+
return new Date(naiveUtc.getTime() - offsetMs);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function timeZoneOffsetMs(date: Date, timezone: string): number {
|
|
229
|
+
const parts = new Intl.DateTimeFormat("en-US", {
|
|
230
|
+
timeZone: timezone,
|
|
231
|
+
timeZoneName: "shortOffset",
|
|
232
|
+
hour: "2-digit",
|
|
233
|
+
}).formatToParts(date);
|
|
234
|
+
const value = parts.find((part) => part.type === "timeZoneName")?.value ?? "GMT";
|
|
235
|
+
const match = /^GMT(?<sign>[+-])(?<hours>\d{1,2})(?::(?<minutes>\d{2}))?$/.exec(value);
|
|
236
|
+
if (!match?.groups) return 0;
|
|
237
|
+
const sign = match.groups.sign === "-" ? -1 : 1;
|
|
238
|
+
const hours = Number(match.groups.hours);
|
|
239
|
+
const minutes = Number(match.groups.minutes ?? "0");
|
|
240
|
+
return sign * ((hours * 60 + minutes) * 60_000);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function numberPart(parts: Intl.DateTimeFormatPart[], type: Intl.DateTimeFormatPartTypes): number {
|
|
244
|
+
const value = parts.find((part) => part.type === type)?.value;
|
|
245
|
+
if (value == null) throw new Error(`Missing ${type} in formatted date`);
|
|
246
|
+
return Number(value);
|
|
247
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import type Database from "better-sqlite3";
|
|
2
|
+
import {
|
|
3
|
+
type AlertRunnerProviders,
|
|
4
|
+
type AlertRunnerResult,
|
|
5
|
+
defaultAlertRunnerProviders,
|
|
6
|
+
runAlertChecks,
|
|
7
|
+
} from "./alert-runner.js";
|
|
8
|
+
import { nextDailyReportRunAt, recordDailyWatchlistReportRun } from "./daily-report.js";
|
|
9
|
+
import { deliverPendingNotifications } from "./notification-delivery.js";
|
|
10
|
+
import {
|
|
11
|
+
type AutomationRunnerLeaseResult,
|
|
12
|
+
MarketStateService,
|
|
13
|
+
type ReportRunRecord,
|
|
14
|
+
} from "./service.js";
|
|
15
|
+
|
|
16
|
+
type DailyReportRunRecorder = typeof recordDailyWatchlistReportRun;
|
|
17
|
+
type NotificationDeliverer = typeof deliverPendingNotifications;
|
|
18
|
+
|
|
19
|
+
export interface LocalAutomationHeartbeatResult {
|
|
20
|
+
lease: AutomationRunnerLeaseResult;
|
|
21
|
+
alertCheck: AlertRunnerResult | null;
|
|
22
|
+
reportRuns: ReportRunRecord[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function runLocalAutomationHeartbeat(
|
|
26
|
+
db: Database.Database,
|
|
27
|
+
params: {
|
|
28
|
+
ownerId: string;
|
|
29
|
+
ownerKind: "writer" | "monitor";
|
|
30
|
+
now?: string;
|
|
31
|
+
ttlSeconds?: number;
|
|
32
|
+
checkAlerts?: boolean;
|
|
33
|
+
checkReports?: boolean;
|
|
34
|
+
providers?: AlertRunnerProviders;
|
|
35
|
+
recordDailyReportRun?: DailyReportRunRecorder;
|
|
36
|
+
deliverNotifications?: NotificationDeliverer;
|
|
37
|
+
releaseLeaseOnComplete?: boolean;
|
|
38
|
+
},
|
|
39
|
+
): Promise<LocalAutomationHeartbeatResult> {
|
|
40
|
+
const service = new MarketStateService(db);
|
|
41
|
+
const now = params.now ?? new Date().toISOString();
|
|
42
|
+
let acquiredLease = false;
|
|
43
|
+
try {
|
|
44
|
+
service.markStaleAutomationRunsLost({ now, graceSeconds: 300 });
|
|
45
|
+
const hadActiveLease = service.getAutomationRunnerLease(now) != null;
|
|
46
|
+
const lease = service.acquireAutomationRunnerLease({
|
|
47
|
+
ownerId: params.ownerId,
|
|
48
|
+
ownerKind: params.ownerKind,
|
|
49
|
+
now,
|
|
50
|
+
ttlSeconds: params.ttlSeconds ?? 90,
|
|
51
|
+
});
|
|
52
|
+
acquiredLease = lease.acquired;
|
|
53
|
+
|
|
54
|
+
if (!lease.acquired) {
|
|
55
|
+
return { lease, alertCheck: null, reportRuns: [] };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const reportRuns =
|
|
59
|
+
params.checkReports === false
|
|
60
|
+
? []
|
|
61
|
+
: await runDueReports(service, {
|
|
62
|
+
ownerId: params.ownerId,
|
|
63
|
+
now,
|
|
64
|
+
recordDailyReportRun: params.recordDailyReportRun ?? recordDailyWatchlistReportRun,
|
|
65
|
+
});
|
|
66
|
+
if (params.checkAlerts === false || !hasDueAlertRules(service, now)) {
|
|
67
|
+
await (params.deliverNotifications ?? deliverPendingNotifications)(service, { now });
|
|
68
|
+
return { lease, alertCheck: null, reportRuns };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const alertCheck = await runAlertChecks(service, {
|
|
72
|
+
ownerId: params.ownerId,
|
|
73
|
+
triggerType: hadActiveLease ? "heartbeat" : "resume",
|
|
74
|
+
now,
|
|
75
|
+
providers: params.providers ?? defaultAlertRunnerProviders,
|
|
76
|
+
});
|
|
77
|
+
await (params.deliverNotifications ?? deliverPendingNotifications)(service, { now });
|
|
78
|
+
return {
|
|
79
|
+
lease,
|
|
80
|
+
alertCheck,
|
|
81
|
+
reportRuns,
|
|
82
|
+
};
|
|
83
|
+
} finally {
|
|
84
|
+
if (params.releaseLeaseOnComplete && acquiredLease) {
|
|
85
|
+
service.releaseAutomationRunnerLease(params.ownerId);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function hasDueAlertRules(service: MarketStateService, now: string): boolean {
|
|
91
|
+
const nowMs = new Date(now).getTime();
|
|
92
|
+
return service.listAlertRules().some((rule) => {
|
|
93
|
+
if (!rule.enabled || rule.status !== "active") return false;
|
|
94
|
+
if (rule.nextCheckAt == null) return true;
|
|
95
|
+
return new Date(rule.nextCheckAt).getTime() <= nowMs;
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function runDueReports(
|
|
100
|
+
service: MarketStateService,
|
|
101
|
+
params: { ownerId: string; now: string; recordDailyReportRun: DailyReportRunRecorder },
|
|
102
|
+
): Promise<ReportRunRecord[]> {
|
|
103
|
+
const nowMs = new Date(params.now).getTime();
|
|
104
|
+
const dueTemplates = service
|
|
105
|
+
.listReportTemplates()
|
|
106
|
+
.filter(
|
|
107
|
+
(template) =>
|
|
108
|
+
template.enabled &&
|
|
109
|
+
template.reportType === "watchlist_daily" &&
|
|
110
|
+
template.nextRunAt != null &&
|
|
111
|
+
new Date(template.nextRunAt).getTime() <= nowMs,
|
|
112
|
+
);
|
|
113
|
+
const runs: ReportRunRecord[] = [];
|
|
114
|
+
for (const template of dueTemplates) {
|
|
115
|
+
const scheduledFor = template.nextRunAt;
|
|
116
|
+
if (scheduledFor == null) continue;
|
|
117
|
+
const nextRunAt = nextDailyReportRunAt(
|
|
118
|
+
template.timezone,
|
|
119
|
+
template.localTime,
|
|
120
|
+
new Date(params.now),
|
|
121
|
+
);
|
|
122
|
+
const claimed = service.claimDueReportTemplateRun(template.id, {
|
|
123
|
+
scheduledFor,
|
|
124
|
+
nextRunAt,
|
|
125
|
+
claimedAt: params.now,
|
|
126
|
+
});
|
|
127
|
+
if (claimed == null) continue;
|
|
128
|
+
try {
|
|
129
|
+
const { run } = await params.recordDailyReportRun(service, {
|
|
130
|
+
templateId: template.id,
|
|
131
|
+
triggerType: "scheduled",
|
|
132
|
+
scheduledFor,
|
|
133
|
+
ownerId: params.ownerId,
|
|
134
|
+
});
|
|
135
|
+
runs.push(run);
|
|
136
|
+
} catch (error) {
|
|
137
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
138
|
+
const failedRun = service.recordReportRun({
|
|
139
|
+
templateId: template.id,
|
|
140
|
+
startedAt: params.now,
|
|
141
|
+
completedAt: new Date().toISOString(),
|
|
142
|
+
status: "failed",
|
|
143
|
+
triggerType: "scheduled",
|
|
144
|
+
scheduledFor,
|
|
145
|
+
ownerId: params.ownerId,
|
|
146
|
+
errors: [message],
|
|
147
|
+
});
|
|
148
|
+
service.recordNotificationEvent({
|
|
149
|
+
sourceType: "report_run",
|
|
150
|
+
sourceId: failedRun.id,
|
|
151
|
+
severity: "error",
|
|
152
|
+
title: "Daily watchlist report failed",
|
|
153
|
+
body: message,
|
|
154
|
+
payload: { template_id: template.id, scheduled_for: scheduledFor },
|
|
155
|
+
createdAt: failedRun.completedAt ?? params.now,
|
|
156
|
+
});
|
|
157
|
+
service.updateReportTemplate(template.id, { nextRunAt: scheduledFor });
|
|
158
|
+
runs.push(failedRun);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return runs;
|
|
162
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import type { MarketStateService } from "./service.js";
|
|
2
|
+
|
|
3
|
+
export interface NotificationDeliveryOptions {
|
|
4
|
+
webhookUrl?: string | null;
|
|
5
|
+
fetchImpl?: typeof fetch;
|
|
6
|
+
now?: string;
|
|
7
|
+
timeoutMs?: number;
|
|
8
|
+
maxAttempts?: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface NotificationDeliveryResult {
|
|
12
|
+
attempted: number;
|
|
13
|
+
succeeded: number;
|
|
14
|
+
failed: number;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export async function deliverPendingNotifications(
|
|
18
|
+
service: MarketStateService,
|
|
19
|
+
options: NotificationDeliveryOptions = {},
|
|
20
|
+
): Promise<NotificationDeliveryResult> {
|
|
21
|
+
const webhookUrl = options.webhookUrl ?? process.env.OPENCANDLE_NOTIFICATION_WEBHOOK_URL ?? null;
|
|
22
|
+
if (!webhookUrl) return { attempted: 0, succeeded: 0, failed: 0 };
|
|
23
|
+
|
|
24
|
+
const now = options.now ?? new Date().toISOString();
|
|
25
|
+
const timeoutMs = options.timeoutMs ?? 10_000;
|
|
26
|
+
const maxAttempts = options.maxAttempts ?? 5;
|
|
27
|
+
const fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
28
|
+
let attempted = 0;
|
|
29
|
+
let succeeded = 0;
|
|
30
|
+
let failed = 0;
|
|
31
|
+
|
|
32
|
+
const attempts = service.listNotificationDeliveryAttempts();
|
|
33
|
+
const deliveredWebhookIds = new Set(
|
|
34
|
+
attempts
|
|
35
|
+
.filter((attempt) => attempt.channel === "webhook" && attempt.status === "success")
|
|
36
|
+
.map((attempt) => attempt.notificationEventId),
|
|
37
|
+
);
|
|
38
|
+
const lastWebhookAttemptAt = new Map<number, string>();
|
|
39
|
+
for (const attempt of attempts) {
|
|
40
|
+
if (attempt.channel !== "webhook" || attempt.status === "success") continue;
|
|
41
|
+
const current = lastWebhookAttemptAt.get(attempt.notificationEventId);
|
|
42
|
+
if (current == null || attempt.attemptedAt > current) {
|
|
43
|
+
lastWebhookAttemptAt.set(attempt.notificationEventId, attempt.attemptedAt);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const pendingNotifications = service
|
|
48
|
+
.listNotificationEvents()
|
|
49
|
+
.filter((notification) => !deliveredWebhookIds.has(notification.id))
|
|
50
|
+
.sort((left, right) => {
|
|
51
|
+
const leftAttempt = lastWebhookAttemptAt.get(left.id);
|
|
52
|
+
const rightAttempt = lastWebhookAttemptAt.get(right.id);
|
|
53
|
+
if (leftAttempt == null && rightAttempt != null) return -1;
|
|
54
|
+
if (leftAttempt != null && rightAttempt == null) return 1;
|
|
55
|
+
if (leftAttempt != null && rightAttempt != null && leftAttempt !== rightAttempt) {
|
|
56
|
+
return leftAttempt.localeCompare(rightAttempt);
|
|
57
|
+
}
|
|
58
|
+
if (left.createdAt !== right.createdAt) return left.createdAt.localeCompare(right.createdAt);
|
|
59
|
+
return left.id - right.id;
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
if (!isAllowedWebhookUrl(webhookUrl)) {
|
|
63
|
+
const rejectedHost = webhookUrlHost(webhookUrl);
|
|
64
|
+
console.warn(`Rejected notification webhook URL host: ${rejectedHost}`);
|
|
65
|
+
const rejectedNotifications = pendingNotifications.slice(0, maxAttempts);
|
|
66
|
+
const error = `Rejected notification webhook URL host: ${rejectedHost}`;
|
|
67
|
+
for (const notification of rejectedNotifications) {
|
|
68
|
+
service.recordNotificationDeliveryAttempt({
|
|
69
|
+
notificationEventId: notification.id,
|
|
70
|
+
channel: "webhook",
|
|
71
|
+
status: "failed",
|
|
72
|
+
attemptedAt: now,
|
|
73
|
+
completedAt: now,
|
|
74
|
+
error,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
const rejected = rejectedNotifications.length;
|
|
78
|
+
return { attempted: rejected, succeeded: 0, failed: rejected };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
for (const notification of pendingNotifications) {
|
|
82
|
+
if (attempted >= maxAttempts) break;
|
|
83
|
+
attempted++;
|
|
84
|
+
const controller = new AbortController();
|
|
85
|
+
const timeout = setTimeout(
|
|
86
|
+
() => controller.abort(new Error(`Webhook delivery timed out after ${timeoutMs}ms`)),
|
|
87
|
+
timeoutMs,
|
|
88
|
+
);
|
|
89
|
+
try {
|
|
90
|
+
const response = await fetchImpl(webhookUrl, {
|
|
91
|
+
method: "POST",
|
|
92
|
+
headers: { "content-type": "application/json" },
|
|
93
|
+
signal: controller.signal,
|
|
94
|
+
body: JSON.stringify({
|
|
95
|
+
id: notification.id,
|
|
96
|
+
source_type: notification.sourceType,
|
|
97
|
+
source_id: notification.sourceId,
|
|
98
|
+
severity: notification.severity,
|
|
99
|
+
title: notification.title,
|
|
100
|
+
body: notification.body,
|
|
101
|
+
payload: notification.payloadJson,
|
|
102
|
+
status: notification.status,
|
|
103
|
+
created_at: notification.createdAt,
|
|
104
|
+
}),
|
|
105
|
+
});
|
|
106
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
107
|
+
clearTimeout(timeout);
|
|
108
|
+
service.recordNotificationDeliveryAttempt({
|
|
109
|
+
notificationEventId: notification.id,
|
|
110
|
+
channel: "webhook",
|
|
111
|
+
status: "success",
|
|
112
|
+
attemptedAt: now,
|
|
113
|
+
completedAt: now,
|
|
114
|
+
response: { status: response.status },
|
|
115
|
+
});
|
|
116
|
+
succeeded++;
|
|
117
|
+
} catch (error) {
|
|
118
|
+
clearTimeout(timeout);
|
|
119
|
+
const message = controller.signal.aborted
|
|
120
|
+
? `Webhook delivery timed out after ${timeoutMs}ms`
|
|
121
|
+
: error instanceof Error
|
|
122
|
+
? error.message
|
|
123
|
+
: String(error);
|
|
124
|
+
service.recordNotificationDeliveryAttempt({
|
|
125
|
+
notificationEventId: notification.id,
|
|
126
|
+
channel: "webhook",
|
|
127
|
+
status: "failed",
|
|
128
|
+
attemptedAt: now,
|
|
129
|
+
completedAt: now,
|
|
130
|
+
error: message,
|
|
131
|
+
});
|
|
132
|
+
failed++;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
return { attempted, succeeded, failed };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function isAllowedWebhookUrl(raw: string): boolean {
|
|
140
|
+
let url: URL;
|
|
141
|
+
try {
|
|
142
|
+
url = new URL(raw);
|
|
143
|
+
} catch {
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") return false;
|
|
147
|
+
const host = url.hostname;
|
|
148
|
+
if (host === "169.254.169.254" || host.startsWith("169.254.")) return false;
|
|
149
|
+
return true;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function webhookUrlHost(raw: string): string {
|
|
153
|
+
try {
|
|
154
|
+
return new URL(raw).hostname || "(empty)";
|
|
155
|
+
} catch {
|
|
156
|
+
return "(invalid URL)";
|
|
157
|
+
}
|
|
158
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { resolveYahooInstrument, searchYahooInstruments } from "./resolve.js";
|
|
2
|
+
|
|
3
|
+
export type MutationInstrumentResolution =
|
|
4
|
+
| { status: "resolved"; instrument: Awaited<ReturnType<typeof resolveYahooInstrument>> }
|
|
5
|
+
| {
|
|
6
|
+
status: "needs_selection";
|
|
7
|
+
query: string;
|
|
8
|
+
candidates: Awaited<ReturnType<typeof searchYahooInstruments>>;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export async function resolveInstrumentForMutation(
|
|
12
|
+
symbol: string,
|
|
13
|
+
): Promise<MutationInstrumentResolution> {
|
|
14
|
+
try {
|
|
15
|
+
return { status: "resolved", instrument: await resolveYahooInstrument(symbol) };
|
|
16
|
+
} catch (error) {
|
|
17
|
+
const query = symbol.trim();
|
|
18
|
+
const candidates = await searchYahooInstruments(query);
|
|
19
|
+
if (candidates.length > 0) {
|
|
20
|
+
return { status: "needs_selection", query, candidates };
|
|
21
|
+
}
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { cache, TTL } from "../infra/cache.js";
|
|
2
|
+
import { httpGet } from "../infra/http-client.js";
|
|
3
|
+
import { rateLimiter } from "../infra/rate-limiter.js";
|
|
4
|
+
import { wrapProvider } from "../providers/wrap-provider.js";
|
|
5
|
+
import { getQuote } from "../providers/yahoo-finance.js";
|
|
6
|
+
import type { StockQuote } from "../types/market.js";
|
|
7
|
+
import type { InstrumentInput } from "./service.js";
|
|
8
|
+
|
|
9
|
+
export interface InstrumentCandidate {
|
|
10
|
+
symbol: string;
|
|
11
|
+
name: string | null;
|
|
12
|
+
quoteType: string;
|
|
13
|
+
assetType: string;
|
|
14
|
+
exchange: string | null;
|
|
15
|
+
provider: "yahoo";
|
|
16
|
+
score: number | null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
interface YahooSearchResponse {
|
|
20
|
+
quotes?: Array<{
|
|
21
|
+
symbol?: string;
|
|
22
|
+
shortname?: string;
|
|
23
|
+
longname?: string;
|
|
24
|
+
quoteType?: string;
|
|
25
|
+
exchange?: string;
|
|
26
|
+
score?: number;
|
|
27
|
+
}>;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function searchYahooInstruments(query: string): Promise<InstrumentCandidate[]> {
|
|
31
|
+
const trimmed = query.trim();
|
|
32
|
+
if (!trimmed) return [];
|
|
33
|
+
|
|
34
|
+
const cacheKey = `yahoo:instrument-search:${trimmed.toLowerCase()}`;
|
|
35
|
+
const cached = cache.get<InstrumentCandidate[]>(cacheKey);
|
|
36
|
+
if (cached) return cached;
|
|
37
|
+
|
|
38
|
+
const url = `https://query1.finance.yahoo.com/v1/finance/search?q=${encodeURIComponent(trimmed)}"esCount=10&newsCount=0`;
|
|
39
|
+
await rateLimiter.acquire("yahoo");
|
|
40
|
+
const data = await httpGet<YahooSearchResponse>(url, {
|
|
41
|
+
headers: { "User-Agent": "OpenCandle/1.0" },
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
const candidates = (data.quotes ?? []).flatMap((quote) => {
|
|
45
|
+
if (!quote.symbol) return [];
|
|
46
|
+
const quoteType = quote.quoteType ?? "UNKNOWN";
|
|
47
|
+
return [
|
|
48
|
+
{
|
|
49
|
+
symbol: quote.symbol.toUpperCase(),
|
|
50
|
+
name: quote.longname ?? quote.shortname ?? null,
|
|
51
|
+
quoteType,
|
|
52
|
+
assetType: assetTypeFromQuoteType(quoteType, quote.symbol),
|
|
53
|
+
exchange: quote.exchange ?? null,
|
|
54
|
+
provider: "yahoo" as const,
|
|
55
|
+
score: quote.score ?? null,
|
|
56
|
+
},
|
|
57
|
+
];
|
|
58
|
+
});
|
|
59
|
+
cache.set(cacheKey, candidates, TTL.WEB_SEARCH);
|
|
60
|
+
return candidates;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export async function resolveYahooInstrument(symbol: string): Promise<InstrumentInput> {
|
|
64
|
+
const normalized = symbol.trim().toUpperCase();
|
|
65
|
+
if (!normalized) {
|
|
66
|
+
throw new Error("symbol is required.");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const result = await wrapProvider("yahoo", () => getQuote(normalized));
|
|
70
|
+
if (result.status === "unavailable") {
|
|
71
|
+
throw new Error(`Could not resolve ${normalized}: ${result.reason}`);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const quote = result.data;
|
|
75
|
+
if (isZeroFilledQuote(quote)) {
|
|
76
|
+
throw new Error(`Could not resolve ${normalized}: Yahoo returned no valid market data.`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
return {
|
|
80
|
+
symbol: quote.symbol?.toUpperCase() ?? normalized,
|
|
81
|
+
assetType: inferAssetType(quote.symbol ?? normalized),
|
|
82
|
+
currency: quote.currency?.trim().toUpperCase() || null,
|
|
83
|
+
provider: "yahoo",
|
|
84
|
+
providerMetadata: {
|
|
85
|
+
price: quote.price,
|
|
86
|
+
volume: quote.volume,
|
|
87
|
+
week52High: quote.week52High,
|
|
88
|
+
week52Low: quote.week52Low,
|
|
89
|
+
timestamp: quote.timestamp,
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function isZeroFilledQuote(quote: StockQuote): boolean {
|
|
95
|
+
return quote.price === 0 && quote.volume === 0 && quote.week52High === 0 && quote.week52Low === 0;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function inferAssetType(symbol: string): string {
|
|
99
|
+
if (symbol.endsWith("-USD")) return "crypto";
|
|
100
|
+
if (symbol.startsWith("^")) return "index";
|
|
101
|
+
return "equity";
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function assetTypeFromQuoteType(quoteType: string, symbol: string): string {
|
|
105
|
+
const normalized = quoteType.toLowerCase();
|
|
106
|
+
if (normalized.includes("etf")) return "etf";
|
|
107
|
+
if (normalized.includes("mutualfund")) return "fund";
|
|
108
|
+
if (normalized.includes("crypto")) return "crypto";
|
|
109
|
+
if (normalized.includes("index")) return "index";
|
|
110
|
+
if (normalized.includes("equity")) return "equity";
|
|
111
|
+
return inferAssetType(symbol.toUpperCase());
|
|
112
|
+
}
|