opencandle 0.10.0 → 0.11.1

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 (223) hide show
  1. package/README.md +12 -9
  2. package/dist/analysts/orchestrator.d.ts +3 -4
  3. package/dist/analysts/orchestrator.js +34 -44
  4. package/dist/analysts/orchestrator.js.map +1 -1
  5. package/dist/cli-main.js +242 -9
  6. package/dist/cli-main.js.map +1 -1
  7. package/dist/config.d.ts +4 -9
  8. package/dist/config.js +7 -10
  9. package/dist/config.js.map +1 -1
  10. package/dist/doctor/report.js +1 -1
  11. package/dist/doctor/report.js.map +1 -1
  12. package/dist/infra/cache.d.ts +6 -0
  13. package/dist/infra/cache.js +16 -6
  14. package/dist/infra/cache.js.map +1 -1
  15. package/dist/infra/freshness.d.ts +21 -0
  16. package/dist/infra/freshness.js +119 -0
  17. package/dist/infra/freshness.js.map +1 -0
  18. package/dist/infra/market-calendar.d.ts +14 -0
  19. package/dist/infra/market-calendar.js +137 -0
  20. package/dist/infra/market-calendar.js.map +1 -0
  21. package/dist/infra/rate-limiter.js +1 -0
  22. package/dist/infra/rate-limiter.js.map +1 -1
  23. package/dist/market-state/daily-report.d.ts +1 -1
  24. package/dist/market-state/daily-report.js +5 -16
  25. package/dist/market-state/daily-report.js.map +1 -1
  26. package/dist/market-state/service.d.ts +0 -35
  27. package/dist/market-state/service.js +0 -63
  28. package/dist/market-state/service.js.map +1 -1
  29. package/dist/market-state/summaries.d.ts +8 -0
  30. package/dist/market-state/summaries.js +70 -0
  31. package/dist/market-state/summaries.js.map +1 -0
  32. package/dist/memory/sqlite.js +20 -19
  33. package/dist/memory/sqlite.js.map +1 -1
  34. package/dist/onboarding/providers.d.ts +25 -1
  35. package/dist/onboarding/providers.js +26 -0
  36. package/dist/onboarding/providers.js.map +1 -1
  37. package/dist/pi/opencandle-extension.js +57 -226
  38. package/dist/pi/opencandle-extension.js.map +1 -1
  39. package/dist/pi/session-action-dedupe.d.ts +6 -0
  40. package/dist/pi/session-action-dedupe.js +126 -0
  41. package/dist/pi/session-action-dedupe.js.map +1 -0
  42. package/dist/pi/session-writer-lock.d.ts +26 -2
  43. package/dist/pi/session-writer-lock.js +230 -18
  44. package/dist/pi/session-writer-lock.js.map +1 -1
  45. package/dist/pi/setup.js +5 -5
  46. package/dist/pi/setup.js.map +1 -1
  47. package/dist/pi/tui-session-coordinator.d.ts +15 -0
  48. package/dist/pi/tui-session-coordinator.js +283 -0
  49. package/dist/pi/tui-session-coordinator.js.map +1 -0
  50. package/dist/prompts/context-builder.js +1 -1
  51. package/dist/prompts/policy-cards.js +1 -1
  52. package/dist/prompts/policy-cards.js.map +1 -1
  53. package/dist/providers/alpha-vantage.js +6 -0
  54. package/dist/providers/alpha-vantage.js.map +1 -1
  55. package/dist/providers/coingecko.js +1 -0
  56. package/dist/providers/coingecko.js.map +1 -1
  57. package/dist/providers/polymarket.d.ts +2 -0
  58. package/dist/providers/polymarket.js +163 -0
  59. package/dist/providers/polymarket.js.map +1 -0
  60. package/dist/providers/wrap-provider.js +5 -3
  61. package/dist/providers/wrap-provider.js.map +1 -1
  62. package/dist/providers/yahoo-finance.d.ts +3 -0
  63. package/dist/providers/yahoo-finance.js +206 -10
  64. package/dist/providers/yahoo-finance.js.map +1 -1
  65. package/dist/routing/classify-intent.js +4 -5
  66. package/dist/routing/classify-intent.js.map +1 -1
  67. package/dist/routing/entity-extractor.js +16 -0
  68. package/dist/routing/entity-extractor.js.map +1 -1
  69. package/dist/routing/route-manifest.js +1 -2
  70. package/dist/routing/route-manifest.js.map +1 -1
  71. package/dist/routing/router-llm-client.js +18 -3
  72. package/dist/routing/router-llm-client.js.map +1 -1
  73. package/dist/routing/router-prompt.js +1 -1
  74. package/dist/routing/router.d.ts +1 -1
  75. package/dist/routing/router.js +309 -9
  76. package/dist/routing/router.js.map +1 -1
  77. package/dist/routing/slot-resolver.d.ts +1 -0
  78. package/dist/routing/slot-resolver.js +1 -1
  79. package/dist/routing/slot-resolver.js.map +1 -1
  80. package/dist/runtime/evidence.d.ts +1 -0
  81. package/dist/runtime/evidence.js.map +1 -1
  82. package/dist/runtime/numeric-claims.d.ts +23 -0
  83. package/dist/runtime/numeric-claims.js +100 -0
  84. package/dist/runtime/numeric-claims.js.map +1 -0
  85. package/dist/runtime/planning-evidence.js +1 -76
  86. package/dist/runtime/planning-evidence.js.map +1 -1
  87. package/dist/runtime/prompt-step.d.ts +10 -1
  88. package/dist/runtime/prompt-step.js +116 -2
  89. package/dist/runtime/prompt-step.js.map +1 -1
  90. package/dist/runtime/session-coordinator.d.ts +11 -1
  91. package/dist/runtime/session-coordinator.js +354 -62
  92. package/dist/runtime/session-coordinator.js.map +1 -1
  93. package/dist/runtime/validation.d.ts +3 -1
  94. package/dist/runtime/workflow-events.d.ts +1 -1
  95. package/dist/runtime/workflow-events.js.map +1 -1
  96. package/dist/runtime/workflow-types.d.ts +3 -0
  97. package/dist/runtime/workflow-types.js.map +1 -1
  98. package/dist/system-prompt.js +1 -1
  99. package/dist/tools/fundamentals/comps.d.ts +1 -0
  100. package/dist/tools/fundamentals/comps.js +20 -9
  101. package/dist/tools/fundamentals/comps.js.map +1 -1
  102. package/dist/tools/fundamentals/dcf.d.ts +1 -1
  103. package/dist/tools/fundamentals/dcf.js +190 -76
  104. package/dist/tools/fundamentals/dcf.js.map +1 -1
  105. package/dist/tools/index.d.ts +1 -1
  106. package/dist/tools/index.js +3 -3
  107. package/dist/tools/index.js.map +1 -1
  108. package/dist/tools/macro/event-probabilities.d.ts +8 -0
  109. package/dist/tools/macro/event-probabilities.js +121 -0
  110. package/dist/tools/macro/event-probabilities.js.map +1 -0
  111. package/dist/tools/market/crypto-price.d.ts +4 -1
  112. package/dist/tools/market/crypto-price.js +10 -1
  113. package/dist/tools/market/crypto-price.js.map +1 -1
  114. package/dist/tools/market/screen-stocks.js +14 -3
  115. package/dist/tools/market/screen-stocks.js.map +1 -1
  116. package/dist/tools/market/stock-quote.d.ts +4 -1
  117. package/dist/tools/market/stock-quote.js +9 -4
  118. package/dist/tools/market/stock-quote.js.map +1 -1
  119. package/dist/tools/options/option-chain.d.ts +4 -1
  120. package/dist/tools/options/option-chain.js +12 -1
  121. package/dist/tools/options/option-chain.js.map +1 -1
  122. package/dist/tools/portfolio/daily-report.js +10 -4
  123. package/dist/tools/portfolio/daily-report.js.map +1 -1
  124. package/dist/tools/portfolio/risk-analysis.js +1 -1
  125. package/dist/tools/portfolio/risk-analysis.js.map +1 -1
  126. package/dist/tools/technical/backtest.d.ts +23 -5
  127. package/dist/tools/technical/backtest.js +131 -94
  128. package/dist/tools/technical/backtest.js.map +1 -1
  129. package/dist/tools/technical/indicators.js +1 -1
  130. package/dist/tools/technical/indicators.js.map +1 -1
  131. package/dist/types/fundamentals.d.ts +1 -0
  132. package/dist/types/index.d.ts +1 -0
  133. package/dist/types/market.d.ts +2 -0
  134. package/dist/types/options.d.ts +1 -0
  135. package/dist/types/prediction-markets.d.ts +13 -0
  136. package/dist/types/prediction-markets.js +2 -0
  137. package/dist/types/prediction-markets.js.map +1 -0
  138. package/gui/server/chat-event-adapter.ts +89 -5
  139. package/gui/server/http-routes.ts +661 -37
  140. package/gui/server/invoke-tool.ts +165 -16
  141. package/gui/server/live-chat-event-adapter.ts +37 -2
  142. package/gui/server/local-session-coordinator.ts +97 -0
  143. package/gui/server/market-state-api.ts +64 -48
  144. package/gui/server/projector.ts +132 -3
  145. package/gui/server/server.ts +51 -6
  146. package/gui/server/session-actions.ts +146 -45
  147. package/gui/server/session-entry-wait.ts +22 -3
  148. package/gui/server/tool-metadata.ts +3 -1
  149. package/gui/server/ws-hub.ts +77 -10
  150. package/gui/shared/chat-events.ts +10 -1
  151. package/gui/shared/event-reducer.ts +1 -0
  152. package/gui/web/dist/assets/CatalogOverlay-DZ1niyQm.js +1 -0
  153. package/gui/web/dist/assets/index-D4F9AJnn.css +2 -0
  154. package/gui/web/dist/assets/index-DtqMMBTr.js +65 -0
  155. package/gui/web/dist/index.html +2 -2
  156. package/package.json +13 -15
  157. package/src/analysts/orchestrator.ts +35 -56
  158. package/src/cli-main.ts +253 -13
  159. package/src/config.ts +12 -20
  160. package/src/doctor/report.ts +1 -1
  161. package/src/infra/cache.ts +24 -11
  162. package/src/infra/freshness.ts +165 -0
  163. package/src/infra/market-calendar.ts +193 -0
  164. package/src/infra/rate-limiter.ts +1 -0
  165. package/src/market-state/daily-report.ts +6 -16
  166. package/src/market-state/service.ts +0 -136
  167. package/src/market-state/summaries.ts +75 -0
  168. package/src/memory/sqlite.ts +23 -19
  169. package/src/onboarding/providers.ts +29 -1
  170. package/src/pi/opencandle-extension.ts +67 -270
  171. package/src/pi/session-action-dedupe.ts +155 -0
  172. package/src/pi/session-writer-lock.ts +290 -20
  173. package/src/pi/setup.ts +6 -6
  174. package/src/pi/tui-session-coordinator.ts +351 -0
  175. package/src/prompts/context-builder.ts +1 -1
  176. package/src/prompts/policy-cards.ts +1 -1
  177. package/src/providers/alpha-vantage.ts +6 -0
  178. package/src/providers/coingecko.ts +2 -0
  179. package/src/providers/polymarket.ts +214 -0
  180. package/src/providers/wrap-provider.ts +5 -3
  181. package/src/providers/yahoo-finance.ts +339 -27
  182. package/src/routing/classify-intent.ts +4 -5
  183. package/src/routing/entity-extractor.ts +17 -0
  184. package/src/routing/route-manifest.ts +1 -2
  185. package/src/routing/router-llm-client.ts +31 -19
  186. package/src/routing/router-prompt.ts +1 -1
  187. package/src/routing/router.ts +379 -8
  188. package/src/routing/slot-resolver.ts +1 -1
  189. package/src/runtime/evidence.ts +1 -0
  190. package/src/runtime/numeric-claims.ts +108 -0
  191. package/src/runtime/planning-evidence.ts +6 -91
  192. package/src/runtime/prompt-step.ts +127 -2
  193. package/src/runtime/session-coordinator.ts +464 -74
  194. package/src/runtime/validation.ts +1 -1
  195. package/src/runtime/workflow-events.ts +2 -0
  196. package/src/runtime/workflow-types.ts +3 -0
  197. package/src/system-prompt.ts +1 -1
  198. package/src/tools/AGENTS.md +1 -1
  199. package/src/tools/fundamentals/comps.ts +25 -14
  200. package/src/tools/fundamentals/dcf.ts +217 -87
  201. package/src/tools/index.ts +3 -3
  202. package/src/tools/macro/event-probabilities.ts +141 -0
  203. package/src/tools/market/crypto-price.ts +14 -2
  204. package/src/tools/market/screen-stocks.ts +14 -3
  205. package/src/tools/market/stock-quote.ts +49 -43
  206. package/src/tools/options/option-chain.ts +16 -2
  207. package/src/tools/portfolio/daily-report.ts +10 -4
  208. package/src/tools/portfolio/risk-analysis.ts +1 -1
  209. package/src/tools/technical/backtest.ts +167 -108
  210. package/src/tools/technical/indicators.ts +1 -1
  211. package/src/types/fundamentals.ts +1 -0
  212. package/src/types/index.ts +1 -0
  213. package/src/types/market.ts +2 -0
  214. package/src/types/options.ts +1 -0
  215. package/src/types/prediction-markets.ts +13 -0
  216. package/dist/tools/portfolio/predictions.d.ts +0 -55
  217. package/dist/tools/portfolio/predictions.js +0 -422
  218. package/dist/tools/portfolio/predictions.js.map +0 -1
  219. package/gui/server/chat-run-session.ts +0 -16
  220. package/gui/web/dist/assets/CatalogOverlay-CYptsda-.js +0 -1
  221. package/gui/web/dist/assets/index-B7QAjY5g.js +0 -65
  222. package/gui/web/dist/assets/index-D5dbWPfM.css +0 -2
  223. package/src/tools/portfolio/predictions.ts +0 -553
@@ -277,5 +277,5 @@ function trendSummary(
277
277
  if (vwap != null && price < vwap)
278
278
  signals.push("Price below cumulative VWAP — bearish volume-weighted bias");
279
279
 
280
- return signals.length > 0 ? "Signals: " + signals.join(" | ") : "No strong signals";
280
+ return signals.length > 0 ? `Signals: ${signals.join(" | ")}` : "No strong signals";
281
281
  }
@@ -43,4 +43,5 @@ export interface FinancialStatement {
43
43
  freeCashFlow: number;
44
44
  totalDebt?: number;
45
45
  cashAndEquivalents?: number;
46
+ sharesOutstanding?: number;
46
47
  }
@@ -4,6 +4,7 @@ export { FRED_SERIES } from "./macro.js";
4
4
  export type { CryptoPrice, OHLCV, StockQuote } from "./market.js";
5
5
  export type { Greeks, OptionContract, OptionsChain } from "./options.js";
6
6
  export type { PortfolioSummary, Position, RiskMetrics, TechnicalIndicators } from "./portfolio.js";
7
+ export type { PredictionMarketQuote } from "./prediction-markets.js";
7
8
  export type {
8
9
  FearGreedData,
9
10
  RedditSentimentResult,
@@ -13,6 +13,7 @@ export interface StockQuote {
13
13
  week52High: number;
14
14
  week52Low: number;
15
15
  timestamp: number;
16
+ asOf?: string;
16
17
  currency?: string | null;
17
18
  }
18
19
 
@@ -41,4 +42,5 @@ export interface CryptoPrice {
41
42
  circulatingSupply: number;
42
43
  totalSupply: number | null;
43
44
  timestamp: number;
45
+ asOf?: string;
44
46
  }
@@ -49,4 +49,5 @@ export interface OptionsChain {
49
49
  putCallRatio: number;
50
50
  quoteStatus: OptionsQuoteStatus;
51
51
  fetchedAt: string;
52
+ asOf?: string;
52
53
  }
@@ -0,0 +1,13 @@
1
+ export interface PredictionMarketQuote {
2
+ source: "polymarket";
3
+ marketId: string;
4
+ title: string;
5
+ outcome: string;
6
+ probability: number;
7
+ volumeUsd?: number;
8
+ liquidityUsd?: number;
9
+ closeDate?: string;
10
+ resolutionCriteria?: string;
11
+ url: string;
12
+ asOf?: string;
13
+ }
@@ -1,55 +0,0 @@
1
- import type { AgentTool } from "@earendil-works/pi-agent-core";
2
- export interface Prediction {
3
- id?: number;
4
- instrumentId?: number;
5
- symbol: string;
6
- direction: "bullish" | "bearish" | "neutral";
7
- conviction: number;
8
- entryPrice: number;
9
- targetPrice?: number;
10
- date: string;
11
- expiresAt: string;
12
- timeframeDays: number;
13
- }
14
- export interface PredictionCheckResult {
15
- total: number;
16
- open: number;
17
- correct: number;
18
- wrong: number;
19
- hitRate: number;
20
- weightedHitRate: number;
21
- details: Array<{
22
- symbol: string;
23
- direction: string;
24
- conviction: number;
25
- entryPrice: number;
26
- targetPrice?: number;
27
- currentPrice: number | null;
28
- pnlPercent: number | null;
29
- correct: boolean;
30
- status: "open" | "resolved";
31
- targetHit?: boolean;
32
- dataGap?: string;
33
- }>;
34
- }
35
- export declare function recordPrediction(params: {
36
- symbol: string;
37
- direction: "bullish" | "bearish" | "neutral";
38
- conviction: number;
39
- entryPrice: number;
40
- targetPrice?: number;
41
- timeframeDays: number;
42
- }): Promise<Prediction>;
43
- export declare function checkPredictions(predictions: Prediction[], currentPrices: Map<string, number>, now?: Date): PredictionCheckResult;
44
- declare const params: import("@sinclair/typebox").TObject<{
45
- action: import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TLiteral<"record">, import("@sinclair/typebox").TLiteral<"check">, import("@sinclair/typebox").TLiteral<"cancel">]>;
46
- id: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TInteger>;
47
- symbol: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TString>;
48
- direction: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TUnion<[import("@sinclair/typebox").TLiteral<"bullish">, import("@sinclair/typebox").TLiteral<"bearish">, import("@sinclair/typebox").TLiteral<"neutral">]>>;
49
- conviction: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TInteger>;
50
- entry_price: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TNumber>;
51
- target_price: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TNumber>;
52
- timeframe_days: import("@sinclair/typebox").TOptional<import("@sinclair/typebox").TInteger>;
53
- }>;
54
- export declare const predictionsTool: AgentTool<typeof params>;
55
- export {};
@@ -1,422 +0,0 @@
1
- import { Type } from "@sinclair/typebox";
2
- import { isZeroFilledQuote, resolveYahooInstrument } from "../../market-state/resolve.js";
3
- import { resolveInstrumentForMutation } from "../../market-state/resolve-for-mutation.js";
4
- import { MarketStateService } from "../../market-state/service.js";
5
- import { initDefaultDatabase } from "../../memory/sqlite.js";
6
- import { wrapProvider } from "../../providers/wrap-provider.js";
7
- import { getQuote } from "../../providers/yahoo-finance.js";
8
- export async function recordPrediction(params) {
9
- const db = initDefaultDatabase();
10
- const service = new MarketStateService(db);
11
- try {
12
- const instrument = await resolveYahooInstrument(params.symbol);
13
- const record = service.recordPrediction({
14
- instrument,
15
- direction: params.direction,
16
- conviction: params.conviction,
17
- entryPrice: params.entryPrice,
18
- targetPrice: params.targetPrice,
19
- timeframeDays: params.timeframeDays,
20
- });
21
- return predictionRecordToPrediction(record, params.timeframeDays);
22
- }
23
- finally {
24
- db.close();
25
- }
26
- }
27
- export function checkPredictions(predictions, currentPrices, now = new Date()) {
28
- if (predictions.length === 0) {
29
- return { total: 0, open: 0, correct: 0, wrong: 0, hitRate: 0, weightedHitRate: 0, details: [] };
30
- }
31
- const details = [];
32
- let totalConviction = 0;
33
- let correctConviction = 0;
34
- let openCount = 0;
35
- const nowStr = now.toISOString().split("T")[0];
36
- for (const p of predictions) {
37
- const currentPrice = currentPrices.get(p.symbol);
38
- if (currentPrice == null) {
39
- openCount++;
40
- details.push({
41
- symbol: p.symbol,
42
- direction: p.direction,
43
- conviction: p.conviction,
44
- entryPrice: p.entryPrice,
45
- currentPrice: null,
46
- pnlPercent: null,
47
- correct: false,
48
- status: "open",
49
- dataGap: "quote unavailable",
50
- });
51
- continue;
52
- }
53
- if (!Number.isFinite(p.entryPrice) || p.entryPrice <= 0) {
54
- openCount++;
55
- details.push({
56
- symbol: p.symbol,
57
- direction: p.direction,
58
- conviction: p.conviction,
59
- entryPrice: p.entryPrice,
60
- targetPrice: p.targetPrice,
61
- currentPrice,
62
- pnlPercent: null,
63
- correct: false,
64
- status: "open",
65
- dataGap: "invalid entry price",
66
- });
67
- continue;
68
- }
69
- const isExpired = p.expiresAt <= nowStr;
70
- const pnlPercent = (currentPrice - p.entryPrice) / p.entryPrice;
71
- if (!isExpired) {
72
- openCount++;
73
- const targetHit = p.targetPrice != null &&
74
- ((p.direction === "bullish" && currentPrice >= p.targetPrice) ||
75
- (p.direction === "bearish" && currentPrice <= p.targetPrice));
76
- details.push({
77
- symbol: p.symbol,
78
- direction: p.direction,
79
- conviction: p.conviction,
80
- entryPrice: p.entryPrice,
81
- targetPrice: p.targetPrice,
82
- currentPrice,
83
- pnlPercent,
84
- correct: false,
85
- status: "open",
86
- targetHit,
87
- });
88
- continue;
89
- }
90
- const correct = (p.direction === "bullish" && currentPrice > p.entryPrice) ||
91
- (p.direction === "bearish" && currentPrice < p.entryPrice) ||
92
- (p.direction === "neutral" && Math.abs(pnlPercent) < 0.02);
93
- details.push({
94
- symbol: p.symbol,
95
- direction: p.direction,
96
- conviction: p.conviction,
97
- entryPrice: p.entryPrice,
98
- currentPrice,
99
- pnlPercent,
100
- correct,
101
- status: "resolved",
102
- });
103
- totalConviction += p.conviction;
104
- if (correct)
105
- correctConviction += p.conviction;
106
- }
107
- const resolved = details.filter((d) => d.status === "resolved");
108
- const correctCount = resolved.filter((d) => d.correct).length;
109
- return {
110
- total: details.length,
111
- open: openCount,
112
- correct: correctCount,
113
- wrong: resolved.length - correctCount,
114
- hitRate: resolved.length > 0 ? correctCount / resolved.length : 0,
115
- weightedHitRate: totalConviction > 0 ? correctConviction / totalConviction : 0,
116
- details,
117
- };
118
- }
119
- const params = Type.Object({
120
- action: Type.Union([Type.Literal("record"), Type.Literal("check"), Type.Literal("cancel")], {
121
- description: "record: save a new prediction. check: evaluate all predictions against current prices. cancel: close an open prediction without scoring it.",
122
- }),
123
- id: Type.Optional(Type.Integer({ minimum: 1, description: "Prediction id (required for cancel)" })),
124
- symbol: Type.Optional(Type.String({ description: "Ticker symbol (required for record)" })),
125
- direction: Type.Optional(Type.Union([Type.Literal("bullish"), Type.Literal("bearish"), Type.Literal("neutral")], {
126
- description: "Predicted direction (required for record)",
127
- })),
128
- conviction: Type.Optional(Type.Integer({ minimum: 1, maximum: 10, description: "Conviction 1-10 (required for record)" })),
129
- entry_price: Type.Optional(Type.Number({
130
- exclusiveMinimum: 0,
131
- description: "Entry price at time of prediction (required for record)",
132
- })),
133
- target_price: Type.Optional(Type.Number({ exclusiveMinimum: 0, description: "Optional target price" })),
134
- timeframe_days: Type.Optional(Type.Integer({
135
- minimum: 1,
136
- maximum: 3650,
137
- description: "Timeframe in days for the prediction (default: 30)",
138
- })),
139
- });
140
- export const predictionsTool = {
141
- name: "track_prediction",
142
- label: "Prediction Tracker",
143
- description: "Track your analysis predictions and measure accuracy over time. Record: save a directional prediction with conviction. Check: evaluate all predictions against current prices, compute hit rate and conviction-weighted accuracy. Inspired by ATLAS's Darwinian scoring approach.",
144
- parameters: params,
145
- async execute(_toolCallId, args) {
146
- if (args.action === "cancel") {
147
- if (args.id == null) {
148
- throw new Error("id is required for cancel action.");
149
- }
150
- const db = initDefaultDatabase();
151
- try {
152
- const service = new MarketStateService(db);
153
- const existing = service.listPredictions().find((record) => record.id === args.id);
154
- if (existing == null) {
155
- return {
156
- content: [{ type: "text", text: `Prediction #${args.id} not found.` }],
157
- details: null,
158
- };
159
- }
160
- if (existing.status !== "open") {
161
- return {
162
- content: [
163
- { type: "text", text: `Prediction #${args.id} is already ${existing.status}.` },
164
- ],
165
- details: existing,
166
- };
167
- }
168
- const now = new Date().toISOString();
169
- const cancelled = service.updatePredictionOutcome({
170
- id: args.id,
171
- status: "cancelled",
172
- resolvedAt: now,
173
- result: { reason: "user_cancelled" },
174
- });
175
- return {
176
- content: [
177
- { type: "text", text: `Cancelled prediction #${args.id} for ${cancelled.symbol}.` },
178
- ],
179
- details: cancelled,
180
- };
181
- }
182
- finally {
183
- db.close();
184
- }
185
- }
186
- if (args.action === "record") {
187
- if (!args.symbol || !args.direction || args.conviction == null || args.entry_price == null) {
188
- throw new Error("symbol, direction, conviction, and entry_price are required for record action.");
189
- }
190
- if (!Number.isInteger(args.conviction) || args.conviction < 1 || args.conviction > 10) {
191
- throw new Error("conviction must be between 1 and 10.");
192
- }
193
- if (args.entry_price <= 0) {
194
- throw new Error("entry_price must be greater than 0.");
195
- }
196
- if (args.target_price != null && args.target_price <= 0) {
197
- throw new Error("target_price must be greater than 0.");
198
- }
199
- if (args.timeframe_days != null &&
200
- (!Number.isInteger(args.timeframe_days) ||
201
- args.timeframe_days < 1 ||
202
- args.timeframe_days > 3650)) {
203
- throw new Error("timeframe_days must be an integer between 1 and 3650.");
204
- }
205
- const resolution = await resolveInstrumentForMutation(args.symbol);
206
- if (resolution.status === "needs_selection") {
207
- return {
208
- content: [
209
- {
210
- type: "text",
211
- text: `Could not verify ${resolution.query}. Choose one of the returned candidates before recording the prediction.`,
212
- },
213
- ],
214
- details: resolution,
215
- };
216
- }
217
- const db = initDefaultDatabase();
218
- let prediction;
219
- try {
220
- const service = new MarketStateService(db);
221
- const record = service.recordPrediction({
222
- instrument: resolution.instrument,
223
- direction: args.direction,
224
- conviction: args.conviction,
225
- entryPrice: args.entry_price,
226
- targetPrice: args.target_price,
227
- timeframeDays: args.timeframe_days ?? 30,
228
- });
229
- prediction = predictionRecordToPrediction(record, args.timeframe_days ?? 30);
230
- }
231
- finally {
232
- db.close();
233
- }
234
- return {
235
- content: [
236
- {
237
- type: "text",
238
- text: `Recorded: ${prediction.symbol} ${prediction.direction} (conviction ${prediction.conviction}/10) at $${prediction.entryPrice}. Expires ${prediction.expiresAt}.`,
239
- },
240
- ],
241
- details: prediction,
242
- };
243
- }
244
- const db = initDefaultDatabase();
245
- try {
246
- const service = new MarketStateService(db);
247
- const records = service.listPredictions();
248
- const openRecords = records.filter((record) => record.status === "open");
249
- const predictions = openRecords.map((record) => predictionRecordToPrediction(record));
250
- const historicalDetails = storedResolvedPredictionDetails(records);
251
- if (records.length === 0) {
252
- return {
253
- content: [
254
- {
255
- type: "text",
256
- text: "No predictions recorded yet. Use record action to track your calls.",
257
- },
258
- ],
259
- details: null,
260
- };
261
- }
262
- if (openRecords.length === 0) {
263
- if (historicalDetails.length > 0) {
264
- const result = predictionResultFromDetails(historicalDetails);
265
- return {
266
- content: [{ type: "text", text: formatPredictionScorecard(result) }],
267
- details: result,
268
- };
269
- }
270
- return {
271
- content: [{ type: "text", text: "No open predictions to check." }],
272
- details: checkPredictions([], new Map()),
273
- };
274
- }
275
- const symbols = [...new Set(predictions.map((p) => p.symbol))];
276
- const priceMap = new Map();
277
- await Promise.all(symbols.map(async (sym) => {
278
- const result = await wrapProvider("yahoo", () => getQuote(sym));
279
- if (result.status === "ok" && !result.stale && !isZeroFilledQuote(result.data)) {
280
- priceMap.set(sym, result.data.price);
281
- }
282
- }));
283
- const currentResult = checkPredictions(predictions, priceMap);
284
- persistPredictionOutcomes(service, openRecords, currentResult);
285
- const result = predictionResultFromDetails([...historicalDetails, ...currentResult.details]);
286
- return {
287
- content: [{ type: "text", text: formatPredictionScorecard(result) }],
288
- details: result,
289
- };
290
- }
291
- finally {
292
- db.close();
293
- }
294
- },
295
- };
296
- function persistPredictionOutcomes(service, records, result) {
297
- const now = new Date().toISOString();
298
- const usedRecordIds = new Set();
299
- for (const detail of result.details) {
300
- if (detail.status !== "resolved")
301
- continue;
302
- const record = findMatchingOpenRecord(records, detail, usedRecordIds);
303
- if (record == null)
304
- continue;
305
- usedRecordIds.add(record.id);
306
- service.updatePredictionOutcome({
307
- id: record.id,
308
- status: "resolved",
309
- resolvedAt: now,
310
- result: {
311
- currentPrice: detail.currentPrice,
312
- pnlPercent: detail.pnlPercent,
313
- correct: detail.correct,
314
- },
315
- });
316
- }
317
- for (const record of records) {
318
- if (usedRecordIds.has(record.id))
319
- continue;
320
- if (record.expiresAt > now)
321
- continue;
322
- if (result.details.some((detail) => detail.status === "open" && matchesPredictionRecord(record, detail))) {
323
- continue;
324
- }
325
- service.updatePredictionOutcome({
326
- id: record.id,
327
- status: "expired",
328
- resolvedAt: now,
329
- result: { reason: "quote_unavailable" },
330
- });
331
- }
332
- }
333
- function storedResolvedPredictionDetails(records) {
334
- return records.flatMap((record) => {
335
- if (record.status !== "resolved" || record.resultJson == null)
336
- return [];
337
- const result = JSON.parse(record.resultJson);
338
- if (typeof result.currentPrice !== "number" ||
339
- typeof result.pnlPercent !== "number" ||
340
- typeof result.correct !== "boolean") {
341
- return [];
342
- }
343
- return [
344
- {
345
- symbol: record.symbol,
346
- direction: record.direction,
347
- conviction: record.conviction,
348
- entryPrice: record.entryPrice,
349
- currentPrice: result.currentPrice,
350
- pnlPercent: result.pnlPercent,
351
- correct: result.correct,
352
- status: "resolved",
353
- },
354
- ];
355
- });
356
- }
357
- function predictionResultFromDetails(details) {
358
- const resolved = details.filter((detail) => detail.status === "resolved");
359
- const correct = resolved.filter((detail) => detail.correct);
360
- const totalConviction = resolved.reduce((sum, detail) => sum + detail.conviction, 0);
361
- const correctConviction = correct.reduce((sum, detail) => sum + detail.conviction, 0);
362
- return {
363
- total: details.length,
364
- open: details.filter((detail) => detail.status === "open").length,
365
- correct: correct.length,
366
- wrong: resolved.length - correct.length,
367
- hitRate: resolved.length > 0 ? correct.length / resolved.length : 0,
368
- weightedHitRate: totalConviction > 0 ? correctConviction / totalConviction : 0,
369
- details,
370
- };
371
- }
372
- function formatPredictionScorecard(result) {
373
- const resolved = result.correct + result.wrong;
374
- const lines = [
375
- `**Prediction Scorecard** — ${result.total} predictions (${resolved} resolved, ${result.open} open)`,
376
- ``,
377
- `Hit Rate: ${(result.hitRate * 100).toFixed(0)}% (${result.correct}/${resolved})`,
378
- `Weighted Hit Rate: ${(result.weightedHitRate * 100).toFixed(0)}% (by conviction)`,
379
- ``,
380
- ...result.details.map((d) => {
381
- const icon = d.status === "open" ? "~" : d.correct ? "+" : "-";
382
- if (d.currentPrice == null || d.pnlPercent == null) {
383
- return `${icon} ${d.symbol} ${d.direction}: quote unavailable (open)`;
384
- }
385
- const sign = d.pnlPercent >= 0 ? "+" : "";
386
- const label = d.status === "open"
387
- ? d.targetHit && d.targetPrice != null
388
- ? ` (open — target hit: $${d.targetPrice.toFixed(2)} reached before expiry; resolve or let it ride)`
389
- : " (open)"
390
- : "";
391
- return ` [${icon}] ${d.symbol}: ${d.direction} (conv ${d.conviction}) → $${d.entryPrice.toFixed(2)} → $${d.currentPrice.toFixed(2)} (${sign}${(d.pnlPercent * 100).toFixed(1)}%)${label}`;
392
- }),
393
- ];
394
- return lines.join("\n");
395
- }
396
- function findMatchingOpenRecord(records, detail, usedRecordIds) {
397
- return (records.find((record) => !usedRecordIds.has(record.id) && matchesPredictionRecord(record, detail)) ?? null);
398
- }
399
- function matchesPredictionRecord(record, detail) {
400
- return (record.symbol === detail.symbol &&
401
- record.direction === detail.direction &&
402
- record.conviction === detail.conviction &&
403
- record.entryPrice === detail.entryPrice);
404
- }
405
- function predictionRecordToPrediction(record, explicitTimeframeDays) {
406
- const openedAt = new Date(record.openedAt);
407
- const expiresAt = new Date(record.expiresAt);
408
- const timeframeDays = explicitTimeframeDays ?? Math.round((expiresAt.getTime() - openedAt.getTime()) / 86_400_000);
409
- return {
410
- id: record.id,
411
- instrumentId: record.instrumentId,
412
- symbol: record.symbol,
413
- direction: record.direction,
414
- conviction: record.conviction,
415
- entryPrice: record.entryPrice,
416
- targetPrice: record.targetPrice ?? undefined,
417
- date: record.openedAt.split("T")[0],
418
- expiresAt: record.expiresAt.split("T")[0],
419
- timeframeDays,
420
- };
421
- }
422
- //# sourceMappingURL=predictions.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"predictions.js","sourceRoot":"","sources":["../../../src/tools/portfolio/predictions.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,MAAM,+BAA+B,CAAC;AAC1F,OAAO,EAAE,4BAA4B,EAAE,MAAM,4CAA4C,CAAC;AAC1F,OAAO,EAAE,kBAAkB,EAAyB,MAAM,+BAA+B,CAAC;AAC1F,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;AAChE,OAAO,EAAE,QAAQ,EAAE,MAAM,kCAAkC,CAAC;AAqC5D,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,MAOtC;IACC,MAAM,EAAE,GAAG,mBAAmB,EAAE,CAAC;IACjC,MAAM,OAAO,GAAG,IAAI,kBAAkB,CAAC,EAAE,CAAC,CAAC;IAC3C,IAAI,CAAC;QACH,MAAM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M,CAAC,UAAU,KAAK,MAAM,CAAC,UAAU,CACxC,CAAC;AACJ,CAAC;AAED,SAAS,4BAA4B,CACnC,MAAwB,EACxB,qBAA8B;IAE9B,MAAM,QAAQ,GAAG,IAAI,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IAC3C,MAAM,SAAS,GAAG,IAAI,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;IAC7C,MAAM,aAAa,GACjB,qBAAqB,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,SAAS,CAAC,OAAO,EAAE,GAAG,QAAQ,CAAC,OAAO,EAAE,CAAC,GAAG,UAAU,CAAC,CAAC;IAE/F,OAAO;QACL,EAAE,EAAE,MAAM,CAAC,EAAE;QACb,YAAY,EAAE,MAAM,CAAC,YAAY;QACjC,MAAM,EAAE,MAAM,CAAC,MAAM;QACrB,SAAS,EAAE,MAAM,CAAC,SAAS;QAC3B,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,UAAU,EAAE,MAAM,CAAC,UAAU;QAC7B,WAAW,EAAE,MAAM,CAAC,WAAW,IAAI,SAAS;QAC5C,IAAI,EAAE,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QACnC,SAAS,EAAE,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QACzC,aAAa;KACd,CAAC;AACJ,CAAC"}
@@ -1,16 +0,0 @@
1
- export interface ChatRunSessionConflict {
2
- error: string;
3
- code: "session_changed";
4
- }
5
-
6
- export function chatRunSessionConflict(
7
- expectedSessionId: unknown,
8
- activeSessionId: string,
9
- ): ChatRunSessionConflict | null {
10
- const expected = typeof expectedSessionId === "string" ? expectedSessionId.trim() : "";
11
- if (!expected || expected === activeSessionId) return null;
12
- return {
13
- error: "The active session changed before this message was sent.",
14
- code: "session_changed",
15
- };
16
- }