@catalyst-team/poly-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/.env +0 -0
  2. package/README.md +803 -0
  3. package/dist/__tests__/clob-api.test.d.ts +5 -0
  4. package/dist/__tests__/clob-api.test.d.ts.map +1 -0
  5. package/dist/__tests__/clob-api.test.js +240 -0
  6. package/dist/__tests__/clob-api.test.js.map +1 -0
  7. package/dist/__tests__/integration/bridge-client.integration.test.d.ts +11 -0
  8. package/dist/__tests__/integration/bridge-client.integration.test.d.ts.map +1 -0
  9. package/dist/__tests__/integration/bridge-client.integration.test.js +260 -0
  10. package/dist/__tests__/integration/bridge-client.integration.test.js.map +1 -0
  11. package/dist/__tests__/integration/clob-api.integration.test.d.ts +13 -0
  12. package/dist/__tests__/integration/clob-api.integration.test.d.ts.map +1 -0
  13. package/dist/__tests__/integration/clob-api.integration.test.js +170 -0
  14. package/dist/__tests__/integration/clob-api.integration.test.js.map +1 -0
  15. package/dist/__tests__/integration/ctf-client.integration.test.d.ts +17 -0
  16. package/dist/__tests__/integration/ctf-client.integration.test.d.ts.map +1 -0
  17. package/dist/__tests__/integration/ctf-client.integration.test.js +234 -0
  18. package/dist/__tests__/integration/ctf-client.integration.test.js.map +1 -0
  19. package/dist/__tests__/integration/data-api.integration.test.d.ts +9 -0
  20. package/dist/__tests__/integration/data-api.integration.test.d.ts.map +1 -0
  21. package/dist/__tests__/integration/data-api.integration.test.js +161 -0
  22. package/dist/__tests__/integration/data-api.integration.test.js.map +1 -0
  23. package/dist/__tests__/integration/gamma-api.integration.test.d.ts +9 -0
  24. package/dist/__tests__/integration/gamma-api.integration.test.d.ts.map +1 -0
  25. package/dist/__tests__/integration/gamma-api.integration.test.js +170 -0
  26. package/dist/__tests__/integration/gamma-api.integration.test.js.map +1 -0
  27. package/dist/__tests__/test-utils.d.ts +92 -0
  28. package/dist/__tests__/test-utils.d.ts.map +1 -0
  29. package/dist/__tests__/test-utils.js +143 -0
  30. package/dist/__tests__/test-utils.js.map +1 -0
  31. package/dist/clients/bridge-client.d.ts +388 -0
  32. package/dist/clients/bridge-client.d.ts.map +1 -0
  33. package/dist/clients/bridge-client.js +587 -0
  34. package/dist/clients/bridge-client.js.map +1 -0
  35. package/dist/clients/clob-api.d.ts +318 -0
  36. package/dist/clients/clob-api.d.ts.map +1 -0
  37. package/dist/clients/clob-api.js +388 -0
  38. package/dist/clients/clob-api.js.map +1 -0
  39. package/dist/clients/ctf-client.d.ts +473 -0
  40. package/dist/clients/ctf-client.d.ts.map +1 -0
  41. package/dist/clients/ctf-client.js +915 -0
  42. package/dist/clients/ctf-client.js.map +1 -0
  43. package/dist/clients/data-api.d.ts +134 -0
  44. package/dist/clients/data-api.d.ts.map +1 -0
  45. package/dist/clients/data-api.js +265 -0
  46. package/dist/clients/data-api.js.map +1 -0
  47. package/dist/clients/gamma-api.d.ts +401 -0
  48. package/dist/clients/gamma-api.d.ts.map +1 -0
  49. package/dist/clients/gamma-api.js +352 -0
  50. package/dist/clients/gamma-api.js.map +1 -0
  51. package/dist/clients/trading-client.d.ts +252 -0
  52. package/dist/clients/trading-client.d.ts.map +1 -0
  53. package/dist/clients/trading-client.js +543 -0
  54. package/dist/clients/trading-client.js.map +1 -0
  55. package/dist/clients/websocket-manager.d.ts +100 -0
  56. package/dist/clients/websocket-manager.d.ts.map +1 -0
  57. package/dist/clients/websocket-manager.js +193 -0
  58. package/dist/clients/websocket-manager.js.map +1 -0
  59. package/dist/core/cache-adapter-bridge.d.ts +36 -0
  60. package/dist/core/cache-adapter-bridge.d.ts.map +1 -0
  61. package/dist/core/cache-adapter-bridge.js +81 -0
  62. package/dist/core/cache-adapter-bridge.js.map +1 -0
  63. package/dist/core/cache.d.ts +40 -0
  64. package/dist/core/cache.d.ts.map +1 -0
  65. package/dist/core/cache.js +71 -0
  66. package/dist/core/cache.js.map +1 -0
  67. package/dist/core/errors.d.ts +38 -0
  68. package/dist/core/errors.d.ts.map +1 -0
  69. package/dist/core/errors.js +84 -0
  70. package/dist/core/errors.js.map +1 -0
  71. package/dist/core/rate-limiter.d.ts +31 -0
  72. package/dist/core/rate-limiter.d.ts.map +1 -0
  73. package/dist/core/rate-limiter.js +70 -0
  74. package/dist/core/rate-limiter.js.map +1 -0
  75. package/dist/core/types.d.ts +314 -0
  76. package/dist/core/types.d.ts.map +1 -0
  77. package/dist/core/types.js +19 -0
  78. package/dist/core/types.js.map +1 -0
  79. package/dist/core/unified-cache.d.ts +63 -0
  80. package/dist/core/unified-cache.d.ts.map +1 -0
  81. package/dist/core/unified-cache.js +114 -0
  82. package/dist/core/unified-cache.js.map +1 -0
  83. package/dist/index.d.ts +94 -0
  84. package/dist/index.d.ts.map +1 -0
  85. package/dist/index.js +258 -0
  86. package/dist/index.js.map +1 -0
  87. package/dist/mcp/errors.d.ts +33 -0
  88. package/dist/mcp/errors.d.ts.map +1 -0
  89. package/dist/mcp/errors.js +86 -0
  90. package/dist/mcp/errors.js.map +1 -0
  91. package/dist/mcp/index.d.ts +62 -0
  92. package/dist/mcp/index.d.ts.map +1 -0
  93. package/dist/mcp/index.js +173 -0
  94. package/dist/mcp/index.js.map +1 -0
  95. package/dist/mcp/server.d.ts +17 -0
  96. package/dist/mcp/server.d.ts.map +1 -0
  97. package/dist/mcp/server.js +155 -0
  98. package/dist/mcp/server.js.map +1 -0
  99. package/dist/mcp/tools/guide.d.ts +12 -0
  100. package/dist/mcp/tools/guide.d.ts.map +1 -0
  101. package/dist/mcp/tools/guide.js +801 -0
  102. package/dist/mcp/tools/guide.js.map +1 -0
  103. package/dist/mcp/tools/index.d.ts +11 -0
  104. package/dist/mcp/tools/index.d.ts.map +1 -0
  105. package/dist/mcp/tools/index.js +27 -0
  106. package/dist/mcp/tools/index.js.map +1 -0
  107. package/dist/mcp/tools/market.d.ts +11 -0
  108. package/dist/mcp/tools/market.d.ts.map +1 -0
  109. package/dist/mcp/tools/market.js +314 -0
  110. package/dist/mcp/tools/market.js.map +1 -0
  111. package/dist/mcp/tools/order.d.ts +10 -0
  112. package/dist/mcp/tools/order.d.ts.map +1 -0
  113. package/dist/mcp/tools/order.js +258 -0
  114. package/dist/mcp/tools/order.js.map +1 -0
  115. package/dist/mcp/tools/trade.d.ts +38 -0
  116. package/dist/mcp/tools/trade.d.ts.map +1 -0
  117. package/dist/mcp/tools/trade.js +314 -0
  118. package/dist/mcp/tools/trade.js.map +1 -0
  119. package/dist/mcp/tools/trader.d.ts +11 -0
  120. package/dist/mcp/tools/trader.d.ts.map +1 -0
  121. package/dist/mcp/tools/trader.js +277 -0
  122. package/dist/mcp/tools/trader.js.map +1 -0
  123. package/dist/mcp/tools/wallet.d.ts +274 -0
  124. package/dist/mcp/tools/wallet.d.ts.map +1 -0
  125. package/dist/mcp/tools/wallet.js +579 -0
  126. package/dist/mcp/tools/wallet.js.map +1 -0
  127. package/dist/mcp/types.d.ts +413 -0
  128. package/dist/mcp/types.d.ts.map +1 -0
  129. package/dist/mcp/types.js +5 -0
  130. package/dist/mcp/types.js.map +1 -0
  131. package/dist/services/authorization-service.d.ts +97 -0
  132. package/dist/services/authorization-service.d.ts.map +1 -0
  133. package/dist/services/authorization-service.js +279 -0
  134. package/dist/services/authorization-service.js.map +1 -0
  135. package/dist/services/market-service.d.ts +108 -0
  136. package/dist/services/market-service.d.ts.map +1 -0
  137. package/dist/services/market-service.js +458 -0
  138. package/dist/services/market-service.js.map +1 -0
  139. package/dist/services/realtime-service.d.ts +82 -0
  140. package/dist/services/realtime-service.d.ts.map +1 -0
  141. package/dist/services/realtime-service.js +150 -0
  142. package/dist/services/realtime-service.js.map +1 -0
  143. package/dist/services/swap-service.d.ts +217 -0
  144. package/dist/services/swap-service.d.ts.map +1 -0
  145. package/dist/services/swap-service.js +695 -0
  146. package/dist/services/swap-service.js.map +1 -0
  147. package/dist/services/wallet-service.d.ts +94 -0
  148. package/dist/services/wallet-service.d.ts.map +1 -0
  149. package/dist/services/wallet-service.js +173 -0
  150. package/dist/services/wallet-service.js.map +1 -0
  151. package/dist/utils/price-utils.d.ts +153 -0
  152. package/dist/utils/price-utils.d.ts.map +1 -0
  153. package/dist/utils/price-utils.js +236 -0
  154. package/dist/utils/price-utils.js.map +1 -0
  155. package/docs/00-design.md +760 -0
  156. package/docs/01-mcp.md +2041 -0
  157. package/docs/02-API.md +1148 -0
  158. package/docs/e2e/01-trader-tools.md +159 -0
  159. package/docs/e2e/02-market-tools.md +180 -0
  160. package/docs/e2e/03-order-tools.md +166 -0
  161. package/docs/e2e/04-wallet-tools.md +224 -0
  162. package/docs/e2e/05-trading-tools.md +327 -0
  163. package/docs/e2e/06-integration-scenarios.md +481 -0
  164. package/docs/e2e/coordinator.md +376 -0
  165. package/examples/01-basic-usage.ts +68 -0
  166. package/examples/02-smart-money.ts +95 -0
  167. package/examples/03-market-analysis.ts +108 -0
  168. package/examples/04-kline-aggregation.ts +158 -0
  169. package/examples/05-follow-wallet-strategy.ts +156 -0
  170. package/examples/06-services-demo.ts +124 -0
  171. package/examples/07-realtime-websocket.ts +117 -0
  172. package/examples/08-trading-orders.ts +278 -0
  173. package/examples/09-rewards-tracking.ts +187 -0
  174. package/examples/10-ctf-operations.ts +336 -0
  175. package/examples/11-live-arbitrage-scan.ts +221 -0
  176. package/examples/12-trending-arb-monitor.ts +406 -0
  177. package/examples/README.md +179 -0
  178. package/package.json +62 -0
  179. package/scripts/README.md +163 -0
  180. package/scripts/approvals/approve-erc1155.ts +129 -0
  181. package/scripts/approvals/approve-neg-risk-erc1155.ts +149 -0
  182. package/scripts/approvals/approve-neg-risk.ts +102 -0
  183. package/scripts/approvals/check-all-allowances.ts +150 -0
  184. package/scripts/approvals/check-allowance.ts +129 -0
  185. package/scripts/approvals/check-ctf-approval.ts +158 -0
  186. package/scripts/datas/001-report.md +486 -0
  187. package/scripts/datas/clone-modal-screenshot.png +0 -0
  188. package/scripts/deposit/deposit-native-usdc.ts +179 -0
  189. package/scripts/deposit/deposit-usdc.ts +155 -0
  190. package/scripts/deposit/swap-usdc-to-usdce.ts +375 -0
  191. package/scripts/research/research-markets.ts +166 -0
  192. package/scripts/trading/check-orders.ts +50 -0
  193. package/scripts/trading/sell-nvidia-positions.ts +206 -0
  194. package/scripts/trading/test-order.ts +172 -0
  195. package/scripts/truth.md +440 -0
  196. package/scripts/verify/test-approve-trading.ts +98 -0
  197. package/scripts/verify/test-provider-fix.ts +43 -0
  198. package/scripts/verify/test-search-mcp.ts +113 -0
  199. package/scripts/verify/verify-all-apis.ts +160 -0
  200. package/scripts/wallet/check-wallet-balances.ts +75 -0
  201. package/scripts/wallet/test-wallet-operations.ts +191 -0
  202. package/scripts/wallet/verify-wallet-tools.ts +124 -0
  203. package/src/__tests__/clob-api.test.ts +301 -0
  204. package/src/__tests__/integration/bridge-client.integration.test.ts +314 -0
  205. package/src/__tests__/integration/clob-api.integration.test.ts +218 -0
  206. package/src/__tests__/integration/ctf-client.integration.test.ts +331 -0
  207. package/src/__tests__/integration/data-api.integration.test.ts +194 -0
  208. package/src/__tests__/integration/gamma-api.integration.test.ts +206 -0
  209. package/src/__tests__/test-utils.ts +170 -0
  210. package/src/clients/bridge-client.ts +841 -0
  211. package/src/clients/clob-api.ts +629 -0
  212. package/src/clients/ctf-client.ts +1216 -0
  213. package/src/clients/data-api.ts +469 -0
  214. package/src/clients/gamma-api.ts +597 -0
  215. package/src/clients/trading-client.ts +749 -0
  216. package/src/clients/websocket-manager.ts +267 -0
  217. package/src/core/cache-adapter-bridge.ts +94 -0
  218. package/src/core/cache.ts +85 -0
  219. package/src/core/errors.ts +117 -0
  220. package/src/core/rate-limiter.ts +74 -0
  221. package/src/core/types.ts +360 -0
  222. package/src/core/unified-cache.ts +153 -0
  223. package/src/index.ts +455 -0
  224. package/src/mcp/README.md +380 -0
  225. package/src/mcp/errors.ts +124 -0
  226. package/src/mcp/index.ts +309 -0
  227. package/src/mcp/server.ts +183 -0
  228. package/src/mcp/tools/guide.ts +821 -0
  229. package/src/mcp/tools/index.ts +73 -0
  230. package/src/mcp/tools/market.ts +363 -0
  231. package/src/mcp/tools/order.ts +326 -0
  232. package/src/mcp/tools/trade.ts +417 -0
  233. package/src/mcp/tools/trader.ts +322 -0
  234. package/src/mcp/tools/wallet.ts +683 -0
  235. package/src/mcp/types.ts +472 -0
  236. package/src/services/authorization-service.ts +357 -0
  237. package/src/services/market-service.ts +544 -0
  238. package/src/services/realtime-service.ts +196 -0
  239. package/src/services/swap-service.ts +896 -0
  240. package/src/services/wallet-service.ts +259 -0
  241. package/src/utils/price-utils.ts +307 -0
  242. package/tsconfig.json +8 -0
  243. package/vitest.config.ts +19 -0
  244. package/vitest.integration.config.ts +18 -0
@@ -0,0 +1,544 @@
1
+ /**
2
+ * Market Service
3
+ *
4
+ * Provides enhanced market analysis features:
5
+ * - K-Line aggregation from trade data
6
+ * - Dual token K-Lines (YES + NO)
7
+ * - Spread analysis
8
+ * - Market signal detection
9
+ */
10
+
11
+ import { DataApiClient, Trade } from '../clients/data-api.js';
12
+ import { GammaApiClient, GammaMarket } from '../clients/gamma-api.js';
13
+ import { ClobApiClient, ClobMarket } from '../clients/clob-api.js';
14
+ import type { UnifiedCache } from '../core/unified-cache.js';
15
+ import { PolymarketError, ErrorCode } from '../core/errors.js';
16
+ import type { UnifiedMarket, ProcessedOrderbook, ArbitrageOpportunity, KLineInterval, KLineCandle, DualKLineData, SpreadDataPoint, RealtimeSpreadAnalysis } from '../core/types.js';
17
+
18
+ export class MarketService {
19
+ constructor(
20
+ private gammaApi: GammaApiClient,
21
+ private clobApi: ClobApiClient,
22
+ private dataApi: DataApiClient,
23
+ private cache: UnifiedCache
24
+ ) {}
25
+
26
+ // ===== Unified Market Access =====
27
+
28
+ /**
29
+ * Get market by slug or condition ID
30
+ */
31
+ async getMarket(identifier: string): Promise<UnifiedMarket> {
32
+ const isConditionId = identifier.startsWith('0x') || /^\d+$/.test(identifier);
33
+
34
+ if (isConditionId) {
35
+ return this.getMarketByConditionId(identifier);
36
+ } else {
37
+ return this.getMarketBySlug(identifier);
38
+ }
39
+ }
40
+
41
+ private async getMarketBySlug(slug: string): Promise<UnifiedMarket> {
42
+ const gammaMarket = await this.gammaApi.getMarketBySlug(slug);
43
+ if (!gammaMarket) {
44
+ throw new PolymarketError(ErrorCode.MARKET_NOT_FOUND, `Market not found: ${slug}`);
45
+ }
46
+
47
+ try {
48
+ const clobMarket = await this.clobApi.getMarket(gammaMarket.conditionId);
49
+ return this.mergeMarkets(gammaMarket, clobMarket);
50
+ } catch {
51
+ return this.fromGammaMarket(gammaMarket);
52
+ }
53
+ }
54
+
55
+ private async getMarketByConditionId(conditionId: string): Promise<UnifiedMarket> {
56
+ // Try to get data from both sources for best accuracy
57
+ let clobMarket: ClobMarket | null = null;
58
+ let gammaMarket: GammaMarket | null = null;
59
+
60
+ // Try CLOB first (authoritative for trading data)
61
+ try {
62
+ clobMarket = await this.clobApi.getMarket(conditionId);
63
+ } catch {
64
+ // CLOB failed, continue to try Gamma
65
+ }
66
+
67
+ // Always try Gamma for accurate slug and metadata
68
+ try {
69
+ gammaMarket = await this.gammaApi.getMarketByConditionId(conditionId);
70
+ } catch {
71
+ // Gamma failed
72
+ }
73
+
74
+ // Merge if both available (preferred)
75
+ if (gammaMarket && clobMarket) {
76
+ return this.mergeMarkets(gammaMarket, clobMarket);
77
+ }
78
+
79
+ // Gamma only - still useful for metadata
80
+ if (gammaMarket) {
81
+ return this.fromGammaMarket(gammaMarket);
82
+ }
83
+
84
+ // CLOB only - slug might be stale, add warning
85
+ if (clobMarket) {
86
+ const market = this.fromClobMarket(clobMarket);
87
+ // Check if CLOB slug looks stale (doesn't match question keywords)
88
+ const questionWords = clobMarket.question.toLowerCase().split(/\s+/).slice(0, 3);
89
+ const slugWords = clobMarket.marketSlug.toLowerCase().split('-');
90
+ const hasMatchingWord = questionWords.some(qw =>
91
+ slugWords.some(sw => sw.includes(qw) || qw.includes(sw))
92
+ );
93
+ if (!hasMatchingWord && clobMarket.marketSlug.length > 0) {
94
+ // Slug appears stale, use conditionId as fallback identifier
95
+ market.slug = `market-${conditionId.slice(0, 10)}`;
96
+ }
97
+ return market;
98
+ }
99
+
100
+ throw new PolymarketError(ErrorCode.MARKET_NOT_FOUND, `Market not found: ${conditionId}`);
101
+ }
102
+
103
+ // ===== K-Line Aggregation =====
104
+
105
+ /**
106
+ * Get K-Line candles for a market (single token)
107
+ */
108
+ async getKLines(
109
+ conditionId: string,
110
+ interval: KLineInterval,
111
+ options?: { limit?: number; tokenId?: string; outcomeIndex?: number }
112
+ ): Promise<KLineCandle[]> {
113
+ const trades = await this.dataApi.getTradesByMarket(conditionId, options?.limit || 1000);
114
+
115
+ // Filter by token/outcome if specified
116
+ let filteredTrades = trades;
117
+ if (options?.tokenId) {
118
+ filteredTrades = trades.filter((t) => t.asset === options.tokenId);
119
+ } else if (options?.outcomeIndex !== undefined) {
120
+ filteredTrades = trades.filter((t) => t.outcomeIndex === options.outcomeIndex);
121
+ }
122
+
123
+ return this.aggregateToKLines(filteredTrades, interval);
124
+ }
125
+
126
+ /**
127
+ * Get dual K-Lines (YES + NO tokens)
128
+ */
129
+ async getDualKLines(
130
+ conditionId: string,
131
+ interval: KLineInterval,
132
+ options?: { limit?: number }
133
+ ): Promise<DualKLineData> {
134
+ const market = await this.getMarket(conditionId);
135
+ const trades = await this.dataApi.getTradesByMarket(conditionId, options?.limit || 1000);
136
+
137
+ // Separate trades by outcome
138
+ const yesTrades = trades.filter((t) => t.outcomeIndex === 0 || t.outcome === 'Yes');
139
+ const noTrades = trades.filter((t) => t.outcomeIndex === 1 || t.outcome === 'No');
140
+
141
+ const yesCandles = this.aggregateToKLines(yesTrades, interval);
142
+ const noCandles = this.aggregateToKLines(noTrades, interval);
143
+
144
+ // Get current orderbook for real-time spread analysis
145
+ let currentOrderbook: ProcessedOrderbook | undefined;
146
+ let realtimeSpread: RealtimeSpreadAnalysis | undefined;
147
+ try {
148
+ currentOrderbook = await this.clobApi.getProcessedOrderbook(conditionId);
149
+ realtimeSpread = this.calculateRealtimeSpread(currentOrderbook);
150
+ } catch {
151
+ // Orderbook not available
152
+ }
153
+
154
+ // Calculate historical spread from trade close prices (for backtesting)
155
+ const spreadAnalysis = this.analyzeHistoricalSpread(yesCandles, noCandles);
156
+
157
+ return {
158
+ conditionId,
159
+ interval,
160
+ market,
161
+ yes: yesCandles,
162
+ no: noCandles,
163
+ spreadAnalysis, // Historical (trade-based)
164
+ realtimeSpread, // Real-time (orderbook-based)
165
+ currentOrderbook,
166
+ };
167
+ }
168
+
169
+ /**
170
+ * Aggregate trades into K-Line candles
171
+ */
172
+ private aggregateToKLines(trades: Trade[], interval: KLineInterval): KLineCandle[] {
173
+ const intervalMs = getIntervalMs(interval);
174
+ const buckets = new Map<number, Trade[]>();
175
+
176
+ // Group trades into time buckets
177
+ for (const trade of trades) {
178
+ const bucketTime = Math.floor(trade.timestamp / intervalMs) * intervalMs;
179
+ const bucket = buckets.get(bucketTime) || [];
180
+ bucket.push(trade);
181
+ buckets.set(bucketTime, bucket);
182
+ }
183
+
184
+ // Convert buckets to candles
185
+ const candles: KLineCandle[] = [];
186
+ for (const [timestamp, bucketTrades] of buckets) {
187
+ if (bucketTrades.length === 0) continue;
188
+
189
+ // Sort by timestamp for correct open/close
190
+ bucketTrades.sort((a, b) => a.timestamp - b.timestamp);
191
+
192
+ const prices = bucketTrades.map((t) => t.price);
193
+ const buyTrades = bucketTrades.filter((t) => t.side === 'BUY');
194
+ const sellTrades = bucketTrades.filter((t) => t.side === 'SELL');
195
+
196
+ candles.push({
197
+ timestamp,
198
+ open: bucketTrades[0].price,
199
+ high: Math.max(...prices),
200
+ low: Math.min(...prices),
201
+ close: bucketTrades[bucketTrades.length - 1].price,
202
+ volume: bucketTrades.reduce((sum, t) => sum + t.size * t.price, 0),
203
+ tradeCount: bucketTrades.length,
204
+ buyVolume: buyTrades.reduce((sum, t) => sum + t.size * t.price, 0),
205
+ sellVolume: sellTrades.reduce((sum, t) => sum + t.size * t.price, 0),
206
+ });
207
+ }
208
+
209
+ return candles.sort((a, b) => a.timestamp - b.timestamp);
210
+ }
211
+
212
+ /**
213
+ * Analyze historical spread from trade close prices (for backtesting)
214
+ *
215
+ * This uses trade close prices, not orderbook bid/ask.
216
+ * Useful for:
217
+ * - Historical analysis / backtesting
218
+ * - Understanding past price movements
219
+ * - Identifying patterns when orderbook data unavailable
220
+ */
221
+ private analyzeHistoricalSpread(
222
+ yesCandles: KLineCandle[],
223
+ noCandles: KLineCandle[]
224
+ ): SpreadDataPoint[] {
225
+ const yesMap = new Map(yesCandles.map((c) => [c.timestamp, c]));
226
+ const noMap = new Map(noCandles.map((c) => [c.timestamp, c]));
227
+
228
+ const allTimestamps = [...new Set([...yesMap.keys(), ...noMap.keys()])].sort();
229
+
230
+ let lastYes = 0.5;
231
+ let lastNo = 0.5;
232
+ const analysis: SpreadDataPoint[] = [];
233
+
234
+ for (const ts of allTimestamps) {
235
+ const yesCandle = yesMap.get(ts);
236
+ const noCandle = noMap.get(ts);
237
+
238
+ if (yesCandle) lastYes = yesCandle.close;
239
+ if (noCandle) lastNo = noCandle.close;
240
+
241
+ const priceSum = lastYes + lastNo;
242
+ const priceSpread = priceSum - 1;
243
+
244
+ // Determine arb opportunity based on price deviation
245
+ // Note: This is indicative only - actual arb requires orderbook analysis
246
+ let arbOpportunity: 'LONG' | 'SHORT' | '' = '';
247
+ if (priceSpread < -0.005) arbOpportunity = 'LONG'; // Sum < 0.995
248
+ else if (priceSpread > 0.005) arbOpportunity = 'SHORT'; // Sum > 1.005
249
+
250
+ analysis.push({
251
+ timestamp: ts,
252
+ yesPrice: lastYes,
253
+ noPrice: lastNo,
254
+ priceSum,
255
+ priceSpread,
256
+ arbOpportunity,
257
+ });
258
+ }
259
+
260
+ return analysis;
261
+ }
262
+
263
+ /**
264
+ * Calculate real-time spread from orderbook (for live trading)
265
+ *
266
+ * This uses orderbook bid/ask prices for accurate arbitrage detection.
267
+ * Useful for:
268
+ * - Real-time arbitrage execution
269
+ * - Live trading decisions
270
+ * - Accurate profit calculations
271
+ */
272
+ private calculateRealtimeSpread(orderbook: ProcessedOrderbook): RealtimeSpreadAnalysis {
273
+ const { yes, no, summary } = orderbook;
274
+
275
+ // Determine arbitrage opportunity
276
+ let arbOpportunity: 'LONG' | 'SHORT' | '' = '';
277
+ let arbProfitPercent = 0;
278
+
279
+ if (summary.longArbProfit > 0.001) { // > 0.1% threshold
280
+ arbOpportunity = 'LONG';
281
+ arbProfitPercent = summary.longArbProfit * 100;
282
+ } else if (summary.shortArbProfit > 0.001) { // > 0.1% threshold
283
+ arbOpportunity = 'SHORT';
284
+ arbProfitPercent = summary.shortArbProfit * 100;
285
+ }
286
+
287
+ return {
288
+ timestamp: Date.now(),
289
+ // Orderbook prices
290
+ yesBid: yes.bid,
291
+ yesAsk: yes.ask,
292
+ noBid: no.bid,
293
+ noAsk: no.ask,
294
+ // Spread metrics
295
+ askSum: summary.askSum,
296
+ bidSum: summary.bidSum,
297
+ askSpread: summary.askSum - 1,
298
+ bidSpread: summary.bidSum - 1,
299
+ // Arbitrage
300
+ longArbProfit: summary.longArbProfit,
301
+ shortArbProfit: summary.shortArbProfit,
302
+ arbOpportunity,
303
+ arbProfitPercent,
304
+ };
305
+ }
306
+
307
+ /**
308
+ * Get real-time spread analysis only (without K-lines)
309
+ * Use this for quick arbitrage checks
310
+ */
311
+ async getRealtimeSpread(conditionId: string): Promise<RealtimeSpreadAnalysis> {
312
+ const orderbook = await this.clobApi.getProcessedOrderbook(conditionId);
313
+ return this.calculateRealtimeSpread(orderbook);
314
+ }
315
+
316
+ // ===== Orderbook Analysis =====
317
+
318
+ /**
319
+ * Get processed orderbook with analytics
320
+ */
321
+ async getOrderbook(conditionId: string): Promise<ProcessedOrderbook> {
322
+ return this.clobApi.getProcessedOrderbook(conditionId);
323
+ }
324
+
325
+ /**
326
+ * Detect arbitrage opportunity
327
+ *
328
+ * 使用有效价格(考虑镜像订单)计算套利机会
329
+ * 详细原理见: docs/01-polymarket-orderbook-arbitrage.md
330
+ */
331
+ async detectArbitrage(conditionId: string, threshold = 0.005): Promise<ArbitrageOpportunity | null> {
332
+ const orderbook = await this.getOrderbook(conditionId);
333
+ const { effectivePrices } = orderbook.summary;
334
+
335
+ if (orderbook.summary.longArbProfit > threshold) {
336
+ return {
337
+ type: 'long',
338
+ profit: orderbook.summary.longArbProfit,
339
+ // 使用有效价格描述实际操作
340
+ action: `Buy YES @ ${effectivePrices.effectiveBuyYes.toFixed(4)} + NO @ ${effectivePrices.effectiveBuyNo.toFixed(4)}, Merge for $1`,
341
+ expectedProfit: orderbook.summary.longArbProfit,
342
+ };
343
+ }
344
+
345
+ if (orderbook.summary.shortArbProfit > threshold) {
346
+ return {
347
+ type: 'short',
348
+ profit: orderbook.summary.shortArbProfit,
349
+ // 使用有效价格描述实际操作
350
+ action: `Split $1, Sell YES @ ${effectivePrices.effectiveSellYes.toFixed(4)} + NO @ ${effectivePrices.effectiveSellNo.toFixed(4)}`,
351
+ expectedProfit: orderbook.summary.shortArbProfit,
352
+ };
353
+ }
354
+
355
+ return null;
356
+ }
357
+
358
+ // ===== Market Discovery =====
359
+
360
+ /**
361
+ * Get trending markets
362
+ */
363
+ async getTrendingMarkets(limit = 20): Promise<GammaMarket[]> {
364
+ return this.gammaApi.getTrendingMarkets(limit);
365
+ }
366
+
367
+ /**
368
+ * Search markets
369
+ */
370
+ async searchMarkets(params: {
371
+ active?: boolean;
372
+ closed?: boolean;
373
+ limit?: number;
374
+ offset?: number;
375
+ order?: string;
376
+ }): Promise<GammaMarket[]> {
377
+ return this.gammaApi.getMarkets(params);
378
+ }
379
+
380
+ // ===== Market Signal Detection =====
381
+
382
+ /**
383
+ * Detect market signals (volume surge, depth imbalance, whale trades)
384
+ */
385
+ async detectMarketSignals(conditionId: string): Promise<
386
+ Array<{
387
+ type: 'volume_surge' | 'depth_imbalance' | 'whale_trade' | 'momentum';
388
+ severity: 'low' | 'medium' | 'high';
389
+ details: Record<string, unknown>;
390
+ }>
391
+ > {
392
+ const signals: Array<{
393
+ type: 'volume_surge' | 'depth_imbalance' | 'whale_trade' | 'momentum';
394
+ severity: 'low' | 'medium' | 'high';
395
+ details: Record<string, unknown>;
396
+ }> = [];
397
+
398
+ const market = await this.getMarket(conditionId);
399
+ const orderbook = await this.getOrderbook(conditionId);
400
+ const trades = await this.dataApi.getTradesByMarket(conditionId, 100);
401
+
402
+ // Volume surge detection
403
+ if (market.volume24hr && market.volume > 0) {
404
+ const avgDaily = market.volume / 7; // Approximate
405
+ const ratio = market.volume24hr / avgDaily;
406
+ if (ratio > 2) {
407
+ signals.push({
408
+ type: 'volume_surge',
409
+ severity: ratio > 5 ? 'high' : ratio > 3 ? 'medium' : 'low',
410
+ details: { volume24hr: market.volume24hr, avgDaily, ratio },
411
+ });
412
+ }
413
+ }
414
+
415
+ // Depth imbalance detection
416
+ if (orderbook.summary.imbalanceRatio > 1.5 || orderbook.summary.imbalanceRatio < 0.67) {
417
+ const ratio = orderbook.summary.imbalanceRatio;
418
+ signals.push({
419
+ type: 'depth_imbalance',
420
+ severity: ratio > 3 || ratio < 0.33 ? 'high' : 'medium',
421
+ details: {
422
+ imbalanceRatio: ratio,
423
+ bidDepth: orderbook.summary.totalBidDepth,
424
+ askDepth: orderbook.summary.totalAskDepth,
425
+ direction: ratio > 1 ? 'BUY_PRESSURE' : 'SELL_PRESSURE',
426
+ },
427
+ });
428
+ }
429
+
430
+ // Whale trade detection
431
+ const recentLargeTrades = trades.filter((t) => t.size * t.price > 1000);
432
+ for (const trade of recentLargeTrades.slice(0, 3)) {
433
+ const value = trade.size * trade.price;
434
+ signals.push({
435
+ type: 'whale_trade',
436
+ severity: value > 10000 ? 'high' : value > 5000 ? 'medium' : 'low',
437
+ details: {
438
+ size: trade.size,
439
+ price: trade.price,
440
+ usdValue: value,
441
+ side: trade.side,
442
+ outcome: trade.outcome,
443
+ },
444
+ });
445
+ }
446
+
447
+ return signals;
448
+ }
449
+
450
+ // ===== Helper Methods =====
451
+
452
+ private mergeMarkets(gamma: GammaMarket, clob: ClobMarket): UnifiedMarket {
453
+ const yesToken = clob.tokens.find((t) => t.outcome === 'Yes');
454
+ const noToken = clob.tokens.find((t) => t.outcome === 'No');
455
+
456
+ return {
457
+ conditionId: clob.conditionId,
458
+ slug: gamma.slug,
459
+ question: clob.question,
460
+ description: clob.description || gamma.description,
461
+ tokens: {
462
+ yes: { tokenId: yesToken?.tokenId || '', price: yesToken?.price || gamma.outcomePrices[0] || 0.5 },
463
+ no: { tokenId: noToken?.tokenId || '', price: noToken?.price || gamma.outcomePrices[1] || 0.5 },
464
+ },
465
+ volume: gamma.volume,
466
+ volume24hr: gamma.volume24hr,
467
+ liquidity: gamma.liquidity,
468
+ spread: gamma.spread,
469
+ oneDayPriceChange: gamma.oneDayPriceChange,
470
+ oneWeekPriceChange: gamma.oneWeekPriceChange,
471
+ active: clob.active,
472
+ closed: clob.closed,
473
+ acceptingOrders: clob.acceptingOrders,
474
+ endDate: clob.endDateIso ? new Date(clob.endDateIso) : new Date(),
475
+ source: 'merged',
476
+ };
477
+ }
478
+
479
+ private fromGammaMarket(gamma: GammaMarket): UnifiedMarket {
480
+ return {
481
+ conditionId: gamma.conditionId,
482
+ slug: gamma.slug,
483
+ question: gamma.question,
484
+ description: gamma.description,
485
+ tokens: {
486
+ yes: { tokenId: '', price: gamma.outcomePrices[0] || 0.5 },
487
+ no: { tokenId: '', price: gamma.outcomePrices[1] || 0.5 },
488
+ },
489
+ volume: gamma.volume,
490
+ volume24hr: gamma.volume24hr,
491
+ liquidity: gamma.liquidity,
492
+ spread: gamma.spread,
493
+ oneDayPriceChange: gamma.oneDayPriceChange,
494
+ oneWeekPriceChange: gamma.oneWeekPriceChange,
495
+ active: gamma.active,
496
+ closed: gamma.closed,
497
+ acceptingOrders: !gamma.closed,
498
+ endDate: gamma.endDate,
499
+ source: 'gamma',
500
+ };
501
+ }
502
+
503
+ private fromClobMarket(clob: ClobMarket): UnifiedMarket {
504
+ const yesToken = clob.tokens.find((t) => t.outcome === 'Yes');
505
+ const noToken = clob.tokens.find((t) => t.outcome === 'No');
506
+
507
+ return {
508
+ conditionId: clob.conditionId,
509
+ slug: clob.marketSlug,
510
+ question: clob.question,
511
+ description: clob.description,
512
+ tokens: {
513
+ yes: { tokenId: yesToken?.tokenId || '', price: yesToken?.price || 0.5 },
514
+ no: { tokenId: noToken?.tokenId || '', price: noToken?.price || 0.5 },
515
+ },
516
+ volume: 0,
517
+ volume24hr: undefined,
518
+ liquidity: 0,
519
+ spread: undefined,
520
+ active: clob.active,
521
+ closed: clob.closed,
522
+ acceptingOrders: clob.acceptingOrders,
523
+ endDate: clob.endDateIso ? new Date(clob.endDateIso) : new Date(),
524
+ source: 'clob',
525
+ };
526
+ }
527
+ }
528
+
529
+ // ===== Utility Functions =====
530
+
531
+ export function getIntervalMs(interval: KLineInterval): number {
532
+ const map: Record<KLineInterval, number> = {
533
+ '30s': 30 * 1000,
534
+ '1m': 60 * 1000,
535
+ '5m': 5 * 60 * 1000,
536
+ '15m': 15 * 60 * 1000,
537
+ '30m': 30 * 60 * 1000,
538
+ '1h': 60 * 60 * 1000,
539
+ '4h': 4 * 60 * 60 * 1000,
540
+ '12h': 12 * 60 * 60 * 1000,
541
+ '1d': 24 * 60 * 60 * 1000,
542
+ };
543
+ return map[interval];
544
+ }