investing 0.1.237 → 0.1.239

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 (268) hide show
  1. package/README.md +167 -119
  2. package/THIRD_PARTY_NOTICES.md +144 -0
  3. package/dist/{archiver-web.es-fg4bLLZa.cjs → archiver-web.es-Bnde7RUO.cjs} +1 -1
  4. package/dist/{archiver-web.es-B69gABHP.js → archiver-web.es-ct9J2dTE.js} +1 -1
  5. package/dist/db/index.d.ts +189 -0
  6. package/dist/db/index.d.ts.map +1 -1
  7. package/dist/db/schema.d.ts +200 -0
  8. package/dist/db/schema.d.ts.map +1 -1
  9. package/dist/index-DjOELXOV.js +15 -0
  10. package/dist/index-UBIHhhww.cjs +13 -0
  11. package/dist/index.d.ts +2 -1
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +1 -1
  14. package/dist/index.mjs +1 -1
  15. package/dist/leaders/zulu.d.ts +35 -5
  16. package/dist/leaders/zulu.d.ts.map +1 -1
  17. package/dist/live-data/dukascopy-client.d.ts +19 -2
  18. package/dist/live-data/dukascopy-client.d.ts.map +1 -1
  19. package/dist/prediction/api/analytics.d.ts.map +1 -1
  20. package/dist/prediction/api/leaderboard.d.ts +29 -11
  21. package/dist/prediction/api/leaderboard.d.ts.map +1 -1
  22. package/dist/prediction/api/markets.d.ts.map +1 -1
  23. package/dist/prediction/api/prices.d.ts.map +1 -1
  24. package/dist/prediction/db/markets.d.ts +13 -0
  25. package/dist/prediction/db/markets.d.ts.map +1 -1
  26. package/dist/prediction/index.d.ts +2 -0
  27. package/dist/prediction/index.d.ts.map +1 -1
  28. package/dist/prediction/sync/incremental-markets.d.ts.map +1 -1
  29. package/dist/prediction/sync/leaderboard.d.ts +1 -1
  30. package/dist/prediction/sync/leaderboard.d.ts.map +1 -1
  31. package/dist/prediction/sync/markets.d.ts +2 -2
  32. package/dist/prediction/sync/markets.d.ts.map +1 -1
  33. package/dist/prediction/sync/orchestration.d.ts +1 -1
  34. package/dist/prediction/sync/refill-limits.d.ts +9 -0
  35. package/dist/prediction/sync/refill-limits.d.ts.map +1 -0
  36. package/dist/prediction/sync/refill.d.ts +34 -0
  37. package/dist/prediction/sync/refill.d.ts.map +1 -0
  38. package/dist/prediction/sync/trade-history.d.ts.map +1 -1
  39. package/dist/prediction/utils/token-ids.d.ts +17 -0
  40. package/dist/prediction/utils/token-ids.d.ts.map +1 -0
  41. package/dist/prediction-markets/adapters/trading-agents.d.ts +21 -0
  42. package/dist/prediction-markets/adapters/trading-agents.d.ts.map +1 -0
  43. package/dist/prediction-markets/agents/bookmaker-agent.d.ts.map +1 -0
  44. package/dist/prediction-markets/agents/event-analysis-agent.d.ts.map +1 -0
  45. package/dist/{predictos → prediction-markets}/agents/index.d.ts +5 -1
  46. package/dist/prediction-markets/agents/index.d.ts.map +1 -0
  47. package/dist/prediction-markets/agents/kalshi-momentum-agent.d.ts +7 -0
  48. package/dist/prediction-markets/agents/kalshi-momentum-agent.d.ts.map +1 -0
  49. package/dist/prediction-markets/agents/mapper-agent.d.ts.map +1 -0
  50. package/dist/{predictos → prediction-markets}/agents/polyfactual-research.d.ts +1 -1
  51. package/dist/prediction-markets/agents/polyfactual-research.d.ts.map +1 -0
  52. package/dist/prediction-markets/agents/polymarket-position-tracker.d.ts.map +1 -0
  53. package/dist/{predictos → prediction-markets}/agents/polymarket-put-order.d.ts +1 -1
  54. package/dist/prediction-markets/agents/polymarket-put-order.d.ts.map +1 -0
  55. package/dist/prediction-markets/agents/polymarket-updown-15-limit-order-bot.d.ts.map +1 -0
  56. package/dist/prediction-markets/agents/x402-seller.d.ts.map +1 -0
  57. package/dist/prediction-markets/ai/callBlockRun.d.ts.map +1 -0
  58. package/dist/prediction-markets/ai/callGrok.d.ts.map +1 -0
  59. package/dist/prediction-markets/ai/callOpenAI.d.ts.map +1 -0
  60. package/dist/prediction-markets/ai/http.d.ts.map +1 -0
  61. package/dist/{predictos → prediction-markets}/ai/index.d.ts +1 -1
  62. package/dist/prediction-markets/ai/index.d.ts.map +1 -0
  63. package/dist/prediction-markets/ai/prompts/analyzeEventMarkets.d.ts.map +1 -0
  64. package/dist/prediction-markets/ai/prompts/arbitrageAnalysis.d.ts.map +1 -0
  65. package/dist/prediction-markets/ai/prompts/bookmakerAnalysis.d.ts.map +1 -0
  66. package/dist/prediction-markets/ai/prompts/searchQueryGenerator.d.ts.map +1 -0
  67. package/dist/prediction-markets/ai/types.d.ts.map +1 -0
  68. package/dist/prediction-markets/arbitrage.d.ts.map +1 -0
  69. package/dist/{predictos → prediction-markets}/clients/polyfactual.d.ts +1 -1
  70. package/dist/prediction-markets/clients/polyfactual.d.ts.map +1 -0
  71. package/dist/{predictos → prediction-markets}/clients/polymarket.d.ts +1 -1
  72. package/dist/prediction-markets/clients/polymarket.d.ts.map +1 -0
  73. package/dist/{predictos → prediction-markets}/clients/x402.d.ts +1 -1
  74. package/dist/prediction-markets/clients/x402.d.ts.map +1 -0
  75. package/dist/{predictos → prediction-markets}/data/kalshi.d.ts +1 -1
  76. package/dist/prediction-markets/data/kalshi.d.ts.map +1 -0
  77. package/dist/{predictos → prediction-markets}/data/polymarket.d.ts +1 -1
  78. package/dist/prediction-markets/data/polymarket.d.ts.map +1 -0
  79. package/dist/prediction-markets/events.d.ts.map +1 -0
  80. package/dist/prediction-markets/execution/paper.d.ts +19 -0
  81. package/dist/prediction-markets/execution/paper.d.ts.map +1 -0
  82. package/dist/prediction-markets/index.cjs +1 -0
  83. package/dist/{predictos → prediction-markets}/index.d.ts +8 -5
  84. package/dist/prediction-markets/index.d.ts.map +1 -0
  85. package/dist/prediction-markets/index.mjs +1 -0
  86. package/dist/prediction-markets/kalshi-momentum.LICENSE +21 -0
  87. package/dist/prediction-markets/strategies/btc15m-fusion.d.ts +27 -0
  88. package/dist/prediction-markets/strategies/btc15m-fusion.d.ts.map +1 -0
  89. package/dist/prediction-markets/strategies/copy-trade-sizing.d.ts +27 -0
  90. package/dist/prediction-markets/strategies/copy-trade-sizing.d.ts.map +1 -0
  91. package/dist/prediction-markets/strategies/gabagool.d.ts +26 -0
  92. package/dist/prediction-markets/strategies/gabagool.d.ts.map +1 -0
  93. package/dist/prediction-markets/strategies/kalshi-momentum.d.ts +13 -0
  94. package/dist/prediction-markets/strategies/kalshi-momentum.d.ts.map +1 -0
  95. package/dist/{predictos → prediction-markets}/types.d.ts +121 -6
  96. package/dist/prediction-markets/types.d.ts.map +1 -0
  97. package/dist/prediction-markets/validation.d.ts +5 -0
  98. package/dist/prediction-markets/validation.d.ts.map +1 -0
  99. package/dist/scripted-llm-C6y_Dk4q.cjs +1 -0
  100. package/dist/scripted-llm-DqaYX5Zn.js +1 -0
  101. package/dist/stocks/index.d.ts +2 -1
  102. package/dist/stocks/index.d.ts.map +1 -1
  103. package/dist/stocks/quote-cache-service.d.ts +11 -2
  104. package/dist/stocks/quote-cache-service.d.ts.map +1 -1
  105. package/dist/stocks/strategies/bb-rsi-breakout.d.ts +63 -0
  106. package/dist/stocks/strategies/bb-rsi-breakout.d.ts.map +1 -0
  107. package/dist/stocks/strategies/ema-crossover.d.ts +51 -0
  108. package/dist/stocks/strategies/ema-crossover.d.ts.map +1 -0
  109. package/dist/stocks/unified-quote-service.d.ts +15 -6
  110. package/dist/stocks/unified-quote-service.d.ts.map +1 -1
  111. package/dist/stocks/yahoo-finance-wrapper.d.ts +39 -3
  112. package/dist/stocks/yahoo-finance-wrapper.d.ts.map +1 -1
  113. package/dist/strategy-signals/data/fixture-data-provider.d.ts +8 -0
  114. package/dist/strategy-signals/data/fixture-data-provider.d.ts.map +1 -0
  115. package/dist/strategy-signals/data/openbb-mapping.d.ts +7 -0
  116. package/dist/strategy-signals/data/openbb-mapping.d.ts.map +1 -0
  117. package/dist/strategy-signals/demo.d.ts +446 -0
  118. package/dist/strategy-signals/demo.d.ts.map +1 -0
  119. package/dist/strategy-signals/execution.d.ts +18 -0
  120. package/dist/strategy-signals/execution.d.ts.map +1 -0
  121. package/dist/strategy-signals/fixtures/openbb-data/bars.d.ts +10 -0
  122. package/dist/strategy-signals/fixtures/openbb-data/bars.d.ts.map +1 -0
  123. package/dist/strategy-signals/index.d.ts +32 -0
  124. package/dist/strategy-signals/index.d.ts.map +1 -0
  125. package/dist/strategy-signals/proposal.d.ts +10 -0
  126. package/dist/strategy-signals/proposal.d.ts.map +1 -0
  127. package/dist/strategy-signals/report.d.ts +6 -0
  128. package/dist/strategy-signals/report.d.ts.map +1 -0
  129. package/dist/strategy-signals/risk-gate.d.ts +3 -0
  130. package/dist/strategy-signals/risk-gate.d.ts.map +1 -0
  131. package/dist/strategy-signals/sources/btc15m-fusion.d.ts +16 -0
  132. package/dist/strategy-signals/sources/btc15m-fusion.d.ts.map +1 -0
  133. package/dist/strategy-signals/sources/copy-trade-sizing.d.ts +15 -0
  134. package/dist/strategy-signals/sources/copy-trade-sizing.d.ts.map +1 -0
  135. package/dist/strategy-signals/sources/gabagool.d.ts +12 -0
  136. package/dist/strategy-signals/sources/gabagool.d.ts.map +1 -0
  137. package/dist/strategy-signals/sources/hedge-fund-technicals.d.ts +42 -0
  138. package/dist/strategy-signals/sources/hedge-fund-technicals.d.ts.map +1 -0
  139. package/dist/strategy-signals/sources/kalshi-momentum.d.ts +10 -0
  140. package/dist/strategy-signals/sources/kalshi-momentum.d.ts.map +1 -0
  141. package/dist/strategy-signals/sources/kalshi-vibe-guards.d.ts +15 -0
  142. package/dist/strategy-signals/sources/kalshi-vibe-guards.d.ts.map +1 -0
  143. package/dist/strategy-signals/sources/kalshi-vibe.d.ts +11 -0
  144. package/dist/strategy-signals/sources/kalshi-vibe.d.ts.map +1 -0
  145. package/dist/strategy-signals/sources/red-flags.d.ts +13 -0
  146. package/dist/strategy-signals/sources/red-flags.d.ts.map +1 -0
  147. package/dist/strategy-signals/survival-posture.d.ts +13 -0
  148. package/dist/strategy-signals/survival-posture.d.ts.map +1 -0
  149. package/dist/strategy-signals/types.d.ts +138 -0
  150. package/dist/strategy-signals/types.d.ts.map +1 -0
  151. package/dist/strategy-signals/validate.d.ts +15 -0
  152. package/dist/strategy-signals/validate.d.ts.map +1 -0
  153. package/dist/strategy-signals/venues/kalshi-venue-mapping.d.ts +3 -0
  154. package/dist/strategy-signals/venues/kalshi-venue-mapping.d.ts.map +1 -0
  155. package/dist/strategy-signals/venues/mock-equity-broker.d.ts +16 -0
  156. package/dist/strategy-signals/venues/mock-equity-broker.d.ts.map +1 -0
  157. package/dist/strategy-signals/venues/mock-venue.d.ts +14 -0
  158. package/dist/strategy-signals/venues/mock-venue.d.ts.map +1 -0
  159. package/dist/strategy-signals/venues/pmxt-venue-mapping.d.ts +7 -0
  160. package/dist/strategy-signals/venues/pmxt-venue-mapping.d.ts.map +1 -0
  161. package/dist/trading-agents/agents/debate-facilitator.d.ts +3 -3
  162. package/dist/trading-agents/agents/debate-facilitator.d.ts.map +1 -1
  163. package/dist/trading-agents/agents/fund-manager.d.ts +4 -2
  164. package/dist/trading-agents/agents/fund-manager.d.ts.map +1 -1
  165. package/dist/trading-agents/agents/improved-researchers.d.ts +3 -3
  166. package/dist/trading-agents/agents/improved-researchers.d.ts.map +1 -1
  167. package/dist/trading-agents/agents/market-analyst.d.ts +2 -2
  168. package/dist/trading-agents/agents/market-analyst.d.ts.map +1 -1
  169. package/dist/trading-agents/agents/news-analyst.d.ts +2 -2
  170. package/dist/trading-agents/agents/news-analyst.d.ts.map +1 -1
  171. package/dist/trading-agents/agents/researchers.d.ts +4 -4
  172. package/dist/trading-agents/agents/researchers.d.ts.map +1 -1
  173. package/dist/trading-agents/agents/risk-judge.d.ts +13 -0
  174. package/dist/trading-agents/agents/risk-judge.d.ts.map +1 -0
  175. package/dist/trading-agents/agents/risk-team.d.ts +4 -4
  176. package/dist/trading-agents/agents/risk-team.d.ts.map +1 -1
  177. package/dist/trading-agents/agents/trader.d.ts +2 -2
  178. package/dist/trading-agents/agents/trader.d.ts.map +1 -1
  179. package/dist/trading-agents/graph/trading-graph.d.ts +28 -2
  180. package/dist/trading-agents/graph/trading-graph.d.ts.map +1 -1
  181. package/dist/trading-agents/index.cjs +1 -0
  182. package/dist/trading-agents/index.d.ts +4 -0
  183. package/dist/trading-agents/index.d.ts.map +1 -1
  184. package/dist/trading-agents/index.mjs +1 -0
  185. package/dist/trading-agents/types/index.d.ts +11 -4
  186. package/dist/trading-agents/types/index.d.ts.map +1 -1
  187. package/dist/trading-agents/utils/llm-client.d.ts +4 -1
  188. package/dist/trading-agents/utils/llm-client.d.ts.map +1 -1
  189. package/dist/trading-agents/utils/parse-final-line.d.ts +7 -0
  190. package/dist/trading-agents/utils/parse-final-line.d.ts.map +1 -0
  191. package/dist/trading-agents/utils/scripted-llm.d.ts +17 -0
  192. package/dist/trading-agents/utils/scripted-llm.d.ts.map +1 -0
  193. package/dist/trading-agents/utils/strategy-prompt.d.ts +6 -0
  194. package/dist/trading-agents/utils/strategy-prompt.d.ts.map +1 -0
  195. package/dist/trading-agents-Bh9OORHe.js +1 -0
  196. package/dist/trading-agents-C8M7tbB0.cjs +1 -0
  197. package/dist/validate-C1MS8RhG.js +1 -0
  198. package/dist/validate-DBxPUXqH.cjs +1 -0
  199. package/package.json +19 -50
  200. package/dist/bookmakerAnalysis-Bfo1zUVm.js +0 -1
  201. package/dist/bookmakerAnalysis-CHn1W8uX.cjs +0 -1
  202. package/dist/callGrok-D0D7zBHK.js +0 -1
  203. package/dist/callGrok-DWO719mN.cjs +0 -1
  204. package/dist/events-BJOyGWeU.cjs +0 -1
  205. package/dist/events-OvBb8rgy.js +0 -1
  206. package/dist/index-D7fsk2gy.js +0 -15
  207. package/dist/index-_V1Ql5Es.cjs +0 -13
  208. package/dist/polymarket-updown-15-limit-order-bot-DCC8HE9Z.cjs +0 -1
  209. package/dist/polymarket-updown-15-limit-order-bot-Dv5oGAF4.js +0 -1
  210. package/dist/predictos/agents/bookmaker-agent.d.ts.map +0 -1
  211. package/dist/predictos/agents/event-analysis-agent.d.ts.map +0 -1
  212. package/dist/predictos/agents/index.d.ts.map +0 -1
  213. package/dist/predictos/agents/index.js +0 -1
  214. package/dist/predictos/agents/index.mjs +0 -1
  215. package/dist/predictos/agents/mapper-agent.d.ts.map +0 -1
  216. package/dist/predictos/agents/polyfactual-research.d.ts.map +0 -1
  217. package/dist/predictos/agents/polymarket-position-tracker.d.ts.map +0 -1
  218. package/dist/predictos/agents/polymarket-put-order.d.ts.map +0 -1
  219. package/dist/predictos/agents/polymarket-updown-15-limit-order-bot.d.ts.map +0 -1
  220. package/dist/predictos/agents/x402-seller.d.ts.map +0 -1
  221. package/dist/predictos/ai/callBlockRun.d.ts.map +0 -1
  222. package/dist/predictos/ai/callGrok.d.ts.map +0 -1
  223. package/dist/predictos/ai/callOpenAI.d.ts.map +0 -1
  224. package/dist/predictos/ai/http.d.ts.map +0 -1
  225. package/dist/predictos/ai/index.d.ts.map +0 -1
  226. package/dist/predictos/ai/index.js +0 -1
  227. package/dist/predictos/ai/index.mjs +0 -1
  228. package/dist/predictos/ai/prompts/analyzeEventMarkets.d.ts.map +0 -1
  229. package/dist/predictos/ai/prompts/arbitrageAnalysis.d.ts.map +0 -1
  230. package/dist/predictos/ai/prompts/bookmakerAnalysis.d.ts.map +0 -1
  231. package/dist/predictos/ai/prompts/searchQueryGenerator.d.ts.map +0 -1
  232. package/dist/predictos/ai/types.d.ts.map +0 -1
  233. package/dist/predictos/arbitrage.d.ts.map +0 -1
  234. package/dist/predictos/arbitrage.js +0 -1
  235. package/dist/predictos/arbitrage.mjs +0 -1
  236. package/dist/predictos/clients/polyfactual.d.ts.map +0 -1
  237. package/dist/predictos/clients/polymarket.d.ts.map +0 -1
  238. package/dist/predictos/clients/x402.d.ts.map +0 -1
  239. package/dist/predictos/data/kalshi.d.ts.map +0 -1
  240. package/dist/predictos/data/kalshi.js +0 -1
  241. package/dist/predictos/data/kalshi.mjs +0 -1
  242. package/dist/predictos/data/polymarket.d.ts.map +0 -1
  243. package/dist/predictos/data/polymarket.js +0 -1
  244. package/dist/predictos/data/polymarket.mjs +0 -1
  245. package/dist/predictos/events.d.ts.map +0 -1
  246. package/dist/predictos/index.d.ts.map +0 -1
  247. package/dist/predictos/index.js +0 -1
  248. package/dist/predictos/index.mjs +0 -1
  249. package/dist/predictos/types.d.ts.map +0 -1
  250. package/dist/searchQueryGenerator-DIIs9xw5.js +0 -1
  251. package/dist/searchQueryGenerator-rCVblXJS.cjs +0 -1
  252. /package/dist/{predictos → prediction-markets}/agents/bookmaker-agent.d.ts +0 -0
  253. /package/dist/{predictos → prediction-markets}/agents/event-analysis-agent.d.ts +0 -0
  254. /package/dist/{predictos → prediction-markets}/agents/mapper-agent.d.ts +0 -0
  255. /package/dist/{predictos → prediction-markets}/agents/polymarket-position-tracker.d.ts +0 -0
  256. /package/dist/{predictos → prediction-markets}/agents/polymarket-updown-15-limit-order-bot.d.ts +0 -0
  257. /package/dist/{predictos → prediction-markets}/agents/x402-seller.d.ts +0 -0
  258. /package/dist/{predictos → prediction-markets}/ai/callBlockRun.d.ts +0 -0
  259. /package/dist/{predictos → prediction-markets}/ai/callGrok.d.ts +0 -0
  260. /package/dist/{predictos → prediction-markets}/ai/callOpenAI.d.ts +0 -0
  261. /package/dist/{predictos → prediction-markets}/ai/http.d.ts +0 -0
  262. /package/dist/{predictos → prediction-markets}/ai/prompts/analyzeEventMarkets.d.ts +0 -0
  263. /package/dist/{predictos → prediction-markets}/ai/prompts/arbitrageAnalysis.d.ts +0 -0
  264. /package/dist/{predictos → prediction-markets}/ai/prompts/bookmakerAnalysis.d.ts +0 -0
  265. /package/dist/{predictos → prediction-markets}/ai/prompts/searchQueryGenerator.d.ts +0 -0
  266. /package/dist/{predictos → prediction-markets}/ai/types.d.ts +0 -0
  267. /package/dist/{predictos → prediction-markets}/arbitrage.d.ts +0 -0
  268. /package/dist/{predictos → prediction-markets}/events.d.ts +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/prediction-markets/types.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE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e;IAC9B,gEAAgE;IAChE,eAAe,EAAE,MAAM,CAAC;IACxB,uDAAuD;IACvD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,6BAA6B;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,gFAAgF;IAChF,SAAS,EAAE,SAAS,CAAC;IACrB,wCAAwC;IACxC,OAAO,EAAE,OAAO,EAAE,CAAC;IACnB,8BAA8B;IAC9B,YAAY,EAAE,MAAM,CAAC;IACrB,yBAAyB;IACzB,YAAY,EAAE,YAAY,CAAC;IAC3B,iDAAiD;IACjD,gBAAgB,EAAE,MAAM,CAAC;CAC1B"}
@@ -0,0 +1,5 @@
1
+ import { KalshiMarketTick } from './types.js';
2
+ export declare function validatePriceCents(value: number, name: string): void;
3
+ export declare function validateMarketObservation(ticker: string, timestamp: string): void;
4
+ export declare function validateKalshiMarketTick(tick: KalshiMarketTick): void;
5
+ //# sourceMappingURL=validation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../../src/prediction-markets/validation.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEnD,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,CAIpE;AAED,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,IAAI,CAYjF;AAED,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,gBAAgB,GAAG,IAAI,CAIrE"}
@@ -0,0 +1 @@
1
+ "use strict";const e=require("./validate-DBxPUXqH.cjs"),t=(e=>e&&e.__esModule?e:{default:e})(require("yahoo-finance2"));class n{provider;model;temperature;apiKey;baseUrl;constructor(e,t){this.provider=e.llmProvider,this.model=t,this.temperature=e.temperature??.3,e.baseUrl?this.baseUrl=e.baseUrl:"groq"===this.provider.toLowerCase()&&(this.baseUrl="https://api.groq.com/openai/v1/chat/completions"),e.apiKeys?this.apiKey=e.apiKeys[this.provider]||"":this.apiKey=process.env[`${this.provider.toUpperCase()}_API_KEY`]||""}async invoke(e){const t="string"==typeof e?[{role:"user",content:e}]:e;switch(this.provider.toLowerCase()){case"openai":return this.invokeOpenAI(t);case"groq":return this.invokeGroq(t);case"anthropic":return this.invokeAnthropic(t);default:throw new Error(`Unsupported LLM provider: ${this.provider}`)}}async invokeOpenAI(e){const t=this.baseUrl||"https://api.openai.com/v1/chat/completions",n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:this.model,messages:e,temperature:this.temperature})});if(!n.ok)throw new Error(`OpenAI API error: ${n.statusText}`);const r=await n.json();return{content:r.choices[0].message.content,toolCalls:r.choices[0].message.tool_calls?.map(e=>({name:e.function.name,arguments:JSON.parse(e.function.arguments)}))}}async invokeGroq(e){const t=this.baseUrl||"https://api.groq.com/openai/v1/chat/completions",n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:this.model,messages:e,temperature:this.temperature})});if(!n.ok){const e=await n.text();throw new Error(`Groq API error: ${n.statusText} - ${e}`)}const r=await n.json();return{content:r.choices[0].message.content,toolCalls:r.choices[0].message.tool_calls?.map(e=>({name:e.function.name,arguments:JSON.parse(e.function.arguments)}))}}async invokeAnthropic(e){const t=this.baseUrl||"https://api.anthropic.com/v1/messages",n=e.find(e=>"system"===e.role),r=e.filter(e=>"system"!==e.role),s=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:this.model,max_tokens:4096,temperature:this.temperature,system:n?.content,messages:r.map(e=>({role:"assistant"===e.role?"assistant":"user",content:e.content}))})});if(!s.ok)throw new Error(`Anthropic API error: ${s.statusText}`);return{content:(await s.json()).content[0].text}}async invokeWithTools(e,t){switch(this.provider.toLowerCase()){case"openai":case"groq":return this.invokeWithToolsOpenAI(e,t);default:return this.invoke(e)}}async invokeWithToolsOpenAI(e,t){const n="groq"===this.provider.toLowerCase()?this.baseUrl||"https://api.groq.com/openai/v1/chat/completions":this.baseUrl||"https://api.openai.com/v1/chat/completions",r=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:this.model,messages:e,temperature:this.temperature,tools:t,tool_choice:"auto"})});if(!r.ok){const e=await r.text();throw new Error(`${this.provider} API error: ${r.statusText} - ${e}`)}const s=await r.json();return{content:s.choices[0].message.content,toolCalls:s.choices[0].message.tool_calls?.map(e=>({name:e.function.name,arguments:JSON.parse(e.function.arguments)}))}}}function r(e,t){return new n(e,t)}function s(e,t=[]){const n=[...e].sort((e,t)=>e.sourceId.localeCompare(t.sourceId)||e.asOf.localeCompare(t.asOf)),r={BUY:0,SELL:0,HOLD:0};for(const a of n)r[a.action]++;const s=n.reduce((e,t)=>e+t.confidence,0)/(n.length||1);return{summary:`BUY ${r.BUY}, SELL ${r.SELL}, HOLD ${r.HOLD}; rejected ${t.length}`,findings:n.map(e=>`${e.sourceId} ${e.asOf}: ${e.action} (${e.confidence}) — ${e.reasoning}`),recommendations:Object.entries(r).filter(([,e])=>e>0).map(([e])=>e),confidence:s>=.75?"High":s>=.5?"Medium":"Low",data:{signals:n.map(e=>({sourceId:e.sourceId,probability:e.probability,evidence:e.evidence,order:e.order,targets:e.targets})),rejected:t}}}function a(e){return`${e.summary}\n${e.findings.join("\n")}\nRecommendations: ${e.recommendations.join(", ")}\nConfidence: ${e.confidence}\nEvidence: ${JSON.stringify(e.data)}`}function o(e,t=[]){return e.length||t.length?a(s(e,t)):"No third-party strategy signals."}function i(e,t,n,r,s){return`${e}:${"event"===t.type?t.venue:"equity"}:${"event"===t.type?t.marketId:t.symbol}:${n??"-"}:${r}:${s}`}function c(e,t){const n=e.account,r=e.instrument;return"equity"===r.type?"equity"===n?.kind?n.shares[r.symbol]?.quantity??0:0:"event"===n?.kind&&n.venue===r.venue?n.portfolio.positions[`${r.marketId}:${t}`]?.quantity??0:0}function l(t,n,r){if("BUY"!==t&&"SELL"!==t)return{reportOnly:"Trader HOLD"};if(!e.isUtcTime(r.evaluationTime))return{reportOnly:"invalid evaluation time"};if(r.event&&(r.event.venue!==("event"===r.instrument.type?r.instrument.venue:"")||r.event.marketId!==("event"===r.instrument.type?r.instrument.marketId:"")))return{reportOnly:"market identity mismatch"};if(r.event&&("closed"===r.event.status||void 0!==r.event.closesAt&&(!e.isUtcTime(r.event.closesAt)||Date.parse(r.event.closesAt)<=Date.parse(r.evaluationTime))))return{reportOnly:"market closed"};const s=n.filter(n=>0===e.validateSignal(n,r.instrument).length&&n.action===t&&e.matchesInstrument(n.instrument,r.instrument)).sort((e,t)=>t.confidence-e.confidence||e.sourceId.localeCompare(t.sourceId)||t.asOf.localeCompare(e.asOf)||i(e.sourceId,e.instrument,"event"===e.instrument.type?e.instrument.outcome:void 0,e.action,e.asOf).localeCompare(i(t.sourceId,t.instrument,"event"===t.instrument.type?t.instrument.outcome:void 0,t.action,t.asOf)))[0];if(!s)return"equity"!==r.instrument.type?{reportOnly:"no agreeing event signal"}:{proposal:{proposalId:i("trader",r.instrument,void 0,t,r.evaluationTime),sourceId:"trader",instrument:r.instrument,action:t,quantity:Number.MAX_SAFE_INTEGER,asOf:r.evaluationTime}};let a="event"===s.instrument.type?s.instrument.outcome:void 0;a||"YES"!==s.evidence?.outcome&&"NO"!==s.evidence?.outcome||(a=s.evidence.outcome);let o=s.sizing?.limitPriceCents,l=s.sizing?.quantity,u=t;if("order"===s.kind&&(a=s.order.outcome??void 0,o=s.order.priceCents,l=s.order.quantity),"portfolio"===s.kind){if(e.validateAccount(r.account).length)return{reportOnly:"portfolio target needs valid account"};const n=s.targets.find(e=>e.quantity!==c({...r,instrument:s.instrument},e.outcome));if(!n)return{reportOnly:"target already held"};const i=n.quantity-c({...r,instrument:s.instrument},n.outcome);if(a=n.outcome,o=n.priceCents,l=Math.abs(i),u=i>0?"BUY":"SELL",u!==t)return{reportOnly:"portfolio delta disagrees with Trader"}}return void 0===o||void 0===l||"event"===s.instrument.type&&!a?{reportOnly:"direction-only signal"}:{signal:s,proposal:{proposalId:i(s.sourceId,s.instrument,a,u,s.asOf),sourceId:s.sourceId,instrument:s.instrument,action:u,outcome:a,limitPriceCents:o,quantity:l,asOf:s.asOf}}}function u(t,n,r,s,a,o){const i=[...e.validateLimits(r),...e.validatePosture(s),...e.validateAccount(n.account),...e.validateInstrument(t.instrument)],l=e=>({allowed:!1,maxQuantity:0,reasons:[...i,e],limits:r});if(i.length)return l("invalid risk configuration or account");if(!e.isQuantity(t.quantity)||!e.isUtcTime(t.asOf)||!e.isUtcTime(n.evaluationTime)||Date.parse(t.asOf)>Date.parse(n.evaluationTime)||!["BUY","SELL"].includes(t.action))return l("invalid proposal");const u=n.account,d=t.instrument;if("event"===d.type&&("event"!==u.kind||u.venue!==d.venue||!t.outcome)||"equity"===d.type&&"equity"!==u.kind)return l("account scope mismatch");const m=c({...n,instrument:d},t.outcome);if("SELL"===t.action){const e=Math.min(m,t.quantity);return{allowed:e>0,maxQuantity:e,reasons:e>0?["exit limited to actual holdings"]:["no holdings to sell"],limits:r}}if(!s.allowNewEntries)return l("new entries blocked by posture");const p=t.limitPriceCents;if(void 0!==p&&(!Number.isFinite(p)||p<=0||"event"===d.type&&p>100)||"event"===d.type&&void 0===p)return l("invalid entry price");const h="event"===u.kind?u.portfolio.cashCents:u.cashCents,y="event"===u.kind?Object.values(u.portfolio.positions):Object.values(u.shares);if(!m&&void 0!==r.maxOpenPositions&&y.filter(e=>e.quantity>0).length>=r.maxOpenPositions)return l("open-position limit");let g=Math.floor(Math.min(t.quantity,Math.max(0,r.maxPositionPerMarket-m),void 0===p?Number.MAX_SAFE_INTEGER:Math.floor(h/p))*s.sizeMultiplier);if(i.push("current cash, position cap and posture applied"),a?.guards?.length){if(a.id!==t.sourceId||!o||o.sourceId!==a.id)return l("source guard identity missing");for(const r of a.guards)try{const s=r(t,n,o);if(s.deny)return l(s.deny);if(void 0!==s.maxQuantity){if(!e.isQuantity(s.maxQuantity))return l("invalid source cap");g=Math.min(g,s.maxQuantity),i.push(`source cap ${s.maxQuantity}`)}}catch{return l("source guard error")}}return{allowed:g>0,maxQuantity:g,reasons:[...i,...0===g?["zero executable quantity"]:[]],limits:r}}function d(e,t,n){const r=e.split(/\r?\n/).filter(e=>e.toUpperCase().includes(t.toUpperCase())).map(e=>{const n=e.toUpperCase().lastIndexOf(t.toUpperCase())+t.length;return e.slice(n).trim().replace(/[.!]+$/,"").trim().replace(/^[*_`\s]+|[*_`\s]+$/g,"").trim()});if(!r.length)return{value:null,reason:"missing final marker"};const s=e=>Array.isArray(n)?e.toUpperCase():e,a=e=>"function"==typeof n?n(e):n.includes(e),o=s(r.at(-1));return a(o)?new Set(r.map(s).filter(a)).size>1?{value:null,reason:"contradictory marker lines"}:{value:o}:{value:null,reason:"invalid final payload"}}const m=e=>/^\d+$/.test(e)&&Number.isSafeInteger(Number(e)),p={"a Bull Analyst":"Argue the strongest evidence-based case FOR taking the selected outcome, and rebut the latest opposing argument in the debate.","a Bear Analyst":"Argue the strongest evidence-based case AGAINST taking the selected outcome: stress missing evidence, resolution risk and price risk, and rebut the latest supporting argument in the debate.","an Investment Judge":"Weigh both sides of the debate and decide whether the evidence justifies taking the selected outcome.","a trading agent":"Propose one concrete action for the selected outcome from the research plan and the evidence.","a Risk-Seeking Analyst":"Argue for capturing the upside of this proposal within every hard limit, and challenge sizing that is more cautious than the evidence requires.","a Risk-Conservative Analyst":"Argue for capital preservation: challenge any size, price or exposure that the evidence does not justify.","a Neutral Risk Analyst":"Balance the aggressive and the conservative views into a proportionate position for this proposal.","a Risk Judge":"Decide whether this exact proposal may proceed, must be reduced to a smaller whole number, or must be blocked.","the **Fund Manager**":"Give the final decision on this exact proposal. Never exceed any cap, and never approve a different proposal."};function h(e,t,n){if("event"!==t.instrument?.type){return e+(t.strategySignalsReport?`\nThird-party strategy signals: ${t.strategySignalsReport}`:"")+(t.proposal?`\nSelected proposal: ${JSON.stringify(t.proposal)}`:"")}const r=t.eventMarket,s=t.proposal?.outcome??t.instrument.outcome,a=r?.outcomes.find(e=>e.side===s);return[`You are ${n} reviewing a binary event contract. Use the recorded evidence and debate; state missing information as absent.`,`Your stance: ${p[n]}`,`Market title: ${r?.title??"absent"}`,`Question: ${r?.question??"absent"}`,`Venue: ${t.instrument.venue}`,`Market: ${t.instrument.marketId}`,`Selected outcome: ${s??"absent"} (${a?.label??"absent"}). YES means the question resolves affirmatively; NO means it does not. Forecast probability always means P(YES); P(NO) = 1 - P(YES).`,`Quote: ${a?JSON.stringify(a):"absent"}`,`Closing time: ${r?.closesAt??"absent"}`,`Fixture evidence: ${t.strategySignalsReport??"absent"}`,`Investment debate: ${t.investmentDebateState.history}`,`Research Manager decision: ${t.investmentDebateState.judgeDecision}`,`Trader recommendation: ${t.traderInvestmentPlan}`,`Selected proposal: ${t.proposal?JSON.stringify(t.proposal):"absent"}`,`Risk debate: ${t.riskDebateState.history}`].join("\n")}class y{llm;memory;constructor(e,t){this.llm=e,this.memory=t}async analyze(e){const{riskDebateState:t,traderInvestmentPlan:n,investmentDebateState:r,companyOfInterest:s}=e,a=`You are a Risk-Seeking Analyst advocating for high-reward, high-risk investment strategies for ${s}.\n\n**Current Trading Plan:**\n${n}\n\n**Investment Debate Summary:**\n${r.judgeDecision}\n\n**Debate History:**\n${t.history}\n\n**Your Role:**\nAs the risk-seeking perspective, you should:\n1. Advocate for maximizing position size to capitalize on opportunities\n2. Highlight the potential for outsized returns\n3. Minimize conservative constraints that might limit gains\n4. Push back against overly cautious risk management\n5. Engage with other risk perspectives to defend your aggressive stance\n\n**Key Points:**\n- Emphasize asymmetric upside potential\n- Challenge conservative stop-loss levels as too tight\n- Advocate for conviction-weighted sizing\n- Use data to show that risk-averse approaches underperform\n\nPresent your argument conversationally, engaging with the other analysts' concerns while making a compelling case for higher risk tolerance.`,o=`Risky Analyst: ${(await this.llm.invoke(h(a,e,"a Risk-Seeking Analyst"))).content}`;return{riskDebateState:{history:t.history+"\n\n"+o,riskyHistory:t.riskyHistory+"\n\n"+o,safeHistory:t.safeHistory,neutralHistory:t.neutralHistory,latestSpeaker:"risky",currentRiskyResponse:o,currentSafeResponse:t.currentSafeResponse,currentNeutralResponse:t.currentNeutralResponse,judgeDecision:t.judgeDecision,count:t.count+1}}}}class g{llm;memory;constructor(e,t){this.llm=e,this.memory=t}async analyze(e){const{riskDebateState:t,traderInvestmentPlan:n,investmentDebateState:r,companyOfInterest:s}=e,a=`You are a Risk-Conservative Analyst emphasizing capital preservation and risk mitigation for ${s}.\n\n**Current Trading Plan:**\n${n}\n\n**Investment Debate Summary:**\n${r.judgeDecision}\n\n**Debate History:**\n${t.history}\n\n**Last Risky Analyst Argument:**\n${t.currentRiskyResponse}\n\n**Your Role:**\nAs the conservative perspective, you should:\n1. Prioritize capital preservation over maximum returns\n2. Advocate for strict stop-losses and position sizing limits\n3. Highlight downside risks and worst-case scenarios\n4. Counter aggressive strategies with prudent risk management\n5. Ensure the firm's assets are protected from excessive exposure\n\n**Key Points:**\n- Emphasize tail risks and maximum drawdown scenarios\n- Advocate for diversification and hedging\n- Reference historical losses from overleveraged positions\n- Push for conservative position sizing (e.g., Kelly Criterion * 0.5)\n- Highlight liquidity and execution risks\n\nEngage conversationally with the risky analyst's arguments, providing counterpoints grounded in risk management principles.`,o=`Safe Analyst: ${(await this.llm.invoke(h(a,e,"a Risk-Conservative Analyst"))).content}`;return{riskDebateState:{history:t.history+"\n\n"+o,riskyHistory:t.riskyHistory,safeHistory:t.safeHistory+"\n\n"+o,neutralHistory:t.neutralHistory,latestSpeaker:"safe",currentRiskyResponse:t.currentRiskyResponse,currentSafeResponse:o,currentNeutralResponse:t.currentNeutralResponse,judgeDecision:t.judgeDecision,count:t.count+1}}}}class f{llm;memory;constructor(e,t){this.llm=e,this.memory=t}async analyze(e){const{riskDebateState:t,traderInvestmentPlan:n,investmentDebateState:r,companyOfInterest:s}=e,a=`You are a Neutral Risk Analyst providing a balanced perspective on risk management for ${s}.\n\n**Current Trading Plan:**\n${n}\n\n**Investment Debate Summary:**\n${r.judgeDecision}\n\n**Debate History:**\n${t.history}\n\n**Risky Perspective:**\n${t.currentRiskyResponse}\n\n**Safe Perspective:**\n${t.currentSafeResponse}\n\n**Your Role:**\nAs the neutral perspective, you should:\n1. Find the optimal balance between risk and reward\n2. Acknowledge valid points from both risky and safe analysts\n3. Propose pragmatic middle-ground solutions\n4. Use quantitative frameworks (Sharpe ratio, risk-adjusted returns)\n5. Focus on expected value and probability-weighted outcomes\n\n**Key Points:**\n- Balance conviction sizing with prudent risk limits\n- Advocate for dynamic position sizing based on confidence\n- Propose tiered entry/exit strategies\n- Consider both opportunity cost and downside protection\n- Use objective metrics to mediate between extremes\n\nProvide a balanced perspective that synthesizes the best elements from both aggressive and conservative approaches.`,o=`Neutral Analyst: ${(await this.llm.invoke(h(a,e,"a Neutral Risk Analyst"))).content}`;return{riskDebateState:{history:t.history+"\n\n"+o,riskyHistory:t.riskyHistory,safeHistory:t.safeHistory,neutralHistory:t.neutralHistory+"\n\n"+o,latestSpeaker:"neutral",currentRiskyResponse:t.currentRiskyResponse,currentSafeResponse:t.currentSafeResponse,currentNeutralResponse:o,judgeDecision:t.judgeDecision,count:t.count+1}}}}function v(e){const t=d(e,"RISK DECISION:",e=>"PROCEED"===e||"BLOCK"===e||e.startsWith("REDUCE ")&&m(e.slice(7)));return t.value?t.value.startsWith("REDUCE ")?{decision:{kind:"REDUCE",maxQuantity:Number(t.value.slice(7))}}:{decision:{kind:t.value}}:{decision:{kind:"BLOCK"},reason:t.reason}}class w{constructor(e){this.llm=e}llm;async makeDecision(e){try{const t=h(`You are a Risk Judge reviewing this concrete proposal: ${JSON.stringify(e.proposal)}\nRisk debate: ${e.riskDebateState.history}`,e,"a Risk Judge")+"\nEnd with exactly RISK DECISION: PROCEED, RISK DECISION: BLOCK or RISK DECISION: REDUCE <whole number>.",n=await this.llm.invoke(t),r=v(n.content);return{judgeDecision:r.decision,finalRiskAdjustedPlan:n.content,riskDebateState:{...e.riskDebateState,judgeDecision:n.content},riskReviewReason:r.reason}}catch{return{judgeDecision:{kind:"BLOCK"},riskReviewReason:"risk judge model error"}}}}function b(e,t){const n=d(e,"PROPOSAL ID:",e=>e===t),r=d(e,"DECISION:",["APPROVE","REJECT","MODIFY"]),s=d(e,"APPROVED QUANTITY:",m);return n.value&&r.value&&("REJECT"===r.value||s.value)?{decision:r.value,proposalId:t,...s.value?{quantity:Number(s.value)}:{}}:{decision:"REJECT",proposalId:t}}class k{llm;constructor(e){this.llm=e}async makeDecision(e){if(e.proposal){const t=e.proposal;try{const n=h(`You are the **Fund Manager** reviewing this exact proposal: ${JSON.stringify(t)}`,e,"the **Fund Manager**")+`\nProposal: ${JSON.stringify(t)}\nDeterministic verdict: ${JSON.stringify(e.riskVerdict)}\nJudge decision: ${JSON.stringify(e.judgeDecision)}\nApprove only this proposal's action, within every cap. End with these lines:\nPROPOSAL ID: ${t.proposalId}\nDECISION: APPROVE|REJECT|MODIFY (one token)\nAPPROVED QUANTITY: <whole number>`,r=await this.llm.invoke(n),s=b(r.content,t.proposalId);return{fundManagerDecision:r.content,fundManagerApproval:s,finalApproval:s.decision,approvedPositionSize:s.quantity?.toString()??null}}catch{return{fundManagerApproval:{decision:"REJECT",proposalId:t.proposalId},finalApproval:"REJECT",riskReviewReason:"fund manager model error"}}}const{companyOfInterest:t,investmentDebateState:n,riskDebateState:r,traderInvestmentPlan:s,finalRiskAdjustedPlan:a}=e,o=`You are the **Fund Manager** with final approval authority for all trading decisions for **${t}**.\n\n## INVESTMENT DEBATE OUTCOME\n${n.judgeDecision}\n\n## RISK MANAGEMENT ASSESSMENT\n${r.judgeDecision}\n\n## TRADER'S RECOMMENDATION\n${s}\n\n## RISK-ADJUSTED PLAN\n${a}\n\n## YOUR RESPONSIBILITY\nAs Fund Manager, you must:\n1. Review all team recommendations and risk assessments\n2. Ensure alignment with fund objectives and risk tolerance\n3. Make the final GO/NO-GO decision\n4. Specify exact execution parameters if approved\n\n## DECISION FRAMEWORK\nConsider:\n- **Conviction Level**: How strong is the evidence across all teams?\n- **Risk-Reward**: Does the setup justify the capital allocation?\n- **Timing**: Is now the right time to enter this position?\n- **Portfolio Fit**: How does this fit with current holdings?\n- **Downside Protection**: Are risk controls adequate?\n\nProvide your decision in this structured format:\n\n### EXECUTIVE SUMMARY\n[2-3 sentence high-level assessment]\n\n### DECISION\n**[APPROVE/REJECT/MODIFY]**\n\n### RATIONALE\n[Key factors influencing your decision]\n\n### EXECUTION PARAMETERS (if APPROVE or MODIFY)\n- Position Size: [% of portfolio or $ amount]\n- Entry Strategy: [market order, limit order at $X, etc.]\n- Stop Loss: [price level or % from entry]\n- Target Exit: [price targets or conditions]\n- Maximum Hold Period: [time limit if applicable]\n\n### ADDITIONAL INSTRUCTIONS\n[Any special instructions for execution or monitoring]\n\n**Note**: Your decision is final. All trades must have your explicit approval.`,i=(await this.llm.invoke(o)).content,c=i.match(/DECISION[\s\S]*?\*\*\[(APPROVE|REJECT|MODIFY)\]\*\*/i),l=c?c[1].toUpperCase():"REJECT";let u=null;if("APPROVE"===l||"MODIFY"===l){const e=i.match(/Position Size:[\s]*([^\n]+)/i);e&&(u=e[1].trim())}return{fundManagerDecision:i,finalApproval:l,approvedPositionSize:u,finalTradeDecision:"APPROVE"===l||"MODIFY"===l?"BUY":"HOLD"}}}class S{name;memories=[];config;constructor(e,t){this.name=e,this.config=t}async addMemory(e){this.memories.push({...e,timestamp:new Date}),this.memories.length>100&&(this.memories=this.memories.slice(-100))}async getMemories(e,t=2){if(0===this.memories.length)return[];const n=this.memories.map(t=>({memory:t,score:this.calculateSimilarity(e,t.situation)}));return n.sort((e,t)=>t.score-e.score),n.slice(0,t).map(e=>e.memory)}calculateSimilarity(e,t){const n=this.tokenize(e),r=this.tokenize(t),s=n.filter(e=>r.includes(e)),a=new Set([...n,...r]);return s.length/a.size}tokenize(e){return e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(e=>e.length>3)}clear(){this.memories=[]}getAllMemories(){return[...this.memories]}getMemoryCount(){return this.memories.length}}const R={queue:{concurrency:1/0,interval:0}};function A(e={}){return new t.default({...e,queue:{...e?.queue,...R.queue}})}const $=A();function D(e){if(null==e)return null;const t="number"==typeof e?e:Number(e);return Number.isFinite(t)?t:null}function I(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){if(!n)continue;const e=n.date instanceof Date?n.date:new Date(n.date);if(Number.isNaN(e.getTime()))continue;const r=D(n.close),s=D(n.open),a=D(n.high),o=D(n.low),i=D(n.adjclose??n.adjClose),c=r??s??i??a??o;null!==c&&t.push({date:e,open:s??c,high:a??Math.max(s??c,r??c),low:o??Math.min(s??c,r??c),close:r??c,adjClose:i??r??c,volume:D(n.volume)??0})}return t}class O{constructor(){}async getQuote(e,t){try{return{success:!0,data:await $.quoteCombine(e,t)}}catch(n){return console.error(`Yahoo Finance quote error for ${e}:`,n),{success:!1,error:n.message||"Failed to fetch quote"}}}async getQuotes(e){try{return{success:!0,data:await Promise.all(e.map(e=>$.quoteCombine(e)))}}catch(t){return console.error("Yahoo Finance quotes error:",t),{success:!1,error:t.message||"Failed to fetch quotes"}}}async getHistorical(e,t){try{const n=t?.period1??new Date(Date.now()-31536e6),r=t?.period2??new Date,s=t?.interval||"1d",a=await $.chart(e,{period1:n,period2:r,interval:s},{validateResult:!1});return{success:!0,data:I(a?.quotes)}}catch(n){return console.error(`Yahoo Finance historical error for ${e}:`,n?.message||n),{success:!1,error:n.message||"Failed to fetch historical data"}}}async getChart(e,t){try{return{success:!0,data:await $.chart(e,{period1:t?.period1||new Date(Date.now()-2592e6),period2:t?.period2||new Date,interval:t?.interval||"1d"})}}catch(n){return console.error(`Yahoo Finance chart error for ${e}:`,n),{success:!1,error:n.message||"Failed to fetch chart data"}}}async getQuoteSummary(e,t){try{const n=t||["assetProfile","summaryDetail","financialData","defaultKeyStatistics","calendarEvents","recommendationTrend","earnings","earningsTrend"];return{success:!0,data:await $.quoteSummary(e,{modules:n})}}catch(n){return console.error(`Yahoo Finance quoteSummary error for ${e}:`,n),{success:!1,error:n.message||"Failed to fetch quote summary"}}}async search(e,t){try{return{success:!0,data:await $.search(e,{quotesCount:t?.quotesCount||10,newsCount:t?.newsCount||5})}}catch(n){return console.error(`Yahoo Finance search error for "${e}":`,n),{success:!1,error:n.message||"Failed to search"}}}async getOptions(e,t){try{return{success:!0,data:await $.options(e,t?{date:t}:void 0)}}catch(n){return console.error(`Yahoo Finance options error for ${e}:`,n),{success:!1,error:n.message||"Failed to fetch options data"}}}async getRecommendations(e){try{return{success:!0,data:await $.recommendationsBySymbol(e)}}catch(t){return console.error(`Yahoo Finance recommendations error for ${e}:`,t),{success:!1,error:t.message||"Failed to fetch recommendations"}}}async getTrending(e="US"){try{return{success:!0,data:await $.trendingSymbols(e)}}catch(t){return console.error(`Yahoo Finance trending error for ${e}:`,t),{success:!1,error:t.message||"Failed to fetch trending symbols"}}}async getInsights(e){try{return{success:!0,data:await $.insights(e)}}catch(t){return console.error(`Yahoo Finance insights error for ${e}:`,t),{success:!1,error:t.message||"Failed to fetch insights"}}}async getFundamentalsTimeSeries(e,t){try{return{success:!0,data:await $.fundamentalsTimeSeries(e,t)}}catch(n){return console.error(`Yahoo Finance fundamentalsTimeSeries error for ${e}:`,n),{success:!1,error:n.message||"Failed to fetch fundamentals time series"}}}async screener(e){try{return{success:!0,data:await $.screener(e)}}catch(t){return console.error("Yahoo Finance screener error:",t),{success:!1,error:t.message||"Failed to run screener"}}}async getCompanyProfile(e){try{const t=await $.quoteSummary(e,{modules:["assetProfile","summaryProfile"]});return{success:!0,data:{assetProfile:t.assetProfile,summaryProfile:t.summaryProfile}}}catch(t){return console.error(`Yahoo Finance company profile error for ${e}:`,t),{success:!1,error:t.message||"Failed to fetch company profile"}}}async getFinancialStatements(e){try{const t=await $.quoteSummary(e,{modules:["incomeStatementHistory","incomeStatementHistoryQuarterly","balanceSheetHistory","balanceSheetHistoryQuarterly","cashflowStatementHistory","cashflowStatementHistoryQuarterly"]});return{success:!0,data:{incomeStatement:t.incomeStatementHistory,incomeStatementQuarterly:t.incomeStatementHistoryQuarterly,balanceSheet:t.balanceSheetHistory,balanceSheetQuarterly:t.balanceSheetHistoryQuarterly,cashFlow:t.cashflowStatementHistory,cashFlowQuarterly:t.cashflowStatementHistoryQuarterly}}}catch(t){return console.error(`Yahoo Finance financial statements error for ${e}:`,t),{success:!1,error:t.message||"Failed to fetch financial statements"}}}async getKeyStatistics(e){try{const t=await $.quoteSummary(e,{modules:["defaultKeyStatistics","summaryDetail"]});return{success:!0,data:{keyStatistics:t.defaultKeyStatistics,summaryDetail:t.summaryDetail}}}catch(t){return console.error(`Yahoo Finance key statistics error for ${e}:`,t),{success:!1,error:t.message||"Failed to fetch key statistics"}}}async getEarnings(e){try{const t=await $.quoteSummary(e,{modules:["earnings","earningsHistory","earningsTrend","calendarEvents"]});return{success:!0,data:{earnings:t.earnings,earningsHistory:t.earningsHistory,earningsTrend:t.earningsTrend,calendarEvents:t.calendarEvents}}}catch(t){return console.error(`Yahoo Finance earnings error for ${e}:`,t),{success:!1,error:t.message||"Failed to fetch earnings data"}}}async getOwnership(e){try{const t=await $.quoteSummary(e,{modules:["institutionOwnership","fundOwnership","insiderHolders","insiderTransactions","majorHoldersBreakdown"]});return{success:!0,data:{institutionOwnership:t.institutionOwnership,fundOwnership:t.fundOwnership,insiderHolders:t.insiderHolders,insiderTransactions:t.insiderTransactions,majorHoldersBreakdown:t.majorHoldersBreakdown}}}catch(t){return console.error(`Yahoo Finance ownership error for ${e}:`,t),{success:!1,error:t.message||"Failed to fetch ownership data"}}}async getSECFilings(e){try{return{success:!0,data:(await $.quoteSummary(e,{modules:["secFilings"]})).secFilings}}catch(t){return console.error(`Yahoo Finance SEC filings error for ${e}:`,t),{success:!1,error:t.message||"Failed to fetch SEC filings"}}}async getComprehensiveData(e){try{const[t,n,r,s]=await Promise.all([this.getQuote(e),this.getQuoteSummary(e),this.getHistorical(e,{period1:new Date(Date.now()-31536e6)}),this.getRecommendations(e)]);return{success:!0,data:{quote:t.data,summary:n.data,historical:r.data,recommendations:s.data}}}catch(t){return console.error(`Yahoo Finance comprehensive data error for ${e}:`,t),{success:!1,error:t.message||"Failed to fetch comprehensive data"}}}}const E=new O,N=E;async function T(e,t,n){try{const r=await N.getHistorical(e,{period1:t,period2:n,interval:"1d"});if(!r.success||!r.data)throw new Error(`Failed to fetch stock data for ${e}`);const s=Array.isArray(r.data)?r.data:r.data.quotes;if(!s||!Array.isArray(s))throw new Error(`Invalid data format returned for ${e}`);return s.map(e=>({date:e.date,open:e.open,high:e.high,low:e.low,close:e.close,volume:e.volume}))}catch(r){throw console.error("Error fetching stock data:",r),r}}async function M(e,t){const n={},r=e.map(e=>e.close),s=e.map(e=>e.high),a=e.map(e=>e.low),o=e.map(e=>e.volume);for(const i of t)switch(i.toLowerCase()){case"close_50_sma":case"sma50":n.sma50=C(r,50);break;case"close_200_sma":case"sma200":n.sma200=C(r,200);break;case"close_10_ema":case"ema10":n.ema10=L(r,10);break;case"rsi":n.rsi=P(r,14);break;case"macd":const e=x(r);n.macd=e.macd,n.macdSignal=e.signal,n.macdHistogram=e.histogram;break;case"boll":case"bollinger":const t=q(r,20,2);n.bollingerUpper=t.upper,n.bollingerMiddle=t.middle,n.bollingerLower=t.lower;break;case"atr":n.atr=F(s,a,r,14);break;case"vwma":n.vwma=j(r,o,20)}return n}function C(e,t){const n=[];for(let r=0;r<e.length;r++)if(r<t-1)n.push(NaN);else{const s=e.slice(r-t+1,r+1).reduce((e,t)=>e+t,0);n.push(s/t)}return n}function L(e,t){const n=[],r=2/(t+1);let s=e.slice(0,t).reduce((e,t)=>e+t,0)/t;n.push(...Array(t-1).fill(NaN)),n.push(s);for(let a=t;a<e.length;a++)s=(e[a]-s)*r+s,n.push(s);return n}function P(e,t=14){const n=[],r=[],s=[];for(let a=1;a<e.length;a++){const t=e[a]-e[a-1];r.push(t>0?t:0),s.push(t<0?Math.abs(t):0)}for(let a=0;a<r.length;a++)if(a<t-1)n.push(NaN);else{const e=r.slice(a-t+1,a+1).reduce((e,t)=>e+t,0)/t,o=s.slice(a-t+1,a+1).reduce((e,t)=>e+t,0)/t,i=100-100/(1+(0===o?100:e/o));n.push(i)}return n.unshift(NaN),n}function x(e){const t=L(e,12),n=L(e,26),r=t.map((e,t)=>e-n[t]),s=L(r.filter(e=>!isNaN(e)),9),a=[...Array(r.length-s.length).fill(NaN),...s],o=r.map((e,t)=>e-a[t]);return{macd:r,signal:a,histogram:o}}function q(e,t=20,n=2){const r=C(e,t),s=[],a=[];for(let o=0;o<e.length;o++)if(o<t-1)s.push(NaN),a.push(NaN);else{const i=e.slice(o-t+1,o+1),c=r[o],l=i.reduce((e,t)=>e+Math.pow(t-c,2),0)/t,u=Math.sqrt(l);s.push(c+n*u),a.push(c-n*u)}return{upper:s,middle:r,lower:a}}function F(e,t,n,r=14){const s=[],a=[];for(let o=1;o<e.length;o++){const r=e[o]-t[o],s=Math.abs(e[o]-n[o-1]),i=Math.abs(t[o]-n[o-1]);a.push(Math.max(r,s,i))}s.push(NaN);for(let o=0;o<a.length;o++)if(o<r-1)s.push(NaN);else{const e=a.slice(o-r+1,o+1).reduce((e,t)=>e+t,0)/r;s.push(e)}return s}function j(e,t,n=20){const r=[];for(let s=0;s<e.length;s++)if(s<n-1)r.push(NaN);else{const a=e.slice(s-n+1,s+1),o=t.slice(s-n+1,s+1),i=a.reduce((e,t,n)=>e+t*o[n],0),c=o.reduce((e,t)=>e+t,0);r.push(i/c)}return r}class H{llm;constructor(e){this.llm=e}async analyze(e){const{companyOfInterest:t,tradeDate:n}=e,r=`You are a trading assistant tasked with analyzing financial markets. Your role is to select the **most relevant indicators** for a given market condition or trading strategy from the following list. The goal is to choose up to **8 indicators** that provide complementary insights without redundancy.\n\nMoving Averages:\n- close_50_sma: 50 SMA: A medium-term trend indicator. Identify trend direction and support/resistance.\n- close_200_sma: 200 SMA: A long-term trend benchmark. Confirm overall market trend and golden/death cross.\n- close_10_ema: 10 EMA: A responsive short-term average. Capture quick momentum shifts.\n\nMACD Related:\n- macd: MACD: Momentum via EMA differences. Look for crossovers and divergence.\n- macds: MACD Signal: EMA smoothing of MACD line. Use crossovers to trigger trades.\n- macdh: MACD Histogram: Gap between MACD and signal. Visualize momentum strength.\n\nMomentum Indicators:\n- rsi: RSI: Measures overbought/oversold conditions using 70/30 thresholds.\n\nVolatility Indicators:\n- boll: Bollinger Middle: 20 SMA basis for Bollinger Bands.\n- boll_ub: Bollinger Upper: 2 std devs above middle, signals overbought.\n- boll_lb: Bollinger Lower: 2 std devs below middle, signals oversold.\n- atr: ATR: Measures volatility for stop-loss and position sizing.\n\nVolume-Based Indicators:\n- vwma: VWMA: Volume-weighted moving average confirms trends.\n\nSelect indicators that provide diverse information and explain why they're suitable. Write a detailed report of trends observed.\nMake sure to append a Markdown table at the end of the report to organize key points.\n\nFor your reference, the current date is ${n}. The company we want to analyze is ${t}.`;try{const s=new Date(n),a=new Date(s);a.setMonth(a.getMonth()-6);const o=await T(t,a,s),i=["close_50_sma","close_200_sma","close_10_ema","rsi","macd","boll","atr","vwma"],c=await M(o,i),l=o.slice(-20),u=[{role:"system",content:r},{role:"user",content:`\nRecent Price Action for ${t}:\n${l.map(e=>`${e.date}: Close=$${e.close.toFixed(2)}, Volume=${e.volume}`).join("\n")}\n\nTechnical Indicators (Latest Values):\n- 50 SMA: ${c.sma50?.slice(-1)[0]?.toFixed(2)||"N/A"}\n- 200 SMA: ${c.sma200?.slice(-1)[0]?.toFixed(2)||"N/A"}\n- 10 EMA: ${c.ema10?.slice(-1)[0]?.toFixed(2)||"N/A"}\n- RSI: ${c.rsi?.slice(-1)[0]?.toFixed(2)||"N/A"}\n- MACD: ${c.macd?.slice(-1)[0]?.toFixed(2)||"N/A"}\n- Bollinger Upper: ${c.bollingerUpper?.slice(-1)[0]?.toFixed(2)||"N/A"}\n- Bollinger Middle: ${c.bollingerMiddle?.slice(-1)[0]?.toFixed(2)||"N/A"}\n- Bollinger Lower: ${c.bollingerLower?.slice(-1)[0]?.toFixed(2)||"N/A"}\n- ATR: ${c.atr?.slice(-1)[0]?.toFixed(2)||"N/A"}\n- VWMA: ${c.vwma?.slice(-1)[0]?.toFixed(2)||"N/A"}\n\nPlease analyze these indicators and provide a comprehensive market analysis report.`}],d=await this.llm.invoke(u);return{marketReport:d.content,messages:[...e.messages,{role:"assistant",content:d.content}],sender:"MarketAnalyst"}}catch(s){return console.error("Market Analyst error:",s),{marketReport:`Error analyzing market data for ${t}: ${s}`,sender:"MarketAnalyst"}}}}class z{llm;memory;constructor(e,t){this.llm=e,this.memory=t}async analyze(e){const{investmentDebateState:t,marketReport:n,sentimentReport:r,newsReport:s,fundamentalsReport:a}=e,o=`${n}\n\n${r}\n\n${s}\n\n${a}`,i=await this.memory.getMemories(o,2);let c="";c=i.length>0?i.map(e=>e.recommendation).join("\n\n"):"No past memories found.";const l=`You are a Bull Analyst advocating for investing in the stock. Your task is to build a strong, evidence-based case emphasizing growth potential, competitive advantages, and positive market indicators. Leverage the provided research and data to address concerns and counter bearish arguments effectively.\n\nKey points to focus on:\n- Growth Potential: Highlight the company's market opportunities, revenue projections, and scalability.\n- Competitive Advantages: Emphasize factors like unique products, strong branding, or dominant market positioning.\n- Positive Indicators: Use financial health, industry trends, and recent positive news as evidence.\n- Bear Counterpoints: Critically analyze the bear argument with specific data and sound reasoning, addressing concerns thoroughly and showing why the bull perspective holds stronger merit.\n- Engagement: Present your argument in a conversational style, engaging directly with the bear analyst's points and debating effectively rather than just listing data.\n\nResources available:\nMarket research report: ${n}\nSocial media sentiment report: ${r}\nLatest world affairs news: ${s}\nCompany fundamentals report: ${a}\nConversation history of the debate: ${t.history}\nLast bear argument: ${t.currentResponse}\nReflections from similar situations and lessons learned: ${c}\n\nUse this information to deliver a compelling bull argument, refute the bear's concerns, and engage in a dynamic debate that demonstrates the strengths of the bull position. You must also address reflections and learn from lessons and mistakes you made in the past.`,u=`Bull Analyst: ${(await this.llm.invoke(h(l,e,"a Bull Analyst"))).content}`;return{investmentDebateState:{history:t.history+"\n"+u,bullHistory:t.bullHistory+"\n"+u,bearHistory:t.bearHistory,currentResponse:u,judgeDecision:t.judgeDecision,count:t.count+1}}}}class U{llm;memory;constructor(e,t){this.llm=e,this.memory=t}async analyze(e){const{investmentDebateState:t,marketReport:n,sentimentReport:r,newsReport:s,fundamentalsReport:a}=e,o=`${n}\n\n${r}\n\n${s}\n\n${a}`,i=await this.memory.getMemories(o,2);let c="";c=i.length>0?i.map(e=>e.recommendation).join("\n\n"):"No past memories found.";const l=`You are a Bear Analyst advocating for caution or avoiding investment in the stock. Your task is to build a strong, evidence-based case emphasizing risks, challenges, and negative market indicators. Use the provided research and data to highlight concerns and counter bullish arguments effectively.\n\nKey points to focus on:\n- Risk Factors: Identify market risks, competitive threats, regulatory challenges, or economic headwinds.\n- Valuation Concerns: Point out if the stock is overvalued based on fundamentals or technical indicators.\n- Negative Indicators: Use weak financial metrics, declining trends, or negative news as evidence.\n- Bull Counterpoints: Critically analyze the bull argument with specific data and reasoning, showing why the bear perspective is more prudent.\n- Engagement: Present your argument conversationally, directly engaging with the bull analyst's points.\n\nResources available:\nMarket research report: ${n}\nSocial media sentiment report: ${r}\nLatest world affairs news: ${s}\nCompany fundamentals report: ${a}\nConversation history of the debate: ${t.history}\nLast bull argument: ${t.currentResponse}\nReflections from similar situations and lessons learned: ${c}\n\nUse this information to deliver a compelling bear argument, highlight risks, and engage in a dynamic debate. Learn from past mistakes reflected in the memories provided.`,u=`Bear Analyst: ${(await this.llm.invoke(h(l,e,"a Bear Analyst"))).content}`;return{investmentDebateState:{history:t.history+"\n"+u,bullHistory:t.bullHistory,bearHistory:t.bearHistory+"\n"+u,currentResponse:u,judgeDecision:t.judgeDecision,count:t.count+1}}}}class Y{llm;memory;constructor(e,t){this.llm=e,this.memory=t}async makeDecision(e){const{investmentDebateState:t,companyOfInterest:n}=e,r=`You are an Investment Judge tasked with evaluating the debate between a Bull Analyst and a Bear Analyst regarding ${n}.\n\nReview the complete debate history:\n${t.history}\n\nBased on the arguments presented by both sides:\n1. Evaluate the strength of each argument\n2. Consider the evidence provided\n3. Assess the risks and opportunities\n4. Make a final decision: Should we INVEST or NOT INVEST?\n\nProvide your reasoning and conclude with a clear decision: "FINAL DECISION: INVEST" or "FINAL DECISION: NOT INVEST"`,s="event"===e.instrument?.type?"\nEnd with FINAL DECISION: INVEST or FINAL DECISION: NOT INVEST.":"",a=await this.llm.invoke(h(r,e,"an Investment Judge")+s),o=d(a.content,"FINAL DECISION:",["INVEST","NOT INVEST"]).value??"NOT INVEST";return{investmentDebateState:{...t,judgeDecision:a.content},investmentPlan:"INVEST"===o?"Proceed with investment based on bull arguments":"Avoid investment due to bear concerns"}}}class B{llm;memory;constructor(e,t){this.llm=e,this.memory=t}async makeDecision(e){const{companyOfInterest:t,investmentPlan:n,marketReport:r,sentimentReport:s,newsReport:a,fundamentalsReport:o}=e,i=`${r}\n\n${s}\n\n${a}\n\n${o}`,c=await this.memory.getMemories(i,2);let l="";l=c.length>0?c.map(e=>e.recommendation).join("\n\n"):"No past memories found.";const u=[{role:"system",content:`You are a trading agent analyzing market data to make investment decisions. Based on your analysis, provide a specific recommendation to buy, sell, or hold. End with a firm decision and always conclude your response with 'FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL**' to confirm your recommendation.\n\nDo not forget to utilize lessons from past decisions to learn from your mistakes. Here is some reflections from similar situations you traded in and the lessons learned:\n\n${l}`},{role:"user",content:`Based on a comprehensive analysis by a team of analysts, here is an investment plan tailored for ${t}. This plan incorporates insights from current technical market trends, macroeconomic indicators, and social media sentiment. Use this plan as a foundation for evaluating your next trading decision.\n\nProposed Investment Plan: ${n}\n\nLeverage these insights to make an informed and strategic decision.`}];"event"===e.instrument?.type?(u[0].content=h("",e,"a trading agent")+"\nEnd with FINAL TRANSACTION PROPOSAL: BUY, SELL or HOLD (one token).",u[1].content=`Research Manager plan: ${n}`):e.strategySignalsReport&&(u[1].content+=`\nThird-party strategy signals: ${e.strategySignalsReport}`);const d=await this.llm.invoke(u);return{traderInvestmentPlan:d.content,messages:[...e.messages,{role:"assistant",content:d.content}],sender:"Trader"}}}const J={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},_=({allowReserved:e,explode:t,name:n,style:r,value:s})=>{if(!t){const t=(e?s:s.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(r));switch(r){case"label":return`.${t}`;case"matrix":return`;${n}=${t}`;case"simple":return t;default:return`${n}=${t}`}}const a=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),o=s.map(t=>"label"===r||"simple"===r?e?t:encodeURIComponent(t):V({allowReserved:e,name:n,value:t})).join(a);return"label"===r||"matrix"===r?a+o:o},V=({allowReserved:e,name:t,value:n})=>{if(null==n)return"";if("object"==typeof n)throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?n:encodeURIComponent(n)}`},K=({allowReserved:e,explode:t,name:n,style:r,value:s,valueOnly:a})=>{if(s instanceof Date)return a?s.toISOString():`${n}=${s.toISOString()}`;if("deepObject"!==r&&!t){let t=[];Object.entries(s).forEach(([n,r])=>{t=[...t,n,e?r:encodeURIComponent(r)]});const a=t.join(",");switch(r){case"form":return`${n}=${a}`;case"label":return`.${a}`;case"matrix":return`;${n}=${a}`;default:return a}}const o=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(r),i=Object.entries(s).map(([t,s])=>V({allowReserved:e,name:"deepObject"===r?`${n}[${t}]`:t,value:s})).join(o);return"label"===r||"matrix"===r?o+i:i},Q=/\{[^{}]+\}/g,W=({baseUrl:e,path:t,query:n,querySerializer:r,url:s})=>{let a=(e??"")+(s.startsWith("/")?s:`/${s}`);t&&(a=(({path:e,url:t})=>{let n=t;const r=t.match(Q);if(r)for(const s of r){let t=!1,r=s.substring(1,s.length-1),a="simple";r.endsWith("*")&&(t=!0,r=r.substring(0,r.length-1)),r.startsWith(".")?(r=r.substring(1),a="label"):r.startsWith(";")&&(r=r.substring(1),a="matrix");const o=e[r];if(null==o)continue;if(Array.isArray(o)){n=n.replace(s,_({explode:t,name:r,style:a,value:o}));continue}if("object"==typeof o){n=n.replace(s,K({explode:t,name:r,style:a,value:o,valueOnly:!0}));continue}if("matrix"===a){n=n.replace(s,`;${V({name:r,value:o})}`);continue}const i=encodeURIComponent("label"===a?`.${o}`:o);n=n.replace(s,i)}return n})({path:t,url:a}));let o=n?r(n):"";return o.startsWith("?")&&(o=o.substring(1)),o&&(a+=`?${o}`),a};function G(e){const t=void 0!==e.body;if(t&&e.bodySerializer){if("serializedBody"in e){return void 0!==e.serializedBody&&""!==e.serializedBody?e.serializedBody:null}return""!==e.body?e.body:null}if(t)return e.body}const X=async(e,t)=>{const n="function"==typeof t?await t(e):t;if(n)return"bearer"===e.scheme?`Bearer ${n}`:"basic"===e.scheme?`Basic ${btoa(n)}`:n},Z=({parameters:e={},...t}={})=>n=>{const r=[];if(n&&"object"==typeof n)for(const s in n){const a=n[s];if(null==a)continue;const o=e[s]||t;if(Array.isArray(a)){const e=_({allowReserved:o.allowReserved,explode:!0,name:s,style:"form",value:a,...o.array});e&&r.push(e)}else if("object"==typeof a){const e=K({allowReserved:o.allowReserved,explode:!0,name:s,style:"deepObject",value:a,...o.object});e&&r.push(e)}else{const e=V({allowReserved:o.allowReserved,name:s,value:a});e&&r.push(e)}}return r.join("&")},ee=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),te=e=>W({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:Z(e.querySerializer),url:e.url}),ne=(e,t)=>{const n={...e,...t};return n.baseUrl?.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=se(e.headers,t.headers),n},re=e=>{const t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},se=(...e)=>{const t=new Headers;for(const n of e){if(!n)continue;const e=n instanceof Headers?re(n):Object.entries(n);for(const[n,r]of e)if(null===r)t.delete(n);else if(Array.isArray(r))for(const e of r)t.append(n,e);else void 0!==r&&t.set(n,"object"==typeof r?JSON.stringify(r):r)}return t};class ae{fns=[];clear(){this.fns=[]}eject(e){const t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){const t=this.getInterceptorIndex(e);return Boolean(this.fns[t])}getInterceptorIndex(e){return"number"==typeof e?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){const n=this.getInterceptorIndex(e);return!!this.fns[n]&&(this.fns[n]=t,e)}use(e){return this.fns.push(e),this.fns.length-1}}const oe=Z({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),ie={"Content-Type":"application/json"},ce=(e={})=>({...J,headers:ie,parseAs:"auto",querySerializer:oe,...e}),le=((e={})=>{let t=ne(ce(),e);const n=()=>({...t}),r={error:new ae,request:new ae,response:new ae},s=async e=>{const n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:se(t.headers,e.headers),serializedBody:void 0};n.security&&await(async({security:e,...t})=>{for(const n of e){if(ee(t,n.name))continue;const e=await X(n,t.auth);if(!e)continue;const r=n.name??"Authorization";switch(n.in){case"query":t.query||(t.query={}),t.query[r]=e;break;case"cookie":t.headers.append("Cookie",`${r}=${e}`);break;default:t.headers.set(r,e)}}})({...n,security:n.security}),n.requestValidator&&await n.requestValidator(n),void 0!==n.body&&n.bodySerializer&&(n.serializedBody=n.bodySerializer(n.body)),void 0!==n.body&&""!==n.serializedBody||n.headers.delete("Content-Type");return{opts:n,url:te(n)}},a=async e=>{const{opts:t,url:n}=await s(e),a={redirect:"follow",...t,body:G(t)};let o=new Request(n,a);for(const s of r.request.fns)s&&(o=await s(o,t));const i=t.fetch;let c;try{c=await i(o)}catch(h){let e=h;for(const n of r.error.fns)n&&(e=await n(h,void 0,o,t));if(e=e||{},t.throwOnError)throw e;return"data"===t.responseStyle?void 0:{error:e,request:o,response:void 0}}for(const s of r.response.fns)s&&(c=await s(c,o,t));const l={request:o,response:c};if(c.ok){const e=("auto"===t.parseAs?(e=>{if(!e)return"stream";const t=e.split(";")[0]?.trim();return t?t.startsWith("application/json")||t.endsWith("+json")?"json":"multipart/form-data"===t?"formData":["application/","audio/","image/","video/"].some(e=>t.startsWith(e))?"blob":t.startsWith("text/")?"text":void 0:void 0})(c.headers.get("Content-Type")):t.parseAs)??"json";if(204===c.status||"0"===c.headers.get("Content-Length")){let n;switch(e){case"arrayBuffer":case"blob":case"text":n=await c[e]();break;case"formData":n=new FormData;break;case"stream":n=c.body;break;default:n={}}return"data"===t.responseStyle?n:{data:n,...l}}let n;switch(e){case"arrayBuffer":case"blob":case"formData":case"json":case"text":n=await c[e]();break;case"stream":return"data"===t.responseStyle?c.body:{data:c.body,...l}}return"json"===e&&(t.responseValidator&&await t.responseValidator(n),t.responseTransformer&&(n=await t.responseTransformer(n))),"data"===t.responseStyle?n:{data:n,...l}}const u=await c.text();let d;try{d=JSON.parse(u)}catch{}const m=d??u;let p=m;for(const s of r.error.fns)s&&(p=await s(m,c,o,t));if(p=p||{},t.throwOnError)throw p;return"data"===t.responseStyle?void 0:{error:p,...l}},o=e=>t=>a({...t,method:e}),i=e=>async t=>{const{opts:n,url:a}=await s(t);return(({onRequest:e,onSseError:t,onSseEvent:n,responseTransformer:r,responseValidator:s,sseDefaultRetryDelay:a,sseMaxRetryAttempts:o,sseMaxRetryDelay:i,sseSleepFn:c,url:l,...u})=>{let d;const m=c??(e=>new Promise(t=>setTimeout(t,e)));return{stream:async function*(){let c=a??3e3,p=0;const h=u.signal??(new AbortController).signal;for(;!h.aborted;){p++;const a=u.headers instanceof Headers?u.headers:new Headers(u.headers);void 0!==d&&a.set("Last-Event-ID",d);try{const t={redirect:"follow",...u,body:u.serializedBody,headers:a,signal:h};let o=new Request(l,t);e&&(o=await e(l,t));const i=u.fetch??globalThis.fetch,m=await i(o);if(!m.ok)throw new Error(`SSE failed: ${m.status} ${m.statusText}`);if(!m.body)throw new Error("No body in SSE response");const p=m.body.pipeThrough(new TextDecoderStream).getReader();let y="";const g=()=>{try{p.cancel()}catch{}};h.addEventListener("abort",g);try{for(;;){const{done:e,value:t}=await p.read();if(e)break;y+=t;const a=y.split("\n\n");y=a.pop()??"";for(const o of a){const e=o.split("\n"),t=[];let a,i;for(const n of e)if(n.startsWith("data:"))t.push(n.replace(/^data:\s*/,""));else if(n.startsWith("event:"))a=n.replace(/^event:\s*/,"");else if(n.startsWith("id:"))d=n.replace(/^id:\s*/,"");else if(n.startsWith("retry:")){const e=Number.parseInt(n.replace(/^retry:\s*/,""),10);Number.isNaN(e)||(c=e)}let l=!1;if(t.length){const e=t.join("\n");try{i=JSON.parse(e),l=!0}catch{i=e}}l&&(s&&await s(i),r&&(i=await r(i))),n?.({data:i,event:a,id:d,retry:c}),t.length&&(yield i)}}}finally{h.removeEventListener("abort",g),p.releaseLock()}break}catch(y){if(t?.(y),void 0!==o&&p>=o)break;const e=Math.min(c*2**(p-1),i??3e4);await m(e)}}}()}})({...n,body:n.body,headers:n.headers,method:e,onRequest:async(e,t)=>{let s=new Request(e,t);for(const a of r.request.fns)a&&(s=await a(s,n));return s},url:a})};return{buildUrl:te,connect:o("CONNECT"),delete:o("DELETE"),get:o("GET"),getConfig:n,head:o("HEAD"),interceptors:r,options:o("OPTIONS"),patch:o("PATCH"),post:o("POST"),put:o("PUT"),request:a,setConfig:e=>(t=ne(t,e),n()),sse:{connect:i("CONNECT"),delete:i("DELETE"),get:i("GET"),head:i("HEAD"),options:i("OPTIONS"),patch:i("PATCH"),post:i("POST"),put:i("PUT"),trace:i("TRACE")},trace:o("TRACE")}})((ue=ce(),{...ue,baseUrl:"https://app.qwksearch.com/api"}));var ue;class de{llm;constructor(e){this.llm=e}async analyze(e){const{companyOfInterest:t,tradeDate:n}=e;try{const s=`${t} stock news analysis ${n}`;console.log(`NewsAnalyst searching for: ${s}`);const a=await(r={query:{q:s,cat:"news",recency:"month"}},(r.client??le).get({url:"/search",...r}));if(!a.data?.results||0===a.data.results.length)return{newsReport:`No significant news found for ${t} around ${n}.`,sender:"NewsAnalyst"};const o=a.data.results.slice(0,5).map((e,t)=>`\nArticle ${t+1}:\nTitle: ${e.title}\nSource: ${e.domain}\nSnippet: ${e.snippet}\nURL: ${e.url}\n`).join("\n"),i=`You are a financial news analyst. Your job is to synthesize news headlines and snippets into a concise, relevant report for a trading strategy.\n \nFocus on:\n1. Significant events (earnings, mergers, regulatory changes).\n2. Market sentiment (positive/negative coverage).\n3. Potential impact on stock price.\n\nProvide a summary first, then a bulleted list of key takeaways.\nThe current date is ${n}. The company is ${t}.`,c=[{role:"system",content:i},{role:"user",content:`Here are the latest news search results:\n${o}\n\nPlease analyze these and write your report.`}],l=await this.llm.invoke(c);return{newsReport:l.content,messages:[...e.messages,{role:"assistant",content:l.content}],sender:"NewsAnalyst"}}catch(s){return console.error("News Analyst error:",s),{newsReport:`Error analyzing news for ${t}: ${s}`,sender:"NewsAnalyst"}}var r}}const me={llmProvider:"groq",deepThinkLLM:"llama3-70b-8192",quickThinkLLM:"llama3-8b-8192",temperature:.3,projectDir:"./data",apiKeys:{groq:process.env.GROQ_API_KEY||""}};exports.BearResearcher=U,exports.BullResearcher=z,exports.FinancialSituationMemory=S,exports.FundManager=k,exports.InvestmentJudge=Y,exports.MarketAnalyst=H,exports.NeutralAnalyst=f,exports.RiskJudge=w,exports.RiskyAnalyst=y,exports.SafeAnalyst=g,exports.ScriptedLLMClient=class{constructor(e){this.rules=e}rules;calls=[];async invoke(e){const t="string"==typeof e?e:JSON.stringify(e,null,2),n=this.rules.find(e=>"string"==typeof e.match?t.includes(e.match):e.match.test(t));if(!n)throw new Error("No scripted rule matched prompt");return this.calls.push({rule:n.name,prompt:t}),{content:"string"==typeof n.response?n.response:n.response(t)}}},exports.Trader=B,exports.TradingAgentsGraph=class{constructor(e=["market","social","news","fundamentals"],t=!1,n,s={}){this.options=s,this.selectedAnalysts=e,this.debug=t,this.config={...me,...n},this.deepThinkingLLM=s.llm?.deep??r(this.config,this.config.deepThinkLLM),this.quickThinkingLLM=s.llm?.quick??r(this.config,this.config.quickThinkLLM),this.bullMemory=new S("bull_memory",this.config),this.bearMemory=new S("bear_memory",this.config),this.traderMemory=new S("trader_memory",this.config),this.investJudgeMemory=new S("invest_judge_memory",this.config),this.riskManagerMemory=new S("risk_manager_memory",this.config),this.marketAnalyst=new H(this.deepThinkingLLM),this.bullResearcher=new z(this.deepThinkingLLM,this.bullMemory),this.bearResearcher=new U(this.deepThinkingLLM,this.bearMemory),this.investmentJudge=new Y(this.quickThinkingLLM,this.investJudgeMemory),this.trader=new B(this.quickThinkingLLM,this.traderMemory),this.newsAnalyst=new de(this.deepThinkingLLM)}options;config;deepThinkingLLM;quickThinkingLLM;selectedAnalysts;debug;bullMemory;bearMemory;traderMemory;investJudgeMemory;riskManagerMemory;marketAnalyst;bullResearcher;bearResearcher;investmentJudge;trader;newsAnalyst;currentState=null;ticker=null;logStatesDict={};async propagate(t,n,r){this.ticker=t;const s=this.createInitialState(t,n),a=r?.instrument??{type:"equity",symbol:t},i=r?.evaluationTime??`${n}T00:00:00Z`;if(r){if(s.instrument=a,s.eventMarket=r.event,void 0!==r.strategySignals){const t=[],n=[];if(Array.isArray(r.strategySignals))for(const s of r.strategySignals){const o=r.sources?.[s?.sourceId],c=e.partitionValidSignals([s],a,i,o);t.push(...c.valid),n.push(...c.rejected)}else n.push(...e.partitionValidSignals(r.strategySignals,a,i).rejected);s.strategySignals=t,s.strategySignalsReport=o(t,n)}"event"===a.type&&(s.marketReport="Not applicable for an event contract.",s.newsReport="Not applicable for an event contract.")}this.debug&&console.log(`\n=== Starting Analysis for ${t} on ${n} ===\n`);let c=s;if(this.selectedAnalysts.includes("market")&&"event"!==a.type){this.debug&&console.log("Running Market Analyst...");const e=await this.marketAnalyst.analyze(c);c={...c,...e}}if(c.sentimentReport||(c.sentimentReport="No social media analysis performed."),this.selectedAnalysts.includes("news")&&"event"!==a.type){this.debug&&console.log("Running News Analyst...");const e=await this.newsAnalyst.analyze(c);c={...c,...e}}else c.newsReport||(c.newsReport="No news analysis performed.");c.fundamentalsReport||(c.fundamentalsReport="No fundamentals analysis performed."),this.debug&&console.log("\n=== Investment Debate ==="),c.investmentDebateState={bullHistory:"",bearHistory:"",history:"",currentResponse:"",judgeDecision:"",count:0};for(let e=0;e<3;e++){this.debug&&console.log(`\nDebate Round ${e+1}`);const t=await this.bullResearcher.analyze(c);c={...c,...t};const n=await this.bearResearcher.analyze(c);c={...c,...n}}this.debug&&console.log("\nInvestment Judge making decision...");const l=await this.investmentJudge.makeDecision(c);c={...c,...l},this.debug&&console.log("\nTrader making final decision...");const u=await this.trader.makeDecision(c);c={...c,...u};const d=this.extractDecision(c.traderInvestmentPlan||"");c.finalTradeDecision=d,this.options.riskReview&&"HOLD"!==d&&(c=await this.runRiskReview(c,d,a,i,r)),this.currentState=c,this.logState(n,c);const m=this.processSignal(c.finalTradeDecision);return r&&(m.timestamp=new Date(i)),this.debug&&console.log(`\n=== Final Decision: ${m.action} (Confidence: ${m.confidence}) ===\n`),{state:c,signal:m}}createInitialState(e,t){return{companyOfInterest:e,tradeDate:t,messages:[],sender:"",marketReport:"",sentimentReport:"",newsReport:"",fundamentalsReport:"",investmentDebateState:{bullHistory:"",bearHistory:"",history:"",currentResponse:"",judgeDecision:"",count:0},investmentPlan:"",traderInvestmentPlan:"",riskDebateState:{riskyHistory:"",safeHistory:"",neutralHistory:"",history:"",latestSpeaker:"",currentRiskyResponse:"",currentSafeResponse:"",currentNeutralResponse:"",judgeDecision:"",count:0},finalTradeDecision:""}}async runRiskReview(e,t,n,r,s){let a=e;const o={instrument:n,account:s?.account,evaluationTime:r,event:s?.event},i=l(t,a.strategySignals??[],o);if("reportOnly"in i)return{...a,finalTradeDecision:"HOLD",riskReviewReason:i.reportOnly};const c=i.proposal;a={...a,proposal:c};try{const e=[new y(this.deepThinkingLLM,this.riskManagerMemory),new g(this.deepThinkingLLM,this.riskManagerMemory),new f(this.deepThinkingLLM,this.riskManagerMemory)];for(const s of e)a={...a,...await s.analyze(a)};a={...a,...await new w(this.quickThinkingLLM).makeDecision(a)};const t=s?.sources?.[c.sourceId];let n=u(c,o,this.options.riskLimits??{maxPositionPerMarket:50},this.options.riskPosture??{label:"Normal",sizeMultiplier:1,allowNewEntries:!0},t,i.signal);"trader"===c.sourceId||t||(n={...n,allowed:!1,maxQuantity:0,reasons:[...n.reasons,"unregistered strategy source"]}),a.riskVerdict=n;const r=a.judgeDecision;if("BLOCK"===r.kind||!n.allowed)return{...a,finalTradeDecision:"HOLD",approval:void 0};a={...a,...await new k(this.quickThinkingLLM).makeDecision(a)};const l=a.fundManagerApproval,d=Math.min(c.quantity,n.maxQuantity,"REDUCE"===r.kind?r.maxQuantity:Number.MAX_SAFE_INTEGER,l.quantity??0);return"REJECT"===l.decision||d<=0?{...a,finalTradeDecision:"HOLD",approval:void 0}:{...a,approval:{proposal:c,finalQuantity:d,verdict:n,judge:r,fundManager:l,reasons:n.reasons}}}catch(d){const e=d instanceof Error?d.message:String(d);return{...a,finalTradeDecision:"HOLD",approval:void 0,riskReviewReason:`risk review error: ${e}`}}}extractDecision(e){return d(e,"FINAL TRANSACTION PROPOSAL:",["BUY","SELL","HOLD"]).value??"HOLD"}processSignal(e){return{action:e,confidence:.75,reasoning:"Based on multi-agent analysis and debate",timestamp:new Date}}logState(e,t){this.logStatesDict[e]={companyOfInterest:t.companyOfInterest,tradeDate:t.tradeDate,marketReport:t.marketReport,sentimentReport:t.sentimentReport,newsReport:t.newsReport,fundamentalsReport:t.fundamentalsReport,investmentDebateState:{bullHistory:t.investmentDebateState.bullHistory,bearHistory:t.investmentDebateState.bearHistory,history:t.investmentDebateState.history,currentResponse:t.investmentDebateState.currentResponse,judgeDecision:t.investmentDebateState.judgeDecision},traderInvestmentDecision:t.traderInvestmentPlan,finalTradeDecision:t.finalTradeDecision}}async reflectAndRemember(e){if(!this.currentState)return;const t=`${this.currentState.marketReport}\n${this.currentState.newsReport}`,n=this.currentState.finalTradeDecision,r=`Decision: ${n}, Outcome: ${e>0?"Positive":"Negative"} (${e.toFixed(2)}%)`,s={situation:t,decision:n,outcome:e,recommendation:r,timestamp:new Date};await this.bullMemory.addMemory(s),await this.bearMemory.addMemory(s),await this.traderMemory.addMemory(s),await this.investJudgeMemory.addMemory(s)}getLogStates(){return this.logStatesDict}getCurrentState(){return this.currentState}},exports.UnifiedLLMClient=n,exports.WORKER_SAFE_YAHOO_FINANCE_OPTIONS=R,exports.YahooFinanceWrapper=O,exports.applyRiskGate=u,exports.createLLM=r,exports.createYahooFinance=A,exports.formatStructuredReport=a,exports.getFundamentals=async function(e){try{const t=await fetch(`/api/stocks/quote/${e}`);if(!t.ok)throw new Error("Failed to fetch fundamentals");const n=await t.json();return{marketCap:n.marketCap,peRatio:n.peRatio,dividendYield:n.dividendYield,eps:n.eps,revenue:n.revenue,profitMargin:n.profitMargin}}catch(t){throw console.error("Error fetching fundamentals:",t),t}},exports.getIndicators=M,exports.getNews=async function(e,t=10){try{return[]}catch(n){return console.error("Error fetching news:",n),[]}},exports.getStockData=T,exports.normalizeChartQuotes=I,exports.parseFundManagerApproval=b,exports.parseJudgeDecision=v,exports.proposalId=i,exports.renderStrategySignalsReport=o,exports.selectProposal=l,exports.toStructuredReport=s,exports.yahooFinance=N,exports.yahooFinanceWrapper=E;
@@ -0,0 +1 @@
1
+ import{i as e,v as t,m as n,a as s,b as r,c as a,d as o,e as i,p as c}from"./validate-C1MS8RhG.js";import l from"yahoo-finance2";class u{provider;model;temperature;apiKey;baseUrl;constructor(e,t){this.provider=e.llmProvider,this.model=t,this.temperature=e.temperature??.3,e.baseUrl?this.baseUrl=e.baseUrl:"groq"===this.provider.toLowerCase()&&(this.baseUrl="https://api.groq.com/openai/v1/chat/completions"),e.apiKeys?this.apiKey=e.apiKeys[this.provider]||"":this.apiKey=process.env[`${this.provider.toUpperCase()}_API_KEY`]||""}async invoke(e){const t="string"==typeof e?[{role:"user",content:e}]:e;switch(this.provider.toLowerCase()){case"openai":return this.invokeOpenAI(t);case"groq":return this.invokeGroq(t);case"anthropic":return this.invokeAnthropic(t);default:throw new Error(`Unsupported LLM provider: ${this.provider}`)}}async invokeOpenAI(e){const t=this.baseUrl||"https://api.openai.com/v1/chat/completions",n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:this.model,messages:e,temperature:this.temperature})});if(!n.ok)throw new Error(`OpenAI API error: ${n.statusText}`);const s=await n.json();return{content:s.choices[0].message.content,toolCalls:s.choices[0].message.tool_calls?.map(e=>({name:e.function.name,arguments:JSON.parse(e.function.arguments)}))}}async invokeGroq(e){const t=this.baseUrl||"https://api.groq.com/openai/v1/chat/completions",n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:this.model,messages:e,temperature:this.temperature})});if(!n.ok){const e=await n.text();throw new Error(`Groq API error: ${n.statusText} - ${e}`)}const s=await n.json();return{content:s.choices[0].message.content,toolCalls:s.choices[0].message.tool_calls?.map(e=>({name:e.function.name,arguments:JSON.parse(e.function.arguments)}))}}async invokeAnthropic(e){const t=this.baseUrl||"https://api.anthropic.com/v1/messages",n=e.find(e=>"system"===e.role),s=e.filter(e=>"system"!==e.role),r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":"2023-06-01"},body:JSON.stringify({model:this.model,max_tokens:4096,temperature:this.temperature,system:n?.content,messages:s.map(e=>({role:"assistant"===e.role?"assistant":"user",content:e.content}))})});if(!r.ok)throw new Error(`Anthropic API error: ${r.statusText}`);return{content:(await r.json()).content[0].text}}async invokeWithTools(e,t){switch(this.provider.toLowerCase()){case"openai":case"groq":return this.invokeWithToolsOpenAI(e,t);default:return this.invoke(e)}}async invokeWithToolsOpenAI(e,t){const n="groq"===this.provider.toLowerCase()?this.baseUrl||"https://api.groq.com/openai/v1/chat/completions":this.baseUrl||"https://api.openai.com/v1/chat/completions",s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({model:this.model,messages:e,temperature:this.temperature,tools:t,tool_choice:"auto"})});if(!s.ok){const e=await s.text();throw new Error(`${this.provider} API error: ${s.statusText} - ${e}`)}const r=await s.json();return{content:r.choices[0].message.content,toolCalls:r.choices[0].message.tool_calls?.map(e=>({name:e.function.name,arguments:JSON.parse(e.function.arguments)}))}}}function d(e,t){return new u(e,t)}function m(e,t=[]){const n=[...e].sort((e,t)=>e.sourceId.localeCompare(t.sourceId)||e.asOf.localeCompare(t.asOf)),s={BUY:0,SELL:0,HOLD:0};for(const a of n)s[a.action]++;const r=n.reduce((e,t)=>e+t.confidence,0)/(n.length||1);return{summary:`BUY ${s.BUY}, SELL ${s.SELL}, HOLD ${s.HOLD}; rejected ${t.length}`,findings:n.map(e=>`${e.sourceId} ${e.asOf}: ${e.action} (${e.confidence}) — ${e.reasoning}`),recommendations:Object.entries(s).filter(([,e])=>e>0).map(([e])=>e),confidence:r>=.75?"High":r>=.5?"Medium":"Low",data:{signals:n.map(e=>({sourceId:e.sourceId,probability:e.probability,evidence:e.evidence,order:e.order,targets:e.targets})),rejected:t}}}function h(e){return`${e.summary}\n${e.findings.join("\n")}\nRecommendations: ${e.recommendations.join(", ")}\nConfidence: ${e.confidence}\nEvidence: ${JSON.stringify(e.data)}`}function p(e,t=[]){return e.length||t.length?h(m(e,t)):"No third-party strategy signals."}function y(e,t,n,s,r){return`${e}:${"event"===t.type?t.venue:"equity"}:${"event"===t.type?t.marketId:t.symbol}:${n??"-"}:${s}:${r}`}function g(e,t){const n=e.account,s=e.instrument;return"equity"===s.type?"equity"===n?.kind?n.shares[s.symbol]?.quantity??0:0:"event"===n?.kind&&n.venue===s.venue?n.portfolio.positions[`${s.marketId}:${t}`]?.quantity??0:0}function f(r,a,o){if("BUY"!==r&&"SELL"!==r)return{reportOnly:"Trader HOLD"};if(!e(o.evaluationTime))return{reportOnly:"invalid evaluation time"};if(o.event&&(o.event.venue!==("event"===o.instrument.type?o.instrument.venue:"")||o.event.marketId!==("event"===o.instrument.type?o.instrument.marketId:"")))return{reportOnly:"market identity mismatch"};if(o.event&&("closed"===o.event.status||void 0!==o.event.closesAt&&(!e(o.event.closesAt)||Date.parse(o.event.closesAt)<=Date.parse(o.evaluationTime))))return{reportOnly:"market closed"};const i=a.filter(e=>0===t(e,o.instrument).length&&e.action===r&&n(e.instrument,o.instrument)).sort((e,t)=>t.confidence-e.confidence||e.sourceId.localeCompare(t.sourceId)||t.asOf.localeCompare(e.asOf)||y(e.sourceId,e.instrument,"event"===e.instrument.type?e.instrument.outcome:void 0,e.action,e.asOf).localeCompare(y(t.sourceId,t.instrument,"event"===t.instrument.type?t.instrument.outcome:void 0,t.action,t.asOf)))[0];if(!i)return"equity"!==o.instrument.type?{reportOnly:"no agreeing event signal"}:{proposal:{proposalId:y("trader",o.instrument,void 0,r,o.evaluationTime),sourceId:"trader",instrument:o.instrument,action:r,quantity:Number.MAX_SAFE_INTEGER,asOf:o.evaluationTime}};let c="event"===i.instrument.type?i.instrument.outcome:void 0;c||"YES"!==i.evidence?.outcome&&"NO"!==i.evidence?.outcome||(c=i.evidence.outcome);let l=i.sizing?.limitPriceCents,u=i.sizing?.quantity,d=r;if("order"===i.kind&&(c=i.order.outcome??void 0,l=i.order.priceCents,u=i.order.quantity),"portfolio"===i.kind){if(s(o.account).length)return{reportOnly:"portfolio target needs valid account"};const e=i.targets.find(e=>e.quantity!==g({...o,instrument:i.instrument},e.outcome));if(!e)return{reportOnly:"target already held"};const t=e.quantity-g({...o,instrument:i.instrument},e.outcome);if(c=e.outcome,l=e.priceCents,u=Math.abs(t),d=t>0?"BUY":"SELL",d!==r)return{reportOnly:"portfolio delta disagrees with Trader"}}return void 0===l||void 0===u||"event"===i.instrument.type&&!c?{reportOnly:"direction-only signal"}:{signal:i,proposal:{proposalId:y(i.sourceId,i.instrument,c,d,i.asOf),sourceId:i.sourceId,instrument:i.instrument,action:d,outcome:c,limitPriceCents:l,quantity:u,asOf:i.asOf}}}function v(t,n,c,l,u,d){const m=[...r(c),...a(l),...s(n.account),...o(t.instrument)],h=e=>({allowed:!1,maxQuantity:0,reasons:[...m,e],limits:c});if(m.length)return h("invalid risk configuration or account");if(!i(t.quantity)||!e(t.asOf)||!e(n.evaluationTime)||Date.parse(t.asOf)>Date.parse(n.evaluationTime)||!["BUY","SELL"].includes(t.action))return h("invalid proposal");const p=n.account,y=t.instrument;if("event"===y.type&&("event"!==p.kind||p.venue!==y.venue||!t.outcome)||"equity"===y.type&&"equity"!==p.kind)return h("account scope mismatch");const f=g({...n,instrument:y},t.outcome);if("SELL"===t.action){const e=Math.min(f,t.quantity);return{allowed:e>0,maxQuantity:e,reasons:e>0?["exit limited to actual holdings"]:["no holdings to sell"],limits:c}}if(!l.allowNewEntries)return h("new entries blocked by posture");const v=t.limitPriceCents;if(void 0!==v&&(!Number.isFinite(v)||v<=0||"event"===y.type&&v>100)||"event"===y.type&&void 0===v)return h("invalid entry price");const w="event"===p.kind?p.portfolio.cashCents:p.cashCents,b="event"===p.kind?Object.values(p.portfolio.positions):Object.values(p.shares);if(!f&&void 0!==c.maxOpenPositions&&b.filter(e=>e.quantity>0).length>=c.maxOpenPositions)return h("open-position limit");let k=Math.floor(Math.min(t.quantity,Math.max(0,c.maxPositionPerMarket-f),void 0===v?Number.MAX_SAFE_INTEGER:Math.floor(w/v))*l.sizeMultiplier);if(m.push("current cash, position cap and posture applied"),u?.guards?.length){if(u.id!==t.sourceId||!d||d.sourceId!==u.id)return h("source guard identity missing");for(const e of u.guards)try{const s=e(t,n,d);if(s.deny)return h(s.deny);if(void 0!==s.maxQuantity){if(!i(s.maxQuantity))return h("invalid source cap");k=Math.min(k,s.maxQuantity),m.push(`source cap ${s.maxQuantity}`)}}catch{return h("source guard error")}}return{allowed:k>0,maxQuantity:k,reasons:[...m,...0===k?["zero executable quantity"]:[]],limits:c}}function w(e,t,n){const s=e.split(/\r?\n/).filter(e=>e.toUpperCase().includes(t.toUpperCase())).map(e=>{const n=e.toUpperCase().lastIndexOf(t.toUpperCase())+t.length;return e.slice(n).trim().replace(/[.!]+$/,"").trim().replace(/^[*_`\s]+|[*_`\s]+$/g,"").trim()});if(!s.length)return{value:null,reason:"missing final marker"};const r=e=>Array.isArray(n)?e.toUpperCase():e,a=e=>"function"==typeof n?n(e):n.includes(e),o=r(s.at(-1));return a(o)?new Set(s.map(r).filter(a)).size>1?{value:null,reason:"contradictory marker lines"}:{value:o}:{value:null,reason:"invalid final payload"}}const b=e=>/^\d+$/.test(e)&&Number.isSafeInteger(Number(e)),k={"a Bull Analyst":"Argue the strongest evidence-based case FOR taking the selected outcome, and rebut the latest opposing argument in the debate.","a Bear Analyst":"Argue the strongest evidence-based case AGAINST taking the selected outcome: stress missing evidence, resolution risk and price risk, and rebut the latest supporting argument in the debate.","an Investment Judge":"Weigh both sides of the debate and decide whether the evidence justifies taking the selected outcome.","a trading agent":"Propose one concrete action for the selected outcome from the research plan and the evidence.","a Risk-Seeking Analyst":"Argue for capturing the upside of this proposal within every hard limit, and challenge sizing that is more cautious than the evidence requires.","a Risk-Conservative Analyst":"Argue for capital preservation: challenge any size, price or exposure that the evidence does not justify.","a Neutral Risk Analyst":"Balance the aggressive and the conservative views into a proportionate position for this proposal.","a Risk Judge":"Decide whether this exact proposal may proceed, must be reduced to a smaller whole number, or must be blocked.","the **Fund Manager**":"Give the final decision on this exact proposal. Never exceed any cap, and never approve a different proposal."};function S(e,t,n){if("event"!==t.instrument?.type){return e+(t.strategySignalsReport?`\nThird-party strategy signals: ${t.strategySignalsReport}`:"")+(t.proposal?`\nSelected proposal: ${JSON.stringify(t.proposal)}`:"")}const s=t.eventMarket,r=t.proposal?.outcome??t.instrument.outcome,a=s?.outcomes.find(e=>e.side===r);return[`You are ${n} reviewing a binary event contract. Use the recorded evidence and debate; state missing information as absent.`,`Your stance: ${k[n]}`,`Market title: ${s?.title??"absent"}`,`Question: ${s?.question??"absent"}`,`Venue: ${t.instrument.venue}`,`Market: ${t.instrument.marketId}`,`Selected outcome: ${r??"absent"} (${a?.label??"absent"}). YES means the question resolves affirmatively; NO means it does not. Forecast probability always means P(YES); P(NO) = 1 - P(YES).`,`Quote: ${a?JSON.stringify(a):"absent"}`,`Closing time: ${s?.closesAt??"absent"}`,`Fixture evidence: ${t.strategySignalsReport??"absent"}`,`Investment debate: ${t.investmentDebateState.history}`,`Research Manager decision: ${t.investmentDebateState.judgeDecision}`,`Trader recommendation: ${t.traderInvestmentPlan}`,`Selected proposal: ${t.proposal?JSON.stringify(t.proposal):"absent"}`,`Risk debate: ${t.riskDebateState.history}`].join("\n")}class R{llm;memory;constructor(e,t){this.llm=e,this.memory=t}async analyze(e){const{riskDebateState:t,traderInvestmentPlan:n,investmentDebateState:s,companyOfInterest:r}=e,a=`You are a Risk-Seeking Analyst advocating for high-reward, high-risk investment strategies for ${r}.\n\n**Current Trading Plan:**\n${n}\n\n**Investment Debate Summary:**\n${s.judgeDecision}\n\n**Debate History:**\n${t.history}\n\n**Your Role:**\nAs the risk-seeking perspective, you should:\n1. Advocate for maximizing position size to capitalize on opportunities\n2. Highlight the potential for outsized returns\n3. Minimize conservative constraints that might limit gains\n4. Push back against overly cautious risk management\n5. Engage with other risk perspectives to defend your aggressive stance\n\n**Key Points:**\n- Emphasize asymmetric upside potential\n- Challenge conservative stop-loss levels as too tight\n- Advocate for conviction-weighted sizing\n- Use data to show that risk-averse approaches underperform\n\nPresent your argument conversationally, engaging with the other analysts' concerns while making a compelling case for higher risk tolerance.`,o=`Risky Analyst: ${(await this.llm.invoke(S(a,e,"a Risk-Seeking Analyst"))).content}`;return{riskDebateState:{history:t.history+"\n\n"+o,riskyHistory:t.riskyHistory+"\n\n"+o,safeHistory:t.safeHistory,neutralHistory:t.neutralHistory,latestSpeaker:"risky",currentRiskyResponse:o,currentSafeResponse:t.currentSafeResponse,currentNeutralResponse:t.currentNeutralResponse,judgeDecision:t.judgeDecision,count:t.count+1}}}}class A{llm;memory;constructor(e,t){this.llm=e,this.memory=t}async analyze(e){const{riskDebateState:t,traderInvestmentPlan:n,investmentDebateState:s,companyOfInterest:r}=e,a=`You are a Risk-Conservative Analyst emphasizing capital preservation and risk mitigation for ${r}.\n\n**Current Trading Plan:**\n${n}\n\n**Investment Debate Summary:**\n${s.judgeDecision}\n\n**Debate History:**\n${t.history}\n\n**Last Risky Analyst Argument:**\n${t.currentRiskyResponse}\n\n**Your Role:**\nAs the conservative perspective, you should:\n1. Prioritize capital preservation over maximum returns\n2. Advocate for strict stop-losses and position sizing limits\n3. Highlight downside risks and worst-case scenarios\n4. Counter aggressive strategies with prudent risk management\n5. Ensure the firm's assets are protected from excessive exposure\n\n**Key Points:**\n- Emphasize tail risks and maximum drawdown scenarios\n- Advocate for diversification and hedging\n- Reference historical losses from overleveraged positions\n- Push for conservative position sizing (e.g., Kelly Criterion * 0.5)\n- Highlight liquidity and execution risks\n\nEngage conversationally with the risky analyst's arguments, providing counterpoints grounded in risk management principles.`,o=`Safe Analyst: ${(await this.llm.invoke(S(a,e,"a Risk-Conservative Analyst"))).content}`;return{riskDebateState:{history:t.history+"\n\n"+o,riskyHistory:t.riskyHistory,safeHistory:t.safeHistory+"\n\n"+o,neutralHistory:t.neutralHistory,latestSpeaker:"safe",currentRiskyResponse:t.currentRiskyResponse,currentSafeResponse:o,currentNeutralResponse:t.currentNeutralResponse,judgeDecision:t.judgeDecision,count:t.count+1}}}}class ${llm;memory;constructor(e,t){this.llm=e,this.memory=t}async analyze(e){const{riskDebateState:t,traderInvestmentPlan:n,investmentDebateState:s,companyOfInterest:r}=e,a=`You are a Neutral Risk Analyst providing a balanced perspective on risk management for ${r}.\n\n**Current Trading Plan:**\n${n}\n\n**Investment Debate Summary:**\n${s.judgeDecision}\n\n**Debate History:**\n${t.history}\n\n**Risky Perspective:**\n${t.currentRiskyResponse}\n\n**Safe Perspective:**\n${t.currentSafeResponse}\n\n**Your Role:**\nAs the neutral perspective, you should:\n1. Find the optimal balance between risk and reward\n2. Acknowledge valid points from both risky and safe analysts\n3. Propose pragmatic middle-ground solutions\n4. Use quantitative frameworks (Sharpe ratio, risk-adjusted returns)\n5. Focus on expected value and probability-weighted outcomes\n\n**Key Points:**\n- Balance conviction sizing with prudent risk limits\n- Advocate for dynamic position sizing based on confidence\n- Propose tiered entry/exit strategies\n- Consider both opportunity cost and downside protection\n- Use objective metrics to mediate between extremes\n\nProvide a balanced perspective that synthesizes the best elements from both aggressive and conservative approaches.`,o=`Neutral Analyst: ${(await this.llm.invoke(S(a,e,"a Neutral Risk Analyst"))).content}`;return{riskDebateState:{history:t.history+"\n\n"+o,riskyHistory:t.riskyHistory,safeHistory:t.safeHistory,neutralHistory:t.neutralHistory+"\n\n"+o,latestSpeaker:"neutral",currentRiskyResponse:t.currentRiskyResponse,currentSafeResponse:t.currentSafeResponse,currentNeutralResponse:o,judgeDecision:t.judgeDecision,count:t.count+1}}}}function D(e){const t=w(e,"RISK DECISION:",e=>"PROCEED"===e||"BLOCK"===e||e.startsWith("REDUCE ")&&b(e.slice(7)));return t.value?t.value.startsWith("REDUCE ")?{decision:{kind:"REDUCE",maxQuantity:Number(t.value.slice(7))}}:{decision:{kind:t.value}}:{decision:{kind:"BLOCK"},reason:t.reason}}class I{constructor(e){this.llm=e}llm;async makeDecision(e){try{const t=S(`You are a Risk Judge reviewing this concrete proposal: ${JSON.stringify(e.proposal)}\nRisk debate: ${e.riskDebateState.history}`,e,"a Risk Judge")+"\nEnd with exactly RISK DECISION: PROCEED, RISK DECISION: BLOCK or RISK DECISION: REDUCE <whole number>.",n=await this.llm.invoke(t),s=D(n.content);return{judgeDecision:s.decision,finalRiskAdjustedPlan:n.content,riskDebateState:{...e.riskDebateState,judgeDecision:n.content},riskReviewReason:s.reason}}catch{return{judgeDecision:{kind:"BLOCK"},riskReviewReason:"risk judge model error"}}}}function E(e,t){const n=w(e,"PROPOSAL ID:",e=>e===t),s=w(e,"DECISION:",["APPROVE","REJECT","MODIFY"]),r=w(e,"APPROVED QUANTITY:",b);return n.value&&s.value&&("REJECT"===s.value||r.value)?{decision:s.value,proposalId:t,...r.value?{quantity:Number(r.value)}:{}}:{decision:"REJECT",proposalId:t}}class O{llm;constructor(e){this.llm=e}async makeDecision(e){if(e.proposal){const t=e.proposal;try{const n=S(`You are the **Fund Manager** reviewing this exact proposal: ${JSON.stringify(t)}`,e,"the **Fund Manager**")+`\nProposal: ${JSON.stringify(t)}\nDeterministic verdict: ${JSON.stringify(e.riskVerdict)}\nJudge decision: ${JSON.stringify(e.judgeDecision)}\nApprove only this proposal's action, within every cap. End with these lines:\nPROPOSAL ID: ${t.proposalId}\nDECISION: APPROVE|REJECT|MODIFY (one token)\nAPPROVED QUANTITY: <whole number>`,s=await this.llm.invoke(n),r=E(s.content,t.proposalId);return{fundManagerDecision:s.content,fundManagerApproval:r,finalApproval:r.decision,approvedPositionSize:r.quantity?.toString()??null}}catch{return{fundManagerApproval:{decision:"REJECT",proposalId:t.proposalId},finalApproval:"REJECT",riskReviewReason:"fund manager model error"}}}const{companyOfInterest:t,investmentDebateState:n,riskDebateState:s,traderInvestmentPlan:r,finalRiskAdjustedPlan:a}=e,o=`You are the **Fund Manager** with final approval authority for all trading decisions for **${t}**.\n\n## INVESTMENT DEBATE OUTCOME\n${n.judgeDecision}\n\n## RISK MANAGEMENT ASSESSMENT\n${s.judgeDecision}\n\n## TRADER'S RECOMMENDATION\n${r}\n\n## RISK-ADJUSTED PLAN\n${a}\n\n## YOUR RESPONSIBILITY\nAs Fund Manager, you must:\n1. Review all team recommendations and risk assessments\n2. Ensure alignment with fund objectives and risk tolerance\n3. Make the final GO/NO-GO decision\n4. Specify exact execution parameters if approved\n\n## DECISION FRAMEWORK\nConsider:\n- **Conviction Level**: How strong is the evidence across all teams?\n- **Risk-Reward**: Does the setup justify the capital allocation?\n- **Timing**: Is now the right time to enter this position?\n- **Portfolio Fit**: How does this fit with current holdings?\n- **Downside Protection**: Are risk controls adequate?\n\nProvide your decision in this structured format:\n\n### EXECUTIVE SUMMARY\n[2-3 sentence high-level assessment]\n\n### DECISION\n**[APPROVE/REJECT/MODIFY]**\n\n### RATIONALE\n[Key factors influencing your decision]\n\n### EXECUTION PARAMETERS (if APPROVE or MODIFY)\n- Position Size: [% of portfolio or $ amount]\n- Entry Strategy: [market order, limit order at $X, etc.]\n- Stop Loss: [price level or % from entry]\n- Target Exit: [price targets or conditions]\n- Maximum Hold Period: [time limit if applicable]\n\n### ADDITIONAL INSTRUCTIONS\n[Any special instructions for execution or monitoring]\n\n**Note**: Your decision is final. All trades must have your explicit approval.`,i=(await this.llm.invoke(o)).content,c=i.match(/DECISION[\s\S]*?\*\*\[(APPROVE|REJECT|MODIFY)\]\*\*/i),l=c?c[1].toUpperCase():"REJECT";let u=null;if("APPROVE"===l||"MODIFY"===l){const e=i.match(/Position Size:[\s]*([^\n]+)/i);e&&(u=e[1].trim())}return{fundManagerDecision:i,finalApproval:l,approvedPositionSize:u,finalTradeDecision:"APPROVE"===l||"MODIFY"===l?"BUY":"HOLD"}}}class N{name;memories=[];config;constructor(e,t){this.name=e,this.config=t}async addMemory(e){this.memories.push({...e,timestamp:/* @__PURE__ */new Date}),this.memories.length>100&&(this.memories=this.memories.slice(-100))}async getMemories(e,t=2){if(0===this.memories.length)return[];const n=this.memories.map(t=>({memory:t,score:this.calculateSimilarity(e,t.situation)}));return n.sort((e,t)=>t.score-e.score),n.slice(0,t).map(e=>e.memory)}calculateSimilarity(e,t){const n=this.tokenize(e),s=this.tokenize(t),r=n.filter(e=>s.includes(e)),a=/* @__PURE__ */new Set([...n,...s]);return r.length/a.size}tokenize(e){return e.toLowerCase().replace(/[^\w\s]/g," ").split(/\s+/).filter(e=>e.length>3)}clear(){this.memories=[]}getAllMemories(){return[...this.memories]}getMemoryCount(){return this.memories.length}}const T={queue:{concurrency:1/0,interval:0}};function M(e={}){return new l({...e,queue:{...e?.queue,...T.queue}})}const C=M();function P(e){if(null==e)return null;const t="number"==typeof e?e:Number(e);return Number.isFinite(t)?t:null}function L(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){if(!n)continue;const e=n.date instanceof Date?n.date:new Date(n.date);if(Number.isNaN(e.getTime()))continue;const s=P(n.close),r=P(n.open),a=P(n.high),o=P(n.low),i=P(n.adjclose??n.adjClose),c=s??r??i??a??o;null!==c&&t.push({date:e,open:r??c,high:a??Math.max(r??c,s??c),low:o??Math.min(r??c,s??c),close:s??c,adjClose:i??s??c,volume:P(n.volume)??0})}return t}class q{constructor(){}async getQuote(e,t){try{return{success:!0,data:await C.quoteCombine(e,t)}}catch(n){return console.error(`Yahoo Finance quote error for ${e}:`,n),{success:!1,error:n.message||"Failed to fetch quote"}}}async getQuotes(e){try{return{success:!0,data:await Promise.all(e.map(e=>C.quoteCombine(e)))}}catch(t){return console.error("Yahoo Finance quotes error:",t),{success:!1,error:t.message||"Failed to fetch quotes"}}}async getHistorical(e,t){try{const n=t?.period1??new Date(Date.now()-31536e6),s=t?.period2??/* @__PURE__ */new Date,r=t?.interval||"1d",a=await C.chart(e,{period1:n,period2:s,interval:r},{validateResult:!1});return{success:!0,data:L(a?.quotes)}}catch(n){return console.error(`Yahoo Finance historical error for ${e}:`,n?.message||n),{success:!1,error:n.message||"Failed to fetch historical data"}}}async getChart(e,t){try{return{success:!0,data:await C.chart(e,{period1:t?.period1||new Date(Date.now()-2592e6),period2:t?.period2||/* @__PURE__ */new Date,interval:t?.interval||"1d"})}}catch(n){return console.error(`Yahoo Finance chart error for ${e}:`,n),{success:!1,error:n.message||"Failed to fetch chart data"}}}async getQuoteSummary(e,t){try{const n=t||["assetProfile","summaryDetail","financialData","defaultKeyStatistics","calendarEvents","recommendationTrend","earnings","earningsTrend"];return{success:!0,data:await C.quoteSummary(e,{modules:n})}}catch(n){return console.error(`Yahoo Finance quoteSummary error for ${e}:`,n),{success:!1,error:n.message||"Failed to fetch quote summary"}}}async search(e,t){try{return{success:!0,data:await C.search(e,{quotesCount:t?.quotesCount||10,newsCount:t?.newsCount||5})}}catch(n){return console.error(`Yahoo Finance search error for "${e}":`,n),{success:!1,error:n.message||"Failed to search"}}}async getOptions(e,t){try{return{success:!0,data:await C.options(e,t?{date:t}:void 0)}}catch(n){return console.error(`Yahoo Finance options error for ${e}:`,n),{success:!1,error:n.message||"Failed to fetch options data"}}}async getRecommendations(e){try{return{success:!0,data:await C.recommendationsBySymbol(e)}}catch(t){return console.error(`Yahoo Finance recommendations error for ${e}:`,t),{success:!1,error:t.message||"Failed to fetch recommendations"}}}async getTrending(e="US"){try{return{success:!0,data:await C.trendingSymbols(e)}}catch(t){return console.error(`Yahoo Finance trending error for ${e}:`,t),{success:!1,error:t.message||"Failed to fetch trending symbols"}}}async getInsights(e){try{return{success:!0,data:await C.insights(e)}}catch(t){return console.error(`Yahoo Finance insights error for ${e}:`,t),{success:!1,error:t.message||"Failed to fetch insights"}}}async getFundamentalsTimeSeries(e,t){try{return{success:!0,data:await C.fundamentalsTimeSeries(e,t)}}catch(n){return console.error(`Yahoo Finance fundamentalsTimeSeries error for ${e}:`,n),{success:!1,error:n.message||"Failed to fetch fundamentals time series"}}}async screener(e){try{return{success:!0,data:await C.screener(e)}}catch(t){return console.error("Yahoo Finance screener error:",t),{success:!1,error:t.message||"Failed to run screener"}}}async getCompanyProfile(e){try{const t=await C.quoteSummary(e,{modules:["assetProfile","summaryProfile"]});return{success:!0,data:{assetProfile:t.assetProfile,summaryProfile:t.summaryProfile}}}catch(t){return console.error(`Yahoo Finance company profile error for ${e}:`,t),{success:!1,error:t.message||"Failed to fetch company profile"}}}async getFinancialStatements(e){try{const t=await C.quoteSummary(e,{modules:["incomeStatementHistory","incomeStatementHistoryQuarterly","balanceSheetHistory","balanceSheetHistoryQuarterly","cashflowStatementHistory","cashflowStatementHistoryQuarterly"]});return{success:!0,data:{incomeStatement:t.incomeStatementHistory,incomeStatementQuarterly:t.incomeStatementHistoryQuarterly,balanceSheet:t.balanceSheetHistory,balanceSheetQuarterly:t.balanceSheetHistoryQuarterly,cashFlow:t.cashflowStatementHistory,cashFlowQuarterly:t.cashflowStatementHistoryQuarterly}}}catch(t){return console.error(`Yahoo Finance financial statements error for ${e}:`,t),{success:!1,error:t.message||"Failed to fetch financial statements"}}}async getKeyStatistics(e){try{const t=await C.quoteSummary(e,{modules:["defaultKeyStatistics","summaryDetail"]});return{success:!0,data:{keyStatistics:t.defaultKeyStatistics,summaryDetail:t.summaryDetail}}}catch(t){return console.error(`Yahoo Finance key statistics error for ${e}:`,t),{success:!1,error:t.message||"Failed to fetch key statistics"}}}async getEarnings(e){try{const t=await C.quoteSummary(e,{modules:["earnings","earningsHistory","earningsTrend","calendarEvents"]});return{success:!0,data:{earnings:t.earnings,earningsHistory:t.earningsHistory,earningsTrend:t.earningsTrend,calendarEvents:t.calendarEvents}}}catch(t){return console.error(`Yahoo Finance earnings error for ${e}:`,t),{success:!1,error:t.message||"Failed to fetch earnings data"}}}async getOwnership(e){try{const t=await C.quoteSummary(e,{modules:["institutionOwnership","fundOwnership","insiderHolders","insiderTransactions","majorHoldersBreakdown"]});return{success:!0,data:{institutionOwnership:t.institutionOwnership,fundOwnership:t.fundOwnership,insiderHolders:t.insiderHolders,insiderTransactions:t.insiderTransactions,majorHoldersBreakdown:t.majorHoldersBreakdown}}}catch(t){return console.error(`Yahoo Finance ownership error for ${e}:`,t),{success:!1,error:t.message||"Failed to fetch ownership data"}}}async getSECFilings(e){try{return{success:!0,data:(await C.quoteSummary(e,{modules:["secFilings"]})).secFilings}}catch(t){return console.error(`Yahoo Finance SEC filings error for ${e}:`,t),{success:!1,error:t.message||"Failed to fetch SEC filings"}}}async getComprehensiveData(e){try{const[t,n,s,r]=await Promise.all([this.getQuote(e),this.getQuoteSummary(e),this.getHistorical(e,{period1:new Date(Date.now()-31536e6)}),this.getRecommendations(e)]);return{success:!0,data:{quote:t.data,summary:n.data,historical:s.data,recommendations:r.data}}}catch(t){return console.error(`Yahoo Finance comprehensive data error for ${e}:`,t),{success:!1,error:t.message||"Failed to fetch comprehensive data"}}}}const j=new q,x=j;async function F(e,t,n){try{const s=await x.getHistorical(e,{period1:t,period2:n,interval:"1d"});if(!s.success||!s.data)throw new Error(`Failed to fetch stock data for ${e}`);const r=Array.isArray(s.data)?s.data:s.data.quotes;if(!r||!Array.isArray(r))throw new Error(`Invalid data format returned for ${e}`);return r.map(e=>({date:e.date,open:e.open,high:e.high,low:e.low,close:e.close,volume:e.volume}))}catch(s){throw console.error("Error fetching stock data:",s),s}}async function H(e,t){const n={},s=e.map(e=>e.close),r=e.map(e=>e.high),a=e.map(e=>e.low),o=e.map(e=>e.volume);for(const i of t)switch(i.toLowerCase()){case"close_50_sma":case"sma50":n.sma50=Y(s,50);break;case"close_200_sma":case"sma200":n.sma200=Y(s,200);break;case"close_10_ema":case"ema10":n.ema10=B(s,10);break;case"rsi":n.rsi=J(s,14);break;case"macd":const e=_(s);n.macd=e.macd,n.macdSignal=e.signal,n.macdHistogram=e.histogram;break;case"boll":case"bollinger":const t=V(s,20,2);n.bollingerUpper=t.upper,n.bollingerMiddle=t.middle,n.bollingerLower=t.lower;break;case"atr":n.atr=K(r,a,s,14);break;case"vwma":n.vwma=Q(s,o,20)}return n}async function z(e){try{const t=await fetch(`/api/stocks/quote/${e}`);if(!t.ok)throw new Error("Failed to fetch fundamentals");const n=await t.json();return{marketCap:n.marketCap,peRatio:n.peRatio,dividendYield:n.dividendYield,eps:n.eps,revenue:n.revenue,profitMargin:n.profitMargin}}catch(t){throw console.error("Error fetching fundamentals:",t),t}}async function U(e,t=10){try{return[]}catch(n){return console.error("Error fetching news:",n),[]}}function Y(e,t){const n=[];for(let s=0;s<e.length;s++)if(s<t-1)n.push(NaN);else{const r=e.slice(s-t+1,s+1).reduce((e,t)=>e+t,0);n.push(r/t)}return n}function B(e,t){const n=[],s=2/(t+1);let r=e.slice(0,t).reduce((e,t)=>e+t,0)/t;n.push(...Array(t-1).fill(NaN)),n.push(r);for(let a=t;a<e.length;a++)r=(e[a]-r)*s+r,n.push(r);return n}function J(e,t=14){const n=[],s=[],r=[];for(let a=1;a<e.length;a++){const t=e[a]-e[a-1];s.push(t>0?t:0),r.push(t<0?Math.abs(t):0)}for(let a=0;a<s.length;a++)if(a<t-1)n.push(NaN);else{const e=s.slice(a-t+1,a+1).reduce((e,t)=>e+t,0)/t,o=r.slice(a-t+1,a+1).reduce((e,t)=>e+t,0)/t,i=100-100/(1+(0===o?100:e/o));n.push(i)}return n.unshift(NaN),n}function _(e){const t=B(e,12),n=B(e,26),s=t.map((e,t)=>e-n[t]),r=B(s.filter(e=>!isNaN(e)),9),a=[...Array(s.length-r.length).fill(NaN),...r],o=s.map((e,t)=>e-a[t]);return{macd:s,signal:a,histogram:o}}function V(e,t=20,n=2){const s=Y(e,t),r=[],a=[];for(let o=0;o<e.length;o++)if(o<t-1)r.push(NaN),a.push(NaN);else{const i=e.slice(o-t+1,o+1),c=s[o],l=i.reduce((e,t)=>e+Math.pow(t-c,2),0)/t,u=Math.sqrt(l);r.push(c+n*u),a.push(c-n*u)}return{upper:r,middle:s,lower:a}}function K(e,t,n,s=14){const r=[],a=[];for(let o=1;o<e.length;o++){const s=e[o]-t[o],r=Math.abs(e[o]-n[o-1]),i=Math.abs(t[o]-n[o-1]);a.push(Math.max(s,r,i))}r.push(NaN);for(let o=0;o<a.length;o++)if(o<s-1)r.push(NaN);else{const e=a.slice(o-s+1,o+1).reduce((e,t)=>e+t,0)/s;r.push(e)}return r}function Q(e,t,n=20){const s=[];for(let r=0;r<e.length;r++)if(r<n-1)s.push(NaN);else{const a=e.slice(r-n+1,r+1),o=t.slice(r-n+1,r+1),i=a.reduce((e,t,n)=>e+t*o[n],0),c=o.reduce((e,t)=>e+t,0);s.push(i/c)}return s}class W{llm;constructor(e){this.llm=e}async analyze(e){const{companyOfInterest:t,tradeDate:n}=e,s=`You are a trading assistant tasked with analyzing financial markets. Your role is to select the **most relevant indicators** for a given market condition or trading strategy from the following list. The goal is to choose up to **8 indicators** that provide complementary insights without redundancy.\n\nMoving Averages:\n- close_50_sma: 50 SMA: A medium-term trend indicator. Identify trend direction and support/resistance.\n- close_200_sma: 200 SMA: A long-term trend benchmark. Confirm overall market trend and golden/death cross.\n- close_10_ema: 10 EMA: A responsive short-term average. Capture quick momentum shifts.\n\nMACD Related:\n- macd: MACD: Momentum via EMA differences. Look for crossovers and divergence.\n- macds: MACD Signal: EMA smoothing of MACD line. Use crossovers to trigger trades.\n- macdh: MACD Histogram: Gap between MACD and signal. Visualize momentum strength.\n\nMomentum Indicators:\n- rsi: RSI: Measures overbought/oversold conditions using 70/30 thresholds.\n\nVolatility Indicators:\n- boll: Bollinger Middle: 20 SMA basis for Bollinger Bands.\n- boll_ub: Bollinger Upper: 2 std devs above middle, signals overbought.\n- boll_lb: Bollinger Lower: 2 std devs below middle, signals oversold.\n- atr: ATR: Measures volatility for stop-loss and position sizing.\n\nVolume-Based Indicators:\n- vwma: VWMA: Volume-weighted moving average confirms trends.\n\nSelect indicators that provide diverse information and explain why they're suitable. Write a detailed report of trends observed.\nMake sure to append a Markdown table at the end of the report to organize key points.\n\nFor your reference, the current date is ${n}. The company we want to analyze is ${t}.`;try{const r=new Date(n),a=new Date(r);a.setMonth(a.getMonth()-6);const o=await F(t,a,r),i=["close_50_sma","close_200_sma","close_10_ema","rsi","macd","boll","atr","vwma"],c=await H(o,i),l=o.slice(-20),u=[{role:"system",content:s},{role:"user",content:`\nRecent Price Action for ${t}:\n${l.map(e=>`${e.date}: Close=$${e.close.toFixed(2)}, Volume=${e.volume}`).join("\n")}\n\nTechnical Indicators (Latest Values):\n- 50 SMA: ${c.sma50?.slice(-1)[0]?.toFixed(2)||"N/A"}\n- 200 SMA: ${c.sma200?.slice(-1)[0]?.toFixed(2)||"N/A"}\n- 10 EMA: ${c.ema10?.slice(-1)[0]?.toFixed(2)||"N/A"}\n- RSI: ${c.rsi?.slice(-1)[0]?.toFixed(2)||"N/A"}\n- MACD: ${c.macd?.slice(-1)[0]?.toFixed(2)||"N/A"}\n- Bollinger Upper: ${c.bollingerUpper?.slice(-1)[0]?.toFixed(2)||"N/A"}\n- Bollinger Middle: ${c.bollingerMiddle?.slice(-1)[0]?.toFixed(2)||"N/A"}\n- Bollinger Lower: ${c.bollingerLower?.slice(-1)[0]?.toFixed(2)||"N/A"}\n- ATR: ${c.atr?.slice(-1)[0]?.toFixed(2)||"N/A"}\n- VWMA: ${c.vwma?.slice(-1)[0]?.toFixed(2)||"N/A"}\n\nPlease analyze these indicators and provide a comprehensive market analysis report.`}],d=await this.llm.invoke(u);return{marketReport:d.content,messages:[...e.messages,{role:"assistant",content:d.content}],sender:"MarketAnalyst"}}catch(r){return console.error("Market Analyst error:",r),{marketReport:`Error analyzing market data for ${t}: ${r}`,sender:"MarketAnalyst"}}}}class G{llm;memory;constructor(e,t){this.llm=e,this.memory=t}async analyze(e){const{investmentDebateState:t,marketReport:n,sentimentReport:s,newsReport:r,fundamentalsReport:a}=e,o=`${n}\n\n${s}\n\n${r}\n\n${a}`,i=await this.memory.getMemories(o,2);let c="";c=i.length>0?i.map(e=>e.recommendation).join("\n\n"):"No past memories found.";const l=`You are a Bull Analyst advocating for investing in the stock. Your task is to build a strong, evidence-based case emphasizing growth potential, competitive advantages, and positive market indicators. Leverage the provided research and data to address concerns and counter bearish arguments effectively.\n\nKey points to focus on:\n- Growth Potential: Highlight the company's market opportunities, revenue projections, and scalability.\n- Competitive Advantages: Emphasize factors like unique products, strong branding, or dominant market positioning.\n- Positive Indicators: Use financial health, industry trends, and recent positive news as evidence.\n- Bear Counterpoints: Critically analyze the bear argument with specific data and sound reasoning, addressing concerns thoroughly and showing why the bull perspective holds stronger merit.\n- Engagement: Present your argument in a conversational style, engaging directly with the bear analyst's points and debating effectively rather than just listing data.\n\nResources available:\nMarket research report: ${n}\nSocial media sentiment report: ${s}\nLatest world affairs news: ${r}\nCompany fundamentals report: ${a}\nConversation history of the debate: ${t.history}\nLast bear argument: ${t.currentResponse}\nReflections from similar situations and lessons learned: ${c}\n\nUse this information to deliver a compelling bull argument, refute the bear's concerns, and engage in a dynamic debate that demonstrates the strengths of the bull position. You must also address reflections and learn from lessons and mistakes you made in the past.`,u=`Bull Analyst: ${(await this.llm.invoke(S(l,e,"a Bull Analyst"))).content}`;return{investmentDebateState:{history:t.history+"\n"+u,bullHistory:t.bullHistory+"\n"+u,bearHistory:t.bearHistory,currentResponse:u,judgeDecision:t.judgeDecision,count:t.count+1}}}}class X{llm;memory;constructor(e,t){this.llm=e,this.memory=t}async analyze(e){const{investmentDebateState:t,marketReport:n,sentimentReport:s,newsReport:r,fundamentalsReport:a}=e,o=`${n}\n\n${s}\n\n${r}\n\n${a}`,i=await this.memory.getMemories(o,2);let c="";c=i.length>0?i.map(e=>e.recommendation).join("\n\n"):"No past memories found.";const l=`You are a Bear Analyst advocating for caution or avoiding investment in the stock. Your task is to build a strong, evidence-based case emphasizing risks, challenges, and negative market indicators. Use the provided research and data to highlight concerns and counter bullish arguments effectively.\n\nKey points to focus on:\n- Risk Factors: Identify market risks, competitive threats, regulatory challenges, or economic headwinds.\n- Valuation Concerns: Point out if the stock is overvalued based on fundamentals or technical indicators.\n- Negative Indicators: Use weak financial metrics, declining trends, or negative news as evidence.\n- Bull Counterpoints: Critically analyze the bull argument with specific data and reasoning, showing why the bear perspective is more prudent.\n- Engagement: Present your argument conversationally, directly engaging with the bull analyst's points.\n\nResources available:\nMarket research report: ${n}\nSocial media sentiment report: ${s}\nLatest world affairs news: ${r}\nCompany fundamentals report: ${a}\nConversation history of the debate: ${t.history}\nLast bull argument: ${t.currentResponse}\nReflections from similar situations and lessons learned: ${c}\n\nUse this information to deliver a compelling bear argument, highlight risks, and engage in a dynamic debate. Learn from past mistakes reflected in the memories provided.`,u=`Bear Analyst: ${(await this.llm.invoke(S(l,e,"a Bear Analyst"))).content}`;return{investmentDebateState:{history:t.history+"\n"+u,bullHistory:t.bullHistory,bearHistory:t.bearHistory+"\n"+u,currentResponse:u,judgeDecision:t.judgeDecision,count:t.count+1}}}}class Z{llm;memory;constructor(e,t){this.llm=e,this.memory=t}async makeDecision(e){const{investmentDebateState:t,companyOfInterest:n}=e,s=`You are an Investment Judge tasked with evaluating the debate between a Bull Analyst and a Bear Analyst regarding ${n}.\n\nReview the complete debate history:\n${t.history}\n\nBased on the arguments presented by both sides:\n1. Evaluate the strength of each argument\n2. Consider the evidence provided\n3. Assess the risks and opportunities\n4. Make a final decision: Should we INVEST or NOT INVEST?\n\nProvide your reasoning and conclude with a clear decision: "FINAL DECISION: INVEST" or "FINAL DECISION: NOT INVEST"`,r="event"===e.instrument?.type?"\nEnd with FINAL DECISION: INVEST or FINAL DECISION: NOT INVEST.":"",a=await this.llm.invoke(S(s,e,"an Investment Judge")+r),o=w(a.content,"FINAL DECISION:",["INVEST","NOT INVEST"]).value??"NOT INVEST";return{investmentDebateState:{...t,judgeDecision:a.content},investmentPlan:"INVEST"===o?"Proceed with investment based on bull arguments":"Avoid investment due to bear concerns"}}}class ee{llm;memory;constructor(e,t){this.llm=e,this.memory=t}async makeDecision(e){const{companyOfInterest:t,investmentPlan:n,marketReport:s,sentimentReport:r,newsReport:a,fundamentalsReport:o}=e,i=`${s}\n\n${r}\n\n${a}\n\n${o}`,c=await this.memory.getMemories(i,2);let l="";l=c.length>0?c.map(e=>e.recommendation).join("\n\n"):"No past memories found.";const u=[{role:"system",content:`You are a trading agent analyzing market data to make investment decisions. Based on your analysis, provide a specific recommendation to buy, sell, or hold. End with a firm decision and always conclude your response with 'FINAL TRANSACTION PROPOSAL: **BUY/HOLD/SELL**' to confirm your recommendation.\n\nDo not forget to utilize lessons from past decisions to learn from your mistakes. Here is some reflections from similar situations you traded in and the lessons learned:\n\n${l}`},{role:"user",content:`Based on a comprehensive analysis by a team of analysts, here is an investment plan tailored for ${t}. This plan incorporates insights from current technical market trends, macroeconomic indicators, and social media sentiment. Use this plan as a foundation for evaluating your next trading decision.\n\nProposed Investment Plan: ${n}\n\nLeverage these insights to make an informed and strategic decision.`}];"event"===e.instrument?.type?(u[0].content=S("",e,"a trading agent")+"\nEnd with FINAL TRANSACTION PROPOSAL: BUY, SELL or HOLD (one token).",u[1].content=`Research Manager plan: ${n}`):e.strategySignalsReport&&(u[1].content+=`\nThird-party strategy signals: ${e.strategySignalsReport}`);const d=await this.llm.invoke(u);return{traderInvestmentPlan:d.content,messages:[...e.messages,{role:"assistant",content:d.content}],sender:"Trader"}}}const te={bodySerializer:e=>JSON.stringify(e,(e,t)=>"bigint"==typeof t?t.toString():t)},ne=({allowReserved:e,explode:t,name:n,style:s,value:r})=>{if(!t){const t=(e?r:r.map(e=>encodeURIComponent(e))).join((e=>{switch(e){case"form":default:return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20"}})(s));switch(s){case"label":return`.${t}`;case"matrix":return`;${n}=${t}`;case"simple":return t;default:return`${n}=${t}`}}const a=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(s),o=r.map(t=>"label"===s||"simple"===s?e?t:encodeURIComponent(t):se({allowReserved:e,name:n,value:t})).join(a);return"label"===s||"matrix"===s?a+o:o},se=({allowReserved:e,name:t,value:n})=>{if(null==n)return"";if("object"==typeof n)throw new Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?n:encodeURIComponent(n)}`},re=({allowReserved:e,explode:t,name:n,style:s,value:r,valueOnly:a})=>{if(r instanceof Date)return a?r.toISOString():`${n}=${r.toISOString()}`;if("deepObject"!==s&&!t){let t=[];Object.entries(r).forEach(([n,s])=>{t=[...t,n,e?s:encodeURIComponent(s)]});const a=t.join(",");switch(s){case"form":return`${n}=${a}`;case"label":return`.${a}`;case"matrix":return`;${n}=${a}`;default:return a}}const o=(e=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}})(s),i=Object.entries(r).map(([t,r])=>se({allowReserved:e,name:"deepObject"===s?`${n}[${t}]`:t,value:r})).join(o);return"label"===s||"matrix"===s?o+i:i},ae=/\{[^{}]+\}/g,oe=({baseUrl:e,path:t,query:n,querySerializer:s,url:r})=>{let a=(e??"")+(r.startsWith("/")?r:`/${r}`);t&&(a=(({path:e,url:t})=>{let n=t;const s=t.match(ae);if(s)for(const r of s){let t=!1,s=r.substring(1,r.length-1),a="simple";s.endsWith("*")&&(t=!0,s=s.substring(0,s.length-1)),s.startsWith(".")?(s=s.substring(1),a="label"):s.startsWith(";")&&(s=s.substring(1),a="matrix");const o=e[s];if(null==o)continue;if(Array.isArray(o)){n=n.replace(r,ne({explode:t,name:s,style:a,value:o}));continue}if("object"==typeof o){n=n.replace(r,re({explode:t,name:s,style:a,value:o,valueOnly:!0}));continue}if("matrix"===a){n=n.replace(r,`;${se({name:s,value:o})}`);continue}const i=encodeURIComponent("label"===a?`.${o}`:o);n=n.replace(r,i)}return n})({path:t,url:a}));let o=n?s(n):"";return o.startsWith("?")&&(o=o.substring(1)),o&&(a+=`?${o}`),a};function ie(e){const t=void 0!==e.body;if(t&&e.bodySerializer){if("serializedBody"in e){return void 0!==e.serializedBody&&""!==e.serializedBody?e.serializedBody:null}return""!==e.body?e.body:null}if(t)return e.body}const ce=async(e,t)=>{const n="function"==typeof t?await t(e):t;if(n)return"bearer"===e.scheme?`Bearer ${n}`:"basic"===e.scheme?`Basic ${btoa(n)}`:n},le=({parameters:e={},...t}={})=>n=>{const s=[];if(n&&"object"==typeof n)for(const r in n){const a=n[r];if(null==a)continue;const o=e[r]||t;if(Array.isArray(a)){const e=ne({allowReserved:o.allowReserved,explode:!0,name:r,style:"form",value:a,...o.array});e&&s.push(e)}else if("object"==typeof a){const e=re({allowReserved:o.allowReserved,explode:!0,name:r,style:"deepObject",value:a,...o.object});e&&s.push(e)}else{const e=se({allowReserved:o.allowReserved,name:r,value:a});e&&s.push(e)}}return s.join("&")},ue=(e,t)=>!!t&&!!(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`)),de=e=>oe({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:"function"==typeof e.querySerializer?e.querySerializer:le(e.querySerializer),url:e.url}),me=(e,t)=>{const n={...e,...t};return n.baseUrl?.endsWith("/")&&(n.baseUrl=n.baseUrl.substring(0,n.baseUrl.length-1)),n.headers=pe(e.headers,t.headers),n},he=e=>{const t=[];return e.forEach((e,n)=>{t.push([n,e])}),t},pe=(...e)=>{const t=new Headers;for(const n of e){if(!n)continue;const e=n instanceof Headers?he(n):Object.entries(n);for(const[n,s]of e)if(null===s)t.delete(n);else if(Array.isArray(s))for(const e of s)t.append(n,e);else void 0!==s&&t.set(n,"object"==typeof s?JSON.stringify(s):s)}return t};class ye{fns=[];clear(){this.fns=[]}eject(e){const t=this.getInterceptorIndex(e);this.fns[t]&&(this.fns[t]=null)}exists(e){const t=this.getInterceptorIndex(e);return Boolean(this.fns[t])}getInterceptorIndex(e){return"number"==typeof e?this.fns[e]?e:-1:this.fns.indexOf(e)}update(e,t){const n=this.getInterceptorIndex(e);return!!this.fns[n]&&(this.fns[n]=t,e)}use(e){return this.fns.push(e),this.fns.length-1}}const ge=le({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),fe={"Content-Type":"application/json"},ve=(e={})=>({...te,headers:fe,parseAs:"auto",querySerializer:ge,...e}),we=((e={})=>{let t=me(ve(),e);const n=()=>({...t}),s={error:new ye,request:new ye,response:new ye},r=async e=>{const n={...t,...e,fetch:e.fetch??t.fetch??globalThis.fetch,headers:pe(t.headers,e.headers),serializedBody:void 0};n.security&&await(async({security:e,...t})=>{for(const n of e){if(ue(t,n.name))continue;const e=await ce(n,t.auth);if(!e)continue;const s=n.name??"Authorization";switch(n.in){case"query":t.query||(t.query={}),t.query[s]=e;break;case"cookie":t.headers.append("Cookie",`${s}=${e}`);break;default:t.headers.set(s,e)}}})({...n,security:n.security}),n.requestValidator&&await n.requestValidator(n),void 0!==n.body&&n.bodySerializer&&(n.serializedBody=n.bodySerializer(n.body)),void 0!==n.body&&""!==n.serializedBody||n.headers.delete("Content-Type");return{opts:n,url:de(n)}},a=async e=>{const{opts:t,url:n}=await r(e),a={redirect:"follow",...t,body:ie(t)};let o=new Request(n,a);for(const r of s.request.fns)r&&(o=await r(o,t));const i=t.fetch;let c;try{c=await i(o)}catch(p){let e=p;for(const n of s.error.fns)n&&(e=await n(p,void 0,o,t));if(e=e||{},t.throwOnError)throw e;return"data"===t.responseStyle?void 0:{error:e,request:o,response:void 0}}for(const r of s.response.fns)r&&(c=await r(c,o,t));const l={request:o,response:c};if(c.ok){const e=("auto"===t.parseAs?(e=>{if(!e)return"stream";const t=e.split(";")[0]?.trim();return t?t.startsWith("application/json")||t.endsWith("+json")?"json":"multipart/form-data"===t?"formData":["application/","audio/","image/","video/"].some(e=>t.startsWith(e))?"blob":t.startsWith("text/")?"text":void 0:void 0})(c.headers.get("Content-Type")):t.parseAs)??"json";if(204===c.status||"0"===c.headers.get("Content-Length")){let n;switch(e){case"arrayBuffer":case"blob":case"text":n=await c[e]();break;case"formData":n=new FormData;break;case"stream":n=c.body;break;default:n={}}return"data"===t.responseStyle?n:{data:n,...l}}let n;switch(e){case"arrayBuffer":case"blob":case"formData":case"json":case"text":n=await c[e]();break;case"stream":return"data"===t.responseStyle?c.body:{data:c.body,...l}}return"json"===e&&(t.responseValidator&&await t.responseValidator(n),t.responseTransformer&&(n=await t.responseTransformer(n))),"data"===t.responseStyle?n:{data:n,...l}}const u=await c.text();let d;try{d=JSON.parse(u)}catch{}const m=d??u;let h=m;for(const r of s.error.fns)r&&(h=await r(m,c,o,t));if(h=h||{},t.throwOnError)throw h;return"data"===t.responseStyle?void 0:{error:h,...l}},o=e=>t=>a({...t,method:e}),i=e=>async t=>{const{opts:n,url:a}=await r(t);return(({onRequest:e,onSseError:t,onSseEvent:n,responseTransformer:s,responseValidator:r,sseDefaultRetryDelay:a,sseMaxRetryAttempts:o,sseMaxRetryDelay:i,sseSleepFn:c,url:l,...u})=>{let d;const m=c??(e=>new Promise(t=>setTimeout(t,e)));return{stream:async function*(){let c=a??3e3,h=0;const p=u.signal??(new AbortController).signal;for(;!p.aborted;){h++;const a=u.headers instanceof Headers?u.headers:new Headers(u.headers);void 0!==d&&a.set("Last-Event-ID",d);try{const t={redirect:"follow",...u,body:u.serializedBody,headers:a,signal:p};let o=new Request(l,t);e&&(o=await e(l,t));const i=u.fetch??globalThis.fetch,m=await i(o);if(!m.ok)throw new Error(`SSE failed: ${m.status} ${m.statusText}`);if(!m.body)throw new Error("No body in SSE response");const h=m.body.pipeThrough(new TextDecoderStream).getReader();let y="";const g=()=>{try{h.cancel()}catch{}};p.addEventListener("abort",g);try{for(;;){const{done:e,value:t}=await h.read();if(e)break;y+=t;const a=y.split("\n\n");y=a.pop()??"";for(const o of a){const e=o.split("\n"),t=[];let a,i;for(const n of e)if(n.startsWith("data:"))t.push(n.replace(/^data:\s*/,""));else if(n.startsWith("event:"))a=n.replace(/^event:\s*/,"");else if(n.startsWith("id:"))d=n.replace(/^id:\s*/,"");else if(n.startsWith("retry:")){const e=Number.parseInt(n.replace(/^retry:\s*/,""),10);Number.isNaN(e)||(c=e)}let l=!1;if(t.length){const e=t.join("\n");try{i=JSON.parse(e),l=!0}catch{i=e}}l&&(r&&await r(i),s&&(i=await s(i))),n?.({data:i,event:a,id:d,retry:c}),t.length&&(yield i)}}}finally{p.removeEventListener("abort",g),h.releaseLock()}break}catch(y){if(t?.(y),void 0!==o&&h>=o)break;const e=Math.min(c*2**(h-1),i??3e4);await m(e)}}}()}})({...n,body:n.body,headers:n.headers,method:e,onRequest:async(e,t)=>{let r=new Request(e,t);for(const a of s.request.fns)a&&(r=await a(r,n));return r},url:a})};return{buildUrl:de,connect:o("CONNECT"),delete:o("DELETE"),get:o("GET"),getConfig:n,head:o("HEAD"),interceptors:s,options:o("OPTIONS"),patch:o("PATCH"),post:o("POST"),put:o("PUT"),request:a,setConfig:e=>(t=me(t,e),n()),sse:{connect:i("CONNECT"),delete:i("DELETE"),get:i("GET"),head:i("HEAD"),options:i("OPTIONS"),patch:i("PATCH"),post:i("POST"),put:i("PUT"),trace:i("TRACE")},trace:o("TRACE")}})((be=ve(),{...be,baseUrl:"https://app.qwksearch.com/api"}));var be;class ke{llm;constructor(e){this.llm=e}async analyze(e){const{companyOfInterest:t,tradeDate:n}=e;try{const r=`${t} stock news analysis ${n}`;console.log(`NewsAnalyst searching for: ${r}`);const a=await(s={query:{q:r,cat:"news",recency:"month"}},(s.client??we).get({url:"/search",...s}));if(!a.data?.results||0===a.data.results.length)return{newsReport:`No significant news found for ${t} around ${n}.`,sender:"NewsAnalyst"};const o=a.data.results.slice(0,5).map((e,t)=>`\nArticle ${t+1}:\nTitle: ${e.title}\nSource: ${e.domain}\nSnippet: ${e.snippet}\nURL: ${e.url}\n`).join("\n"),i=`You are a financial news analyst. Your job is to synthesize news headlines and snippets into a concise, relevant report for a trading strategy.\n \nFocus on:\n1. Significant events (earnings, mergers, regulatory changes).\n2. Market sentiment (positive/negative coverage).\n3. Potential impact on stock price.\n\nProvide a summary first, then a bulleted list of key takeaways.\nThe current date is ${n}. The company is ${t}.`,c=[{role:"system",content:i},{role:"user",content:`Here are the latest news search results:\n${o}\n\nPlease analyze these and write your report.`}],l=await this.llm.invoke(c);return{newsReport:l.content,messages:[...e.messages,{role:"assistant",content:l.content}],sender:"NewsAnalyst"}}catch(r){return console.error("News Analyst error:",r),{newsReport:`Error analyzing news for ${t}: ${r}`,sender:"NewsAnalyst"}}var s}}const Se={llmProvider:"groq",deepThinkLLM:"llama3-70b-8192",quickThinkLLM:"llama3-8b-8192",temperature:.3,projectDir:"./data",apiKeys:{groq:process.env.GROQ_API_KEY||""}};class Re{constructor(e=["market","social","news","fundamentals"],t=!1,n,s={}){this.options=s,this.selectedAnalysts=e,this.debug=t,this.config={...Se,...n},this.deepThinkingLLM=s.llm?.deep??d(this.config,this.config.deepThinkLLM),this.quickThinkingLLM=s.llm?.quick??d(this.config,this.config.quickThinkLLM),this.bullMemory=new N("bull_memory",this.config),this.bearMemory=new N("bear_memory",this.config),this.traderMemory=new N("trader_memory",this.config),this.investJudgeMemory=new N("invest_judge_memory",this.config),this.riskManagerMemory=new N("risk_manager_memory",this.config),this.marketAnalyst=new W(this.deepThinkingLLM),this.bullResearcher=new G(this.deepThinkingLLM,this.bullMemory),this.bearResearcher=new X(this.deepThinkingLLM,this.bearMemory),this.investmentJudge=new Z(this.quickThinkingLLM,this.investJudgeMemory),this.trader=new ee(this.quickThinkingLLM,this.traderMemory),this.newsAnalyst=new ke(this.deepThinkingLLM)}options;config;deepThinkingLLM;quickThinkingLLM;selectedAnalysts;debug;bullMemory;bearMemory;traderMemory;investJudgeMemory;riskManagerMemory;marketAnalyst;bullResearcher;bearResearcher;investmentJudge;trader;newsAnalyst;currentState=null;ticker=null;logStatesDict={};async propagate(e,t,n){this.ticker=e;const s=this.createInitialState(e,t),r=n?.instrument??{type:"equity",symbol:e},a=n?.evaluationTime??`${t}T00:00:00Z`;if(n){if(s.instrument=r,s.eventMarket=n.event,void 0!==n.strategySignals){const e=[],t=[];if(Array.isArray(n.strategySignals))for(const s of n.strategySignals){const o=n.sources?.[s?.sourceId],i=c([s],r,a,o);e.push(...i.valid),t.push(...i.rejected)}else t.push(...c(n.strategySignals,r,a).rejected);s.strategySignals=e,s.strategySignalsReport=p(e,t)}"event"===r.type&&(s.marketReport="Not applicable for an event contract.",s.newsReport="Not applicable for an event contract.")}this.debug&&console.log(`\n=== Starting Analysis for ${e} on ${t} ===\n`);let o=s;if(this.selectedAnalysts.includes("market")&&"event"!==r.type){this.debug&&console.log("Running Market Analyst...");const e=await this.marketAnalyst.analyze(o);o={...o,...e}}if(o.sentimentReport||(o.sentimentReport="No social media analysis performed."),this.selectedAnalysts.includes("news")&&"event"!==r.type){this.debug&&console.log("Running News Analyst...");const e=await this.newsAnalyst.analyze(o);o={...o,...e}}else o.newsReport||(o.newsReport="No news analysis performed.");o.fundamentalsReport||(o.fundamentalsReport="No fundamentals analysis performed."),this.debug&&console.log("\n=== Investment Debate ==="),o.investmentDebateState={bullHistory:"",bearHistory:"",history:"",currentResponse:"",judgeDecision:"",count:0};for(let c=0;c<3;c++){this.debug&&console.log(`\nDebate Round ${c+1}`);const e=await this.bullResearcher.analyze(o);o={...o,...e};const t=await this.bearResearcher.analyze(o);o={...o,...t}}this.debug&&console.log("\nInvestment Judge making decision...");const i=await this.investmentJudge.makeDecision(o);o={...o,...i},this.debug&&console.log("\nTrader making final decision...");const l=await this.trader.makeDecision(o);o={...o,...l};const u=this.extractDecision(o.traderInvestmentPlan||"");o.finalTradeDecision=u,this.options.riskReview&&"HOLD"!==u&&(o=await this.runRiskReview(o,u,r,a,n)),this.currentState=o,this.logState(t,o);const d=this.processSignal(o.finalTradeDecision);return n&&(d.timestamp=new Date(a)),this.debug&&console.log(`\n=== Final Decision: ${d.action} (Confidence: ${d.confidence}) ===\n`),{state:o,signal:d}}createInitialState(e,t){return{companyOfInterest:e,tradeDate:t,messages:[],sender:"",marketReport:"",sentimentReport:"",newsReport:"",fundamentalsReport:"",investmentDebateState:{bullHistory:"",bearHistory:"",history:"",currentResponse:"",judgeDecision:"",count:0},investmentPlan:"",traderInvestmentPlan:"",riskDebateState:{riskyHistory:"",safeHistory:"",neutralHistory:"",history:"",latestSpeaker:"",currentRiskyResponse:"",currentSafeResponse:"",currentNeutralResponse:"",judgeDecision:"",count:0},finalTradeDecision:""}}async runRiskReview(e,t,n,s,r){let a=e;const o={instrument:n,account:r?.account,evaluationTime:s,event:r?.event},i=f(t,a.strategySignals??[],o);if("reportOnly"in i)return{...a,finalTradeDecision:"HOLD",riskReviewReason:i.reportOnly};const c=i.proposal;a={...a,proposal:c};try{const e=[new R(this.deepThinkingLLM,this.riskManagerMemory),new A(this.deepThinkingLLM,this.riskManagerMemory),new $(this.deepThinkingLLM,this.riskManagerMemory)];for(const r of e)a={...a,...await r.analyze(a)};a={...a,...await new I(this.quickThinkingLLM).makeDecision(a)};const t=r?.sources?.[c.sourceId];let n=v(c,o,this.options.riskLimits??{maxPositionPerMarket:50},this.options.riskPosture??{label:"Normal",sizeMultiplier:1,allowNewEntries:!0},t,i.signal);"trader"===c.sourceId||t||(n={...n,allowed:!1,maxQuantity:0,reasons:[...n.reasons,"unregistered strategy source"]}),a.riskVerdict=n;const s=a.judgeDecision;if("BLOCK"===s.kind||!n.allowed)return{...a,finalTradeDecision:"HOLD",approval:void 0};a={...a,...await new O(this.quickThinkingLLM).makeDecision(a)};const l=a.fundManagerApproval,u=Math.min(c.quantity,n.maxQuantity,"REDUCE"===s.kind?s.maxQuantity:Number.MAX_SAFE_INTEGER,l.quantity??0);return"REJECT"===l.decision||u<=0?{...a,finalTradeDecision:"HOLD",approval:void 0}:{...a,approval:{proposal:c,finalQuantity:u,verdict:n,judge:s,fundManager:l,reasons:n.reasons}}}catch(l){const e=l instanceof Error?l.message:String(l);return{...a,finalTradeDecision:"HOLD",approval:void 0,riskReviewReason:`risk review error: ${e}`}}}extractDecision(e){return w(e,"FINAL TRANSACTION PROPOSAL:",["BUY","SELL","HOLD"]).value??"HOLD"}processSignal(e){return{action:e,confidence:.75,reasoning:"Based on multi-agent analysis and debate",timestamp:/* @__PURE__ */new Date}}logState(e,t){this.logStatesDict[e]={companyOfInterest:t.companyOfInterest,tradeDate:t.tradeDate,marketReport:t.marketReport,sentimentReport:t.sentimentReport,newsReport:t.newsReport,fundamentalsReport:t.fundamentalsReport,investmentDebateState:{bullHistory:t.investmentDebateState.bullHistory,bearHistory:t.investmentDebateState.bearHistory,history:t.investmentDebateState.history,currentResponse:t.investmentDebateState.currentResponse,judgeDecision:t.investmentDebateState.judgeDecision},traderInvestmentDecision:t.traderInvestmentPlan,finalTradeDecision:t.finalTradeDecision}}async reflectAndRemember(e){if(!this.currentState)return;const t=`${this.currentState.marketReport}\n${this.currentState.newsReport}`,n=this.currentState.finalTradeDecision,s=`Decision: ${n}, Outcome: ${e>0?"Positive":"Negative"} (${e.toFixed(2)}%)`,r={situation:t,decision:n,outcome:e,recommendation:s,timestamp:/* @__PURE__ */new Date};await this.bullMemory.addMemory(r),await this.bearMemory.addMemory(r),await this.traderMemory.addMemory(r),await this.investJudgeMemory.addMemory(r)}getLogStates(){return this.logStatesDict}getCurrentState(){return this.currentState}}class Ae{constructor(e){this.rules=e}rules;calls=[];async invoke(e){const t="string"==typeof e?e:JSON.stringify(e,null,2),n=this.rules.find(e=>"string"==typeof e.match?t.includes(e.match):e.match.test(t));if(!n)throw new Error("No scripted rule matched prompt");return this.calls.push({rule:n.name,prompt:t}),{content:"string"==typeof n.response?n.response:n.response(t)}}}export{X as B,N as F,Z as I,W as M,$ as N,I as R,A as S,ee as T,u as U,T as W,q as Y,G as a,O as b,R as c,Ae as d,Re as e,d as f,z as g,H as h,U as i,F as j,D as k,j as l,v as m,M as n,h as o,E as p,L as q,y as r,p as s,f as t,m as u,x as y};
@@ -5,8 +5,9 @@ export * from './stock-names';
5
5
  export * from './yfinance-wrapper';
6
6
  export * from './yahoo-finance-wrapper';
7
7
  export * from './sec-filing-api';
8
- export * from './import-stock-names';
9
8
  export * from './finnhub-wrapper';
10
9
  export * from './types';
11
10
  export * from './unified-quote-service';
11
+ export * from './strategies/ema-crossover';
12
+ export * from './strategies/bb-rsi-breakout';
12
13
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/stocks/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,eAAe,CAAC;AAC9B,cAAc,oBAAoB,CAAC;AACnC,cAAc,yBAAyB,CAAC;AACxC,cAAc,kBAAkB,CAAC;AACjC,cAAc,sBAAsB,CAAC;AACrC,cAAc,mBAAmB,CAAC;AAClC,cAAc,SAAS,CAAC;AACxB,cAAc,yBAAyB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/stocks/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,eAAe,CAAC;AAC9B,cAAc,oBAAoB,CAAC;AACnC,cAAc,yBAAyB,CAAC;AACxC,cAAc,kBAAkB,CAAC;AAGjC,cAAc,mBAAmB,CAAC;AAClC,cAAc,SAAS,CAAC;AACxB,cAAc,yBAAyB,CAAC;AAExC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,8BAA8B,CAAC"}
@@ -1,4 +1,6 @@
1
1
  import { NormalizedQuote } from './unified-quote-service';
2
+ /** Default freshness window for a cached quote when the caller names none. */
3
+ export declare const QUOTE_CACHE_TTL: number;
2
4
  export interface CachedQuote {
3
5
  symbol: string;
4
6
  price: number;
@@ -25,9 +27,16 @@ export declare class QuoteCacheService {
25
27
  */
26
28
  private roundPrice;
27
29
  /**
28
- * Get cached quote if available
30
+ * Get cached quote if available and still fresh.
31
+ *
32
+ * @param symbol - Ticker to look up; matched case-insensitively.
33
+ * @param cacheTTL - Maximum age in milliseconds. Defaults to
34
+ * {@link QUOTE_CACHE_TTL}. A row older than this — or one with no
35
+ * timestamp, which is how rows written before the column existed read back
36
+ * — is treated as a miss so the caller refetches. Pass `Infinity` to accept
37
+ * a cached quote at any age.
29
38
  */
30
- getCachedQuote(symbol: string): Promise<CachedQuote | null>;
39
+ getCachedQuote(symbol: string, cacheTTL?: number): Promise<CachedQuote | null>;
31
40
  /**
32
41
  * Save quote to cache
33
42
  */
@@ -1 +1 @@
1
- {"version":3,"file":"quote-cache-service.d.ts","sourceRoot":"","sources":["../../src/stocks/quote-cache-service.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAKH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAS/D,MAAM,WAAW,WAAW;IAC1B,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,IAAI,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,CAAC,EAAE,MAAM,CAAC;QACrB,UAAU,CAAC,EAAE,MAAM,CAAC;QACpB,SAAS,CAAC,EAAE,MAAM,CAAC;KACpB,GACA,OAAO,CAAC,IAAI,CAAC;IAsDhB;;OAEG;IACG,qBAAqB,CAAC,MAAM,EAAE,MAAM;;;;;;;;;;;;;;;;;;;IA6B1C;;OAEG;IACG,iBAAiB,IAAI,OAAO,CAAC,IAAI,CAAC;CAKzC;AAGD,eAAO,MAAM,iBAAiB,mBAA0B,CAAC;AACzD,eAAe,iBAAiB,CAAC"}
@@ -0,0 +1,63 @@
1
+ import { TradeSignal } from '../../trading-agents/types';
2
+ import { HistoricalQuote } from '../quote-cache-service';
3
+ /** Configuration for {@link evaluateBbRsiBreakout}. Periods are in bars. */
4
+ export interface BbRsiBreakoutConfig {
5
+ /** Bollinger Band SMA / stdev length (Pine: 30). */
6
+ bbPeriod: number;
7
+ /** Bollinger Band standard-deviation multiplier (Pine: 2.0). */
8
+ bbStdDev: number;
9
+ /** RSI length (Pine: 13). */
10
+ rsiPeriod: number;
11
+ /** Long take-profit multiplier applied to entry price (Pine: 1.03). */
12
+ longTpMult: number;
13
+ /** Short take-profit multiplier applied to entry price (Pine: 0.97). */
14
+ shortTpMult: number;
15
+ /**
16
+ * Bars that must be observed (inclusive of the current bar) before any
17
+ * actionable signal is emitted; earlier bars are forced to HOLD. Defaults to
18
+ * `bbPeriod` so the Bollinger window — the longest lookback, longer than the
19
+ * RSI window — has seen a full span of data before any trade.
20
+ */
21
+ warmupBars: number;
22
+ }
23
+ export declare const DEFAULT_BB_RSI_BREAKOUT_CONFIG: BbRsiBreakoutConfig;
24
+ /**
25
+ * The minimal bar shape this strategy reads. `HistoricalQuote` (returned by
26
+ * `getHistoricalQuotes`) satisfies it, so recorded data can be replayed
27
+ * unchanged. Unlike the close-only EMA strategy, the take-profit is a limit
28
+ * order, so `high` and `low` are required to detect intrabar TP fills.
29
+ */
30
+ export type BbRsiBreakoutBar = Pick<HistoricalQuote, "date" | "high" | "low" | "close">;
31
+ export declare function normalizeBbRsiBreakoutConfig(config?: Partial<BbRsiBreakoutConfig>): BbRsiBreakoutConfig;
32
+ /**
33
+ * Replay recorded bars through the BB + RSI breakout rules and return one
34
+ * {@link TradeSignal} per input bar (same length and order as `bars`).
35
+ *
36
+ * Semantics, faithful to the Pine source:
37
+ * - BUY (open long) when `close < lowerBand && rsi < rsiOversold` while flat.
38
+ * - SELL (open short) when `close > upperBand && rsi > rsiOverbought` while flat.
39
+ * - SELL (close long) once long and a bar's `high >= entryPrice * longTpMult`.
40
+ * - BUY (cover short) once short and a bar's `low <= entryPrice * shortTpMult`.
41
+ * - HOLD otherwise. No stop loss; no pyramiding — only one open position, so
42
+ * the "average entry price" of the Pine source equals the single entry price.
43
+ *
44
+ * Warm-up: the first `warmupBars` (default `bbPeriod` = 30) bars are forced to
45
+ * HOLD so the Bollinger window has observed a full span before any trade. With
46
+ * fewer than `warmupBars` bars the function returns all HOLD. `confidence` is 1
47
+ * for an actionable BUY/SELL and 0 for HOLD. `timestamp` is taken from the
48
+ * bar's own `date`, never the wall clock, so replays are deterministic.
49
+ *
50
+ * The RSI oversold / overbought thresholds (30 / 70) are the Pine constants and
51
+ * are intentionally not configurable here — changing them would change the
52
+ * strategy, not merely tune it.
53
+ *
54
+ * This is pure and offline: no network, no credentials, no order placement. The
55
+ * take-profit is reported as a BUY/SELL signal because {@link TradeSignal}
56
+ * cannot carry a limit price; the consumer places the actual order.
57
+ *
58
+ * @throws if `config` is invalid, or if any bar has a non-finite
59
+ * `close`/`high`/`low` or an unparseable `date` — malformed data fails loudly
60
+ * instead of silently degrading to all-HOLD.
61
+ */
62
+ export declare function evaluateBbRsiBreakout(bars: readonly BbRsiBreakoutBar[], config?: Partial<BbRsiBreakoutConfig>): TradeSignal[];
63
+ //# sourceMappingURL=bb-rsi-breakout.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bb-rsi-breakout.d.ts","sourceRoot":"","sources":["../../../src/stocks/strategies/bb-rsi-breakout.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiDG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAE9D,4EAA4E;AAC5E,MAAM,WAAW,mBAAmB;IAClC,oDAAoD;IACpD,QAAQ,EAAE,MAAM,CAAC;IACjB,gEAAgE;IAChE,QAAQ,EAAE,MAAM,CAAC;IACjB,6BAA6B;IAC7B,SAAS,EAAE,MAAM,CAAC;IAClB,uEAAuE;IACvE,UAAU,EAAE,MAAM,CAAC;IACnB,wEAAwE;IACxE,WAAW,EAAE,MAAM,CAAC;IACpB;;;;;OAKG;IACH,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,eAAO,MAAM,8BAA8B,EAAE,mBAO5C,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,gBAAgB,GAAG,IAAI,CAAC,eAAe,EAAE,MAAM,GAAG,MAAM,GAAG,KAAK,GAAG,OAAO,CAAC,CAAC;AAExF,wBAAgB,4BAA4B,CAC1C,MAAM,GAAE,OAAO,CAAC,mBAAmB,CAAM,GACxC,mBAAmB,CAmBrB;AA2GD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,SAAS,gBAAgB,EAAE,EACjC,MAAM,GAAE,OAAO,CAAC,mBAAmB,CAAM,GACxC,WAAW,EAAE,CAyEf"}
@@ -0,0 +1,51 @@
1
+ import { TradeSignal } from '../../trading-agents/types';
2
+ import { HistoricalQuote } from '../quote-cache-service';
3
+ /** Configuration for {@link evaluateEmaCrossover}. All periods are in bars. */
4
+ export interface EmaCrossoverConfig {
5
+ /** Fast EMA length (Pine: 9). */
6
+ shortPeriod: number;
7
+ /** Slow EMA length and the exit reference (Pine: 20). */
8
+ longPeriod: number;
9
+ /** Trend-filter EMA length (Pine: 200). */
10
+ trendPeriod: number;
11
+ /**
12
+ * Bars that must be observed (inclusive of the current bar) before any
13
+ * actionable BUY/SELL is emitted; earlier bars are forced to HOLD. Defaults
14
+ * to `trendPeriod` so the 200 EMA has seen a full window of data — see the
15
+ * warm-up note on {@link evaluateEmaCrossover}.
16
+ */
17
+ warmupBars: number;
18
+ }
19
+ export declare const DEFAULT_EMA_CROSSOVER_CONFIG: EmaCrossoverConfig;
20
+ /**
21
+ * The minimal bar shape this strategy reads. Both `HistoricalQuote` (returned
22
+ * by `getHistoricalQuotes`) and `HistoricalDataPoint` (the Yahoo wrapper shape)
23
+ * satisfy it, so recorded data from either source can be replayed unchanged.
24
+ */
25
+ export type EmaCrossoverBar = Pick<HistoricalQuote, "date" | "close">;
26
+ export declare function normalizeEmaCrossoverConfig(config?: Partial<EmaCrossoverConfig>): EmaCrossoverConfig;
27
+ /**
28
+ * Replay recorded bars through the long-only EMA crossover rules and return one
29
+ * {@link TradeSignal} per input bar (same length and order as `bars`).
30
+ *
31
+ * Semantics, faithful to the Pine source:
32
+ * - BUY when EMA-short crosses above EMA-long AND close is above EMA-trend, and
33
+ * only while flat — a second BUY is never emitted while a long is already
34
+ * open (Pine's default no-pyramiding `strategy.entry`).
35
+ * - SELL when close crosses below EMA-long AND a long position is open.
36
+ * - HOLD otherwise.
37
+ *
38
+ * Warm-up: the first `warmupBars` (default `trendPeriod` = 200) bars are forced
39
+ * to HOLD so the 200 EMA has observed a full window before any trade. With
40
+ * fewer than `warmupBars` bars the function returns all HOLD. `confidence` is 1
41
+ * for an actionable BUY/SELL and 0 for HOLD. `timestamp` is taken from the
42
+ * bar's own `date`, never the wall clock, so replays are deterministic.
43
+ *
44
+ * This is pure and offline: no network, no credentials, no order placement.
45
+ *
46
+ * @throws if `config` is invalid, or if any bar has a non-finite `close` or an
47
+ * unparseable `date` — malformed data fails loudly instead of silently
48
+ * degrading to all-HOLD.
49
+ */
50
+ export declare function evaluateEmaCrossover(bars: readonly EmaCrossoverBar[], config?: Partial<EmaCrossoverConfig>): TradeSignal[];
51
+ //# sourceMappingURL=ema-crossover.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ema-crossover.d.ts","sourceRoot":"","sources":["../../../src/stocks/strategies/ema-crossover.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAE9D,+EAA+E;AAC/E,MAAM,WAAW,kBAAkB;IACjC,iCAAiC;IACjC,WAAW,EAAE,MAAM,CAAC;IACpB,yDAAyD;IACzD,UAAU,EAAE,MAAM,CAAC;IACnB,2CAA2C;IAC3C,WAAW,EAAE,MAAM,CAAC;IACpB;;;;;OAKG;IACH,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,eAAO,MAAM,4BAA4B,EAAE,kBAK1C,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,eAAe,GAAG,IAAI,CAAC,eAAe,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC;AAEtE,wBAAgB,2BAA2B,CACzC,MAAM,GAAE,OAAO,CAAC,kBAAkB,CAAM,GACvC,kBAAkB,CAcpB;AAiDD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,oBAAoB,CAClC,IAAI,EAAE,SAAS,eAAe,EAAE,EAChC,MAAM,GAAE,OAAO,CAAC,kBAAkB,CAAM,GACvC,WAAW,EAAE,CAiDf"}
@@ -55,7 +55,7 @@ export declare class UnifiedQuoteService {
55
55
  * @param symbol - Stock symbol to fetch
56
56
  * @param options - Options object with useCache flag (default: true) and cacheTTL in milliseconds
57
57
  */
58
- getQuote(symbol: string, options?: {
58
+ getQuote(rawSymbol: string, options?: {
59
59
  useCache?: boolean;
60
60
  cacheTTL?: number;
61
61
  }): Promise<QuoteServiceResponse>;
@@ -97,12 +97,21 @@ export declare class UnifiedQuoteService {
97
97
  getQuoteFromSource(symbol: string, source: "yfinance" | "finnhub" | "alpaca"): Promise<QuoteServiceResponse>;
98
98
  }
99
99
  export declare const unifiedQuoteService: UnifiedQuoteService;
100
- export declare function getQuote(symbol: string, options?: {
101
- useCache?: boolean;
102
- }): Promise<QuoteServiceResponse>;
103
- export declare function getQuotes(symbols: string[], options?: {
100
+ /**
101
+ * Options accepted by the quote helpers.
102
+ *
103
+ * `cacheTTL` belongs in the type: the methods behind these wrappers have always
104
+ * taken it and callers have always passed it, but omitting it here made every
105
+ * such call a type error.
106
+ */
107
+ export interface GetQuoteOptions {
108
+ /** Read from the quote cache before calling a provider. Defaults to true. */
104
109
  useCache?: boolean;
105
- }): Promise<QuotesServiceResponse>;
110
+ /** Maximum age in ms for a cached quote to count as fresh. */
111
+ cacheTTL?: number;
112
+ }
113
+ export declare function getQuote(symbol: string, options?: GetQuoteOptions): Promise<QuoteServiceResponse>;
114
+ export declare function getQuotes(symbols: string[], options?: GetQuoteOptions): Promise<QuotesServiceResponse>;
106
115
  export declare function getQuoteFromSource(symbol: string, source: "yfinance" | "finnhub" | "alpaca"): Promise<QuoteServiceResponse>;
107
116
  export declare function getHistoricalQuotes(symbol: string, startDate: string | Date, endDate: string | Date, options?: {
108
117
  forceRefreshRecent?: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"unified-quote-service.d.ts","sourceRoot":"","sources":["../../src/stocks/unified-quote-service.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAaH,OAAO,EAAqB,KAAK,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAGhF,MAAM,WAAW,sBAAsB;IACrC,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE;QACL,MAAM,EAAE,eAAe,EAAE,CAAC;QAC1B,IAAI,CAAC,EAAE;YACL,MAAM,EAAE,MAAM,CAAC;YACf,WAAW,EAAE,MAAM,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