@catalyst-team/poly-sdk 0.2.1 → 0.4.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 (277) hide show
  1. package/README.md +665 -807
  2. package/README.zh-CN.md +645 -342
  3. package/dist/__tests__/integration/arbitrage-service.integration.test.d.ts +12 -0
  4. package/dist/__tests__/integration/arbitrage-service.integration.test.d.ts.map +1 -0
  5. package/dist/__tests__/integration/arbitrage-service.integration.test.js +267 -0
  6. package/dist/__tests__/integration/arbitrage-service.integration.test.js.map +1 -0
  7. package/dist/__tests__/integration/data-api.integration.test.js +6 -3
  8. package/dist/__tests__/integration/data-api.integration.test.js.map +1 -1
  9. package/dist/__tests__/integration/market-service.integration.test.d.ts +10 -0
  10. package/dist/__tests__/integration/market-service.integration.test.d.ts.map +1 -0
  11. package/dist/__tests__/integration/market-service.integration.test.js +173 -0
  12. package/dist/__tests__/integration/market-service.integration.test.js.map +1 -0
  13. package/dist/__tests__/integration/realtime-service-v2.integration.test.d.ts +10 -0
  14. package/dist/__tests__/integration/realtime-service-v2.integration.test.d.ts.map +1 -0
  15. package/dist/__tests__/integration/realtime-service-v2.integration.test.js +307 -0
  16. package/dist/__tests__/integration/realtime-service-v2.integration.test.js.map +1 -0
  17. package/dist/__tests__/integration/trading-service.integration.test.d.ts +10 -0
  18. package/dist/__tests__/integration/trading-service.integration.test.d.ts.map +1 -0
  19. package/dist/__tests__/integration/trading-service.integration.test.js +58 -0
  20. package/dist/__tests__/integration/trading-service.integration.test.js.map +1 -0
  21. package/dist/clients/clob-api.d.ts +73 -0
  22. package/dist/clients/clob-api.d.ts.map +1 -1
  23. package/dist/clients/clob-api.js +60 -0
  24. package/dist/clients/clob-api.js.map +1 -1
  25. package/dist/clients/ctf-client.d.ts +6 -4
  26. package/dist/clients/ctf-client.d.ts.map +1 -1
  27. package/dist/clients/ctf-client.js.map +1 -1
  28. package/dist/clients/data-api.d.ts +333 -15
  29. package/dist/clients/data-api.d.ts.map +1 -1
  30. package/dist/clients/data-api.js +398 -26
  31. package/dist/clients/data-api.js.map +1 -1
  32. package/dist/clients/gamma-api.d.ts +5 -0
  33. package/dist/clients/gamma-api.d.ts.map +1 -1
  34. package/dist/clients/gamma-api.js +2 -0
  35. package/dist/clients/gamma-api.js.map +1 -1
  36. package/dist/clients/subgraph.d.ts +196 -0
  37. package/dist/clients/subgraph.d.ts.map +1 -0
  38. package/dist/clients/subgraph.js +332 -0
  39. package/dist/clients/subgraph.js.map +1 -0
  40. package/dist/clients/websocket-manager.d.ts +3 -0
  41. package/dist/clients/websocket-manager.d.ts.map +1 -1
  42. package/dist/clients/websocket-manager.js +10 -3
  43. package/dist/clients/websocket-manager.js.map +1 -1
  44. package/dist/core/cache.d.ts +3 -0
  45. package/dist/core/cache.d.ts.map +1 -1
  46. package/dist/core/cache.js +5 -0
  47. package/dist/core/cache.js.map +1 -1
  48. package/dist/core/errors.d.ts +2 -1
  49. package/dist/core/errors.d.ts.map +1 -1
  50. package/dist/core/errors.js +2 -0
  51. package/dist/core/errors.js.map +1 -1
  52. package/dist/core/rate-limiter.d.ts +3 -1
  53. package/dist/core/rate-limiter.d.ts.map +1 -1
  54. package/dist/core/rate-limiter.js +12 -0
  55. package/dist/core/rate-limiter.js.map +1 -1
  56. package/dist/core/types.d.ts +205 -13
  57. package/dist/core/types.d.ts.map +1 -1
  58. package/dist/core/types.js +30 -0
  59. package/dist/core/types.js.map +1 -1
  60. package/dist/core/types.test.d.ts +7 -0
  61. package/dist/core/types.test.d.ts.map +1 -0
  62. package/dist/core/types.test.js +122 -0
  63. package/dist/core/types.test.js.map +1 -0
  64. package/dist/index.d.ts +84 -18
  65. package/dist/index.d.ts.map +1 -1
  66. package/dist/index.js +139 -132
  67. package/dist/index.js.map +1 -1
  68. package/dist/scripts/dip-arb/auto-trade.d.ts +20 -0
  69. package/dist/scripts/dip-arb/auto-trade.d.ts.map +1 -0
  70. package/dist/scripts/dip-arb/auto-trade.js +373 -0
  71. package/dist/scripts/dip-arb/auto-trade.js.map +1 -0
  72. package/dist/scripts/dip-arb/example-basic.d.ts +30 -0
  73. package/dist/scripts/dip-arb/example-basic.d.ts.map +1 -0
  74. package/dist/scripts/dip-arb/example-basic.js +222 -0
  75. package/dist/scripts/dip-arb/example-basic.js.map +1 -0
  76. package/dist/scripts/dip-arb/redeem-positions.d.ts +11 -0
  77. package/dist/scripts/dip-arb/redeem-positions.d.ts.map +1 -0
  78. package/dist/scripts/dip-arb/redeem-positions.js +201 -0
  79. package/dist/scripts/dip-arb/redeem-positions.js.map +1 -0
  80. package/dist/scripts/dip-arb/scan-markets.d.ts +6 -0
  81. package/dist/scripts/dip-arb/scan-markets.d.ts.map +1 -0
  82. package/dist/scripts/dip-arb/scan-markets.js +73 -0
  83. package/dist/scripts/dip-arb/scan-markets.js.map +1 -0
  84. package/dist/services/arbitrage-service.d.ts +3 -2
  85. package/dist/services/arbitrage-service.d.ts.map +1 -1
  86. package/dist/services/arbitrage-service.js +71 -43
  87. package/dist/services/arbitrage-service.js.map +1 -1
  88. package/dist/services/binance-service.d.ts +154 -0
  89. package/dist/services/binance-service.d.ts.map +1 -0
  90. package/dist/services/binance-service.js +266 -0
  91. package/dist/services/binance-service.js.map +1 -0
  92. package/dist/services/dip-arb-service.d.ts +209 -0
  93. package/dist/services/dip-arb-service.d.ts.map +1 -0
  94. package/dist/services/dip-arb-service.js +1602 -0
  95. package/dist/services/dip-arb-service.js.map +1 -0
  96. package/dist/services/dip-arb-types.d.ts +553 -0
  97. package/dist/services/dip-arb-types.d.ts.map +1 -0
  98. package/dist/services/dip-arb-types.js +164 -0
  99. package/dist/services/dip-arb-types.js.map +1 -0
  100. package/dist/services/market-service.d.ts +267 -8
  101. package/dist/services/market-service.d.ts.map +1 -1
  102. package/dist/services/market-service.js +771 -42
  103. package/dist/services/market-service.js.map +1 -1
  104. package/dist/services/onchain-service.d.ts +309 -0
  105. package/dist/services/onchain-service.d.ts.map +1 -0
  106. package/dist/services/onchain-service.js +417 -0
  107. package/dist/services/onchain-service.js.map +1 -0
  108. package/dist/services/realtime-service-v2.d.ts +362 -0
  109. package/dist/services/realtime-service-v2.d.ts.map +1 -0
  110. package/dist/services/realtime-service-v2.js +858 -0
  111. package/dist/services/realtime-service-v2.js.map +1 -0
  112. package/dist/services/realtime-service.d.ts +17 -17
  113. package/dist/services/realtime-service.d.ts.map +1 -1
  114. package/dist/services/realtime-service.js +91 -59
  115. package/dist/services/realtime-service.js.map +1 -1
  116. package/dist/services/smart-money-service.d.ts +352 -0
  117. package/dist/services/smart-money-service.d.ts.map +1 -0
  118. package/dist/services/smart-money-service.js +582 -0
  119. package/dist/services/smart-money-service.js.map +1 -0
  120. package/dist/services/trading-service.d.ts +177 -0
  121. package/dist/services/trading-service.d.ts.map +1 -0
  122. package/dist/services/trading-service.js +422 -0
  123. package/dist/services/trading-service.js.map +1 -0
  124. package/dist/services/wallet-service.d.ts +225 -3
  125. package/dist/services/wallet-service.d.ts.map +1 -1
  126. package/dist/services/wallet-service.js +511 -3
  127. package/dist/services/wallet-service.js.map +1 -1
  128. package/dist/src/__tests__/integration/arbitrage-service.integration.test.d.ts +12 -0
  129. package/dist/src/__tests__/integration/arbitrage-service.integration.test.d.ts.map +1 -0
  130. package/dist/src/__tests__/integration/arbitrage-service.integration.test.js +267 -0
  131. package/dist/src/__tests__/integration/arbitrage-service.integration.test.js.map +1 -0
  132. package/dist/src/__tests__/integration/bridge-client.integration.test.d.ts +11 -0
  133. package/dist/src/__tests__/integration/bridge-client.integration.test.d.ts.map +1 -0
  134. package/dist/src/__tests__/integration/bridge-client.integration.test.js +260 -0
  135. package/dist/src/__tests__/integration/bridge-client.integration.test.js.map +1 -0
  136. package/dist/src/__tests__/integration/ctf-client.integration.test.d.ts +17 -0
  137. package/dist/src/__tests__/integration/ctf-client.integration.test.d.ts.map +1 -0
  138. package/dist/src/__tests__/integration/ctf-client.integration.test.js +234 -0
  139. package/dist/src/__tests__/integration/ctf-client.integration.test.js.map +1 -0
  140. package/dist/src/__tests__/integration/data-api.integration.test.d.ts +9 -0
  141. package/dist/src/__tests__/integration/data-api.integration.test.d.ts.map +1 -0
  142. package/dist/src/__tests__/integration/data-api.integration.test.js +164 -0
  143. package/dist/src/__tests__/integration/data-api.integration.test.js.map +1 -0
  144. package/dist/src/__tests__/integration/gamma-api.integration.test.d.ts +9 -0
  145. package/dist/src/__tests__/integration/gamma-api.integration.test.d.ts.map +1 -0
  146. package/dist/src/__tests__/integration/gamma-api.integration.test.js +170 -0
  147. package/dist/src/__tests__/integration/gamma-api.integration.test.js.map +1 -0
  148. package/dist/src/__tests__/integration/market-service.integration.test.d.ts +10 -0
  149. package/dist/src/__tests__/integration/market-service.integration.test.d.ts.map +1 -0
  150. package/dist/src/__tests__/integration/market-service.integration.test.js +180 -0
  151. package/dist/src/__tests__/integration/market-service.integration.test.js.map +1 -0
  152. package/dist/src/__tests__/integration/realtime-service-v2.integration.test.d.ts +10 -0
  153. package/dist/src/__tests__/integration/realtime-service-v2.integration.test.d.ts.map +1 -0
  154. package/dist/src/__tests__/integration/realtime-service-v2.integration.test.js +307 -0
  155. package/dist/src/__tests__/integration/realtime-service-v2.integration.test.js.map +1 -0
  156. package/dist/src/__tests__/integration/trading-service.integration.test.d.ts +10 -0
  157. package/dist/src/__tests__/integration/trading-service.integration.test.d.ts.map +1 -0
  158. package/dist/src/__tests__/integration/trading-service.integration.test.js +58 -0
  159. package/dist/src/__tests__/integration/trading-service.integration.test.js.map +1 -0
  160. package/dist/src/__tests__/test-utils.d.ts +92 -0
  161. package/dist/src/__tests__/test-utils.d.ts.map +1 -0
  162. package/dist/src/__tests__/test-utils.js +143 -0
  163. package/dist/src/__tests__/test-utils.js.map +1 -0
  164. package/dist/src/clients/bridge-client.d.ts +388 -0
  165. package/dist/src/clients/bridge-client.d.ts.map +1 -0
  166. package/dist/src/clients/bridge-client.js +587 -0
  167. package/dist/src/clients/bridge-client.js.map +1 -0
  168. package/dist/src/clients/ctf-client.d.ts +475 -0
  169. package/dist/src/clients/ctf-client.d.ts.map +1 -0
  170. package/dist/src/clients/ctf-client.js +915 -0
  171. package/dist/src/clients/ctf-client.js.map +1 -0
  172. package/dist/src/clients/data-api.d.ts +452 -0
  173. package/dist/src/clients/data-api.d.ts.map +1 -0
  174. package/dist/src/clients/data-api.js +637 -0
  175. package/dist/src/clients/data-api.js.map +1 -0
  176. package/dist/src/clients/gamma-api.d.ts +421 -0
  177. package/dist/src/clients/gamma-api.d.ts.map +1 -0
  178. package/dist/src/clients/gamma-api.js +359 -0
  179. package/dist/src/clients/gamma-api.js.map +1 -0
  180. package/dist/src/clients/subgraph.d.ts +196 -0
  181. package/dist/src/clients/subgraph.d.ts.map +1 -0
  182. package/dist/src/clients/subgraph.js +332 -0
  183. package/dist/src/clients/subgraph.js.map +1 -0
  184. package/dist/src/core/cache-adapter-bridge.d.ts +36 -0
  185. package/dist/src/core/cache-adapter-bridge.d.ts.map +1 -0
  186. package/dist/src/core/cache-adapter-bridge.js +81 -0
  187. package/dist/src/core/cache-adapter-bridge.js.map +1 -0
  188. package/dist/src/core/cache.d.ts +43 -0
  189. package/dist/src/core/cache.d.ts.map +1 -0
  190. package/dist/src/core/cache.js +76 -0
  191. package/dist/src/core/cache.js.map +1 -0
  192. package/dist/src/core/errors.d.ts +39 -0
  193. package/dist/src/core/errors.d.ts.map +1 -0
  194. package/dist/src/core/errors.js +86 -0
  195. package/dist/src/core/errors.js.map +1 -0
  196. package/dist/src/core/rate-limiter.d.ts +33 -0
  197. package/dist/src/core/rate-limiter.d.ts.map +1 -0
  198. package/dist/src/core/rate-limiter.js +82 -0
  199. package/dist/src/core/rate-limiter.js.map +1 -0
  200. package/dist/src/core/types.d.ts +506 -0
  201. package/dist/src/core/types.d.ts.map +1 -0
  202. package/dist/src/core/types.js +49 -0
  203. package/dist/src/core/types.js.map +1 -0
  204. package/dist/src/core/types.test.d.ts +7 -0
  205. package/dist/src/core/types.test.d.ts.map +1 -0
  206. package/dist/src/core/types.test.js +122 -0
  207. package/dist/src/core/types.test.js.map +1 -0
  208. package/dist/src/core/unified-cache.d.ts +63 -0
  209. package/dist/src/core/unified-cache.d.ts.map +1 -0
  210. package/dist/src/core/unified-cache.js +114 -0
  211. package/dist/src/core/unified-cache.js.map +1 -0
  212. package/dist/src/index.d.ts +159 -0
  213. package/dist/src/index.d.ts.map +1 -0
  214. package/dist/src/index.js +262 -0
  215. package/dist/src/index.js.map +1 -0
  216. package/dist/src/services/arbitrage-service.d.ts +409 -0
  217. package/dist/src/services/arbitrage-service.d.ts.map +1 -0
  218. package/dist/src/services/arbitrage-service.js +1450 -0
  219. package/dist/src/services/arbitrage-service.js.map +1 -0
  220. package/dist/src/services/authorization-service.d.ts +97 -0
  221. package/dist/src/services/authorization-service.d.ts.map +1 -0
  222. package/dist/src/services/authorization-service.js +279 -0
  223. package/dist/src/services/authorization-service.js.map +1 -0
  224. package/dist/src/services/binance-service.d.ts +154 -0
  225. package/dist/src/services/binance-service.d.ts.map +1 -0
  226. package/dist/src/services/binance-service.js +266 -0
  227. package/dist/src/services/binance-service.js.map +1 -0
  228. package/dist/src/services/dip-arb-service.d.ts +245 -0
  229. package/dist/src/services/dip-arb-service.d.ts.map +1 -0
  230. package/dist/src/services/dip-arb-service.js +1865 -0
  231. package/dist/src/services/dip-arb-service.js.map +1 -0
  232. package/dist/src/services/dip-arb-types.d.ts +553 -0
  233. package/dist/src/services/dip-arb-types.d.ts.map +1 -0
  234. package/dist/src/services/dip-arb-types.js +164 -0
  235. package/dist/src/services/dip-arb-types.js.map +1 -0
  236. package/dist/src/services/market-service.d.ts +370 -0
  237. package/dist/src/services/market-service.d.ts.map +1 -0
  238. package/dist/src/services/market-service.js +1200 -0
  239. package/dist/src/services/market-service.js.map +1 -0
  240. package/dist/src/services/onchain-service.d.ts +309 -0
  241. package/dist/src/services/onchain-service.d.ts.map +1 -0
  242. package/dist/src/services/onchain-service.js +417 -0
  243. package/dist/src/services/onchain-service.js.map +1 -0
  244. package/dist/src/services/realtime-service-v2.d.ts +367 -0
  245. package/dist/src/services/realtime-service-v2.d.ts.map +1 -0
  246. package/dist/src/services/realtime-service-v2.js +876 -0
  247. package/dist/src/services/realtime-service-v2.js.map +1 -0
  248. package/dist/src/services/smart-money-service.d.ts +352 -0
  249. package/dist/src/services/smart-money-service.d.ts.map +1 -0
  250. package/dist/src/services/smart-money-service.js +582 -0
  251. package/dist/src/services/smart-money-service.js.map +1 -0
  252. package/dist/src/services/swap-service.d.ts +217 -0
  253. package/dist/src/services/swap-service.d.ts.map +1 -0
  254. package/dist/src/services/swap-service.js +695 -0
  255. package/dist/src/services/swap-service.js.map +1 -0
  256. package/dist/src/services/trading-service.d.ts +177 -0
  257. package/dist/src/services/trading-service.d.ts.map +1 -0
  258. package/dist/src/services/trading-service.js +422 -0
  259. package/dist/src/services/trading-service.js.map +1 -0
  260. package/dist/src/services/wallet-service.d.ts +316 -0
  261. package/dist/src/services/wallet-service.d.ts.map +1 -0
  262. package/dist/src/services/wallet-service.js +681 -0
  263. package/dist/src/services/wallet-service.js.map +1 -0
  264. package/dist/src/utils/price-utils.d.ts +153 -0
  265. package/dist/src/utils/price-utils.d.ts.map +1 -0
  266. package/dist/src/utils/price-utils.js +236 -0
  267. package/dist/src/utils/price-utils.js.map +1 -0
  268. package/dist/src/utils/price-utils.test.d.ts +5 -0
  269. package/dist/src/utils/price-utils.test.d.ts.map +1 -0
  270. package/dist/src/utils/price-utils.test.js +192 -0
  271. package/dist/src/utils/price-utils.test.js.map +1 -0
  272. package/dist/utils/price-utils.test.d.ts +5 -0
  273. package/dist/utils/price-utils.test.d.ts.map +1 -0
  274. package/dist/utils/price-utils.test.js +192 -0
  275. package/dist/utils/price-utils.test.js.map +1 -0
  276. package/package.json +6 -5
  277. package/README.en.md +0 -502
@@ -0,0 +1,1450 @@
1
+ /**
2
+ * ArbitrageService - Real-time Arbitrage Detection and Execution
3
+ *
4
+ * Uses WebSocket for real-time orderbook monitoring and automatically
5
+ * detects arbitrage opportunities in Polymarket binary markets.
6
+ *
7
+ * Strategy:
8
+ * - Long Arb: Buy YES + NO (effective cost < $1) → Merge → $1 USDC
9
+ * - Short Arb: Sell pre-held YES + NO tokens (effective revenue > $1)
10
+ *
11
+ * Features:
12
+ * - Real-time orderbook monitoring via WebSocket
13
+ * - Automatic arbitrage detection using effective prices
14
+ * - Configurable profit threshold and trade sizes
15
+ * - Auto-execute mode or event-based manual mode
16
+ * - Balance tracking and position management
17
+ *
18
+ * Based on: scripts/arb/faze-bo3-arb.ts
19
+ * Docs: docs/arbitrage.md
20
+ */
21
+ import { EventEmitter } from 'events';
22
+ import { RealtimeServiceV2, } from './realtime-service-v2.js';
23
+ import { TradingService } from './trading-service.js';
24
+ import { MarketService } from './market-service.js';
25
+ import { CTFClient } from '../clients/ctf-client.js';
26
+ import { GammaApiClient } from '../clients/gamma-api.js';
27
+ import { RateLimiter } from '../core/rate-limiter.js';
28
+ import { createUnifiedCache } from '../core/unified-cache.js';
29
+ import { getEffectivePrices } from '../utils/price-utils.js';
30
+ // ===== ArbitrageService =====
31
+ export class ArbitrageService extends EventEmitter {
32
+ realtimeService;
33
+ marketSubscription = null;
34
+ ctf = null;
35
+ tradingService = null;
36
+ rateLimiter;
37
+ market = null;
38
+ config;
39
+ orderbook = {
40
+ yesBids: [],
41
+ yesAsks: [],
42
+ noBids: [],
43
+ noAsks: [],
44
+ lastUpdate: 0,
45
+ };
46
+ balance = {
47
+ usdc: 0,
48
+ yesTokens: 0,
49
+ noTokens: 0,
50
+ lastUpdate: 0,
51
+ };
52
+ isExecuting = false;
53
+ lastExecutionTime = 0;
54
+ lastRebalanceTime = 0;
55
+ balanceUpdateInterval = null;
56
+ rebalanceInterval = null;
57
+ isRunning = false;
58
+ totalCapital = 0;
59
+ // Statistics
60
+ stats = {
61
+ opportunitiesDetected: 0,
62
+ executionsAttempted: 0,
63
+ executionsSucceeded: 0,
64
+ totalProfit: 0,
65
+ startTime: 0,
66
+ };
67
+ constructor(config = {}) {
68
+ super();
69
+ this.config = {
70
+ privateKey: config.privateKey,
71
+ rpcUrl: config.rpcUrl || 'https://polygon-rpc.com',
72
+ profitThreshold: config.profitThreshold ?? 0.005,
73
+ minTradeSize: config.minTradeSize ?? 5,
74
+ maxTradeSize: config.maxTradeSize ?? 100,
75
+ minTokenReserve: config.minTokenReserve ?? 10,
76
+ autoExecute: config.autoExecute ?? false,
77
+ enableLogging: config.enableLogging ?? true,
78
+ executionCooldown: config.executionCooldown ?? 5000,
79
+ // Rebalancer config
80
+ enableRebalancer: config.enableRebalancer ?? false,
81
+ minUsdcRatio: config.minUsdcRatio ?? 0.2,
82
+ maxUsdcRatio: config.maxUsdcRatio ?? 0.8,
83
+ targetUsdcRatio: config.targetUsdcRatio ?? 0.5,
84
+ imbalanceThreshold: config.imbalanceThreshold ?? 5,
85
+ rebalanceIntervalMs: config.rebalanceInterval ?? 10000,
86
+ rebalanceCooldown: config.rebalanceCooldown ?? 30000,
87
+ // Execution safety
88
+ sizeSafetyFactor: config.sizeSafetyFactor ?? 0.8,
89
+ autoFixImbalance: config.autoFixImbalance ?? true,
90
+ };
91
+ this.rateLimiter = new RateLimiter();
92
+ this.realtimeService = new RealtimeServiceV2({ debug: false });
93
+ // Initialize trading clients if private key provided
94
+ if (this.config.privateKey) {
95
+ this.ctf = new CTFClient({
96
+ privateKey: this.config.privateKey,
97
+ rpcUrl: this.config.rpcUrl,
98
+ });
99
+ const cache = createUnifiedCache();
100
+ this.tradingService = new TradingService(this.rateLimiter, cache, {
101
+ privateKey: this.config.privateKey,
102
+ chainId: 137,
103
+ });
104
+ }
105
+ // RealtimeServiceV2 event handlers are set up during subscription
106
+ }
107
+ // ===== Public API =====
108
+ /**
109
+ * Start monitoring a market for arbitrage opportunities
110
+ */
111
+ async start(market) {
112
+ if (this.isRunning) {
113
+ throw new Error('ArbitrageService is already running. Call stop() first.');
114
+ }
115
+ this.market = market;
116
+ this.isRunning = true;
117
+ this.stats.startTime = Date.now();
118
+ this.log(`Starting arbitrage monitor for: ${market.name}`);
119
+ this.log(`Condition ID: ${market.conditionId.slice(0, 20)}...`);
120
+ this.log(`Profit Threshold: ${(this.config.profitThreshold * 100).toFixed(2)}%`);
121
+ this.log(`Auto Execute: ${this.config.autoExecute ? 'YES' : 'NO'}`);
122
+ // Initialize trading service
123
+ if (this.tradingService) {
124
+ await this.tradingService.initialize();
125
+ this.log(`Wallet: ${this.ctf?.getAddress()}`);
126
+ await this.updateBalance();
127
+ this.log(`USDC Balance: ${this.balance.usdc.toFixed(2)}`);
128
+ this.log(`YES Tokens: ${this.balance.yesTokens.toFixed(2)}`);
129
+ this.log(`NO Tokens: ${this.balance.noTokens.toFixed(2)}`);
130
+ // Calculate total capital (USDC + paired tokens)
131
+ const pairedTokens = Math.min(this.balance.yesTokens, this.balance.noTokens);
132
+ this.totalCapital = this.balance.usdc + pairedTokens;
133
+ this.log(`Total Capital: ${this.totalCapital.toFixed(2)}`);
134
+ // Start balance update interval
135
+ this.balanceUpdateInterval = setInterval(() => this.updateBalance(), 30000);
136
+ // Start rebalancer if enabled
137
+ if (this.config.enableRebalancer) {
138
+ this.log(`Rebalancer: ENABLED (USDC range: ${(this.config.minUsdcRatio * 100).toFixed(0)}%-${(this.config.maxUsdcRatio * 100).toFixed(0)}%, target: ${(this.config.targetUsdcRatio * 100).toFixed(0)}%)`);
139
+ this.rebalanceInterval = setInterval(() => this.checkAndRebalance(), this.config.rebalanceIntervalMs);
140
+ }
141
+ }
142
+ else {
143
+ this.log('No wallet configured - monitoring only');
144
+ }
145
+ // Connect and subscribe to WebSocket
146
+ this.realtimeService.connect();
147
+ this.marketSubscription = this.realtimeService.subscribeMarkets([market.yesTokenId, market.noTokenId], {
148
+ onOrderbook: (book) => {
149
+ // Convert OrderbookSnapshot to BookUpdate format
150
+ const bookUpdate = {
151
+ assetId: book.assetId,
152
+ bids: book.bids,
153
+ asks: book.asks,
154
+ timestamp: book.timestamp,
155
+ };
156
+ this.handleBookUpdate(bookUpdate);
157
+ },
158
+ onError: (error) => this.emit('error', error),
159
+ });
160
+ this.emit('started', market);
161
+ this.log('Monitoring for arbitrage opportunities...');
162
+ }
163
+ /**
164
+ * Stop monitoring
165
+ */
166
+ async stop() {
167
+ if (!this.isRunning)
168
+ return;
169
+ this.isRunning = false;
170
+ if (this.balanceUpdateInterval) {
171
+ clearInterval(this.balanceUpdateInterval);
172
+ this.balanceUpdateInterval = null;
173
+ }
174
+ if (this.rebalanceInterval) {
175
+ clearInterval(this.rebalanceInterval);
176
+ this.rebalanceInterval = null;
177
+ }
178
+ // Unsubscribe and disconnect
179
+ if (this.marketSubscription) {
180
+ this.marketSubscription.unsubscribe();
181
+ this.marketSubscription = null;
182
+ }
183
+ this.realtimeService.disconnect();
184
+ this.log('Stopped');
185
+ this.log(`Total opportunities: ${this.stats.opportunitiesDetected}`);
186
+ this.log(`Executions: ${this.stats.executionsSucceeded}/${this.stats.executionsAttempted}`);
187
+ this.log(`Total profit: $${this.stats.totalProfit.toFixed(2)}`);
188
+ this.emit('stopped');
189
+ }
190
+ /**
191
+ * Get current orderbook state
192
+ */
193
+ getOrderbook() {
194
+ return { ...this.orderbook };
195
+ }
196
+ /**
197
+ * Get current balance state
198
+ */
199
+ getBalance() {
200
+ return { ...this.balance };
201
+ }
202
+ /**
203
+ * Get statistics
204
+ */
205
+ getStats() {
206
+ return {
207
+ ...this.stats,
208
+ runningTimeMs: this.isRunning ? Date.now() - this.stats.startTime : 0,
209
+ };
210
+ }
211
+ /**
212
+ * Check for arbitrage opportunity based on current orderbook
213
+ */
214
+ checkOpportunity() {
215
+ if (!this.market)
216
+ return null;
217
+ const { yesBids, yesAsks, noBids, noAsks } = this.orderbook;
218
+ if (yesBids.length === 0 || yesAsks.length === 0 || noBids.length === 0 || noAsks.length === 0) {
219
+ return null;
220
+ }
221
+ const yesBestBid = yesBids[0]?.price || 0;
222
+ const yesBestAsk = yesAsks[0]?.price || 1;
223
+ const noBestBid = noBids[0]?.price || 0;
224
+ const noBestAsk = noAsks[0]?.price || 1;
225
+ // Calculate effective prices
226
+ const effective = getEffectivePrices(yesBestAsk, yesBestBid, noBestAsk, noBestBid);
227
+ // Check for arbitrage
228
+ const longCost = effective.effectiveBuyYes + effective.effectiveBuyNo;
229
+ const longProfit = 1 - longCost;
230
+ const shortRevenue = effective.effectiveSellYes + effective.effectiveSellNo;
231
+ const shortProfit = shortRevenue - 1;
232
+ // Calculate sizes with safety factor to prevent partial fills
233
+ // Use min of both sides * safety factor to ensure both orders can fill
234
+ const safetyFactor = this.config.sizeSafetyFactor;
235
+ const orderbookLongSize = Math.min(yesAsks[0]?.size || 0, noAsks[0]?.size || 0) * safetyFactor;
236
+ const orderbookShortSize = Math.min(yesBids[0]?.size || 0, noBids[0]?.size || 0) * safetyFactor;
237
+ const heldPairs = Math.min(this.balance.yesTokens, this.balance.noTokens);
238
+ const balanceLongSize = longCost > 0 ? this.balance.usdc / longCost : 0;
239
+ // Check long arb
240
+ if (longProfit > this.config.profitThreshold) {
241
+ const maxSize = Math.min(orderbookLongSize, balanceLongSize * safetyFactor, this.config.maxTradeSize);
242
+ if (maxSize >= this.config.minTradeSize) {
243
+ return {
244
+ type: 'long',
245
+ profitRate: longProfit,
246
+ profitPercent: longProfit * 100,
247
+ effectivePrices: {
248
+ buyYes: effective.effectiveBuyYes,
249
+ buyNo: effective.effectiveBuyNo,
250
+ sellYes: effective.effectiveSellYes,
251
+ sellNo: effective.effectiveSellNo,
252
+ },
253
+ maxOrderbookSize: orderbookLongSize,
254
+ maxBalanceSize: balanceLongSize,
255
+ recommendedSize: maxSize,
256
+ estimatedProfit: longProfit * maxSize,
257
+ description: `Buy YES @ ${effective.effectiveBuyYes.toFixed(4)} + NO @ ${effective.effectiveBuyNo.toFixed(4)}, Merge for $1`,
258
+ timestamp: Date.now(),
259
+ };
260
+ }
261
+ }
262
+ // Check short arb
263
+ if (shortProfit > this.config.profitThreshold) {
264
+ const maxSize = Math.min(orderbookShortSize, heldPairs, this.config.maxTradeSize);
265
+ if (maxSize >= this.config.minTradeSize && heldPairs >= this.config.minTokenReserve) {
266
+ return {
267
+ type: 'short',
268
+ profitRate: shortProfit,
269
+ profitPercent: shortProfit * 100,
270
+ effectivePrices: {
271
+ buyYes: effective.effectiveBuyYes,
272
+ buyNo: effective.effectiveBuyNo,
273
+ sellYes: effective.effectiveSellYes,
274
+ sellNo: effective.effectiveSellNo,
275
+ },
276
+ maxOrderbookSize: orderbookShortSize,
277
+ maxBalanceSize: heldPairs,
278
+ recommendedSize: maxSize,
279
+ estimatedProfit: shortProfit * maxSize,
280
+ description: `Sell YES @ ${effective.effectiveSellYes.toFixed(4)} + NO @ ${effective.effectiveSellNo.toFixed(4)}`,
281
+ timestamp: Date.now(),
282
+ };
283
+ }
284
+ }
285
+ return null;
286
+ }
287
+ /**
288
+ * Manually execute an arbitrage opportunity
289
+ */
290
+ async execute(opportunity) {
291
+ if (!this.ctf || !this.tradingService || !this.market) {
292
+ return {
293
+ success: false,
294
+ type: opportunity.type,
295
+ size: 0,
296
+ profit: 0,
297
+ txHashes: [],
298
+ error: 'Trading not configured (no private key)',
299
+ executionTimeMs: 0,
300
+ };
301
+ }
302
+ if (this.isExecuting) {
303
+ return {
304
+ success: false,
305
+ type: opportunity.type,
306
+ size: 0,
307
+ profit: 0,
308
+ txHashes: [],
309
+ error: 'Another execution in progress',
310
+ executionTimeMs: 0,
311
+ };
312
+ }
313
+ this.isExecuting = true;
314
+ this.stats.executionsAttempted++;
315
+ const startTime = Date.now();
316
+ try {
317
+ const result = opportunity.type === 'long'
318
+ ? await this.executeLongArb(opportunity)
319
+ : await this.executeShortArb(opportunity);
320
+ if (result.success) {
321
+ this.stats.executionsSucceeded++;
322
+ this.stats.totalProfit += result.profit;
323
+ this.lastExecutionTime = Date.now();
324
+ }
325
+ this.emit('execution', result);
326
+ return result;
327
+ }
328
+ finally {
329
+ this.isExecuting = false;
330
+ // Update balance after execution
331
+ await this.updateBalance();
332
+ }
333
+ }
334
+ // ===== Rebalancer Methods =====
335
+ /**
336
+ * Calculate recommended rebalance action based on current state
337
+ */
338
+ calculateRebalanceAction() {
339
+ if (!this.market || this.totalCapital === 0) {
340
+ return { type: 'none', amount: 0, reason: 'No market or capital', priority: 0 };
341
+ }
342
+ const { usdc, yesTokens, noTokens } = this.balance;
343
+ const pairedTokens = Math.min(yesTokens, noTokens);
344
+ const currentTotal = usdc + pairedTokens;
345
+ const usdcRatio = usdc / currentTotal;
346
+ const tokenImbalance = yesTokens - noTokens;
347
+ // Priority 1: Fix YES/NO imbalance (highest priority - risk control)
348
+ if (Math.abs(tokenImbalance) > this.config.imbalanceThreshold) {
349
+ if (tokenImbalance > 0) {
350
+ const sellAmount = Math.min(tokenImbalance, yesTokens * 0.5);
351
+ if (sellAmount >= this.config.minTradeSize) {
352
+ return {
353
+ type: 'sell_yes',
354
+ amount: Math.floor(sellAmount * 1e6) / 1e6,
355
+ reason: `Risk: YES > NO by ${tokenImbalance.toFixed(2)}`,
356
+ priority: 100,
357
+ };
358
+ }
359
+ }
360
+ else {
361
+ const sellAmount = Math.min(-tokenImbalance, noTokens * 0.5);
362
+ if (sellAmount >= this.config.minTradeSize) {
363
+ return {
364
+ type: 'sell_no',
365
+ amount: Math.floor(sellAmount * 1e6) / 1e6,
366
+ reason: `Risk: NO > YES by ${(-tokenImbalance).toFixed(2)}`,
367
+ priority: 100,
368
+ };
369
+ }
370
+ }
371
+ }
372
+ // Priority 2: USDC ratio too high (> maxUsdcRatio) → Split to create tokens
373
+ if (usdcRatio > this.config.maxUsdcRatio) {
374
+ const targetUsdc = this.totalCapital * this.config.targetUsdcRatio;
375
+ const excessUsdc = usdc - targetUsdc;
376
+ const splitAmount = Math.min(excessUsdc * 0.5, usdc * 0.3);
377
+ if (splitAmount >= this.config.minTradeSize) {
378
+ return {
379
+ type: 'split',
380
+ amount: Math.floor(splitAmount * 100) / 100,
381
+ reason: `USDC ${(usdcRatio * 100).toFixed(0)}% > ${(this.config.maxUsdcRatio * 100).toFixed(0)}% max`,
382
+ priority: 50,
383
+ };
384
+ }
385
+ }
386
+ // Priority 3: USDC ratio too low (< minUsdcRatio) → Merge tokens to recover USDC
387
+ if (usdcRatio < this.config.minUsdcRatio && pairedTokens >= this.config.minTradeSize) {
388
+ const targetUsdc = this.totalCapital * this.config.targetUsdcRatio;
389
+ const neededUsdc = targetUsdc - usdc;
390
+ const mergeAmount = Math.min(neededUsdc * 0.5, pairedTokens * 0.5);
391
+ if (mergeAmount >= this.config.minTradeSize) {
392
+ return {
393
+ type: 'merge',
394
+ amount: Math.floor(mergeAmount * 100) / 100,
395
+ reason: `USDC ${(usdcRatio * 100).toFixed(0)}% < ${(this.config.minUsdcRatio * 100).toFixed(0)}% min`,
396
+ priority: 50,
397
+ };
398
+ }
399
+ }
400
+ return { type: 'none', amount: 0, reason: 'Balanced', priority: 0 };
401
+ }
402
+ /**
403
+ * Execute a rebalance action
404
+ */
405
+ async rebalance(action) {
406
+ if (!this.ctf || !this.tradingService || !this.market) {
407
+ return {
408
+ success: false,
409
+ action: action || { type: 'none', amount: 0, reason: 'No trading config', priority: 0 },
410
+ error: 'Trading not configured',
411
+ };
412
+ }
413
+ const rebalanceAction = action || this.calculateRebalanceAction();
414
+ if (rebalanceAction.type === 'none') {
415
+ return { success: true, action: rebalanceAction };
416
+ }
417
+ this.log(`\n🔄 Rebalance: ${rebalanceAction.type.toUpperCase()} ${rebalanceAction.amount.toFixed(2)}`);
418
+ this.log(` Reason: ${rebalanceAction.reason}`);
419
+ try {
420
+ let txHash;
421
+ switch (rebalanceAction.type) {
422
+ case 'split': {
423
+ const result = await this.ctf.split(this.market.conditionId, rebalanceAction.amount.toString());
424
+ txHash = result.txHash;
425
+ this.log(` ✅ Split TX: ${txHash}`);
426
+ break;
427
+ }
428
+ case 'merge': {
429
+ const tokenIds = {
430
+ yesTokenId: this.market.yesTokenId,
431
+ noTokenId: this.market.noTokenId,
432
+ };
433
+ const result = await this.ctf.mergeByTokenIds(this.market.conditionId, tokenIds, rebalanceAction.amount.toString());
434
+ txHash = result.txHash;
435
+ this.log(` ✅ Merge TX: ${txHash}`);
436
+ break;
437
+ }
438
+ case 'sell_yes': {
439
+ const result = await this.tradingService.createMarketOrder({
440
+ tokenId: this.market.yesTokenId,
441
+ side: 'SELL',
442
+ amount: rebalanceAction.amount,
443
+ orderType: 'FOK',
444
+ });
445
+ if (!result.success) {
446
+ throw new Error(result.errorMsg || 'Sell YES failed');
447
+ }
448
+ this.log(` ✅ Sold ${rebalanceAction.amount.toFixed(2)} YES tokens`);
449
+ break;
450
+ }
451
+ case 'sell_no': {
452
+ const result = await this.tradingService.createMarketOrder({
453
+ tokenId: this.market.noTokenId,
454
+ side: 'SELL',
455
+ amount: rebalanceAction.amount,
456
+ orderType: 'FOK',
457
+ });
458
+ if (!result.success) {
459
+ throw new Error(result.errorMsg || 'Sell NO failed');
460
+ }
461
+ this.log(` ✅ Sold ${rebalanceAction.amount.toFixed(2)} NO tokens`);
462
+ break;
463
+ }
464
+ }
465
+ await this.updateBalance();
466
+ const rebalanceResult = { success: true, action: rebalanceAction, txHash };
467
+ this.emit('rebalance', rebalanceResult);
468
+ return rebalanceResult;
469
+ }
470
+ catch (error) {
471
+ this.log(` ❌ Failed: ${error.message}`);
472
+ const rebalanceResult = {
473
+ success: false,
474
+ action: rebalanceAction,
475
+ error: error.message,
476
+ };
477
+ this.emit('rebalance', rebalanceResult);
478
+ return rebalanceResult;
479
+ }
480
+ }
481
+ // ===== Settle Position Methods =====
482
+ /**
483
+ * Settle a market position - merge paired tokens to recover USDC
484
+ * @param market Market to settle (defaults to current market)
485
+ * @param execute If true, execute the merge. If false, just return info.
486
+ */
487
+ async settlePosition(market, execute = false) {
488
+ const targetMarket = market || this.market;
489
+ if (!targetMarket) {
490
+ throw new Error('No market specified');
491
+ }
492
+ if (!this.ctf) {
493
+ return {
494
+ market: targetMarket,
495
+ yesBalance: 0,
496
+ noBalance: 0,
497
+ pairedTokens: 0,
498
+ unpairedYes: 0,
499
+ unpairedNo: 0,
500
+ merged: false,
501
+ error: 'CTF client not configured',
502
+ };
503
+ }
504
+ const tokenIds = {
505
+ yesTokenId: targetMarket.yesTokenId,
506
+ noTokenId: targetMarket.noTokenId,
507
+ };
508
+ // Get token balances
509
+ const positions = await this.ctf.getPositionBalanceByTokenIds(targetMarket.conditionId, tokenIds);
510
+ const yesBalance = parseFloat(positions.yesBalance);
511
+ const noBalance = parseFloat(positions.noBalance);
512
+ const pairedTokens = Math.min(yesBalance, noBalance);
513
+ const unpairedYes = yesBalance - pairedTokens;
514
+ const unpairedNo = noBalance - pairedTokens;
515
+ this.log(`\n📊 Position: ${targetMarket.name}`);
516
+ this.log(` YES: ${yesBalance.toFixed(6)}`);
517
+ this.log(` NO: ${noBalance.toFixed(6)}`);
518
+ this.log(` Paired: ${pairedTokens.toFixed(6)} (can merge → $${pairedTokens.toFixed(2)} USDC)`);
519
+ if (unpairedYes > 0.001) {
520
+ this.log(` ⚠️ Unpaired YES: ${unpairedYes.toFixed(6)}`);
521
+ }
522
+ if (unpairedNo > 0.001) {
523
+ this.log(` ⚠️ Unpaired NO: ${unpairedNo.toFixed(6)}`);
524
+ }
525
+ const result = {
526
+ market: targetMarket,
527
+ yesBalance,
528
+ noBalance,
529
+ pairedTokens,
530
+ unpairedYes,
531
+ unpairedNo,
532
+ merged: false,
533
+ };
534
+ // Execute merge if requested and we have enough pairs
535
+ if (execute && pairedTokens >= 1) {
536
+ const mergeAmount = Math.floor(pairedTokens * 1e6) / 1e6;
537
+ this.log(`\n🔄 Merging ${mergeAmount.toFixed(6)} token pairs...`);
538
+ try {
539
+ const mergeResult = await this.ctf.mergeByTokenIds(targetMarket.conditionId, tokenIds, mergeAmount.toString());
540
+ result.merged = true;
541
+ result.mergeAmount = mergeAmount;
542
+ result.mergeTxHash = mergeResult.txHash;
543
+ result.usdcRecovered = mergeAmount;
544
+ this.log(` ✅ Merge TX: ${mergeResult.txHash}`);
545
+ this.log(` ✅ Recovered: $${mergeAmount.toFixed(2)} USDC`);
546
+ }
547
+ catch (error) {
548
+ result.error = error.message;
549
+ this.log(` ❌ Merge failed: ${error.message}`);
550
+ }
551
+ }
552
+ else if (pairedTokens >= 1) {
553
+ this.log(` 💡 Run settlePosition(market, true) to recover $${pairedTokens.toFixed(2)} USDC`);
554
+ }
555
+ this.emit('settle', result);
556
+ return result;
557
+ }
558
+ /**
559
+ * Settle multiple markets at once
560
+ */
561
+ async settleMultiple(markets, execute = false) {
562
+ const results = [];
563
+ let totalMerged = 0;
564
+ let totalUnpairedYes = 0;
565
+ let totalUnpairedNo = 0;
566
+ for (const market of markets) {
567
+ const result = await this.settlePosition(market, execute);
568
+ results.push(result);
569
+ if (result.usdcRecovered)
570
+ totalMerged += result.usdcRecovered;
571
+ totalUnpairedYes += result.unpairedYes;
572
+ totalUnpairedNo += result.unpairedNo;
573
+ }
574
+ this.log(`\n═══════════════════════════════════════`);
575
+ this.log(`SUMMARY: ${markets.length} markets`);
576
+ if (execute) {
577
+ this.log(`Total Merged: $${totalMerged.toFixed(2)} USDC`);
578
+ }
579
+ if (totalUnpairedYes > 0.001 || totalUnpairedNo > 0.001) {
580
+ this.log(`Unpaired YES: ${totalUnpairedYes.toFixed(6)}`);
581
+ this.log(`Unpaired NO: ${totalUnpairedNo.toFixed(6)}`);
582
+ }
583
+ return results;
584
+ }
585
+ /**
586
+ * Clear all positions in a market using the best strategy
587
+ *
588
+ * Strategy:
589
+ * - Active market: Merge paired tokens → Sell remaining unpaired tokens
590
+ * - Resolved market: Redeem winning tokens
591
+ *
592
+ * @param market Market to clear positions from
593
+ * @param execute If true, execute the clearing. If false, just return info.
594
+ * @returns Result with all actions taken
595
+ *
596
+ * @example
597
+ * ```typescript
598
+ * const service = new ArbitrageService({ privateKey: '0x...' });
599
+ *
600
+ * // View clearing plan
601
+ * const plan = await service.clearPositions(market, false);
602
+ * console.log(`Will recover: $${plan.totalUsdcRecovered}`);
603
+ *
604
+ * // Execute clearing
605
+ * const result = await service.clearPositions(market, true);
606
+ * ```
607
+ */
608
+ async clearPositions(market, execute = false) {
609
+ if (!this.ctf) {
610
+ return {
611
+ market,
612
+ marketStatus: 'unknown',
613
+ yesBalance: 0,
614
+ noBalance: 0,
615
+ actions: [],
616
+ totalUsdcRecovered: 0,
617
+ success: false,
618
+ error: 'CTF client not configured',
619
+ };
620
+ }
621
+ const tokenIds = {
622
+ yesTokenId: market.yesTokenId,
623
+ noTokenId: market.noTokenId,
624
+ };
625
+ // Get token balances
626
+ const positions = await this.ctf.getPositionBalanceByTokenIds(market.conditionId, tokenIds);
627
+ const yesBalance = parseFloat(positions.yesBalance);
628
+ const noBalance = parseFloat(positions.noBalance);
629
+ if (yesBalance < 0.001 && noBalance < 0.001) {
630
+ this.log(`No positions to clear for ${market.name}`);
631
+ return {
632
+ market,
633
+ marketStatus: 'unknown',
634
+ yesBalance,
635
+ noBalance,
636
+ actions: [],
637
+ totalUsdcRecovered: 0,
638
+ success: true,
639
+ };
640
+ }
641
+ this.log(`\n🧹 Clearing positions: ${market.name}`);
642
+ this.log(` YES: ${yesBalance.toFixed(6)}, NO: ${noBalance.toFixed(6)}`);
643
+ // Check if market is resolved
644
+ let marketStatus = 'unknown';
645
+ // winningOutcome can be any outcome name (YES/NO, Up/Down, Team1/Team2, etc.)
646
+ let winningOutcome;
647
+ try {
648
+ const resolution = await this.ctf.getMarketResolution(market.conditionId);
649
+ marketStatus = resolution.isResolved ? 'resolved' : 'active';
650
+ winningOutcome = resolution.winningOutcome;
651
+ this.log(` Status: ${marketStatus}${resolution.isResolved ? ` (Winner: ${winningOutcome})` : ''}`);
652
+ }
653
+ catch {
654
+ // If we can't determine resolution, try to get market status from MarketService
655
+ try {
656
+ const cache = createUnifiedCache();
657
+ const tempMarketService = new MarketService(undefined, undefined, this.rateLimiter, cache);
658
+ const clobMarket = await tempMarketService.getClobMarket(market.conditionId);
659
+ if (clobMarket) {
660
+ marketStatus = clobMarket.closed ? 'resolved' : 'active';
661
+ this.log(` Status: ${marketStatus} (from MarketService)`);
662
+ }
663
+ else {
664
+ this.log(` Status: unknown (market not found, assuming active)`);
665
+ marketStatus = 'active';
666
+ }
667
+ }
668
+ catch {
669
+ this.log(` Status: unknown (assuming active)`);
670
+ marketStatus = 'active';
671
+ }
672
+ }
673
+ const actions = [];
674
+ let totalUsdcRecovered = 0;
675
+ if (!execute) {
676
+ // Dry run - calculate expected actions
677
+ if (marketStatus === 'resolved' && winningOutcome) {
678
+ // Resolved market: redeem winning tokens
679
+ const winningBalance = winningOutcome === 'YES' ? yesBalance : noBalance;
680
+ if (winningBalance >= 0.001) {
681
+ actions.push({
682
+ type: 'redeem',
683
+ amount: winningBalance,
684
+ usdcResult: winningBalance, // 1 USDC per winning token
685
+ success: true,
686
+ });
687
+ totalUsdcRecovered = winningBalance;
688
+ }
689
+ }
690
+ else {
691
+ // Active market: merge + sell
692
+ const pairedTokens = Math.min(yesBalance, noBalance);
693
+ const unpairedYes = yesBalance - pairedTokens;
694
+ const unpairedNo = noBalance - pairedTokens;
695
+ if (pairedTokens >= 1) {
696
+ actions.push({
697
+ type: 'merge',
698
+ amount: pairedTokens,
699
+ usdcResult: pairedTokens,
700
+ success: true,
701
+ });
702
+ totalUsdcRecovered += pairedTokens;
703
+ }
704
+ // For unpaired tokens, estimate sell price (assume ~0.5 if unknown)
705
+ if (unpairedYes >= this.config.minTradeSize) {
706
+ const estimatedPrice = 0.5; // Conservative estimate
707
+ actions.push({
708
+ type: 'sell_yes',
709
+ amount: unpairedYes,
710
+ usdcResult: unpairedYes * estimatedPrice,
711
+ success: true,
712
+ });
713
+ totalUsdcRecovered += unpairedYes * estimatedPrice;
714
+ }
715
+ if (unpairedNo >= this.config.minTradeSize) {
716
+ const estimatedPrice = 0.5;
717
+ actions.push({
718
+ type: 'sell_no',
719
+ amount: unpairedNo,
720
+ usdcResult: unpairedNo * estimatedPrice,
721
+ success: true,
722
+ });
723
+ totalUsdcRecovered += unpairedNo * estimatedPrice;
724
+ }
725
+ }
726
+ this.log(` 📋 Plan: ${actions.length} actions, ~$${totalUsdcRecovered.toFixed(2)} USDC`);
727
+ for (const action of actions) {
728
+ this.log(` - ${action.type}: ${action.amount.toFixed(4)} → ~$${action.usdcResult.toFixed(2)}`);
729
+ }
730
+ return {
731
+ market,
732
+ marketStatus,
733
+ yesBalance,
734
+ noBalance,
735
+ actions,
736
+ totalUsdcRecovered,
737
+ success: true,
738
+ };
739
+ }
740
+ // Execute clearing
741
+ this.log(` 🔄 Executing...`);
742
+ if (marketStatus === 'resolved' && winningOutcome) {
743
+ // Resolved market: redeem
744
+ const winningBalance = winningOutcome === 'YES' ? yesBalance : noBalance;
745
+ if (winningBalance >= 0.001) {
746
+ try {
747
+ const redeemResult = await this.ctf.redeem(market.conditionId);
748
+ actions.push({
749
+ type: 'redeem',
750
+ amount: winningBalance,
751
+ usdcResult: winningBalance,
752
+ txHash: redeemResult.txHash,
753
+ success: true,
754
+ });
755
+ totalUsdcRecovered = winningBalance;
756
+ this.log(` ✅ Redeemed: ${winningBalance.toFixed(4)} tokens → $${winningBalance.toFixed(2)} USDC`);
757
+ }
758
+ catch (error) {
759
+ actions.push({
760
+ type: 'redeem',
761
+ amount: winningBalance,
762
+ usdcResult: 0,
763
+ success: false,
764
+ error: error.message,
765
+ });
766
+ this.log(` ❌ Redeem failed: ${error.message}`);
767
+ }
768
+ }
769
+ }
770
+ else {
771
+ // Active market: merge + sell
772
+ const pairedTokens = Math.min(yesBalance, noBalance);
773
+ let unpairedYes = yesBalance - pairedTokens;
774
+ let unpairedNo = noBalance - pairedTokens;
775
+ // Step 1: Merge paired tokens
776
+ if (pairedTokens >= 1) {
777
+ const mergeAmount = Math.floor(pairedTokens * 1e6) / 1e6;
778
+ try {
779
+ const mergeResult = await this.ctf.mergeByTokenIds(market.conditionId, tokenIds, mergeAmount.toString());
780
+ actions.push({
781
+ type: 'merge',
782
+ amount: mergeAmount,
783
+ usdcResult: mergeAmount,
784
+ txHash: mergeResult.txHash,
785
+ success: true,
786
+ });
787
+ totalUsdcRecovered += mergeAmount;
788
+ this.log(` ✅ Merged: ${mergeAmount.toFixed(4)} pairs → $${mergeAmount.toFixed(2)} USDC`);
789
+ }
790
+ catch (error) {
791
+ actions.push({
792
+ type: 'merge',
793
+ amount: mergeAmount,
794
+ usdcResult: 0,
795
+ success: false,
796
+ error: error.message,
797
+ });
798
+ this.log(` ❌ Merge failed: ${error.message}`);
799
+ // Update unpaired amounts since merge failed
800
+ unpairedYes = yesBalance;
801
+ unpairedNo = noBalance;
802
+ }
803
+ }
804
+ // Step 2: Sell unpaired tokens
805
+ if (this.tradingService && unpairedYes >= this.config.minTradeSize) {
806
+ try {
807
+ const sellAmount = Math.floor(unpairedYes * 1e6) / 1e6;
808
+ const result = await this.tradingService.createMarketOrder({
809
+ tokenId: market.yesTokenId,
810
+ side: 'SELL',
811
+ amount: sellAmount,
812
+ orderType: 'FOK',
813
+ });
814
+ if (result.success) {
815
+ // Estimate USDC received (conservative estimate since we don't have exact trade info)
816
+ const usdcReceived = sellAmount * 0.5; // Assume ~0.5 average price
817
+ actions.push({
818
+ type: 'sell_yes',
819
+ amount: sellAmount,
820
+ usdcResult: usdcReceived,
821
+ success: true,
822
+ });
823
+ totalUsdcRecovered += usdcReceived;
824
+ this.log(` ✅ Sold YES: ${sellAmount.toFixed(4)} → ~$${usdcReceived.toFixed(2)} USDC`);
825
+ }
826
+ else {
827
+ throw new Error(result.errorMsg || 'Sell failed');
828
+ }
829
+ }
830
+ catch (error) {
831
+ actions.push({
832
+ type: 'sell_yes',
833
+ amount: unpairedYes,
834
+ usdcResult: 0,
835
+ success: false,
836
+ error: error.message,
837
+ });
838
+ this.log(` ❌ Sell YES failed: ${error.message}`);
839
+ }
840
+ }
841
+ if (this.tradingService && unpairedNo >= this.config.minTradeSize) {
842
+ try {
843
+ const sellAmount = Math.floor(unpairedNo * 1e6) / 1e6;
844
+ const result = await this.tradingService.createMarketOrder({
845
+ tokenId: market.noTokenId,
846
+ side: 'SELL',
847
+ amount: sellAmount,
848
+ orderType: 'FOK',
849
+ });
850
+ if (result.success) {
851
+ // Estimate USDC received (conservative estimate since we don't have exact trade info)
852
+ const usdcReceived = sellAmount * 0.5; // Assume ~0.5 average price
853
+ actions.push({
854
+ type: 'sell_no',
855
+ amount: sellAmount,
856
+ usdcResult: usdcReceived,
857
+ success: true,
858
+ });
859
+ totalUsdcRecovered += usdcReceived;
860
+ this.log(` ✅ Sold NO: ${sellAmount.toFixed(4)} → ~$${usdcReceived.toFixed(2)} USDC`);
861
+ }
862
+ else {
863
+ throw new Error(result.errorMsg || 'Sell failed');
864
+ }
865
+ }
866
+ catch (error) {
867
+ actions.push({
868
+ type: 'sell_no',
869
+ amount: unpairedNo,
870
+ usdcResult: 0,
871
+ success: false,
872
+ error: error.message,
873
+ });
874
+ this.log(` ❌ Sell NO failed: ${error.message}`);
875
+ }
876
+ }
877
+ }
878
+ const allSuccess = actions.every((a) => a.success);
879
+ this.log(` 📊 Result: ${actions.filter((a) => a.success).length}/${actions.length} succeeded, $${totalUsdcRecovered.toFixed(2)} recovered`);
880
+ const result = {
881
+ market,
882
+ marketStatus,
883
+ yesBalance,
884
+ noBalance,
885
+ actions,
886
+ totalUsdcRecovered,
887
+ success: allSuccess,
888
+ };
889
+ this.emit('settle', result);
890
+ return result;
891
+ }
892
+ /**
893
+ * Clear positions from multiple markets
894
+ *
895
+ * @param markets Markets to clear
896
+ * @param execute If true, execute clearing
897
+ * @returns Results for all markets
898
+ */
899
+ async clearAllPositions(markets, execute = false) {
900
+ const results = [];
901
+ let totalRecovered = 0;
902
+ this.log(`\n🧹 Clearing positions from ${markets.length} markets...`);
903
+ for (const market of markets) {
904
+ const result = await this.clearPositions(market, execute);
905
+ results.push(result);
906
+ totalRecovered += result.totalUsdcRecovered;
907
+ }
908
+ this.log(`\n═══════════════════════════════════════`);
909
+ this.log(`TOTAL: $${totalRecovered.toFixed(2)} USDC ${execute ? 'recovered' : 'expected'}`);
910
+ return results;
911
+ }
912
+ // ===== Private Methods =====
913
+ handleBookUpdate(update) {
914
+ if (!this.market)
915
+ return;
916
+ const { assetId, bids, asks } = update;
917
+ if (assetId === this.market.yesTokenId) {
918
+ this.orderbook.yesBids = bids.sort((a, b) => b.price - a.price);
919
+ this.orderbook.yesAsks = asks.sort((a, b) => a.price - b.price);
920
+ }
921
+ else if (assetId === this.market.noTokenId) {
922
+ this.orderbook.noBids = bids.sort((a, b) => b.price - a.price);
923
+ this.orderbook.noAsks = asks.sort((a, b) => a.price - b.price);
924
+ }
925
+ this.orderbook.lastUpdate = Date.now();
926
+ this.emit('orderbookUpdate', this.orderbook);
927
+ // Check for arbitrage opportunity
928
+ this.checkAndHandleOpportunity();
929
+ }
930
+ checkAndHandleOpportunity() {
931
+ const opportunity = this.checkOpportunity();
932
+ if (opportunity) {
933
+ this.stats.opportunitiesDetected++;
934
+ this.emit('opportunity', opportunity);
935
+ this.log(`\n${'!'.repeat(60)}`);
936
+ this.log(`${opportunity.type.toUpperCase()} ARB: ${opportunity.description}`);
937
+ this.log(`Profit: ${opportunity.profitPercent.toFixed(2)}%, Size: ${opportunity.recommendedSize.toFixed(2)}, Est: $${opportunity.estimatedProfit.toFixed(2)}`);
938
+ this.log('!'.repeat(60));
939
+ // Auto-execute if enabled and cooldown has passed
940
+ if (this.config.autoExecute && !this.isExecuting) {
941
+ const timeSinceLastExecution = Date.now() - this.lastExecutionTime;
942
+ if (timeSinceLastExecution >= this.config.executionCooldown) {
943
+ this.execute(opportunity).catch((error) => {
944
+ this.emit('error', error);
945
+ });
946
+ }
947
+ }
948
+ }
949
+ }
950
+ async checkAndRebalance() {
951
+ if (!this.isRunning || this.isExecuting)
952
+ return;
953
+ // Check cooldown
954
+ const timeSinceLastRebalance = Date.now() - this.lastRebalanceTime;
955
+ if (timeSinceLastRebalance < this.config.rebalanceCooldown) {
956
+ return;
957
+ }
958
+ await this.updateBalance();
959
+ const action = this.calculateRebalanceAction();
960
+ if (action.type !== 'none' && action.amount >= this.config.minTradeSize) {
961
+ await this.rebalance(action);
962
+ this.lastRebalanceTime = Date.now();
963
+ }
964
+ }
965
+ /**
966
+ * Fix YES/NO imbalance immediately after partial execution
967
+ * This is critical when one side of a parallel order fails
968
+ */
969
+ async fixImbalanceIfNeeded() {
970
+ if (!this.config.autoFixImbalance || !this.ctf || !this.tradingService || !this.market)
971
+ return;
972
+ await this.updateBalance();
973
+ const imbalance = this.balance.yesTokens - this.balance.noTokens;
974
+ if (Math.abs(imbalance) <= this.config.imbalanceThreshold)
975
+ return;
976
+ this.log(`\n⚠️ Imbalance detected after execution: ${imbalance > 0 ? 'YES' : 'NO'} excess = ${Math.abs(imbalance).toFixed(2)}`);
977
+ // Sell the excess tokens to restore balance
978
+ const sellAmount = Math.floor(Math.abs(imbalance) * 0.9 * 1e6) / 1e6; // Sell 90% to be safe
979
+ if (sellAmount < this.config.minTradeSize)
980
+ return;
981
+ try {
982
+ if (imbalance > 0) {
983
+ // Sell excess YES
984
+ const result = await this.tradingService.createMarketOrder({
985
+ tokenId: this.market.yesTokenId,
986
+ side: 'SELL',
987
+ amount: sellAmount,
988
+ orderType: 'FOK',
989
+ });
990
+ if (result.success) {
991
+ this.log(` ✅ Sold ${sellAmount.toFixed(2)} excess YES to restore balance`);
992
+ }
993
+ }
994
+ else {
995
+ // Sell excess NO
996
+ const result = await this.tradingService.createMarketOrder({
997
+ tokenId: this.market.noTokenId,
998
+ side: 'SELL',
999
+ amount: sellAmount,
1000
+ orderType: 'FOK',
1001
+ });
1002
+ if (result.success) {
1003
+ this.log(` ✅ Sold ${sellAmount.toFixed(2)} excess NO to restore balance`);
1004
+ }
1005
+ }
1006
+ }
1007
+ catch (error) {
1008
+ this.log(` ❌ Failed to fix imbalance: ${error.message}`);
1009
+ }
1010
+ }
1011
+ async updateBalance() {
1012
+ if (!this.ctf || !this.market)
1013
+ return;
1014
+ try {
1015
+ const tokenIds = {
1016
+ yesTokenId: this.market.yesTokenId,
1017
+ noTokenId: this.market.noTokenId,
1018
+ };
1019
+ const [usdcBalance, positions] = await Promise.all([
1020
+ this.ctf.getUsdcBalance(),
1021
+ this.ctf.getPositionBalanceByTokenIds(this.market.conditionId, tokenIds),
1022
+ ]);
1023
+ this.balance = {
1024
+ usdc: parseFloat(usdcBalance),
1025
+ yesTokens: parseFloat(positions.yesBalance),
1026
+ noTokens: parseFloat(positions.noBalance),
1027
+ lastUpdate: Date.now(),
1028
+ };
1029
+ this.emit('balanceUpdate', this.balance);
1030
+ }
1031
+ catch (error) {
1032
+ this.emit('error', error);
1033
+ }
1034
+ }
1035
+ async executeLongArb(opportunity) {
1036
+ const startTime = Date.now();
1037
+ const txHashes = [];
1038
+ const size = opportunity.recommendedSize;
1039
+ this.log(`\nExecuting Long Arb (Buy → Merge)...`);
1040
+ try {
1041
+ const { buyYes, buyNo } = opportunity.effectivePrices;
1042
+ const requiredUsdc = (buyYes + buyNo) * size;
1043
+ if (this.balance.usdc < requiredUsdc) {
1044
+ return {
1045
+ success: false,
1046
+ type: 'long',
1047
+ size,
1048
+ profit: 0,
1049
+ txHashes,
1050
+ error: `Insufficient USDC.e: have ${this.balance.usdc.toFixed(2)}, need ${requiredUsdc.toFixed(2)}`,
1051
+ executionTimeMs: Date.now() - startTime,
1052
+ };
1053
+ }
1054
+ // Buy both tokens in parallel
1055
+ this.log(` 1. Buying tokens in parallel...`);
1056
+ const [buyYesResult, buyNoResult] = await Promise.all([
1057
+ this.tradingService.createMarketOrder({
1058
+ tokenId: this.market.yesTokenId,
1059
+ side: 'BUY',
1060
+ amount: size * buyYes,
1061
+ orderType: 'FOK',
1062
+ }),
1063
+ this.tradingService.createMarketOrder({
1064
+ tokenId: this.market.noTokenId,
1065
+ side: 'BUY',
1066
+ amount: size * buyNo,
1067
+ orderType: 'FOK',
1068
+ }),
1069
+ ]);
1070
+ const outcomes = this.market.outcomes || ['YES', 'NO'];
1071
+ this.log(` ${outcomes[0]}: ${buyYesResult.success ? '✓' : '✗'}, ${outcomes[1]}: ${buyNoResult.success ? '✓' : '✗'}`);
1072
+ // If one succeeded and the other failed, we have an imbalance - fix it
1073
+ if (!buyYesResult.success || !buyNoResult.success) {
1074
+ // Check if partial execution created imbalance
1075
+ if (buyYesResult.success !== buyNoResult.success) {
1076
+ this.log(` ⚠️ Partial execution detected - attempting to fix imbalance...`);
1077
+ await this.fixImbalanceIfNeeded();
1078
+ }
1079
+ return {
1080
+ success: false,
1081
+ type: 'long',
1082
+ size,
1083
+ profit: 0,
1084
+ txHashes,
1085
+ error: `Order(s) failed: YES=${buyYesResult.errorMsg}, NO=${buyNoResult.errorMsg}`,
1086
+ executionTimeMs: Date.now() - startTime,
1087
+ };
1088
+ }
1089
+ // Merge tokens
1090
+ const tokenIds = {
1091
+ yesTokenId: this.market.yesTokenId,
1092
+ noTokenId: this.market.noTokenId,
1093
+ };
1094
+ // Update balance to get accurate token counts
1095
+ await this.updateBalance();
1096
+ const heldPairs = Math.min(this.balance.yesTokens, this.balance.noTokens);
1097
+ const mergeSize = Math.floor(Math.min(size, heldPairs) * 1e6) / 1e6;
1098
+ if (mergeSize >= this.config.minTradeSize) {
1099
+ this.log(` 2. Merging ${mergeSize.toFixed(2)} pairs...`);
1100
+ try {
1101
+ const mergeResult = await this.ctf.mergeByTokenIds(this.market.conditionId, tokenIds, mergeSize.toString());
1102
+ txHashes.push(mergeResult.txHash);
1103
+ this.log(` TX: ${mergeResult.txHash}`);
1104
+ const profit = opportunity.profitRate * mergeSize;
1105
+ this.log(` ✅ Long Arb completed! Profit: ~$${profit.toFixed(2)}`);
1106
+ return {
1107
+ success: true,
1108
+ type: 'long',
1109
+ size: mergeSize,
1110
+ profit,
1111
+ txHashes,
1112
+ executionTimeMs: Date.now() - startTime,
1113
+ };
1114
+ }
1115
+ catch (mergeError) {
1116
+ this.log(` ⚠️ Merge failed: ${mergeError.message}`);
1117
+ return {
1118
+ success: false,
1119
+ type: 'long',
1120
+ size,
1121
+ profit: 0,
1122
+ txHashes,
1123
+ error: `Merge failed: ${mergeError.message}`,
1124
+ executionTimeMs: Date.now() - startTime,
1125
+ };
1126
+ }
1127
+ }
1128
+ return {
1129
+ success: false,
1130
+ type: 'long',
1131
+ size,
1132
+ profit: 0,
1133
+ txHashes,
1134
+ error: `Insufficient pairs for merge: ${heldPairs.toFixed(2)}`,
1135
+ executionTimeMs: Date.now() - startTime,
1136
+ };
1137
+ }
1138
+ catch (error) {
1139
+ return {
1140
+ success: false,
1141
+ type: 'long',
1142
+ size,
1143
+ profit: 0,
1144
+ txHashes,
1145
+ error: error.message,
1146
+ executionTimeMs: Date.now() - startTime,
1147
+ };
1148
+ }
1149
+ }
1150
+ async executeShortArb(opportunity) {
1151
+ const startTime = Date.now();
1152
+ const txHashes = [];
1153
+ const size = opportunity.recommendedSize;
1154
+ this.log(`\nExecuting Short Arb (Sell Pre-held Tokens)...`);
1155
+ try {
1156
+ const heldPairs = Math.min(this.balance.yesTokens, this.balance.noTokens);
1157
+ if (heldPairs < size) {
1158
+ return {
1159
+ success: false,
1160
+ type: 'short',
1161
+ size,
1162
+ profit: 0,
1163
+ txHashes,
1164
+ error: `Insufficient held tokens: have ${heldPairs.toFixed(2)}, need ${size.toFixed(2)}`,
1165
+ executionTimeMs: Date.now() - startTime,
1166
+ };
1167
+ }
1168
+ // Sell both tokens in parallel
1169
+ this.log(` 1. Selling pre-held tokens in parallel...`);
1170
+ const [sellYesResult, sellNoResult] = await Promise.all([
1171
+ this.tradingService.createMarketOrder({
1172
+ tokenId: this.market.yesTokenId,
1173
+ side: 'SELL',
1174
+ amount: size,
1175
+ orderType: 'FOK',
1176
+ }),
1177
+ this.tradingService.createMarketOrder({
1178
+ tokenId: this.market.noTokenId,
1179
+ side: 'SELL',
1180
+ amount: size,
1181
+ orderType: 'FOK',
1182
+ }),
1183
+ ]);
1184
+ const outcomes = this.market.outcomes || ['YES', 'NO'];
1185
+ this.log(` ${outcomes[0]}: ${sellYesResult.success ? '✓' : '✗'}, ${outcomes[1]}: ${sellNoResult.success ? '✓' : '✗'}`);
1186
+ // If one succeeded and the other failed, we have an imbalance
1187
+ if (!sellYesResult.success || !sellNoResult.success) {
1188
+ // Check if partial execution created imbalance
1189
+ if (sellYesResult.success !== sellNoResult.success) {
1190
+ this.log(` ⚠️ Partial execution detected - imbalance created`);
1191
+ // Note: For short arb, we just sold one side, creating imbalance
1192
+ // The rebalancer will fix this on next cycle
1193
+ await this.fixImbalanceIfNeeded();
1194
+ }
1195
+ return {
1196
+ success: false,
1197
+ type: 'short',
1198
+ size,
1199
+ profit: 0,
1200
+ txHashes,
1201
+ error: `Order(s) failed: YES=${sellYesResult.errorMsg}, NO=${sellNoResult.errorMsg}`,
1202
+ executionTimeMs: Date.now() - startTime,
1203
+ };
1204
+ }
1205
+ const profit = opportunity.profitRate * size;
1206
+ this.log(` ✅ Short Arb completed! Profit: ~$${profit.toFixed(2)}`);
1207
+ return {
1208
+ success: true,
1209
+ type: 'short',
1210
+ size,
1211
+ profit,
1212
+ txHashes,
1213
+ executionTimeMs: Date.now() - startTime,
1214
+ };
1215
+ }
1216
+ catch (error) {
1217
+ return {
1218
+ success: false,
1219
+ type: 'short',
1220
+ size,
1221
+ profit: 0,
1222
+ txHashes,
1223
+ error: error.message,
1224
+ executionTimeMs: Date.now() - startTime,
1225
+ };
1226
+ }
1227
+ }
1228
+ log(message) {
1229
+ if (this.config.enableLogging) {
1230
+ console.log(`[ArbitrageService] ${message}`);
1231
+ }
1232
+ }
1233
+ // ===== Market Scanning Methods =====
1234
+ /**
1235
+ * Scan markets for arbitrage opportunities
1236
+ *
1237
+ * @param criteria Filter criteria for markets
1238
+ * @param minProfit Minimum profit threshold (default: 0.005 = 0.5%)
1239
+ * @returns Array of scan results sorted by profit
1240
+ *
1241
+ * @example
1242
+ * ```typescript
1243
+ * const service = new ArbitrageService({ privateKey: '0x...' });
1244
+ *
1245
+ * // Scan markets with at least $5000 volume
1246
+ * const results = await service.scanMarkets({ minVolume24h: 5000 }, 0.005);
1247
+ *
1248
+ * // Start arbitraging the best opportunity
1249
+ * if (results.length > 0 && results[0].arbType !== 'none') {
1250
+ * await service.start(results[0].market);
1251
+ * }
1252
+ * ```
1253
+ */
1254
+ async scanMarkets(criteria = {}, minProfit = 0.005) {
1255
+ const { minVolume24h = 1000, maxVolume24h, keywords = [], limit = 100, } = criteria;
1256
+ this.log(`Scanning markets (minVolume: $${minVolume24h}, minProfit: ${(minProfit * 100).toFixed(2)}%)...`);
1257
+ // Create temporary API clients for scanning
1258
+ const cache = createUnifiedCache();
1259
+ const gammaApi = new GammaApiClient(this.rateLimiter, cache);
1260
+ const tempMarketService = new MarketService(gammaApi, undefined, this.rateLimiter, cache);
1261
+ // Fetch active markets from Gamma API
1262
+ const markets = await gammaApi.getMarkets({
1263
+ active: true,
1264
+ closed: false,
1265
+ limit,
1266
+ });
1267
+ this.log(`Found ${markets.length} active markets`);
1268
+ const results = [];
1269
+ for (const gammaMarket of markets) {
1270
+ try {
1271
+ // Filter by volume
1272
+ const volume24h = gammaMarket.volume24hr || 0;
1273
+ if (volume24h < minVolume24h)
1274
+ continue;
1275
+ if (maxVolume24h && volume24h > maxVolume24h)
1276
+ continue;
1277
+ // Filter by keywords
1278
+ if (keywords.length > 0) {
1279
+ const marketText = `${gammaMarket.question} ${gammaMarket.description || ''}`.toLowerCase();
1280
+ const hasKeyword = keywords.some((kw) => marketText.includes(kw.toLowerCase()));
1281
+ if (!hasKeyword)
1282
+ continue;
1283
+ }
1284
+ // Skip non-binary markets
1285
+ if (!gammaMarket.conditionId || gammaMarket.outcomes?.length !== 2)
1286
+ continue;
1287
+ // Get market data for token IDs
1288
+ let clobMarket;
1289
+ try {
1290
+ clobMarket = await tempMarketService.getClobMarket(gammaMarket.conditionId);
1291
+ if (!clobMarket)
1292
+ continue; // Skip if market not found
1293
+ }
1294
+ catch {
1295
+ continue; // Skip if market data not available
1296
+ }
1297
+ // Use index-based access instead of name-based (supports Yes/No, Up/Down, Team1/Team2, etc.)
1298
+ const yesToken = clobMarket.tokens[0]; // primary outcome
1299
+ const noToken = clobMarket.tokens[1]; // secondary outcome
1300
+ if (!yesToken || !noToken)
1301
+ continue;
1302
+ // Get orderbook data
1303
+ let orderbook;
1304
+ try {
1305
+ orderbook = await tempMarketService.getProcessedOrderbook(gammaMarket.conditionId);
1306
+ }
1307
+ catch {
1308
+ continue; // Skip if orderbook not available
1309
+ }
1310
+ const { effectivePrices, longArbProfit, shortArbProfit } = orderbook.summary;
1311
+ // Determine best arbitrage type
1312
+ let arbType = 'none';
1313
+ let profitRate = 0;
1314
+ if (longArbProfit > minProfit && longArbProfit >= shortArbProfit) {
1315
+ arbType = 'long';
1316
+ profitRate = longArbProfit;
1317
+ }
1318
+ else if (shortArbProfit > minProfit) {
1319
+ arbType = 'short';
1320
+ profitRate = shortArbProfit;
1321
+ }
1322
+ // Calculate available size (min of both sides)
1323
+ const yesAskSize = orderbook.yes.askSize || 0;
1324
+ const noAskSize = orderbook.no.askSize || 0;
1325
+ const yesBidSize = orderbook.yes.bidSize || 0;
1326
+ const noBidSize = orderbook.no.bidSize || 0;
1327
+ const availableSize = arbType === 'long'
1328
+ ? Math.min(yesAskSize, noAskSize)
1329
+ : Math.min(yesBidSize, noBidSize);
1330
+ // Calculate score (profit * volume * available_size)
1331
+ const score = profitRate * 100 * Math.log10(volume24h + 1) * Math.min(availableSize, 100) / 100;
1332
+ // Create market config
1333
+ const marketConfig = {
1334
+ name: gammaMarket.question.slice(0, 60) + (gammaMarket.question.length > 60 ? '...' : ''),
1335
+ conditionId: gammaMarket.conditionId,
1336
+ yesTokenId: yesToken.tokenId,
1337
+ noTokenId: noToken.tokenId,
1338
+ outcomes: gammaMarket.outcomes,
1339
+ };
1340
+ const longCost = effectivePrices.effectiveBuyYes + effectivePrices.effectiveBuyNo;
1341
+ const shortRevenue = effectivePrices.effectiveSellYes + effectivePrices.effectiveSellNo;
1342
+ let description;
1343
+ if (arbType === 'long') {
1344
+ description = `Buy YES@${effectivePrices.effectiveBuyYes.toFixed(4)} + NO@${effectivePrices.effectiveBuyNo.toFixed(4)} = ${longCost.toFixed(4)} → Merge for $1`;
1345
+ }
1346
+ else if (arbType === 'short') {
1347
+ description = `Sell YES@${effectivePrices.effectiveSellYes.toFixed(4)} + NO@${effectivePrices.effectiveSellNo.toFixed(4)} = ${shortRevenue.toFixed(4)}`;
1348
+ }
1349
+ else {
1350
+ description = `No opportunity (Long cost: ${longCost.toFixed(4)}, Short rev: ${shortRevenue.toFixed(4)})`;
1351
+ }
1352
+ results.push({
1353
+ market: marketConfig,
1354
+ arbType,
1355
+ profitRate,
1356
+ profitPercent: profitRate * 100,
1357
+ effectivePrices: {
1358
+ buyYes: effectivePrices.effectiveBuyYes,
1359
+ buyNo: effectivePrices.effectiveBuyNo,
1360
+ sellYes: effectivePrices.effectiveSellYes,
1361
+ sellNo: effectivePrices.effectiveSellNo,
1362
+ longCost,
1363
+ shortRevenue,
1364
+ },
1365
+ volume24h,
1366
+ availableSize,
1367
+ score,
1368
+ description,
1369
+ });
1370
+ }
1371
+ catch (error) {
1372
+ // Skip markets with errors
1373
+ continue;
1374
+ }
1375
+ }
1376
+ // Sort by profit (descending), then by score
1377
+ results.sort((a, b) => {
1378
+ if (b.profitRate !== a.profitRate)
1379
+ return b.profitRate - a.profitRate;
1380
+ return b.score - a.score;
1381
+ });
1382
+ this.log(`Found ${results.filter((r) => r.arbType !== 'none').length} markets with arbitrage opportunities`);
1383
+ return results;
1384
+ }
1385
+ /**
1386
+ * Quick scan for best arbitrage opportunities
1387
+ *
1388
+ * @param minProfit Minimum profit threshold (default: 0.005 = 0.5%)
1389
+ * @param limit Maximum number of results to return (default: 10)
1390
+ * @returns Top arbitrage opportunities
1391
+ *
1392
+ * @example
1393
+ * ```typescript
1394
+ * const service = new ArbitrageService({ privateKey: '0x...' });
1395
+ *
1396
+ * // Find best arbitrage opportunities
1397
+ * const top = await service.quickScan(0.005, 5);
1398
+ *
1399
+ * // Print results
1400
+ * for (const r of top) {
1401
+ * console.log(`${r.market.name}: ${r.arbType} +${r.profitPercent.toFixed(2)}%`);
1402
+ * }
1403
+ *
1404
+ * // Start the best one
1405
+ * if (top.length > 0) {
1406
+ * await service.start(top[0].market);
1407
+ * }
1408
+ * ```
1409
+ */
1410
+ async quickScan(minProfit = 0.005, limit = 10) {
1411
+ const results = await this.scanMarkets({ minVolume24h: 5000, limit: 100 }, minProfit);
1412
+ // Return only markets with opportunities, limited to requested count
1413
+ return results
1414
+ .filter((r) => r.arbType !== 'none')
1415
+ .slice(0, limit);
1416
+ }
1417
+ /**
1418
+ * Find and start arbitraging the best opportunity
1419
+ *
1420
+ * @param minProfit Minimum profit threshold (default: 0.005 = 0.5%)
1421
+ * @returns The scan result that was started, or null if none found
1422
+ *
1423
+ * @example
1424
+ * ```typescript
1425
+ * const service = new ArbitrageService({
1426
+ * privateKey: '0x...',
1427
+ * autoExecute: true,
1428
+ * profitThreshold: 0.005,
1429
+ * });
1430
+ *
1431
+ * // Find and start the best opportunity
1432
+ * const started = await service.findAndStart(0.005);
1433
+ * if (started) {
1434
+ * console.log(`Started: ${started.market.name} (+${started.profitPercent.toFixed(2)}%)`);
1435
+ * }
1436
+ * ```
1437
+ */
1438
+ async findAndStart(minProfit = 0.005) {
1439
+ const results = await this.quickScan(minProfit, 1);
1440
+ if (results.length === 0) {
1441
+ this.log('No arbitrage opportunities found');
1442
+ return null;
1443
+ }
1444
+ const best = results[0];
1445
+ this.log(`Best opportunity: ${best.market.name} (${best.arbType} +${best.profitPercent.toFixed(2)}%)`);
1446
+ await this.start(best.market);
1447
+ return best;
1448
+ }
1449
+ }
1450
+ //# sourceMappingURL=arbitrage-service.js.map