opencandle 0.4.0 → 0.6.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.
Files changed (564) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +186 -117
  3. package/dist/analysts/contracts.d.ts +1 -3
  4. package/dist/analysts/contracts.js +1 -11
  5. package/dist/analysts/contracts.js.map +1 -1
  6. package/dist/analysts/orchestrator.d.ts +1 -3
  7. package/dist/analysts/orchestrator.js +1 -26
  8. package/dist/analysts/orchestrator.js.map +1 -1
  9. package/dist/cli.js +32 -8
  10. package/dist/cli.js.map +1 -1
  11. package/dist/config.d.ts +19 -3
  12. package/dist/config.js +69 -3
  13. package/dist/config.js.map +1 -1
  14. package/dist/index.d.ts +1 -1
  15. package/dist/index.js +1 -1
  16. package/dist/index.js.map +1 -1
  17. package/dist/infra/browser.d.ts +1 -3
  18. package/dist/infra/browser.js +4 -2
  19. package/dist/infra/browser.js.map +1 -1
  20. package/dist/infra/cache.d.ts +8 -11
  21. package/dist/infra/cache.js +17 -15
  22. package/dist/infra/cache.js.map +1 -1
  23. package/dist/infra/http-client.d.ts +4 -1
  24. package/dist/infra/http-client.js +59 -6
  25. package/dist/infra/http-client.js.map +1 -1
  26. package/dist/infra/index.d.ts +3 -3
  27. package/dist/infra/index.js +3 -3
  28. package/dist/infra/index.js.map +1 -1
  29. package/dist/infra/native-dependencies.js +2 -2
  30. package/dist/infra/native-dependencies.js.map +1 -1
  31. package/dist/infra/node-version.js.map +1 -1
  32. package/dist/infra/opencandle-paths.d.ts +0 -3
  33. package/dist/infra/opencandle-paths.js +4 -11
  34. package/dist/infra/opencandle-paths.js.map +1 -1
  35. package/dist/infra/rate-limiter.d.ts +4 -0
  36. package/dist/infra/rate-limiter.js +17 -10
  37. package/dist/infra/rate-limiter.js.map +1 -1
  38. package/dist/market-state/alert-conditions.d.ts +34 -0
  39. package/dist/market-state/alert-conditions.js +23 -0
  40. package/dist/market-state/alert-conditions.js.map +1 -0
  41. package/dist/market-state/alert-runner.d.ts +55 -0
  42. package/dist/market-state/alert-runner.js +634 -0
  43. package/dist/market-state/alert-runner.js.map +1 -0
  44. package/dist/market-state/daily-report.d.ts +26 -0
  45. package/dist/market-state/daily-report.js +179 -0
  46. package/dist/market-state/daily-report.js.map +1 -0
  47. package/dist/market-state/local-automation-service.d.ts +25 -0
  48. package/dist/market-state/local-automation-service.js +119 -0
  49. package/dist/market-state/local-automation-service.js.map +1 -0
  50. package/dist/market-state/notification-delivery.d.ts +14 -0
  51. package/dist/market-state/notification-delivery.js +139 -0
  52. package/dist/market-state/notification-delivery.js.map +1 -0
  53. package/dist/market-state/resolve-for-mutation.d.ts +10 -0
  54. package/dist/market-state/resolve-for-mutation.js +15 -0
  55. package/dist/market-state/resolve-for-mutation.js.map +1 -0
  56. package/dist/market-state/resolve.d.ts +14 -0
  57. package/dist/market-state/resolve.js +89 -0
  58. package/dist/market-state/resolve.js.map +1 -0
  59. package/dist/market-state/service.d.ts +527 -0
  60. package/dist/market-state/service.js +1099 -0
  61. package/dist/market-state/service.js.map +1 -0
  62. package/dist/memory/index.d.ts +7 -7
  63. package/dist/memory/index.js +6 -6
  64. package/dist/memory/index.js.map +1 -1
  65. package/dist/memory/manager.d.ts +9 -0
  66. package/dist/memory/manager.js +39 -22
  67. package/dist/memory/manager.js.map +1 -1
  68. package/dist/memory/retrieval.js +7 -4
  69. package/dist/memory/retrieval.js.map +1 -1
  70. package/dist/memory/sqlite.js +385 -3
  71. package/dist/memory/sqlite.js.map +1 -1
  72. package/dist/memory/storage.d.ts +3 -2
  73. package/dist/memory/storage.js +1 -2
  74. package/dist/memory/storage.js.map +1 -1
  75. package/dist/memory/tool-defaults.js +64 -28
  76. package/dist/memory/tool-defaults.js.map +1 -1
  77. package/dist/memory/types.js +4 -0
  78. package/dist/memory/types.js.map +1 -1
  79. package/dist/monitor.d.ts +2 -0
  80. package/dist/monitor.js +104 -0
  81. package/dist/monitor.js.map +1 -0
  82. package/dist/onboarding/connect.js +4 -6
  83. package/dist/onboarding/connect.js.map +1 -1
  84. package/dist/onboarding/credential-interceptor.js +1 -1
  85. package/dist/onboarding/credential-interceptor.js.map +1 -1
  86. package/dist/onboarding/degradation-accumulator.js +1 -3
  87. package/dist/onboarding/degradation-accumulator.js.map +1 -1
  88. package/dist/onboarding/providers.js +3 -16
  89. package/dist/onboarding/providers.js.map +1 -1
  90. package/dist/onboarding/state.js.map +1 -1
  91. package/dist/onboarding/tool-helpers.js +1 -1
  92. package/dist/onboarding/tool-helpers.js.map +1 -1
  93. package/dist/onboarding/tool-tags.js +6 -4
  94. package/dist/onboarding/tool-tags.js.map +1 -1
  95. package/dist/onboarding/validation.js +1 -1
  96. package/dist/onboarding/validation.js.map +1 -1
  97. package/dist/pi/opencandle-extension.d.ts +8 -0
  98. package/dist/pi/opencandle-extension.js +637 -59
  99. package/dist/pi/opencandle-extension.js.map +1 -1
  100. package/dist/pi/session.d.ts +1 -1
  101. package/dist/pi/session.js +3 -1
  102. package/dist/pi/session.js.map +1 -1
  103. package/dist/pi/setup.js +17 -2
  104. package/dist/pi/setup.js.map +1 -1
  105. package/dist/pi/tool-adapter.js +5 -2
  106. package/dist/pi/tool-adapter.js.map +1 -1
  107. package/dist/prompts/context-builder.d.ts +18 -3
  108. package/dist/prompts/context-builder.js +117 -18
  109. package/dist/prompts/context-builder.js.map +1 -1
  110. package/dist/prompts/disclaimer.js +1 -1
  111. package/dist/prompts/disclaimer.js.map +1 -1
  112. package/dist/prompts/policy-cards.d.ts +13 -0
  113. package/dist/prompts/policy-cards.js +197 -0
  114. package/dist/prompts/policy-cards.js.map +1 -0
  115. package/dist/prompts/sections.d.ts +1 -1
  116. package/dist/prompts/sections.js +3 -3
  117. package/dist/prompts/sections.js.map +1 -1
  118. package/dist/prompts/symbol-preflight.d.ts +20 -0
  119. package/dist/prompts/symbol-preflight.js +49 -0
  120. package/dist/prompts/symbol-preflight.js.map +1 -0
  121. package/dist/prompts/workflow-prompts.d.ts +1 -1
  122. package/dist/prompts/workflow-prompts.js +209 -19
  123. package/dist/prompts/workflow-prompts.js.map +1 -1
  124. package/dist/providers/alpha-vantage.d.ts +1 -1
  125. package/dist/providers/alpha-vantage.js +49 -8
  126. package/dist/providers/alpha-vantage.js.map +1 -1
  127. package/dist/providers/coingecko.js +1 -1
  128. package/dist/providers/coingecko.js.map +1 -1
  129. package/dist/providers/errors.d.ts +5 -0
  130. package/dist/providers/errors.js +11 -0
  131. package/dist/providers/errors.js.map +1 -0
  132. package/dist/providers/exa-search.d.ts +2 -2
  133. package/dist/providers/exa-search.js +19 -11
  134. package/dist/providers/exa-search.js.map +1 -1
  135. package/dist/providers/fear-greed.js +1 -1
  136. package/dist/providers/fear-greed.js.map +1 -1
  137. package/dist/providers/finnhub.js +3 -5
  138. package/dist/providers/finnhub.js.map +1 -1
  139. package/dist/providers/fred.js +2 -2
  140. package/dist/providers/fred.js.map +1 -1
  141. package/dist/providers/index.d.ts +7 -6
  142. package/dist/providers/index.js +6 -5
  143. package/dist/providers/index.js.map +1 -1
  144. package/dist/providers/reddit.js +2 -2
  145. package/dist/providers/reddit.js.map +1 -1
  146. package/dist/providers/sec-edgar.d.ts +9 -1
  147. package/dist/providers/sec-edgar.js +181 -6
  148. package/dist/providers/sec-edgar.js.map +1 -1
  149. package/dist/providers/tradingview.d.ts +47 -0
  150. package/dist/providers/tradingview.js +275 -0
  151. package/dist/providers/tradingview.js.map +1 -0
  152. package/dist/providers/twitter.js +6 -8
  153. package/dist/providers/twitter.js.map +1 -1
  154. package/dist/providers/web-search.js +26 -12
  155. package/dist/providers/web-search.js.map +1 -1
  156. package/dist/providers/with-fallback.js +4 -2
  157. package/dist/providers/with-fallback.js.map +1 -1
  158. package/dist/providers/wrap-provider.d.ts +2 -3
  159. package/dist/providers/wrap-provider.js +14 -8
  160. package/dist/providers/wrap-provider.js.map +1 -1
  161. package/dist/providers/yahoo-finance.d.ts +3 -1
  162. package/dist/providers/yahoo-finance.js +226 -11
  163. package/dist/providers/yahoo-finance.js.map +1 -1
  164. package/dist/routing/classify-intent.d.ts +9 -0
  165. package/dist/routing/classify-intent.js +153 -3
  166. package/dist/routing/classify-intent.js.map +1 -1
  167. package/dist/routing/defaults.d.ts +1 -1
  168. package/dist/routing/defaults.js +3 -3
  169. package/dist/routing/defaults.js.map +1 -1
  170. package/dist/routing/entity-extractor.d.ts +2 -0
  171. package/dist/routing/entity-extractor.js +377 -26
  172. package/dist/routing/entity-extractor.js.map +1 -1
  173. package/dist/routing/fund-symbols.d.ts +2 -0
  174. package/dist/routing/fund-symbols.js +55 -0
  175. package/dist/routing/fund-symbols.js.map +1 -0
  176. package/dist/routing/horizon.d.ts +1 -0
  177. package/dist/routing/horizon.js +10 -0
  178. package/dist/routing/horizon.js.map +1 -0
  179. package/dist/routing/index.d.ts +12 -6
  180. package/dist/routing/index.js +8 -4
  181. package/dist/routing/index.js.map +1 -1
  182. package/dist/routing/legacy-rule-router.d.ts +9 -0
  183. package/dist/routing/legacy-rule-router.js +12 -0
  184. package/dist/routing/legacy-rule-router.js.map +1 -0
  185. package/dist/routing/planning.d.ts +54 -0
  186. package/dist/routing/planning.js +562 -0
  187. package/dist/routing/planning.js.map +1 -0
  188. package/dist/routing/route-manifest.d.ts +35 -0
  189. package/dist/routing/route-manifest.js +242 -0
  190. package/dist/routing/route-manifest.js.map +1 -0
  191. package/dist/routing/router-llm-client.js.map +1 -1
  192. package/dist/routing/router-prompt.js +46 -45
  193. package/dist/routing/router-prompt.js.map +1 -1
  194. package/dist/routing/router-types.d.ts +10 -0
  195. package/dist/routing/router.d.ts +1 -0
  196. package/dist/routing/router.js +572 -13
  197. package/dist/routing/router.js.map +1 -1
  198. package/dist/routing/slot-resolver.d.ts +1 -1
  199. package/dist/routing/slot-resolver.js +45 -7
  200. package/dist/routing/slot-resolver.js.map +1 -1
  201. package/dist/routing/symbol-disambiguator.d.ts +11 -0
  202. package/dist/routing/symbol-disambiguator.js +52 -0
  203. package/dist/routing/symbol-disambiguator.js.map +1 -0
  204. package/dist/routing/turn-context.d.ts +44 -0
  205. package/dist/routing/turn-context.js +45 -0
  206. package/dist/routing/turn-context.js.map +1 -0
  207. package/dist/routing/types.d.ts +15 -1
  208. package/dist/runtime/answer-contracts.d.ts +82 -0
  209. package/dist/runtime/answer-contracts.js +442 -0
  210. package/dist/runtime/answer-contracts.js.map +1 -0
  211. package/dist/runtime/artifact-contracts.d.ts +14 -0
  212. package/dist/runtime/artifact-contracts.js +57 -0
  213. package/dist/runtime/artifact-contracts.js.map +1 -0
  214. package/dist/runtime/planning-evidence.d.ts +99 -0
  215. package/dist/runtime/planning-evidence.js +466 -0
  216. package/dist/runtime/planning-evidence.js.map +1 -0
  217. package/dist/runtime/prompt-step.d.ts +1 -9
  218. package/dist/runtime/prompt-step.js +0 -10
  219. package/dist/runtime/prompt-step.js.map +1 -1
  220. package/dist/runtime/run-context.d.ts +5 -2
  221. package/dist/runtime/run-context.js +8 -1
  222. package/dist/runtime/run-context.js.map +1 -1
  223. package/dist/runtime/session-coordinator.d.ts +29 -3
  224. package/dist/runtime/session-coordinator.js +204 -31
  225. package/dist/runtime/session-coordinator.js.map +1 -1
  226. package/dist/runtime/session-title.d.ts +14 -0
  227. package/dist/runtime/session-title.js +50 -0
  228. package/dist/runtime/session-title.js.map +1 -0
  229. package/dist/runtime/tool-defaults-wrapper.js +1 -3
  230. package/dist/runtime/tool-defaults-wrapper.js.map +1 -1
  231. package/dist/runtime/validation.js.map +1 -1
  232. package/dist/runtime/workflow-events.js.map +1 -1
  233. package/dist/runtime/workflow-runner.d.ts +3 -3
  234. package/dist/runtime/workflow-runner.js +1 -1
  235. package/dist/runtime/workflow-runner.js.map +1 -1
  236. package/dist/sentiment/adapters/finnhub.d.ts +1 -1
  237. package/dist/sentiment/adapters/finnhub.js +6 -1
  238. package/dist/sentiment/adapters/finnhub.js.map +1 -1
  239. package/dist/sentiment/adapters/reddit.d.ts +2 -2
  240. package/dist/sentiment/adapters/twitter.d.ts +1 -1
  241. package/dist/sentiment/adapters/web.d.ts +1 -1
  242. package/dist/sentiment/index.d.ts +9 -11
  243. package/dist/sentiment/index.js +9 -20
  244. package/dist/sentiment/index.js.map +1 -1
  245. package/dist/sentiment/keywords.js +26 -4
  246. package/dist/sentiment/keywords.js.map +1 -1
  247. package/dist/sentiment/pipeline.d.ts +2 -2
  248. package/dist/sentiment/pipeline.js +1 -1
  249. package/dist/sentiment/pipeline.js.map +1 -1
  250. package/dist/sentiment/scorer.js +1 -1
  251. package/dist/sentiment/store.d.ts +1 -1
  252. package/dist/sentiment/store.js +1 -1
  253. package/dist/sentiment/store.js.map +1 -1
  254. package/dist/sentiment/trends.d.ts +1 -1
  255. package/dist/sentiment/trends.js.map +1 -1
  256. package/dist/sentiment/types.js.map +1 -1
  257. package/dist/system-prompt.js +7 -3
  258. package/dist/system-prompt.js.map +1 -1
  259. package/dist/tool-kit.d.ts +7 -7
  260. package/dist/tool-kit.js +4 -4
  261. package/dist/tool-kit.js.map +1 -1
  262. package/dist/tools/fundamentals/company-overview.js +12 -7
  263. package/dist/tools/fundamentals/company-overview.js.map +1 -1
  264. package/dist/tools/fundamentals/comps.js +19 -10
  265. package/dist/tools/fundamentals/comps.js.map +1 -1
  266. package/dist/tools/fundamentals/dcf.js +24 -12
  267. package/dist/tools/fundamentals/dcf.js.map +1 -1
  268. package/dist/tools/fundamentals/earnings.js +9 -4
  269. package/dist/tools/fundamentals/earnings.js.map +1 -1
  270. package/dist/tools/fundamentals/financials.js +9 -4
  271. package/dist/tools/fundamentals/financials.js.map +1 -1
  272. package/dist/tools/fundamentals/sec-filings.d.ts +1 -0
  273. package/dist/tools/fundamentals/sec-filings.js +36 -4
  274. package/dist/tools/fundamentals/sec-filings.js.map +1 -1
  275. package/dist/tools/index.d.ts +23 -18
  276. package/dist/tools/index.js +53 -38
  277. package/dist/tools/index.js.map +1 -1
  278. package/dist/tools/interaction/ask-user.js +15 -3
  279. package/dist/tools/interaction/ask-user.js.map +1 -1
  280. package/dist/tools/interaction/twitter-login.js +13 -3
  281. package/dist/tools/interaction/twitter-login.js.map +1 -1
  282. package/dist/tools/macro/fear-greed.js +1 -1
  283. package/dist/tools/macro/fear-greed.js.map +1 -1
  284. package/dist/tools/macro/fred-data.d.ts +1 -1
  285. package/dist/tools/macro/fred-data.js +44 -9
  286. package/dist/tools/macro/fred-data.js.map +1 -1
  287. package/dist/tools/market/crypto-history.js +21 -3
  288. package/dist/tools/market/crypto-history.js.map +1 -1
  289. package/dist/tools/market/crypto-price.js +4 -2
  290. package/dist/tools/market/crypto-price.js.map +1 -1
  291. package/dist/tools/market/screen-stocks.d.ts +18 -0
  292. package/dist/tools/market/screen-stocks.js +252 -0
  293. package/dist/tools/market/screen-stocks.js.map +1 -0
  294. package/dist/tools/market/search-ticker.js +161 -9
  295. package/dist/tools/market/search-ticker.js.map +1 -1
  296. package/dist/tools/market/stock-history.d.ts +2 -2
  297. package/dist/tools/market/stock-history.js +27 -8
  298. package/dist/tools/market/stock-history.js.map +1 -1
  299. package/dist/tools/market/stock-quote.js +6 -4
  300. package/dist/tools/market/stock-quote.js.map +1 -1
  301. package/dist/tools/options/greeks.js +1 -2
  302. package/dist/tools/options/greeks.js.map +1 -1
  303. package/dist/tools/options/option-chain.js +27 -9
  304. package/dist/tools/options/option-chain.js.map +1 -1
  305. package/dist/tools/portfolio/alerts.d.ts +15 -0
  306. package/dist/tools/portfolio/alerts.js +357 -0
  307. package/dist/tools/portfolio/alerts.js.map +1 -0
  308. package/dist/tools/portfolio/correlation.d.ts +1 -1
  309. package/dist/tools/portfolio/correlation.js +34 -14
  310. package/dist/tools/portfolio/correlation.js.map +1 -1
  311. package/dist/tools/portfolio/daily-report.d.ts +8 -0
  312. package/dist/tools/portfolio/daily-report.js +83 -0
  313. package/dist/tools/portfolio/daily-report.js.map +1 -0
  314. package/dist/tools/portfolio/holdings-overlap.d.ts +8 -0
  315. package/dist/tools/portfolio/holdings-overlap.js +112 -0
  316. package/dist/tools/portfolio/holdings-overlap.js.map +1 -0
  317. package/dist/tools/portfolio/notifications.d.ts +7 -0
  318. package/dist/tools/portfolio/notifications.js +43 -0
  319. package/dist/tools/portfolio/notifications.js.map +1 -0
  320. package/dist/tools/portfolio/predictions.d.ts +12 -6
  321. package/dist/tools/portfolio/predictions.js +338 -88
  322. package/dist/tools/portfolio/predictions.js.map +1 -1
  323. package/dist/tools/portfolio/risk-analysis.d.ts +1 -1
  324. package/dist/tools/portfolio/risk-analysis.js +46 -7
  325. package/dist/tools/portfolio/risk-analysis.js.map +1 -1
  326. package/dist/tools/portfolio/tracker.d.ts +4 -3
  327. package/dist/tools/portfolio/tracker.js +247 -102
  328. package/dist/tools/portfolio/tracker.js.map +1 -1
  329. package/dist/tools/portfolio/watchlist.d.ts +6 -4
  330. package/dist/tools/portfolio/watchlist.js +209 -101
  331. package/dist/tools/portfolio/watchlist.js.map +1 -1
  332. package/dist/tools/sentiment/reddit-sentiment.js +24 -11
  333. package/dist/tools/sentiment/reddit-sentiment.js.map +1 -1
  334. package/dist/tools/sentiment/sentiment-summary.js +71 -14
  335. package/dist/tools/sentiment/sentiment-summary.js.map +1 -1
  336. package/dist/tools/sentiment/sentiment-trend.d.ts +1 -1
  337. package/dist/tools/sentiment/sentiment-trend.js +12 -2
  338. package/dist/tools/sentiment/sentiment-trend.js.map +1 -1
  339. package/dist/tools/sentiment/twitter-sentiment.js +13 -6
  340. package/dist/tools/sentiment/twitter-sentiment.js.map +1 -1
  341. package/dist/tools/sentiment/untrusted-text.d.ts +2 -0
  342. package/dist/tools/sentiment/untrusted-text.js +17 -0
  343. package/dist/tools/sentiment/untrusted-text.js.map +1 -0
  344. package/dist/tools/sentiment/web-search.js +37 -12
  345. package/dist/tools/sentiment/web-search.js.map +1 -1
  346. package/dist/tools/sentiment/web-sentiment.js +16 -4
  347. package/dist/tools/sentiment/web-sentiment.js.map +1 -1
  348. package/dist/tools/technical/backtest.d.ts +3 -3
  349. package/dist/tools/technical/backtest.js +65 -44
  350. package/dist/tools/technical/backtest.js.map +1 -1
  351. package/dist/tools/technical/indicators.js +24 -8
  352. package/dist/tools/technical/indicators.js.map +1 -1
  353. package/dist/types/index.d.ts +3 -3
  354. package/dist/types/index.js.map +1 -1
  355. package/dist/types/market.d.ts +1 -0
  356. package/dist/types/options.d.ts +10 -0
  357. package/dist/types/portfolio.d.ts +41 -4
  358. package/dist/workflows/compare-assets.d.ts +0 -3
  359. package/dist/workflows/compare-assets.js +55 -10
  360. package/dist/workflows/compare-assets.js.map +1 -1
  361. package/dist/workflows/index.d.ts +3 -4
  362. package/dist/workflows/index.js +3 -3
  363. package/dist/workflows/index.js.map +1 -1
  364. package/dist/workflows/options-screener.d.ts +0 -3
  365. package/dist/workflows/options-screener.js +88 -14
  366. package/dist/workflows/options-screener.js.map +1 -1
  367. package/dist/workflows/portfolio-builder.d.ts +0 -3
  368. package/dist/workflows/portfolio-builder.js +7 -11
  369. package/dist/workflows/portfolio-builder.js.map +1 -1
  370. package/gui/server/ask-user-bridge.ts +82 -0
  371. package/gui/server/automation-heartbeat.ts +97 -0
  372. package/gui/server/background-quotes.ts +97 -1
  373. package/gui/server/chat-event-adapter.ts +32 -10
  374. package/gui/server/chat-run-session.ts +16 -0
  375. package/gui/server/gui-session-manager.ts +5 -0
  376. package/gui/server/invoke-tool.ts +144 -1
  377. package/gui/server/live-chat-event-adapter.ts +21 -6
  378. package/gui/server/market-state-api.ts +315 -0
  379. package/gui/server/model-setup.ts +149 -2
  380. package/gui/server/private-api-access.ts +62 -0
  381. package/gui/server/projector.ts +58 -11
  382. package/gui/server/prompt-observation.ts +58 -0
  383. package/gui/server/quote-snapshot-store.ts +50 -0
  384. package/gui/server/server.ts +236 -376
  385. package/gui/server/session-actions.ts +186 -1
  386. package/gui/server/session-entry-wait.ts +81 -0
  387. package/gui/server/shutdown.ts +47 -0
  388. package/gui/server/tool-invoke-ack.ts +49 -0
  389. package/gui/server/tool-metadata.ts +23 -10
  390. package/gui/server/websocket.ts +13 -3
  391. package/gui/server/writer-lock.ts +6 -2
  392. package/gui/server/ws-hub.ts +292 -0
  393. package/gui/shared/chat-events.ts +16 -1
  394. package/gui/shared/event-reducer.ts +24 -6
  395. package/gui/web/dist/assets/CatalogOverlay-eJ2cBk33.js +1 -0
  396. package/gui/web/dist/assets/index-2KZtKBmu.css +1 -0
  397. package/gui/web/dist/assets/index-CveNgtDg.js +69 -0
  398. package/gui/web/dist/index.html +2 -2
  399. package/package.json +22 -12
  400. package/src/analysts/contracts.ts +10 -23
  401. package/src/analysts/orchestrator.ts +8 -43
  402. package/src/cli.ts +37 -13
  403. package/src/config.ts +99 -7
  404. package/src/index.ts +1 -1
  405. package/src/infra/browser.ts +4 -2
  406. package/src/infra/cache.ts +41 -30
  407. package/src/infra/http-client.ts +72 -6
  408. package/src/infra/index.ts +7 -10
  409. package/src/infra/native-dependencies.ts +8 -3
  410. package/src/infra/node-version.ts +3 -1
  411. package/src/infra/opencandle-paths.ts +3 -14
  412. package/src/infra/rate-limiter.ts +32 -20
  413. package/src/market-state/alert-conditions.ts +82 -0
  414. package/src/market-state/alert-runner.ts +863 -0
  415. package/src/market-state/daily-report.ts +247 -0
  416. package/src/market-state/local-automation-service.ts +162 -0
  417. package/src/market-state/notification-delivery.ts +158 -0
  418. package/src/market-state/resolve-for-mutation.ts +24 -0
  419. package/src/market-state/resolve.ts +112 -0
  420. package/src/market-state/service.ts +2344 -0
  421. package/src/memory/index.ts +7 -7
  422. package/src/memory/manager.ts +57 -26
  423. package/src/memory/retrieval.ts +8 -7
  424. package/src/memory/sqlite.ts +407 -6
  425. package/src/memory/storage.ts +8 -17
  426. package/src/memory/tool-defaults.ts +60 -39
  427. package/src/memory/types.ts +7 -3
  428. package/src/monitor.ts +121 -0
  429. package/src/onboarding/connect.ts +10 -33
  430. package/src/onboarding/credential-interceptor.ts +3 -15
  431. package/src/onboarding/degradation-accumulator.ts +1 -3
  432. package/src/onboarding/providers.ts +9 -40
  433. package/src/onboarding/state.ts +4 -15
  434. package/src/onboarding/tool-helpers.ts +2 -9
  435. package/src/onboarding/tool-tags.ts +6 -6
  436. package/src/onboarding/validation.ts +14 -20
  437. package/src/pi/opencandle-extension.ts +795 -120
  438. package/src/pi/session.ts +7 -5
  439. package/src/pi/setup.ts +61 -33
  440. package/src/pi/tool-adapter.ts +5 -2
  441. package/src/prompts/context-builder.ts +143 -21
  442. package/src/prompts/disclaimer.ts +1 -1
  443. package/src/prompts/policy-cards.ts +220 -0
  444. package/src/prompts/sections.ts +4 -4
  445. package/src/prompts/symbol-preflight.ts +80 -0
  446. package/src/prompts/workflow-prompts.ts +231 -28
  447. package/src/providers/alpha-vantage.ts +82 -40
  448. package/src/providers/coingecko.ts +2 -5
  449. package/src/providers/errors.ts +9 -0
  450. package/src/providers/exa-search.ts +24 -22
  451. package/src/providers/fear-greed.ts +1 -1
  452. package/src/providers/finnhub.ts +7 -6
  453. package/src/providers/fred.ts +3 -3
  454. package/src/providers/index.ts +14 -6
  455. package/src/providers/reddit.ts +17 -6
  456. package/src/providers/sec-edgar.ts +235 -5
  457. package/src/providers/tradingview.ts +399 -0
  458. package/src/providers/twitter.ts +6 -8
  459. package/src/providers/web-search.ts +30 -20
  460. package/src/providers/with-fallback.ts +8 -7
  461. package/src/providers/wrap-provider.ts +15 -10
  462. package/src/providers/yahoo-finance.ts +292 -20
  463. package/src/routing/classify-intent.ts +186 -4
  464. package/src/routing/defaults.ts +4 -4
  465. package/src/routing/entity-extractor.ts +428 -28
  466. package/src/routing/fund-symbols.ts +58 -0
  467. package/src/routing/horizon.ts +7 -0
  468. package/src/routing/index.ts +60 -16
  469. package/src/routing/legacy-rule-router.ts +13 -0
  470. package/src/routing/planning.ts +823 -0
  471. package/src/routing/route-manifest.ts +309 -0
  472. package/src/routing/router-llm-client.ts +4 -4
  473. package/src/routing/router-prompt.ts +52 -52
  474. package/src/routing/router-types.ts +18 -0
  475. package/src/routing/router.ts +717 -20
  476. package/src/routing/slot-resolver.ts +75 -14
  477. package/src/routing/symbol-disambiguator.ts +72 -0
  478. package/src/routing/turn-context.ts +108 -0
  479. package/src/routing/types.ts +15 -1
  480. package/src/runtime/answer-contracts.ts +672 -0
  481. package/src/runtime/artifact-contracts.ts +77 -0
  482. package/src/runtime/planning-evidence.ts +682 -0
  483. package/src/runtime/prompt-step.ts +1 -16
  484. package/src/runtime/run-context.ts +12 -2
  485. package/src/runtime/session-coordinator.ts +297 -56
  486. package/src/runtime/session-title.ts +60 -0
  487. package/src/runtime/tool-defaults-wrapper.ts +1 -3
  488. package/src/runtime/validation.ts +1 -4
  489. package/src/runtime/workflow-events.ts +7 -7
  490. package/src/runtime/workflow-runner.ts +5 -11
  491. package/src/sentiment/adapters/finnhub.ts +7 -2
  492. package/src/sentiment/adapters/reddit.ts +2 -2
  493. package/src/sentiment/adapters/twitter.ts +1 -1
  494. package/src/sentiment/adapters/web.ts +1 -1
  495. package/src/sentiment/index.ts +16 -26
  496. package/src/sentiment/keywords.ts +26 -4
  497. package/src/sentiment/pipeline.ts +15 -4
  498. package/src/sentiment/scorer.ts +1 -1
  499. package/src/sentiment/store.ts +2 -2
  500. package/src/sentiment/trends.ts +9 -3
  501. package/src/sentiment/types.ts +5 -4
  502. package/src/system-prompt.ts +7 -3
  503. package/src/tool-kit.ts +10 -9
  504. package/src/tools/fundamentals/company-overview.ts +20 -10
  505. package/src/tools/fundamentals/comps.ts +69 -56
  506. package/src/tools/fundamentals/dcf.ts +146 -96
  507. package/src/tools/fundamentals/earnings.ts +17 -7
  508. package/src/tools/fundamentals/financials.ts +17 -8
  509. package/src/tools/fundamentals/sec-filings.ts +52 -8
  510. package/src/tools/index.ts +53 -38
  511. package/src/tools/interaction/ask-user.ts +22 -10
  512. package/src/tools/interaction/twitter-login.ts +17 -5
  513. package/src/tools/macro/fear-greed.ts +2 -2
  514. package/src/tools/macro/fred-data.ts +80 -42
  515. package/src/tools/market/crypto-history.ts +25 -4
  516. package/src/tools/market/crypto-price.ts +7 -7
  517. package/src/tools/market/screen-stocks.ts +279 -0
  518. package/src/tools/market/search-ticker.ts +219 -18
  519. package/src/tools/market/stock-history.ts +38 -13
  520. package/src/tools/market/stock-quote.ts +11 -8
  521. package/src/tools/options/greeks.ts +5 -6
  522. package/src/tools/options/option-chain.ts +47 -18
  523. package/src/tools/portfolio/alerts.ts +457 -0
  524. package/src/tools/portfolio/correlation.ts +48 -21
  525. package/src/tools/portfolio/daily-report.ts +101 -0
  526. package/src/tools/portfolio/holdings-overlap.ts +139 -0
  527. package/src/tools/portfolio/notifications.ts +45 -0
  528. package/src/tools/portfolio/predictions.ts +407 -107
  529. package/src/tools/portfolio/risk-analysis.ts +47 -8
  530. package/src/tools/portfolio/tracker.ts +271 -110
  531. package/src/tools/portfolio/watchlist.ts +251 -116
  532. package/src/tools/sentiment/reddit-sentiment.ts +51 -25
  533. package/src/tools/sentiment/sentiment-summary.ts +116 -35
  534. package/src/tools/sentiment/sentiment-trend.ts +24 -7
  535. package/src/tools/sentiment/twitter-sentiment.ts +23 -16
  536. package/src/tools/sentiment/untrusted-text.ts +21 -0
  537. package/src/tools/sentiment/web-search.ts +52 -16
  538. package/src/tools/sentiment/web-sentiment.ts +27 -11
  539. package/src/tools/technical/backtest.ts +78 -47
  540. package/src/tools/technical/indicators.ts +40 -17
  541. package/src/types/index.ts +8 -3
  542. package/src/types/market.ts +1 -0
  543. package/src/types/options.ts +17 -0
  544. package/src/types/portfolio.ts +46 -4
  545. package/src/types/sentiment.ts +2 -2
  546. package/src/workflows/compare-assets.ts +67 -19
  547. package/src/workflows/index.ts +3 -4
  548. package/src/workflows/options-screener.ts +98 -22
  549. package/src/workflows/portfolio-builder.ts +40 -29
  550. package/dist/runtime/index.d.ts +0 -16
  551. package/dist/runtime/index.js +0 -10
  552. package/dist/runtime/index.js.map +0 -1
  553. package/dist/runtime/provider-ids.d.ts +0 -14
  554. package/dist/runtime/provider-ids.js +0 -14
  555. package/dist/runtime/provider-ids.js.map +0 -1
  556. package/dist/workflows/types.d.ts +0 -4
  557. package/dist/workflows/types.js +0 -2
  558. package/dist/workflows/types.js.map +0 -1
  559. package/gui/web/dist/assets/CatalogOverlay-D1ImSJTe.js +0 -1
  560. package/gui/web/dist/assets/index-DBrWq43L.css +0 -1
  561. package/gui/web/dist/assets/index-RflHaj0y.js +0 -67
  562. package/src/runtime/index.ts +0 -55
  563. package/src/runtime/provider-ids.ts +0 -15
  564. package/src/workflows/types.ts +0 -4
@@ -1,43 +1,29 @@
1
1
  import { Type } from "@sinclair/typebox";
2
- import { readFileSync, writeFileSync, existsSync } from "node:fs";
3
- import { getQuote } from "../../providers/yahoo-finance.js";
2
+ import { isZeroFilledQuote, resolveYahooInstrument } from "../../market-state/resolve.js";
3
+ import { resolveInstrumentForMutation } from "../../market-state/resolve-for-mutation.js";
4
+ import { MarketStateService } from "../../market-state/service.js";
5
+ import { initDefaultDatabase } from "../../memory/sqlite.js";
4
6
  import { wrapProvider } from "../../providers/wrap-provider.js";
5
- import { ensureParentDir, getPredictionsPath } from "../../infra/opencandle-paths.js";
6
- function loadPredictions() {
7
- const predictionsPath = getPredictionsPath();
8
- if (!existsSync(predictionsPath))
9
- return [];
7
+ import { getQuote } from "../../providers/yahoo-finance.js";
8
+ export async function recordPrediction(params) {
9
+ const db = initDefaultDatabase();
10
+ const service = new MarketStateService(db);
10
11
  try {
11
- return JSON.parse(readFileSync(predictionsPath, "utf-8"));
12
+ const instrument = await resolveYahooInstrument(params.symbol);
13
+ const record = service.recordPrediction({
14
+ instrument,
15
+ direction: params.direction,
16
+ conviction: params.conviction,
17
+ entryPrice: params.entryPrice,
18
+ targetPrice: params.targetPrice,
19
+ timeframeDays: params.timeframeDays,
20
+ });
21
+ return predictionRecordToPrediction(record, params.timeframeDays);
12
22
  }
13
- catch {
14
- return [];
23
+ finally {
24
+ db.close();
15
25
  }
16
26
  }
17
- function savePredictions(predictions) {
18
- const predictionsPath = getPredictionsPath();
19
- ensureParentDir(predictionsPath);
20
- writeFileSync(predictionsPath, JSON.stringify(predictions, null, 2));
21
- }
22
- export function recordPrediction(params) {
23
- const predictions = loadPredictions();
24
- const now = new Date();
25
- const expires = new Date(now);
26
- expires.setDate(expires.getDate() + params.timeframeDays);
27
- const prediction = {
28
- symbol: params.symbol.toUpperCase(),
29
- direction: params.direction,
30
- conviction: params.conviction,
31
- entryPrice: params.entryPrice,
32
- targetPrice: params.targetPrice,
33
- date: now.toISOString().split("T")[0],
34
- expiresAt: expires.toISOString().split("T")[0],
35
- timeframeDays: params.timeframeDays,
36
- };
37
- predictions.push(prediction);
38
- savePredictions(predictions);
39
- return prediction;
40
- }
41
27
  export function checkPredictions(predictions, currentPrices, now = new Date()) {
42
28
  if (predictions.length === 0) {
43
29
  return { total: 0, open: 0, correct: 0, wrong: 0, hitRate: 0, weightedHitRate: 0, details: [] };
@@ -49,21 +35,55 @@ export function checkPredictions(predictions, currentPrices, now = new Date()) {
49
35
  const nowStr = now.toISOString().split("T")[0];
50
36
  for (const p of predictions) {
51
37
  const currentPrice = currentPrices.get(p.symbol);
52
- if (currentPrice == null)
38
+ if (currentPrice == null) {
39
+ openCount++;
40
+ details.push({
41
+ symbol: p.symbol,
42
+ direction: p.direction,
43
+ conviction: p.conviction,
44
+ entryPrice: p.entryPrice,
45
+ currentPrice: null,
46
+ pnlPercent: null,
47
+ correct: false,
48
+ status: "open",
49
+ dataGap: "quote unavailable",
50
+ });
53
51
  continue;
52
+ }
53
+ if (!Number.isFinite(p.entryPrice) || p.entryPrice <= 0) {
54
+ openCount++;
55
+ details.push({
56
+ symbol: p.symbol,
57
+ direction: p.direction,
58
+ conviction: p.conviction,
59
+ entryPrice: p.entryPrice,
60
+ targetPrice: p.targetPrice,
61
+ currentPrice,
62
+ pnlPercent: null,
63
+ correct: false,
64
+ status: "open",
65
+ dataGap: "invalid entry price",
66
+ });
67
+ continue;
68
+ }
54
69
  const isExpired = p.expiresAt <= nowStr;
55
70
  const pnlPercent = (currentPrice - p.entryPrice) / p.entryPrice;
56
71
  if (!isExpired) {
57
72
  openCount++;
73
+ const targetHit = p.targetPrice != null &&
74
+ ((p.direction === "bullish" && currentPrice >= p.targetPrice) ||
75
+ (p.direction === "bearish" && currentPrice <= p.targetPrice));
58
76
  details.push({
59
77
  symbol: p.symbol,
60
78
  direction: p.direction,
61
79
  conviction: p.conviction,
62
80
  entryPrice: p.entryPrice,
81
+ targetPrice: p.targetPrice,
63
82
  currentPrice,
64
83
  pnlPercent,
65
84
  correct: false,
66
85
  status: "open",
86
+ targetHit,
67
87
  });
68
88
  continue;
69
89
  }
@@ -97,76 +117,306 @@ export function checkPredictions(predictions, currentPrices, now = new Date()) {
97
117
  };
98
118
  }
99
119
  const params = Type.Object({
100
- action: Type.Union([Type.Literal("record"), Type.Literal("check")], { description: "record: save a new prediction. check: evaluate all predictions against current prices." }),
120
+ action: Type.Union([Type.Literal("record"), Type.Literal("check"), Type.Literal("cancel")], {
121
+ description: "record: save a new prediction. check: evaluate all predictions against current prices. cancel: close an open prediction without scoring it.",
122
+ }),
123
+ id: Type.Optional(Type.Integer({ minimum: 1, description: "Prediction id (required for cancel)" })),
101
124
  symbol: Type.Optional(Type.String({ description: "Ticker symbol (required for record)" })),
102
- direction: Type.Optional(Type.Union([Type.Literal("bullish"), Type.Literal("bearish"), Type.Literal("neutral")], { description: "Predicted direction (required for record)" })),
103
- conviction: Type.Optional(Type.Number({ description: "Conviction 1-10 (required for record)" })),
104
- entry_price: Type.Optional(Type.Number({ description: "Entry price at time of prediction (required for record)" })),
105
- target_price: Type.Optional(Type.Number({ description: "Optional target price" })),
106
- timeframe_days: Type.Optional(Type.Number({ description: "Timeframe in days for the prediction (default: 30)" })),
125
+ direction: Type.Optional(Type.Union([Type.Literal("bullish"), Type.Literal("bearish"), Type.Literal("neutral")], {
126
+ description: "Predicted direction (required for record)",
127
+ })),
128
+ conviction: Type.Optional(Type.Integer({ minimum: 1, maximum: 10, description: "Conviction 1-10 (required for record)" })),
129
+ entry_price: Type.Optional(Type.Number({
130
+ exclusiveMinimum: 0,
131
+ description: "Entry price at time of prediction (required for record)",
132
+ })),
133
+ target_price: Type.Optional(Type.Number({ exclusiveMinimum: 0, description: "Optional target price" })),
134
+ timeframe_days: Type.Optional(Type.Integer({
135
+ minimum: 1,
136
+ maximum: 3650,
137
+ description: "Timeframe in days for the prediction (default: 30)",
138
+ })),
107
139
  });
108
140
  export const predictionsTool = {
109
141
  name: "track_prediction",
110
142
  label: "Prediction Tracker",
111
143
  description: "Track your analysis predictions and measure accuracy over time. Record: save a directional prediction with conviction. Check: evaluate all predictions against current prices, compute hit rate and conviction-weighted accuracy. Inspired by ATLAS's Darwinian scoring approach.",
112
144
  parameters: params,
113
- async execute(toolCallId, args) {
145
+ async execute(_toolCallId, args) {
146
+ if (args.action === "cancel") {
147
+ if (args.id == null) {
148
+ throw new Error("id is required for cancel action.");
149
+ }
150
+ const db = initDefaultDatabase();
151
+ try {
152
+ const service = new MarketStateService(db);
153
+ const existing = service.listPredictions().find((record) => record.id === args.id);
154
+ if (existing == null) {
155
+ return {
156
+ content: [{ type: "text", text: `Prediction #${args.id} not found.` }],
157
+ details: null,
158
+ };
159
+ }
160
+ if (existing.status !== "open") {
161
+ return {
162
+ content: [
163
+ { type: "text", text: `Prediction #${args.id} is already ${existing.status}.` },
164
+ ],
165
+ details: existing,
166
+ };
167
+ }
168
+ const now = new Date().toISOString();
169
+ const cancelled = service.updatePredictionOutcome({
170
+ id: args.id,
171
+ status: "cancelled",
172
+ resolvedAt: now,
173
+ result: { reason: "user_cancelled" },
174
+ });
175
+ return {
176
+ content: [
177
+ { type: "text", text: `Cancelled prediction #${args.id} for ${cancelled.symbol}.` },
178
+ ],
179
+ details: cancelled,
180
+ };
181
+ }
182
+ finally {
183
+ db.close();
184
+ }
185
+ }
114
186
  if (args.action === "record") {
115
- if (!args.symbol || !args.direction || !args.conviction || !args.entry_price) {
187
+ if (!args.symbol || !args.direction || args.conviction == null || args.entry_price == null) {
116
188
  throw new Error("symbol, direction, conviction, and entry_price are required for record action.");
117
189
  }
118
- const prediction = recordPrediction({
119
- symbol: args.symbol,
120
- direction: args.direction,
121
- conviction: args.conviction,
122
- entryPrice: args.entry_price,
123
- targetPrice: args.target_price,
124
- timeframeDays: args.timeframe_days ?? 30,
125
- });
190
+ if (!Number.isInteger(args.conviction) || args.conviction < 1 || args.conviction > 10) {
191
+ throw new Error("conviction must be between 1 and 10.");
192
+ }
193
+ if (args.entry_price <= 0) {
194
+ throw new Error("entry_price must be greater than 0.");
195
+ }
196
+ if (args.target_price != null && args.target_price <= 0) {
197
+ throw new Error("target_price must be greater than 0.");
198
+ }
199
+ if (args.timeframe_days != null &&
200
+ (!Number.isInteger(args.timeframe_days) ||
201
+ args.timeframe_days < 1 ||
202
+ args.timeframe_days > 3650)) {
203
+ throw new Error("timeframe_days must be an integer between 1 and 3650.");
204
+ }
205
+ const resolution = await resolveInstrumentForMutation(args.symbol);
206
+ if (resolution.status === "needs_selection") {
207
+ return {
208
+ content: [
209
+ {
210
+ type: "text",
211
+ text: `Could not verify ${resolution.query}. Choose one of the returned candidates before recording the prediction.`,
212
+ },
213
+ ],
214
+ details: resolution,
215
+ };
216
+ }
217
+ const db = initDefaultDatabase();
218
+ let prediction;
219
+ try {
220
+ const service = new MarketStateService(db);
221
+ const record = service.recordPrediction({
222
+ instrument: resolution.instrument,
223
+ direction: args.direction,
224
+ conviction: args.conviction,
225
+ entryPrice: args.entry_price,
226
+ targetPrice: args.target_price,
227
+ timeframeDays: args.timeframe_days ?? 30,
228
+ });
229
+ prediction = predictionRecordToPrediction(record, args.timeframe_days ?? 30);
230
+ }
231
+ finally {
232
+ db.close();
233
+ }
126
234
  return {
127
- content: [{ type: "text", text: `Recorded: ${prediction.symbol} ${prediction.direction} (conviction ${prediction.conviction}/10) at $${prediction.entryPrice}. Expires ${prediction.expiresAt}.` }],
235
+ content: [
236
+ {
237
+ type: "text",
238
+ text: `Recorded: ${prediction.symbol} ${prediction.direction} (conviction ${prediction.conviction}/10) at $${prediction.entryPrice}. Expires ${prediction.expiresAt}.`,
239
+ },
240
+ ],
128
241
  details: prediction,
129
242
  };
130
243
  }
131
- // Check action
132
- const predictions = loadPredictions();
133
- if (predictions.length === 0) {
244
+ const db = initDefaultDatabase();
245
+ try {
246
+ const service = new MarketStateService(db);
247
+ const records = service.listPredictions();
248
+ const openRecords = records.filter((record) => record.status === "open");
249
+ const predictions = openRecords.map((record) => predictionRecordToPrediction(record));
250
+ const historicalDetails = storedResolvedPredictionDetails(records);
251
+ if (records.length === 0) {
252
+ return {
253
+ content: [
254
+ {
255
+ type: "text",
256
+ text: "No predictions recorded yet. Use record action to track your calls.",
257
+ },
258
+ ],
259
+ details: null,
260
+ };
261
+ }
262
+ if (openRecords.length === 0) {
263
+ if (historicalDetails.length > 0) {
264
+ const result = predictionResultFromDetails(historicalDetails);
265
+ return {
266
+ content: [{ type: "text", text: formatPredictionScorecard(result) }],
267
+ details: result,
268
+ };
269
+ }
270
+ return {
271
+ content: [{ type: "text", text: "No open predictions to check." }],
272
+ details: checkPredictions([], new Map()),
273
+ };
274
+ }
275
+ const symbols = [...new Set(predictions.map((p) => p.symbol))];
276
+ const priceMap = new Map();
277
+ await Promise.all(symbols.map(async (sym) => {
278
+ const result = await wrapProvider("yahoo", () => getQuote(sym));
279
+ if (result.status === "ok" && !result.stale && !isZeroFilledQuote(result.data)) {
280
+ priceMap.set(sym, result.data.price);
281
+ }
282
+ }));
283
+ const currentResult = checkPredictions(predictions, priceMap);
284
+ persistPredictionOutcomes(service, openRecords, currentResult);
285
+ const result = predictionResultFromDetails([...historicalDetails, ...currentResult.details]);
134
286
  return {
135
- content: [{ type: "text", text: "No predictions recorded yet. Use record action to track your calls." }],
136
- details: null,
287
+ content: [{ type: "text", text: formatPredictionScorecard(result) }],
288
+ details: result,
137
289
  };
138
290
  }
139
- // Fetch current prices for all symbols
140
- const symbols = [...new Set(predictions.map((p) => p.symbol))];
141
- const priceMap = new Map();
142
- await Promise.all(symbols.map(async (sym) => {
143
- const result = await wrapProvider("yahoo", () => getQuote(sym));
144
- if (result.status === "ok") {
145
- priceMap.set(sym, result.data.price);
146
- }
147
- else {
148
- // Skip symbols that are unavailable
149
- }
150
- }));
151
- const result = checkPredictions(predictions, priceMap);
152
- const resolved = result.correct + result.wrong;
153
- const lines = [
154
- `**Prediction Scorecard** — ${result.total} predictions (${resolved} resolved, ${result.open} open)`,
155
- ``,
156
- `Hit Rate: ${(result.hitRate * 100).toFixed(0)}% (${result.correct}/${resolved})`,
157
- `Weighted Hit Rate: ${(result.weightedHitRate * 100).toFixed(0)}% (by conviction)`,
158
- ``,
159
- ...result.details.map((d) => {
160
- const icon = d.status === "open" ? "~" : d.correct ? "+" : "-";
161
- const sign = d.pnlPercent >= 0 ? "+" : "";
162
- const label = d.status === "open" ? " (open)" : "";
163
- return ` [${icon}] ${d.symbol}: ${d.direction} (conv ${d.conviction}) → $${d.entryPrice.toFixed(2)} → $${d.currentPrice.toFixed(2)} (${sign}${(d.pnlPercent * 100).toFixed(1)}%)${label}`;
164
- }),
165
- ];
166
- return {
167
- content: [{ type: "text", text: lines.join("\n") }],
168
- details: result,
169
- };
291
+ finally {
292
+ db.close();
293
+ }
170
294
  },
171
295
  };
296
+ function persistPredictionOutcomes(service, records, result) {
297
+ const now = new Date().toISOString();
298
+ const usedRecordIds = new Set();
299
+ for (const detail of result.details) {
300
+ if (detail.status !== "resolved")
301
+ continue;
302
+ const record = findMatchingOpenRecord(records, detail, usedRecordIds);
303
+ if (record == null)
304
+ continue;
305
+ usedRecordIds.add(record.id);
306
+ service.updatePredictionOutcome({
307
+ id: record.id,
308
+ status: "resolved",
309
+ resolvedAt: now,
310
+ result: {
311
+ currentPrice: detail.currentPrice,
312
+ pnlPercent: detail.pnlPercent,
313
+ correct: detail.correct,
314
+ },
315
+ });
316
+ }
317
+ for (const record of records) {
318
+ if (usedRecordIds.has(record.id))
319
+ continue;
320
+ if (record.expiresAt > now)
321
+ continue;
322
+ if (result.details.some((detail) => detail.status === "open" && matchesPredictionRecord(record, detail))) {
323
+ continue;
324
+ }
325
+ service.updatePredictionOutcome({
326
+ id: record.id,
327
+ status: "expired",
328
+ resolvedAt: now,
329
+ result: { reason: "quote_unavailable" },
330
+ });
331
+ }
332
+ }
333
+ function storedResolvedPredictionDetails(records) {
334
+ return records.flatMap((record) => {
335
+ if (record.status !== "resolved" || record.resultJson == null)
336
+ return [];
337
+ const result = JSON.parse(record.resultJson);
338
+ if (typeof result.currentPrice !== "number" ||
339
+ typeof result.pnlPercent !== "number" ||
340
+ typeof result.correct !== "boolean") {
341
+ return [];
342
+ }
343
+ return [
344
+ {
345
+ symbol: record.symbol,
346
+ direction: record.direction,
347
+ conviction: record.conviction,
348
+ entryPrice: record.entryPrice,
349
+ currentPrice: result.currentPrice,
350
+ pnlPercent: result.pnlPercent,
351
+ correct: result.correct,
352
+ status: "resolved",
353
+ },
354
+ ];
355
+ });
356
+ }
357
+ function predictionResultFromDetails(details) {
358
+ const resolved = details.filter((detail) => detail.status === "resolved");
359
+ const correct = resolved.filter((detail) => detail.correct);
360
+ const totalConviction = resolved.reduce((sum, detail) => sum + detail.conviction, 0);
361
+ const correctConviction = correct.reduce((sum, detail) => sum + detail.conviction, 0);
362
+ return {
363
+ total: details.length,
364
+ open: details.filter((detail) => detail.status === "open").length,
365
+ correct: correct.length,
366
+ wrong: resolved.length - correct.length,
367
+ hitRate: resolved.length > 0 ? correct.length / resolved.length : 0,
368
+ weightedHitRate: totalConviction > 0 ? correctConviction / totalConviction : 0,
369
+ details,
370
+ };
371
+ }
372
+ function formatPredictionScorecard(result) {
373
+ const resolved = result.correct + result.wrong;
374
+ const lines = [
375
+ `**Prediction Scorecard** — ${result.total} predictions (${resolved} resolved, ${result.open} open)`,
376
+ ``,
377
+ `Hit Rate: ${(result.hitRate * 100).toFixed(0)}% (${result.correct}/${resolved})`,
378
+ `Weighted Hit Rate: ${(result.weightedHitRate * 100).toFixed(0)}% (by conviction)`,
379
+ ``,
380
+ ...result.details.map((d) => {
381
+ const icon = d.status === "open" ? "~" : d.correct ? "+" : "-";
382
+ if (d.currentPrice == null || d.pnlPercent == null) {
383
+ return `${icon} ${d.symbol} ${d.direction}: quote unavailable (open)`;
384
+ }
385
+ const sign = d.pnlPercent >= 0 ? "+" : "";
386
+ const label = d.status === "open"
387
+ ? d.targetHit && d.targetPrice != null
388
+ ? ` (open — target hit: $${d.targetPrice.toFixed(2)} reached before expiry; resolve or let it ride)`
389
+ : " (open)"
390
+ : "";
391
+ return ` [${icon}] ${d.symbol}: ${d.direction} (conv ${d.conviction}) → $${d.entryPrice.toFixed(2)} → $${d.currentPrice.toFixed(2)} (${sign}${(d.pnlPercent * 100).toFixed(1)}%)${label}`;
392
+ }),
393
+ ];
394
+ return lines.join("\n");
395
+ }
396
+ function findMatchingOpenRecord(records, detail, usedRecordIds) {
397
+ return (records.find((record) => !usedRecordIds.has(record.id) && matchesPredictionRecord(record, detail)) ?? null);
398
+ }
399
+ function matchesPredictionRecord(record, detail) {
400
+ return (record.symbol === detail.symbol &&
401
+ record.direction === detail.direction &&
402
+ record.conviction === detail.conviction &&
403
+ record.entryPrice === detail.entryPrice);
404
+ }
405
+ function predictionRecordToPrediction(record, explicitTimeframeDays) {
406
+ const openedAt = new Date(record.openedAt);
407
+ const expiresAt = new Date(record.expiresAt);
408
+ const timeframeDays = explicitTimeframeDays ?? Math.round((expiresAt.getTime() - openedAt.getTime()) / 86_400_000);
409
+ return {
410
+ id: record.id,
411
+ instrumentId: record.instrumentId,
412
+ symbol: record.symbol,
413
+ direction: record.direction,
414
+ conviction: record.conviction,
415
+ entryPrice: record.entryPrice,
416
+ targetPrice: record.targetPrice ?? undefined,
417
+ date: record.openedAt.split("T")[0],
418
+ expiresAt: record.expiresAt.split("T")[0],
419
+ timeframeDays,
420
+ };
421
+ }
172
422
  //# sourceMappingURL=predictions.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"predictions.js","sourceRoot":"","sources":["../../../src/tools/portfolio/predictions.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAEzC,OAAO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AE,MAAM,CAAC,SAAS;QAC3B,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,WAAW,EAAE,MAAM,CAAC,WAAW,IAAI,SAAS;QAC5C,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QACnC,SAAS,EAAE,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QACzC,aAAa;KACd,CAAC;AACJ,CAAC"}
@@ -2,7 +2,7 @@ import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import type { RiskMetrics } from "../../types/portfolio.js";
3
3
  declare const params: import("@sinclair/typebox").TObject<{
4
4
  symbol: import("@sinclair/typebox").TString;
5
- period: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TString>;
5
+ period: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TUnion<import("@sinclair/typebox").TLiteral<"6mo" | "1y" | "2y">[]>>;
6
6
  }>;
7
7
  export declare const riskAnalysisTool: AgentTool<typeof params, RiskMetrics>;
8
8
  export declare function computeRiskMetrics(symbol: string, closes: number[]): RiskMetrics;
@@ -1,22 +1,27 @@
1
1
  import { Type } from "@sinclair/typebox";
2
- import { getHistory } from "../../providers/yahoo-finance.js";
3
2
  import { wrapProvider } from "../../providers/wrap-provider.js";
3
+ import { getHistory } from "../../providers/yahoo-finance.js";
4
+ const RISK_PERIODS = ["6mo", "1y", "2y"];
4
5
  const params = Type.Object({
5
6
  symbol: Type.String({ description: "Stock ticker symbol (e.g. AAPL, MSFT, SPY)" }),
6
- period: Type.Optional(Type.String({ description: "Historical period for analysis: 6mo, 1y, 2y. Default: 1y" })),
7
+ period: Type.Optional(Type.Union(RISK_PERIODS.map((period) => Type.Literal(period)), {
8
+ description: "Historical period for analysis: 6mo, 1y, 2y. Default: 1y",
9
+ })),
7
10
  });
8
11
  export const riskAnalysisTool = {
9
12
  name: "analyze_risk",
10
13
  label: "Risk Analysis",
11
14
  description: "Compute risk metrics for a stock: annualized return, volatility, Sharpe ratio, max drawdown, and Value at Risk (95%). All computed locally from historical data.",
12
15
  parameters: params,
13
- async execute(toolCallId, args) {
16
+ async execute(_toolCallId, args) {
14
17
  const symbol = args.symbol.toUpperCase();
15
18
  const period = args.period ?? "1y";
16
19
  const result = await wrapProvider("yahoo", () => getHistory(symbol, period, "1d"));
17
20
  if (result.status === "unavailable") {
18
21
  return {
19
- content: [{ type: "text", text: `⚠ Risk analysis unavailable for ${symbol} (${result.reason}).` }],
22
+ content: [
23
+ { type: "text", text: `⚠ Risk analysis unavailable for ${symbol} (${result.reason}).` },
24
+ ],
20
25
  details: null,
21
26
  };
22
27
  }
@@ -24,11 +29,33 @@ export const riskAnalysisTool = {
24
29
  const closes = bars.map((b) => b.close);
25
30
  if (closes.length < 30) {
26
31
  return {
27
- content: [{ type: "text", text: `Insufficient data for risk analysis (need 30+ days, got ${closes.length})` }],
32
+ content: [
33
+ {
34
+ type: "text",
35
+ text: `Insufficient data for risk analysis (need 30+ days, got ${closes.length})`,
36
+ },
37
+ ],
28
38
  details: null,
29
39
  };
30
40
  }
31
- const metrics = computeRiskMetrics(symbol, closes);
41
+ let metrics;
42
+ try {
43
+ metrics = computeRiskMetrics(symbol, closes);
44
+ }
45
+ catch (error) {
46
+ if (error instanceof Error && error.message === "insufficient usable price history") {
47
+ return {
48
+ content: [
49
+ {
50
+ type: "text",
51
+ text: `Insufficient data for risk analysis (no usable price returns after filtering invalid closes)`,
52
+ },
53
+ ],
54
+ details: null,
55
+ };
56
+ }
57
+ throw error;
58
+ }
32
59
  const text = [
33
60
  `**${symbol} Risk Analysis** (${bars[0].date} to ${bars[bars.length - 1].date}, ${closes.length} days)`,
34
61
  ``,
@@ -45,6 +72,9 @@ export const riskAnalysisTool = {
45
72
  };
46
73
  export function computeRiskMetrics(symbol, closes) {
47
74
  const dailyReturns = computeDailyReturns(closes);
75
+ if (dailyReturns.length === 0) {
76
+ throw new Error("insufficient usable price history");
77
+ }
48
78
  const avgDailyReturn = mean(dailyReturns);
49
79
  const dailyVol = stddev(dailyReturns);
50
80
  const annualizedReturn = avgDailyReturn * 252;
@@ -66,16 +96,22 @@ export function computeRiskMetrics(symbol, closes) {
66
96
  export function computeDailyReturns(prices) {
67
97
  const returns = [];
68
98
  for (let i = 1; i < prices.length; i++) {
99
+ if (prices[i - 1] <= 0)
100
+ continue;
69
101
  returns.push((prices[i] - prices[i - 1]) / prices[i - 1]);
70
102
  }
71
103
  return returns;
72
104
  }
73
105
  export function computeMaxDrawdown(prices) {
74
- let peak = prices[0];
106
+ let peak = 0;
75
107
  let maxDd = 0;
76
108
  for (const price of prices) {
109
+ if (price <= 0 && peak <= 0)
110
+ continue;
77
111
  if (price > peak)
78
112
  peak = price;
113
+ if (peak <= 0)
114
+ continue;
79
115
  const dd = (peak - price) / peak;
80
116
  if (dd > maxDd)
81
117
  maxDd = dd;
@@ -83,6 +119,9 @@ export function computeMaxDrawdown(prices) {
83
119
  return maxDd;
84
120
  }
85
121
  export function computeVaR(returns, confidence) {
122
+ if (returns.length === 0) {
123
+ throw new Error("insufficient usable price history");
124
+ }
86
125
  const sorted = [...returns].sort((a, b) => a - b);
87
126
  const idx = Math.floor(sorted.length * confidence);
88
127
  return Math.abs(sorted[idx]);