@catalyst-team/poly-sdk 0.2.0 → 0.2.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 (197) hide show
  1. package/LICENSE +1 -1
  2. package/README.en.md +8 -44
  3. package/README.md +5 -3
  4. package/README.zh-CN.md +502 -0
  5. package/dist/__tests__/clob-api.test.d.ts +5 -0
  6. package/dist/__tests__/clob-api.test.d.ts.map +1 -0
  7. package/dist/__tests__/clob-api.test.js +240 -0
  8. package/dist/__tests__/clob-api.test.js.map +1 -0
  9. package/dist/__tests__/integration/bridge-client.integration.test.d.ts +11 -0
  10. package/dist/__tests__/integration/bridge-client.integration.test.d.ts.map +1 -0
  11. package/dist/__tests__/integration/bridge-client.integration.test.js +260 -0
  12. package/dist/__tests__/integration/bridge-client.integration.test.js.map +1 -0
  13. package/dist/__tests__/integration/clob-api.integration.test.d.ts +13 -0
  14. package/dist/__tests__/integration/clob-api.integration.test.d.ts.map +1 -0
  15. package/dist/__tests__/integration/clob-api.integration.test.js +170 -0
  16. package/dist/__tests__/integration/clob-api.integration.test.js.map +1 -0
  17. package/dist/__tests__/integration/ctf-client.integration.test.d.ts +17 -0
  18. package/dist/__tests__/integration/ctf-client.integration.test.d.ts.map +1 -0
  19. package/dist/__tests__/integration/ctf-client.integration.test.js +234 -0
  20. package/dist/__tests__/integration/ctf-client.integration.test.js.map +1 -0
  21. package/dist/__tests__/integration/data-api.integration.test.d.ts +9 -0
  22. package/dist/__tests__/integration/data-api.integration.test.d.ts.map +1 -0
  23. package/dist/__tests__/integration/data-api.integration.test.js +161 -0
  24. package/dist/__tests__/integration/data-api.integration.test.js.map +1 -0
  25. package/dist/__tests__/integration/gamma-api.integration.test.d.ts +9 -0
  26. package/dist/__tests__/integration/gamma-api.integration.test.d.ts.map +1 -0
  27. package/dist/__tests__/integration/gamma-api.integration.test.js +170 -0
  28. package/dist/__tests__/integration/gamma-api.integration.test.js.map +1 -0
  29. package/dist/__tests__/test-utils.d.ts +92 -0
  30. package/dist/__tests__/test-utils.d.ts.map +1 -0
  31. package/dist/__tests__/test-utils.js +143 -0
  32. package/dist/__tests__/test-utils.js.map +1 -0
  33. package/dist/clients/bridge-client.d.ts +388 -0
  34. package/dist/clients/bridge-client.d.ts.map +1 -0
  35. package/dist/clients/bridge-client.js +587 -0
  36. package/dist/clients/bridge-client.js.map +1 -0
  37. package/dist/clients/clob-api.d.ts +318 -0
  38. package/dist/clients/clob-api.d.ts.map +1 -0
  39. package/dist/clients/clob-api.js +388 -0
  40. package/dist/clients/clob-api.js.map +1 -0
  41. package/dist/clients/ctf-client.d.ts +473 -0
  42. package/dist/clients/ctf-client.d.ts.map +1 -0
  43. package/dist/clients/ctf-client.js +915 -0
  44. package/dist/clients/ctf-client.js.map +1 -0
  45. package/dist/clients/data-api.d.ts +134 -0
  46. package/dist/clients/data-api.d.ts.map +1 -0
  47. package/dist/clients/data-api.js +265 -0
  48. package/dist/clients/data-api.js.map +1 -0
  49. package/dist/clients/gamma-api.d.ts +401 -0
  50. package/dist/clients/gamma-api.d.ts.map +1 -0
  51. package/dist/clients/gamma-api.js +352 -0
  52. package/dist/clients/gamma-api.js.map +1 -0
  53. package/dist/clients/trading-client.d.ts +252 -0
  54. package/dist/clients/trading-client.d.ts.map +1 -0
  55. package/dist/clients/trading-client.js +543 -0
  56. package/dist/clients/trading-client.js.map +1 -0
  57. package/dist/clients/websocket-manager.d.ts +100 -0
  58. package/dist/clients/websocket-manager.d.ts.map +1 -0
  59. package/dist/clients/websocket-manager.js +193 -0
  60. package/dist/clients/websocket-manager.js.map +1 -0
  61. package/dist/core/cache-adapter-bridge.d.ts +36 -0
  62. package/dist/core/cache-adapter-bridge.d.ts.map +1 -0
  63. package/dist/core/cache-adapter-bridge.js +81 -0
  64. package/dist/core/cache-adapter-bridge.js.map +1 -0
  65. package/dist/core/cache.d.ts +40 -0
  66. package/dist/core/cache.d.ts.map +1 -0
  67. package/dist/core/cache.js +71 -0
  68. package/dist/core/cache.js.map +1 -0
  69. package/dist/core/errors.d.ts +38 -0
  70. package/dist/core/errors.d.ts.map +1 -0
  71. package/dist/core/errors.js +84 -0
  72. package/dist/core/errors.js.map +1 -0
  73. package/dist/core/rate-limiter.d.ts +31 -0
  74. package/dist/core/rate-limiter.d.ts.map +1 -0
  75. package/dist/core/rate-limiter.js +70 -0
  76. package/dist/core/rate-limiter.js.map +1 -0
  77. package/{src/core/types.ts → dist/core/types.d.ts} +169 -215
  78. package/dist/core/types.d.ts.map +1 -0
  79. package/dist/core/types.js +19 -0
  80. package/dist/core/types.js.map +1 -0
  81. package/dist/core/unified-cache.d.ts +63 -0
  82. package/dist/core/unified-cache.d.ts.map +1 -0
  83. package/dist/core/unified-cache.js +114 -0
  84. package/dist/core/unified-cache.js.map +1 -0
  85. package/dist/index.d.ts +93 -0
  86. package/dist/index.d.ts.map +1 -0
  87. package/dist/index.js +255 -0
  88. package/dist/index.js.map +1 -0
  89. package/dist/services/arbitrage-service.d.ts +408 -0
  90. package/dist/services/arbitrage-service.d.ts.map +1 -0
  91. package/dist/services/arbitrage-service.js +1422 -0
  92. package/dist/services/arbitrage-service.js.map +1 -0
  93. package/dist/services/authorization-service.d.ts +97 -0
  94. package/dist/services/authorization-service.d.ts.map +1 -0
  95. package/dist/services/authorization-service.js +279 -0
  96. package/dist/services/authorization-service.js.map +1 -0
  97. package/dist/services/market-service.d.ts +108 -0
  98. package/dist/services/market-service.d.ts.map +1 -0
  99. package/dist/services/market-service.js +458 -0
  100. package/dist/services/market-service.js.map +1 -0
  101. package/dist/services/realtime-service.d.ts +82 -0
  102. package/dist/services/realtime-service.d.ts.map +1 -0
  103. package/dist/services/realtime-service.js +150 -0
  104. package/dist/services/realtime-service.js.map +1 -0
  105. package/dist/services/swap-service.d.ts +217 -0
  106. package/dist/services/swap-service.d.ts.map +1 -0
  107. package/dist/services/swap-service.js +695 -0
  108. package/dist/services/swap-service.js.map +1 -0
  109. package/dist/services/wallet-service.d.ts +94 -0
  110. package/dist/services/wallet-service.d.ts.map +1 -0
  111. package/dist/services/wallet-service.js +173 -0
  112. package/dist/services/wallet-service.js.map +1 -0
  113. package/dist/utils/price-utils.d.ts +153 -0
  114. package/dist/utils/price-utils.d.ts.map +1 -0
  115. package/dist/utils/price-utils.js +236 -0
  116. package/dist/utils/price-utils.js.map +1 -0
  117. package/package.json +7 -2
  118. package/docs/00-design.md +0 -760
  119. package/docs/02-API.md +0 -1148
  120. package/docs/arb/test-plan.md +0 -387
  121. package/docs/arb/test-results.md +0 -336
  122. package/docs/arbitrage.md +0 -754
  123. package/docs/reports/smart-money-analysis-2025-12-23-cn.md +0 -840
  124. package/examples/01-basic-usage.ts +0 -68
  125. package/examples/02-smart-money.ts +0 -95
  126. package/examples/03-market-analysis.ts +0 -108
  127. package/examples/04-kline-aggregation.ts +0 -158
  128. package/examples/05-follow-wallet-strategy.ts +0 -156
  129. package/examples/06-services-demo.ts +0 -124
  130. package/examples/07-realtime-websocket.ts +0 -117
  131. package/examples/08-trading-orders.ts +0 -278
  132. package/examples/09-rewards-tracking.ts +0 -187
  133. package/examples/10-ctf-operations.ts +0 -336
  134. package/examples/11-live-arbitrage-scan.ts +0 -221
  135. package/examples/12-trending-arb-monitor.ts +0 -406
  136. package/examples/13-arbitrage-service.ts +0 -211
  137. package/examples/README.md +0 -179
  138. package/scripts/README.md +0 -163
  139. package/scripts/approvals/approve-erc1155.ts +0 -129
  140. package/scripts/approvals/approve-neg-risk-erc1155.ts +0 -149
  141. package/scripts/approvals/approve-neg-risk.ts +0 -102
  142. package/scripts/approvals/check-all-allowances.ts +0 -150
  143. package/scripts/approvals/check-allowance.ts +0 -129
  144. package/scripts/approvals/check-ctf-approval.ts +0 -158
  145. package/scripts/arb/faze-bo3-arb.ts +0 -385
  146. package/scripts/arb/settle-position.ts +0 -190
  147. package/scripts/arb/token-rebalancer.ts +0 -420
  148. package/scripts/arb-tests/01-unit-tests.ts +0 -495
  149. package/scripts/arb-tests/02-integration-tests.ts +0 -412
  150. package/scripts/arb-tests/03-e2e-tests.ts +0 -503
  151. package/scripts/arb-tests/README.md +0 -109
  152. package/scripts/datas/001-report.md +0 -486
  153. package/scripts/datas/clone-modal-screenshot.png +0 -0
  154. package/scripts/deposit/deposit-native-usdc.ts +0 -179
  155. package/scripts/deposit/deposit-usdc.ts +0 -155
  156. package/scripts/deposit/swap-usdc-to-usdce.ts +0 -375
  157. package/scripts/research/research-markets.ts +0 -166
  158. package/scripts/trading/check-orders.ts +0 -50
  159. package/scripts/trading/sell-nvidia-positions.ts +0 -206
  160. package/scripts/trading/test-order.ts +0 -172
  161. package/scripts/verify/test-approve-trading.ts +0 -98
  162. package/scripts/verify/test-provider-fix.ts +0 -43
  163. package/scripts/verify/test-search-mcp.ts +0 -113
  164. package/scripts/verify/verify-all-apis.ts +0 -160
  165. package/scripts/wallet/check-wallet-balances.ts +0 -75
  166. package/scripts/wallet/test-wallet-operations.ts +0 -191
  167. package/scripts/wallet/verify-wallet-tools.ts +0 -124
  168. package/src/__tests__/clob-api.test.ts +0 -301
  169. package/src/__tests__/integration/bridge-client.integration.test.ts +0 -314
  170. package/src/__tests__/integration/clob-api.integration.test.ts +0 -218
  171. package/src/__tests__/integration/ctf-client.integration.test.ts +0 -331
  172. package/src/__tests__/integration/data-api.integration.test.ts +0 -194
  173. package/src/__tests__/integration/gamma-api.integration.test.ts +0 -206
  174. package/src/__tests__/test-utils.ts +0 -170
  175. package/src/clients/bridge-client.ts +0 -841
  176. package/src/clients/clob-api.ts +0 -629
  177. package/src/clients/ctf-client.ts +0 -1216
  178. package/src/clients/data-api.ts +0 -469
  179. package/src/clients/gamma-api.ts +0 -597
  180. package/src/clients/trading-client.ts +0 -749
  181. package/src/clients/websocket-manager.ts +0 -267
  182. package/src/core/cache-adapter-bridge.ts +0 -94
  183. package/src/core/cache.ts +0 -85
  184. package/src/core/errors.ts +0 -117
  185. package/src/core/rate-limiter.ts +0 -74
  186. package/src/core/unified-cache.ts +0 -153
  187. package/src/index.ts +0 -461
  188. package/src/services/arbitrage-service.ts +0 -1807
  189. package/src/services/authorization-service.ts +0 -357
  190. package/src/services/market-service.ts +0 -544
  191. package/src/services/realtime-service.ts +0 -196
  192. package/src/services/swap-service.ts +0 -896
  193. package/src/services/wallet-service.ts +0 -259
  194. package/src/utils/price-utils.ts +0 -307
  195. package/tsconfig.json +0 -8
  196. package/vitest.config.ts +0 -19
  197. package/vitest.integration.config.ts +0 -18
@@ -1,259 +0,0 @@
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
- }
@@ -1,307 +0,0 @@
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 DELETED
@@ -1,8 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.base.json",
3
- "compilerOptions": {
4
- "outDir": "./dist",
5
- "rootDir": "./src"
6
- },
7
- "include": ["src/**/*"]
8
- }
package/vitest.config.ts DELETED
@@ -1,19 +0,0 @@
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
- });
@@ -1,18 +0,0 @@
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
- });