@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,259 @@
1
+ /**
2
+ * Wallet Service
3
+ *
4
+ * Provides smart money analysis features:
5
+ * - Wallet profile analysis
6
+ * - Position tracking
7
+ * - Activity monitoring
8
+ * - Sell detection for follow wallet strategy
9
+ */
10
+
11
+ import { DataApiClient, Position, Activity, LeaderboardEntry, LeaderboardPage } from '../clients/data-api.js';
12
+ import type { UnifiedCache } from '../core/unified-cache.js';
13
+ import { CACHE_TTL } from '../core/unified-cache.js';
14
+
15
+ export interface WalletProfile {
16
+ address: string;
17
+ totalPnL: number;
18
+ realizedPnL: number;
19
+ unrealizedPnL: number;
20
+ avgPercentPnL: number;
21
+ positionCount: number;
22
+ tradeCount: number;
23
+ smartScore: number; // 0-100
24
+ lastActiveAt: Date;
25
+ }
26
+
27
+ export interface WalletActivitySummary {
28
+ address: string;
29
+ activities: Activity[];
30
+ summary: {
31
+ totalBuys: number;
32
+ totalSells: number;
33
+ buyVolume: number;
34
+ sellVolume: number;
35
+ activeMarkets: string[];
36
+ };
37
+ }
38
+
39
+ export interface SellActivityResult {
40
+ totalSellAmount: number;
41
+ sellTransactions: Activity[];
42
+ sellRatio: number;
43
+ shouldExit: boolean;
44
+ }
45
+
46
+ export class WalletService {
47
+ constructor(
48
+ private dataApi: DataApiClient,
49
+ private cache: UnifiedCache
50
+ ) {}
51
+
52
+ // ===== Wallet Analysis =====
53
+
54
+ /**
55
+ * Get comprehensive wallet profile with PnL analysis
56
+ */
57
+ async getWalletProfile(address: string): Promise<WalletProfile> {
58
+ const [positions, activities] = await Promise.all([
59
+ this.dataApi.getPositions(address),
60
+ this.dataApi.getActivity(address, { limit: 100 }),
61
+ ]);
62
+
63
+ const totalPnL = positions.reduce((sum, p) => sum + (p.cashPnl || 0), 0);
64
+ const realizedPnL = positions.reduce((sum, p) => sum + (p.realizedPnl || 0), 0);
65
+ const unrealizedPnL = totalPnL - realizedPnL;
66
+
67
+ const avgPercentPnL =
68
+ positions.length > 0
69
+ ? positions.reduce((sum, p) => sum + (p.percentPnl || 0), 0) / positions.length
70
+ : 0;
71
+
72
+ const lastActivity = activities[0];
73
+
74
+ return {
75
+ address,
76
+ totalPnL,
77
+ realizedPnL,
78
+ unrealizedPnL,
79
+ avgPercentPnL,
80
+ positionCount: positions.length,
81
+ tradeCount: activities.filter((a) => a.type === 'TRADE').length,
82
+ smartScore: this.calculateSmartScore(positions, activities),
83
+ lastActiveAt: lastActivity ? new Date(lastActivity.timestamp) : new Date(0),
84
+ };
85
+ }
86
+
87
+ /**
88
+ * Get positions for a wallet
89
+ */
90
+ async getWalletPositions(address: string): Promise<Position[]> {
91
+ return this.dataApi.getPositions(address);
92
+ }
93
+
94
+ /**
95
+ * Get positions for a specific market
96
+ */
97
+ async getPositionsForMarket(address: string, conditionId: string): Promise<Position[]> {
98
+ const positions = await this.dataApi.getPositions(address);
99
+ return positions.filter((p) => p.conditionId === conditionId);
100
+ }
101
+
102
+ /**
103
+ * Get wallet activity with summary
104
+ */
105
+ async getWalletActivity(address: string, limit = 100): Promise<WalletActivitySummary> {
106
+ const activities = await this.dataApi.getActivity(address, { limit });
107
+
108
+ const buys = activities.filter((a) => a.side === 'BUY');
109
+ const sells = activities.filter((a) => a.side === 'SELL');
110
+
111
+ return {
112
+ address,
113
+ activities,
114
+ summary: {
115
+ totalBuys: buys.length,
116
+ totalSells: sells.length,
117
+ buyVolume: buys.reduce((sum, a) => sum + (a.usdcSize || 0), 0),
118
+ sellVolume: sells.reduce((sum, a) => sum + (a.usdcSize || 0), 0),
119
+ activeMarkets: [...new Set(activities.map((a) => a.conditionId))],
120
+ },
121
+ };
122
+ }
123
+
124
+ // ===== Wallet Discovery =====
125
+
126
+ /**
127
+ * Get leaderboard
128
+ */
129
+ async getLeaderboard(page = 0, pageSize = 50): Promise<LeaderboardPage> {
130
+ return this.dataApi.getLeaderboard({ limit: pageSize, offset: page * pageSize });
131
+ }
132
+
133
+ /**
134
+ * Get top traders from leaderboard
135
+ */
136
+ async getTopTraders(limit = 10): Promise<LeaderboardEntry[]> {
137
+ const leaderboard = await this.dataApi.getLeaderboard({ limit });
138
+ return leaderboard.entries;
139
+ }
140
+
141
+ /**
142
+ * Discover active wallets from recent trades
143
+ */
144
+ async discoverActiveWallets(limit = 100): Promise<Array<{ address: string; tradeCount: number }>> {
145
+ const trades = await this.dataApi.getTrades({ limit: 1000 });
146
+
147
+ // Count trades per wallet
148
+ const walletCounts = new Map<string, number>();
149
+ for (const trade of trades) {
150
+ if (trade.proxyWallet) {
151
+ walletCounts.set(trade.proxyWallet, (walletCounts.get(trade.proxyWallet) || 0) + 1);
152
+ }
153
+ }
154
+
155
+ // Sort by trade count
156
+ return [...walletCounts.entries()]
157
+ .sort((a, b) => b[1] - a[1])
158
+ .slice(0, limit)
159
+ .map(([address, tradeCount]) => ({ address, tradeCount }));
160
+ }
161
+
162
+ // ===== Sell Detection (Follow Wallet Strategy) =====
163
+
164
+ /**
165
+ * Detect sell activity for a wallet in a specific market
166
+ */
167
+ async detectSellActivity(
168
+ address: string,
169
+ conditionId: string,
170
+ sinceTimestamp: number,
171
+ peakValue?: number
172
+ ): Promise<SellActivityResult> {
173
+ const activities = await this.dataApi.getActivity(address, { limit: 200, type: 'TRADE' });
174
+
175
+ const sellTransactions = activities.filter(
176
+ (a) => a.conditionId === conditionId && a.side === 'SELL' && a.timestamp >= sinceTimestamp
177
+ );
178
+
179
+ const totalSellAmount = sellTransactions.reduce((sum, a) => sum + (a.usdcSize || a.size * a.price), 0);
180
+
181
+ // Calculate sell ratio if peak value is provided
182
+ const sellRatio = peakValue && peakValue > 0 ? totalSellAmount / peakValue : 0;
183
+
184
+ return {
185
+ totalSellAmount,
186
+ sellTransactions,
187
+ sellRatio,
188
+ shouldExit: sellRatio >= 0.3, // 30% threshold for exit signal
189
+ };
190
+ }
191
+
192
+ /**
193
+ * Track sell ratio for multiple wallets (aggregated)
194
+ */
195
+ async trackGroupSellRatio(
196
+ addresses: string[],
197
+ conditionId: string,
198
+ peakTotalValue: number,
199
+ sinceTimestamp: number
200
+ ): Promise<{
201
+ cumulativeSellAmount: number;
202
+ sellRatio: number;
203
+ shouldExit: boolean;
204
+ walletSells: Array<{ address: string; sellAmount: number }>;
205
+ }> {
206
+ const walletSells: Array<{ address: string; sellAmount: number }> = [];
207
+ let cumulativeSellAmount = 0;
208
+
209
+ for (const address of addresses) {
210
+ const sellData = await this.detectSellActivity(address, conditionId, sinceTimestamp);
211
+ walletSells.push({ address, sellAmount: sellData.totalSellAmount });
212
+ cumulativeSellAmount += sellData.totalSellAmount;
213
+ }
214
+
215
+ const sellRatio = peakTotalValue > 0 ? cumulativeSellAmount / peakTotalValue : 0;
216
+
217
+ return {
218
+ cumulativeSellAmount,
219
+ sellRatio,
220
+ shouldExit: sellRatio >= 0.3,
221
+ walletSells,
222
+ };
223
+ }
224
+
225
+ // ===== Smart Score Calculation =====
226
+
227
+ private calculateSmartScore(positions: Position[], activities: Activity[]): number {
228
+ // Weights: PnL 40%, Win Rate 30%, Consistency 20%, Activity 10%
229
+
230
+ // PnL Score (0-40)
231
+ const avgPnL =
232
+ positions.length > 0
233
+ ? positions.reduce((sum, p) => sum + (p.percentPnl || 0), 0) / positions.length
234
+ : 0;
235
+ const pnlScore = Math.min(40, Math.max(0, ((avgPnL + 50) / 100) * 40));
236
+
237
+ // Win Rate Score (0-30)
238
+ const winningPositions = positions.filter((p) => (p.cashPnl || 0) > 0).length;
239
+ const winRate = positions.length > 0 ? winningPositions / positions.length : 0;
240
+ const winRateScore = winRate * 30;
241
+
242
+ // Consistency Score (0-20)
243
+ const pnlValues = positions.map((p) => p.percentPnl || 0);
244
+ const variance = this.calculateVariance(pnlValues);
245
+ const consistencyScore = Math.max(0, 20 - variance / 10);
246
+
247
+ // Activity Score (0-10)
248
+ const recentTrades = activities.filter((a) => a.timestamp > Date.now() - 7 * 24 * 60 * 60 * 1000).length;
249
+ const activityScore = Math.min(10, (recentTrades / 5) * 10);
250
+
251
+ return Math.round(pnlScore + winRateScore + consistencyScore + activityScore);
252
+ }
253
+
254
+ private calculateVariance(values: number[]): number {
255
+ if (values.length === 0) return 0;
256
+ const mean = values.reduce((a, b) => a + b, 0) / values.length;
257
+ return values.reduce((sum, v) => sum + Math.pow(v - mean, 2), 0) / values.length;
258
+ }
259
+ }
@@ -0,0 +1,307 @@
1
+ /**
2
+ * Price Utilities for Polymarket Trading
3
+ *
4
+ * Provides helpers for:
5
+ * - Price validation and rounding to tick size
6
+ * - Size validation
7
+ * - Order amount calculation
8
+ */
9
+
10
+ // Tick size types (as defined by Polymarket)
11
+ export type TickSize = '0.1' | '0.01' | '0.001' | '0.0001';
12
+
13
+ // Rounding configuration for each tick size
14
+ export const ROUNDING_CONFIG: Record<
15
+ TickSize,
16
+ { price: number; size: number; amount: number }
17
+ > = {
18
+ '0.1': { price: 1, size: 2, amount: 2 },
19
+ '0.01': { price: 2, size: 2, amount: 4 },
20
+ '0.001': { price: 3, size: 2, amount: 5 },
21
+ '0.0001': { price: 4, size: 2, amount: 6 },
22
+ };
23
+
24
+ /**
25
+ * Round a price to the appropriate tick size
26
+ *
27
+ * @param price - The price to round (0 to 1)
28
+ * @param tickSize - The tick size for the market
29
+ * @param direction - 'floor' for sells, 'ceil' for buys, 'round' for midpoint
30
+ * @returns Rounded price
31
+ *
32
+ * @example
33
+ * roundPrice(0.523, '0.01', 'floor') // 0.52
34
+ * roundPrice(0.523, '0.01', 'ceil') // 0.53
35
+ */
36
+ export function roundPrice(
37
+ price: number,
38
+ tickSize: TickSize,
39
+ direction: 'floor' | 'ceil' | 'round' = 'round'
40
+ ): number {
41
+ const decimals = ROUNDING_CONFIG[tickSize].price;
42
+ const multiplier = Math.pow(10, decimals);
43
+
44
+ let rounded: number;
45
+ switch (direction) {
46
+ case 'floor':
47
+ rounded = Math.floor(price * multiplier) / multiplier;
48
+ break;
49
+ case 'ceil':
50
+ rounded = Math.ceil(price * multiplier) / multiplier;
51
+ break;
52
+ default:
53
+ rounded = Math.round(price * multiplier) / multiplier;
54
+ }
55
+
56
+ // Clamp to valid price range
57
+ return Math.max(0.001, Math.min(0.999, rounded));
58
+ }
59
+
60
+ /**
61
+ * Round a size to valid decimals (always 2 decimal places)
62
+ */
63
+ export function roundSize(size: number): number {
64
+ return Math.round(size * 100) / 100;
65
+ }
66
+
67
+ /**
68
+ * Validate a price is within valid range and tick size
69
+ *
70
+ * @param price - The price to validate
71
+ * @param tickSize - The tick size for the market
72
+ * @returns Validation result with error message if invalid
73
+ */
74
+ export function validatePrice(
75
+ price: number,
76
+ tickSize: TickSize
77
+ ): { valid: boolean; error?: string } {
78
+ // Check range
79
+ if (price < 0.001 || price > 0.999) {
80
+ return { valid: false, error: 'Price must be between 0.001 and 0.999' };
81
+ }
82
+
83
+ // Check tick size alignment
84
+ const decimals = ROUNDING_CONFIG[tickSize].price;
85
+ const multiplier = Math.pow(10, decimals);
86
+ const rounded = Math.round(price * multiplier) / multiplier;
87
+
88
+ if (Math.abs(price - rounded) > 1e-10) {
89
+ return {
90
+ valid: false,
91
+ error: `Price ${price} does not align with tick size ${tickSize}. Use ${rounded} instead.`,
92
+ };
93
+ }
94
+
95
+ return { valid: true };
96
+ }
97
+
98
+ /**
99
+ * Validate minimum size requirements
100
+ *
101
+ * @param size - The size to validate
102
+ * @param minOrderSize - Minimum order size from market config (usually 0.1)
103
+ */
104
+ export function validateSize(
105
+ size: number,
106
+ minOrderSize = 0.1
107
+ ): { valid: boolean; error?: string } {
108
+ if (size < minOrderSize) {
109
+ return {
110
+ valid: false,
111
+ error: `Size ${size} is below minimum order size ${minOrderSize}`,
112
+ };
113
+ }
114
+
115
+ return { valid: true };
116
+ }
117
+
118
+ /**
119
+ * Calculate the amount needed for a buy order (in USDC)
120
+ *
121
+ * @param price - Price per share
122
+ * @param size - Number of shares to buy
123
+ * @returns Amount in USDC
124
+ */
125
+ export function calculateBuyAmount(price: number, size: number): number {
126
+ return price * size;
127
+ }
128
+
129
+ /**
130
+ * Calculate the payout for a sell order (in USDC)
131
+ *
132
+ * @param price - Price per share
133
+ * @param size - Number of shares to sell
134
+ * @returns Amount in USDC
135
+ */
136
+ export function calculateSellPayout(price: number, size: number): number {
137
+ return price * size;
138
+ }
139
+
140
+ /**
141
+ * Calculate number of shares that can be bought with a given amount
142
+ *
143
+ * @param amount - USDC amount to spend
144
+ * @param price - Price per share
145
+ * @returns Number of shares
146
+ */
147
+ export function calculateSharesForAmount(
148
+ amount: number,
149
+ price: number
150
+ ): number {
151
+ return roundSize(amount / price);
152
+ }
153
+
154
+ /**
155
+ * Calculate the spread between bid and ask
156
+ *
157
+ * @param bid - Highest bid price
158
+ * @param ask - Lowest ask price
159
+ * @returns Spread as a decimal (0 to 1)
160
+ */
161
+ export function calculateSpread(bid: number, ask: number): number {
162
+ return ask - bid;
163
+ }
164
+
165
+ /**
166
+ * Calculate the midpoint price between bid and ask
167
+ *
168
+ * @param bid - Highest bid price
169
+ * @param ask - Lowest ask price
170
+ * @returns Midpoint price
171
+ */
172
+ export function calculateMidpoint(bid: number, ask: number): number {
173
+ return (bid + ask) / 2;
174
+ }
175
+
176
+ /**
177
+ * 计算有效价格(考虑 Polymarket 订单簿的镜像特性)
178
+ *
179
+ * Polymarket 的关键特性:买 YES @ P = 卖 NO @ (1-P)
180
+ * 因此同一订单会在两个订单簿中出现
181
+ *
182
+ * 有效价格是考虑镜像后的最优价格
183
+ *
184
+ * @param yesAsk - YES token 的最低卖价
185
+ * @param yesBid - YES token 的最高买价
186
+ * @param noAsk - NO token 的最低卖价
187
+ * @param noBid - NO token 的最高买价
188
+ */
189
+ export function getEffectivePrices(
190
+ yesAsk: number,
191
+ yesBid: number,
192
+ noAsk: number,
193
+ noBid: number
194
+ ): {
195
+ effectiveBuyYes: number;
196
+ effectiveBuyNo: number;
197
+ effectiveSellYes: number;
198
+ effectiveSellNo: number;
199
+ } {
200
+ return {
201
+ // 买 YES: 直接买 YES.ask 或 通过卖 NO (成本 = 1 - NO.bid)
202
+ effectiveBuyYes: Math.min(yesAsk, 1 - noBid),
203
+
204
+ // 买 NO: 直接买 NO.ask 或 通过卖 YES (成本 = 1 - YES.bid)
205
+ effectiveBuyNo: Math.min(noAsk, 1 - yesBid),
206
+
207
+ // 卖 YES: 直接卖 YES.bid 或 通过买 NO (收入 = 1 - NO.ask)
208
+ effectiveSellYes: Math.max(yesBid, 1 - noAsk),
209
+
210
+ // 卖 NO: 直接卖 NO.bid 或 通过买 YES (收入 = 1 - YES.ask)
211
+ effectiveSellNo: Math.max(noBid, 1 - yesAsk),
212
+ };
213
+ }
214
+
215
+ /**
216
+ * Check if there's an arbitrage opportunity
217
+ *
218
+ * 使用有效价格计算套利机会(正确考虑镜像订单)
219
+ *
220
+ * Long arb: Buy YES + Buy NO < 1 (使用有效买入价格)
221
+ * Short arb: Sell YES + Sell NO > 1 (使用有效卖出价格)
222
+ *
223
+ * 详细文档见: docs/01-polymarket-orderbook-arbitrage.md
224
+ *
225
+ * @param yesAsk - Lowest ask for YES token
226
+ * @param noAsk - Lowest ask for NO token
227
+ * @param yesBid - Highest bid for YES token
228
+ * @param noBid - Highest bid for NO token
229
+ * @returns Arbitrage info or null
230
+ */
231
+ export function checkArbitrage(
232
+ yesAsk: number,
233
+ noAsk: number,
234
+ yesBid: number,
235
+ noBid: number
236
+ ): { type: 'long' | 'short'; profit: number; description: string } | null {
237
+ // 计算有效价格
238
+ const effective = getEffectivePrices(yesAsk, yesBid, noAsk, noBid);
239
+
240
+ // Long arbitrage: Buy complete set (YES + NO) cheaper than $1
241
+ const effectiveLongCost = effective.effectiveBuyYes + effective.effectiveBuyNo;
242
+ const longProfit = 1 - effectiveLongCost;
243
+
244
+ if (longProfit > 0) {
245
+ return {
246
+ type: 'long',
247
+ profit: longProfit,
248
+ description: `Buy YES @ ${effective.effectiveBuyYes.toFixed(4)} + NO @ ${effective.effectiveBuyNo.toFixed(4)}, Merge for $1`,
249
+ };
250
+ }
251
+
252
+ // Short arbitrage: Sell complete set (YES + NO) for more than $1
253
+ const effectiveShortRevenue = effective.effectiveSellYes + effective.effectiveSellNo;
254
+ const shortProfit = effectiveShortRevenue - 1;
255
+
256
+ if (shortProfit > 0) {
257
+ return {
258
+ type: 'short',
259
+ profit: shortProfit,
260
+ description: `Split $1, Sell YES @ ${effective.effectiveSellYes.toFixed(4)} + NO @ ${effective.effectiveSellNo.toFixed(4)}`,
261
+ };
262
+ }
263
+
264
+ return null;
265
+ }
266
+
267
+ /**
268
+ * Format price for display
269
+ */
270
+ export function formatPrice(price: number, tickSize?: TickSize): string {
271
+ const decimals = tickSize ? ROUNDING_CONFIG[tickSize].price : 4;
272
+ return price.toFixed(decimals);
273
+ }
274
+
275
+ /**
276
+ * Format amount in USDC
277
+ */
278
+ export function formatUSDC(amount: number): string {
279
+ return `$${amount.toFixed(2)}`;
280
+ }
281
+
282
+ /**
283
+ * Calculate PnL for a position
284
+ *
285
+ * @param entryPrice - Average entry price
286
+ * @param currentPrice - Current market price
287
+ * @param size - Position size
288
+ * @param side - 'long' for YES, 'short' for NO
289
+ */
290
+ export function calculatePnL(
291
+ entryPrice: number,
292
+ currentPrice: number,
293
+ size: number,
294
+ side: 'long' | 'short' = 'long'
295
+ ): { pnl: number; pnlPercent: number } {
296
+ const pnl =
297
+ side === 'long'
298
+ ? (currentPrice - entryPrice) * size
299
+ : (entryPrice - currentPrice) * size;
300
+
301
+ const pnlPercent =
302
+ side === 'long'
303
+ ? ((currentPrice - entryPrice) / entryPrice) * 100
304
+ : ((entryPrice - currentPrice) / entryPrice) * 100;
305
+
306
+ return { pnl, pnlPercent };
307
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "outDir": "./dist",
5
+ "rootDir": "./src"
6
+ },
7
+ "include": ["src/**/*"]
8
+ }
@@ -0,0 +1,19 @@
1
+ import { defineConfig } from 'vitest/config';
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ globals: true,
6
+ environment: 'node',
7
+ // Default: run only unit tests
8
+ include: ['src/**/*.test.ts'],
9
+ exclude: ['src/__tests__/integration/**'],
10
+ coverage: {
11
+ provider: 'v8',
12
+ reporter: ['text', 'json', 'html'],
13
+ include: ['src/**/*.ts'],
14
+ exclude: ['src/**/*.test.ts', 'src/__tests__/**'],
15
+ },
16
+ // Longer timeout for integration tests
17
+ testTimeout: 30000,
18
+ },
19
+ });
@@ -0,0 +1,18 @@
1
+ import { defineConfig } from 'vitest/config';
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ globals: true,
6
+ environment: 'node',
7
+ // Run only integration tests
8
+ include: ['src/__tests__/integration/**/*.test.ts'],
9
+ coverage: {
10
+ provider: 'v8',
11
+ reporter: ['text', 'json', 'html'],
12
+ include: ['src/**/*.ts'],
13
+ exclude: ['src/**/*.test.ts', 'src/__tests__/**'],
14
+ },
15
+ // Longer timeout for integration tests (real API calls)
16
+ testTimeout: 60000,
17
+ },
18
+ });