@catalyst-team/poly-sdk 0.2.0 → 0.3.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.
- package/LICENSE +1 -1
- package/README.md +548 -813
- package/README.zh-CN.md +805 -0
- package/dist/__tests__/clob-api.test.d.ts +5 -0
- package/dist/__tests__/clob-api.test.d.ts.map +1 -0
- package/dist/__tests__/clob-api.test.js +240 -0
- package/dist/__tests__/clob-api.test.js.map +1 -0
- package/dist/__tests__/integration/arbitrage-service.integration.test.d.ts +12 -0
- package/dist/__tests__/integration/arbitrage-service.integration.test.d.ts.map +1 -0
- package/dist/__tests__/integration/arbitrage-service.integration.test.js +267 -0
- package/dist/__tests__/integration/arbitrage-service.integration.test.js.map +1 -0
- package/dist/__tests__/integration/bridge-client.integration.test.d.ts +11 -0
- package/dist/__tests__/integration/bridge-client.integration.test.d.ts.map +1 -0
- package/dist/__tests__/integration/bridge-client.integration.test.js +260 -0
- package/dist/__tests__/integration/bridge-client.integration.test.js.map +1 -0
- package/dist/__tests__/integration/clob-api.integration.test.d.ts +13 -0
- package/dist/__tests__/integration/clob-api.integration.test.d.ts.map +1 -0
- package/dist/__tests__/integration/clob-api.integration.test.js +170 -0
- package/dist/__tests__/integration/clob-api.integration.test.js.map +1 -0
- package/dist/__tests__/integration/ctf-client.integration.test.d.ts +17 -0
- package/dist/__tests__/integration/ctf-client.integration.test.d.ts.map +1 -0
- package/dist/__tests__/integration/ctf-client.integration.test.js +234 -0
- package/dist/__tests__/integration/ctf-client.integration.test.js.map +1 -0
- package/dist/__tests__/integration/data-api.integration.test.d.ts +9 -0
- package/dist/__tests__/integration/data-api.integration.test.d.ts.map +1 -0
- package/dist/__tests__/integration/data-api.integration.test.js +164 -0
- package/dist/__tests__/integration/data-api.integration.test.js.map +1 -0
- package/dist/__tests__/integration/gamma-api.integration.test.d.ts +9 -0
- package/dist/__tests__/integration/gamma-api.integration.test.d.ts.map +1 -0
- package/dist/__tests__/integration/gamma-api.integration.test.js +170 -0
- package/dist/__tests__/integration/gamma-api.integration.test.js.map +1 -0
- package/dist/__tests__/integration/market-service.integration.test.d.ts +10 -0
- package/dist/__tests__/integration/market-service.integration.test.d.ts.map +1 -0
- package/dist/__tests__/integration/market-service.integration.test.js +173 -0
- package/dist/__tests__/integration/market-service.integration.test.js.map +1 -0
- package/dist/__tests__/integration/realtime-service-v2.integration.test.d.ts +10 -0
- package/dist/__tests__/integration/realtime-service-v2.integration.test.d.ts.map +1 -0
- package/dist/__tests__/integration/realtime-service-v2.integration.test.js +307 -0
- package/dist/__tests__/integration/realtime-service-v2.integration.test.js.map +1 -0
- package/dist/__tests__/integration/trading-service.integration.test.d.ts +10 -0
- package/dist/__tests__/integration/trading-service.integration.test.d.ts.map +1 -0
- package/dist/__tests__/integration/trading-service.integration.test.js +58 -0
- package/dist/__tests__/integration/trading-service.integration.test.js.map +1 -0
- package/dist/__tests__/test-utils.d.ts +92 -0
- package/dist/__tests__/test-utils.d.ts.map +1 -0
- package/dist/__tests__/test-utils.js +143 -0
- package/dist/__tests__/test-utils.js.map +1 -0
- package/dist/clients/bridge-client.d.ts +388 -0
- package/dist/clients/bridge-client.d.ts.map +1 -0
- package/dist/clients/bridge-client.js +587 -0
- package/dist/clients/bridge-client.js.map +1 -0
- package/dist/clients/clob-api.d.ts +391 -0
- package/dist/clients/clob-api.d.ts.map +1 -0
- package/dist/clients/clob-api.js +448 -0
- package/dist/clients/clob-api.js.map +1 -0
- package/dist/clients/ctf-client.d.ts +473 -0
- package/dist/clients/ctf-client.d.ts.map +1 -0
- package/dist/clients/ctf-client.js +915 -0
- package/dist/clients/ctf-client.js.map +1 -0
- package/dist/clients/data-api.d.ts +439 -0
- package/dist/clients/data-api.d.ts.map +1 -0
- package/dist/clients/data-api.js +592 -0
- package/dist/clients/data-api.js.map +1 -0
- package/dist/clients/gamma-api.d.ts +401 -0
- package/dist/clients/gamma-api.d.ts.map +1 -0
- package/dist/clients/gamma-api.js +352 -0
- package/dist/clients/gamma-api.js.map +1 -0
- package/dist/clients/subgraph.d.ts +196 -0
- package/dist/clients/subgraph.d.ts.map +1 -0
- package/dist/clients/subgraph.js +332 -0
- package/dist/clients/subgraph.js.map +1 -0
- package/dist/clients/trading-client.d.ts +252 -0
- package/dist/clients/trading-client.d.ts.map +1 -0
- package/dist/clients/trading-client.js +543 -0
- package/dist/clients/trading-client.js.map +1 -0
- package/dist/clients/websocket-manager.d.ts +103 -0
- package/dist/clients/websocket-manager.d.ts.map +1 -0
- package/dist/clients/websocket-manager.js +200 -0
- package/dist/clients/websocket-manager.js.map +1 -0
- package/dist/core/cache-adapter-bridge.d.ts +36 -0
- package/dist/core/cache-adapter-bridge.d.ts.map +1 -0
- package/dist/core/cache-adapter-bridge.js +81 -0
- package/dist/core/cache-adapter-bridge.js.map +1 -0
- package/dist/core/cache.d.ts +41 -0
- package/dist/core/cache.d.ts.map +1 -0
- package/dist/core/cache.js +72 -0
- package/dist/core/cache.js.map +1 -0
- package/dist/core/errors.d.ts +39 -0
- package/dist/core/errors.d.ts.map +1 -0
- package/dist/core/errors.js +86 -0
- package/dist/core/errors.js.map +1 -0
- package/dist/core/rate-limiter.d.ts +32 -0
- package/dist/core/rate-limiter.d.ts.map +1 -0
- package/dist/core/rate-limiter.js +75 -0
- package/dist/core/rate-limiter.js.map +1 -0
- package/dist/core/types.d.ts +402 -0
- package/dist/core/types.d.ts.map +1 -0
- package/dist/core/types.js +19 -0
- package/dist/core/types.js.map +1 -0
- package/dist/core/types.test.d.ts +7 -0
- package/dist/core/types.test.d.ts.map +1 -0
- package/dist/core/types.test.js +122 -0
- package/dist/core/types.test.js.map +1 -0
- package/dist/core/unified-cache.d.ts +63 -0
- package/dist/core/unified-cache.d.ts.map +1 -0
- package/dist/core/unified-cache.js +114 -0
- package/dist/core/unified-cache.js.map +1 -0
- package/dist/index.d.ts +151 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +248 -0
- package/dist/index.js.map +1 -0
- package/dist/services/arbitrage-service.d.ts +409 -0
- package/dist/services/arbitrage-service.d.ts.map +1 -0
- package/dist/services/arbitrage-service.js +1440 -0
- package/dist/services/arbitrage-service.js.map +1 -0
- package/dist/services/authorization-service.d.ts +97 -0
- package/dist/services/authorization-service.d.ts.map +1 -0
- package/dist/services/authorization-service.js +279 -0
- package/dist/services/authorization-service.js.map +1 -0
- package/dist/services/market-service.d.ts +208 -0
- package/dist/services/market-service.d.ts.map +1 -0
- package/dist/services/market-service.js +774 -0
- package/dist/services/market-service.js.map +1 -0
- package/dist/services/onchain-service.d.ts +309 -0
- package/dist/services/onchain-service.d.ts.map +1 -0
- package/dist/services/onchain-service.js +417 -0
- package/dist/services/onchain-service.js.map +1 -0
- package/dist/services/realtime-service-v2.d.ts +361 -0
- package/dist/services/realtime-service-v2.d.ts.map +1 -0
- package/dist/services/realtime-service-v2.js +840 -0
- package/dist/services/realtime-service-v2.js.map +1 -0
- package/dist/services/realtime-service.d.ts +82 -0
- package/dist/services/realtime-service.d.ts.map +1 -0
- package/dist/services/realtime-service.js +182 -0
- package/dist/services/realtime-service.js.map +1 -0
- package/dist/services/smart-money-service.d.ts +196 -0
- package/dist/services/smart-money-service.d.ts.map +1 -0
- package/dist/services/smart-money-service.js +358 -0
- package/dist/services/smart-money-service.js.map +1 -0
- package/dist/services/swap-service.d.ts +217 -0
- package/dist/services/swap-service.d.ts.map +1 -0
- package/dist/services/swap-service.js +695 -0
- package/dist/services/swap-service.js.map +1 -0
- package/dist/services/trading-service.d.ts +156 -0
- package/dist/services/trading-service.d.ts.map +1 -0
- package/dist/services/trading-service.js +356 -0
- package/dist/services/trading-service.js.map +1 -0
- package/dist/services/wallet-service.d.ts +275 -0
- package/dist/services/wallet-service.d.ts.map +1 -0
- package/dist/services/wallet-service.js +630 -0
- package/dist/services/wallet-service.js.map +1 -0
- package/dist/utils/price-utils.d.ts +153 -0
- package/dist/utils/price-utils.d.ts.map +1 -0
- package/dist/utils/price-utils.js +236 -0
- package/dist/utils/price-utils.js.map +1 -0
- package/dist/utils/price-utils.test.d.ts +5 -0
- package/dist/utils/price-utils.test.d.ts.map +1 -0
- package/dist/utils/price-utils.test.js +192 -0
- package/dist/utils/price-utils.test.js.map +1 -0
- package/package.json +10 -4
- package/README.en.md +0 -538
- package/docs/00-design.md +0 -760
- package/docs/02-API.md +0 -1148
- package/docs/arb/test-plan.md +0 -387
- package/docs/arb/test-results.md +0 -336
- package/docs/arbitrage.md +0 -754
- package/docs/reports/smart-money-analysis-2025-12-23-cn.md +0 -840
- package/examples/01-basic-usage.ts +0 -68
- package/examples/02-smart-money.ts +0 -95
- package/examples/03-market-analysis.ts +0 -108
- package/examples/04-kline-aggregation.ts +0 -158
- package/examples/05-follow-wallet-strategy.ts +0 -156
- package/examples/06-services-demo.ts +0 -124
- package/examples/07-realtime-websocket.ts +0 -117
- package/examples/08-trading-orders.ts +0 -278
- package/examples/09-rewards-tracking.ts +0 -187
- package/examples/10-ctf-operations.ts +0 -336
- package/examples/11-live-arbitrage-scan.ts +0 -221
- package/examples/12-trending-arb-monitor.ts +0 -406
- package/examples/13-arbitrage-service.ts +0 -211
- package/examples/README.md +0 -179
- package/scripts/README.md +0 -163
- package/scripts/approvals/approve-erc1155.ts +0 -129
- package/scripts/approvals/approve-neg-risk-erc1155.ts +0 -149
- package/scripts/approvals/approve-neg-risk.ts +0 -102
- package/scripts/approvals/check-all-allowances.ts +0 -150
- package/scripts/approvals/check-allowance.ts +0 -129
- package/scripts/approvals/check-ctf-approval.ts +0 -158
- package/scripts/arb/faze-bo3-arb.ts +0 -385
- package/scripts/arb/settle-position.ts +0 -190
- package/scripts/arb/token-rebalancer.ts +0 -420
- package/scripts/arb-tests/01-unit-tests.ts +0 -495
- package/scripts/arb-tests/02-integration-tests.ts +0 -412
- package/scripts/arb-tests/03-e2e-tests.ts +0 -503
- package/scripts/arb-tests/README.md +0 -109
- package/scripts/datas/001-report.md +0 -486
- package/scripts/datas/clone-modal-screenshot.png +0 -0
- package/scripts/deposit/deposit-native-usdc.ts +0 -179
- package/scripts/deposit/deposit-usdc.ts +0 -155
- package/scripts/deposit/swap-usdc-to-usdce.ts +0 -375
- package/scripts/research/research-markets.ts +0 -166
- package/scripts/trading/check-orders.ts +0 -50
- package/scripts/trading/sell-nvidia-positions.ts +0 -206
- package/scripts/trading/test-order.ts +0 -172
- package/scripts/verify/test-approve-trading.ts +0 -98
- package/scripts/verify/test-provider-fix.ts +0 -43
- package/scripts/verify/test-search-mcp.ts +0 -113
- package/scripts/verify/verify-all-apis.ts +0 -160
- package/scripts/wallet/check-wallet-balances.ts +0 -75
- package/scripts/wallet/test-wallet-operations.ts +0 -191
- package/scripts/wallet/verify-wallet-tools.ts +0 -124
- package/src/__tests__/clob-api.test.ts +0 -301
- package/src/__tests__/integration/bridge-client.integration.test.ts +0 -314
- package/src/__tests__/integration/clob-api.integration.test.ts +0 -218
- package/src/__tests__/integration/ctf-client.integration.test.ts +0 -331
- package/src/__tests__/integration/data-api.integration.test.ts +0 -194
- package/src/__tests__/integration/gamma-api.integration.test.ts +0 -206
- package/src/__tests__/test-utils.ts +0 -170
- package/src/clients/bridge-client.ts +0 -841
- package/src/clients/clob-api.ts +0 -629
- package/src/clients/ctf-client.ts +0 -1216
- package/src/clients/data-api.ts +0 -469
- package/src/clients/gamma-api.ts +0 -597
- package/src/clients/trading-client.ts +0 -749
- package/src/clients/websocket-manager.ts +0 -267
- package/src/core/cache-adapter-bridge.ts +0 -94
- package/src/core/cache.ts +0 -85
- package/src/core/errors.ts +0 -117
- package/src/core/rate-limiter.ts +0 -74
- package/src/core/types.ts +0 -360
- package/src/core/unified-cache.ts +0 -153
- package/src/index.ts +0 -461
- package/src/services/arbitrage-service.ts +0 -1807
- package/src/services/authorization-service.ts +0 -357
- package/src/services/market-service.ts +0 -544
- package/src/services/realtime-service.ts +0 -196
- package/src/services/swap-service.ts +0 -896
- package/src/services/wallet-service.ts +0 -259
- package/src/utils/price-utils.ts +0 -307
- package/tsconfig.json +0 -8
- package/vitest.config.ts +0 -19
- package/vitest.integration.config.ts +0 -18
|
@@ -0,0 +1,774 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Market Service
|
|
3
|
+
*
|
|
4
|
+
* Provides market data and analysis:
|
|
5
|
+
* - Market info and discovery
|
|
6
|
+
* - Orderbook data and analysis
|
|
7
|
+
* - K-Line aggregation from trade data
|
|
8
|
+
* - Spread analysis
|
|
9
|
+
* - Arbitrage detection
|
|
10
|
+
*/
|
|
11
|
+
import { ClobClient, Side as ClobSide, PriceHistoryInterval, } from '@polymarket/clob-client';
|
|
12
|
+
import { Wallet } from 'ethers';
|
|
13
|
+
import { CACHE_TTL } from '../core/unified-cache.js';
|
|
14
|
+
import { ApiType } from '../core/rate-limiter.js';
|
|
15
|
+
import { PolymarketError, ErrorCode } from '../core/errors.js';
|
|
16
|
+
// CLOB Host
|
|
17
|
+
const CLOB_HOST = 'https://clob.polymarket.com';
|
|
18
|
+
// Chain IDs
|
|
19
|
+
export const POLYGON_MAINNET = 137;
|
|
20
|
+
// ============================================================================
|
|
21
|
+
// MarketService Implementation
|
|
22
|
+
// ============================================================================
|
|
23
|
+
export class MarketService {
|
|
24
|
+
gammaApi;
|
|
25
|
+
dataApi;
|
|
26
|
+
rateLimiter;
|
|
27
|
+
cache;
|
|
28
|
+
config;
|
|
29
|
+
clobClient = null;
|
|
30
|
+
initialized = false;
|
|
31
|
+
constructor(gammaApi, dataApi, rateLimiter, cache, config) {
|
|
32
|
+
this.gammaApi = gammaApi;
|
|
33
|
+
this.dataApi = dataApi;
|
|
34
|
+
this.rateLimiter = rateLimiter;
|
|
35
|
+
this.cache = cache;
|
|
36
|
+
this.config = config;
|
|
37
|
+
}
|
|
38
|
+
// ============================================================================
|
|
39
|
+
// Initialization
|
|
40
|
+
// ============================================================================
|
|
41
|
+
async ensureInitialized() {
|
|
42
|
+
if (!this.initialized || !this.clobClient) {
|
|
43
|
+
const chainId = (this.config?.chainId || POLYGON_MAINNET);
|
|
44
|
+
if (this.config?.privateKey) {
|
|
45
|
+
// Authenticated client
|
|
46
|
+
const wallet = new Wallet(this.config.privateKey);
|
|
47
|
+
this.clobClient = new ClobClient(CLOB_HOST, chainId, wallet);
|
|
48
|
+
}
|
|
49
|
+
else {
|
|
50
|
+
// Read-only client (no auth needed for market data)
|
|
51
|
+
this.clobClient = new ClobClient(CLOB_HOST, chainId);
|
|
52
|
+
}
|
|
53
|
+
this.initialized = true;
|
|
54
|
+
}
|
|
55
|
+
return this.clobClient;
|
|
56
|
+
}
|
|
57
|
+
// ============================================================================
|
|
58
|
+
// CLOB Market Data Methods
|
|
59
|
+
// ============================================================================
|
|
60
|
+
/**
|
|
61
|
+
* Get market from CLOB by condition ID
|
|
62
|
+
*/
|
|
63
|
+
async getClobMarket(conditionId) {
|
|
64
|
+
const cacheKey = `clob:market:${conditionId}`;
|
|
65
|
+
return this.cache.getOrSet(cacheKey, CACHE_TTL.MARKET_INFO, async () => {
|
|
66
|
+
const client = await this.ensureInitialized();
|
|
67
|
+
return this.rateLimiter.execute(ApiType.CLOB_API, async () => {
|
|
68
|
+
const market = await client.getMarket(conditionId);
|
|
69
|
+
return this.normalizeClobMarket(market);
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Get multiple markets from CLOB
|
|
75
|
+
*/
|
|
76
|
+
async getClobMarkets(nextCursor) {
|
|
77
|
+
const client = await this.ensureInitialized();
|
|
78
|
+
return this.rateLimiter.execute(ApiType.CLOB_API, async () => {
|
|
79
|
+
const result = await client.getMarkets(nextCursor);
|
|
80
|
+
return {
|
|
81
|
+
markets: result.data.map(m => this.normalizeClobMarket(m)),
|
|
82
|
+
nextCursor: result.next_cursor,
|
|
83
|
+
};
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Get orderbook for a single token
|
|
88
|
+
*/
|
|
89
|
+
async getTokenOrderbook(tokenId) {
|
|
90
|
+
const client = await this.ensureInitialized();
|
|
91
|
+
return this.rateLimiter.execute(ApiType.CLOB_API, async () => {
|
|
92
|
+
const book = await client.getOrderBook(tokenId);
|
|
93
|
+
const bids = (book.bids || [])
|
|
94
|
+
.map((l) => ({
|
|
95
|
+
price: parseFloat(l.price),
|
|
96
|
+
size: parseFloat(l.size),
|
|
97
|
+
}))
|
|
98
|
+
.sort((a, b) => b.price - a.price);
|
|
99
|
+
const asks = (book.asks || [])
|
|
100
|
+
.map((l) => ({
|
|
101
|
+
price: parseFloat(l.price),
|
|
102
|
+
size: parseFloat(l.size),
|
|
103
|
+
}))
|
|
104
|
+
.sort((a, b) => a.price - b.price);
|
|
105
|
+
return {
|
|
106
|
+
tokenId: book.asset_id,
|
|
107
|
+
assetId: book.asset_id, // Backward compatibility
|
|
108
|
+
bids,
|
|
109
|
+
asks,
|
|
110
|
+
timestamp: parseInt(book.timestamp || '0', 10) || Date.now(),
|
|
111
|
+
market: book.market,
|
|
112
|
+
hash: book.hash,
|
|
113
|
+
};
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Get orderbooks for multiple tokens
|
|
118
|
+
*/
|
|
119
|
+
async getTokenOrderbooks(params) {
|
|
120
|
+
const client = await this.ensureInitialized();
|
|
121
|
+
return this.rateLimiter.execute(ApiType.CLOB_API, async () => {
|
|
122
|
+
const bookParams = params.map(p => ({
|
|
123
|
+
token_id: p.tokenId,
|
|
124
|
+
side: p.side === 'BUY' ? ClobSide.BUY : ClobSide.SELL,
|
|
125
|
+
}));
|
|
126
|
+
const books = await client.getOrderBooks(bookParams);
|
|
127
|
+
const result = new Map();
|
|
128
|
+
for (const book of books) {
|
|
129
|
+
const bids = (book.bids || [])
|
|
130
|
+
.map((l) => ({
|
|
131
|
+
price: parseFloat(l.price),
|
|
132
|
+
size: parseFloat(l.size),
|
|
133
|
+
}))
|
|
134
|
+
.sort((a, b) => b.price - a.price);
|
|
135
|
+
const asks = (book.asks || [])
|
|
136
|
+
.map((l) => ({
|
|
137
|
+
price: parseFloat(l.price),
|
|
138
|
+
size: parseFloat(l.size),
|
|
139
|
+
}))
|
|
140
|
+
.sort((a, b) => a.price - b.price);
|
|
141
|
+
result.set(book.asset_id, {
|
|
142
|
+
tokenId: book.asset_id,
|
|
143
|
+
assetId: book.asset_id, // Backward compatibility
|
|
144
|
+
bids,
|
|
145
|
+
asks,
|
|
146
|
+
timestamp: parseInt(book.timestamp || '0', 10) || Date.now(),
|
|
147
|
+
market: book.market,
|
|
148
|
+
hash: book.hash,
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
return result;
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Get processed orderbook with arbitrage analysis for a market
|
|
156
|
+
*/
|
|
157
|
+
async getProcessedOrderbook(conditionId) {
|
|
158
|
+
const market = await this.getClobMarket(conditionId);
|
|
159
|
+
const yesToken = market.tokens.find(t => t.outcome === 'Yes');
|
|
160
|
+
const noToken = market.tokens.find(t => t.outcome === 'No');
|
|
161
|
+
if (!yesToken || !noToken) {
|
|
162
|
+
throw new PolymarketError(ErrorCode.INVALID_RESPONSE, 'Missing tokens in market');
|
|
163
|
+
}
|
|
164
|
+
const [yesBook, noBook] = await Promise.all([
|
|
165
|
+
this.getTokenOrderbook(yesToken.tokenId),
|
|
166
|
+
this.getTokenOrderbook(noToken.tokenId),
|
|
167
|
+
]);
|
|
168
|
+
return this.processOrderbooks(yesBook, noBook, yesToken.tokenId, noToken.tokenId);
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Get price history for a token
|
|
172
|
+
*/
|
|
173
|
+
async getPricesHistory(params) {
|
|
174
|
+
const client = await this.ensureInitialized();
|
|
175
|
+
return this.rateLimiter.execute(ApiType.CLOB_API, async () => {
|
|
176
|
+
const intervalMap = {
|
|
177
|
+
'1h': PriceHistoryInterval.ONE_HOUR,
|
|
178
|
+
'6h': PriceHistoryInterval.SIX_HOURS,
|
|
179
|
+
'1d': PriceHistoryInterval.ONE_DAY,
|
|
180
|
+
'1w': PriceHistoryInterval.ONE_WEEK,
|
|
181
|
+
'max': PriceHistoryInterval.MAX,
|
|
182
|
+
};
|
|
183
|
+
const history = await client.getPricesHistory({
|
|
184
|
+
market: params.tokenId,
|
|
185
|
+
interval: params.interval ? intervalMap[params.interval] : undefined,
|
|
186
|
+
startTs: params.startTs,
|
|
187
|
+
endTs: params.endTs,
|
|
188
|
+
fidelity: params.fidelity,
|
|
189
|
+
});
|
|
190
|
+
const historyArray = Array.isArray(history)
|
|
191
|
+
? history
|
|
192
|
+
: history?.history || [];
|
|
193
|
+
return historyArray.map((pt) => ({
|
|
194
|
+
timestamp: pt.t,
|
|
195
|
+
price: pt.p,
|
|
196
|
+
}));
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* Get midpoint price for a token
|
|
201
|
+
*/
|
|
202
|
+
async getMidpoint(tokenId) {
|
|
203
|
+
const client = await this.ensureInitialized();
|
|
204
|
+
return this.rateLimiter.execute(ApiType.CLOB_API, async () => {
|
|
205
|
+
const midpoint = await client.getMidpoint(tokenId);
|
|
206
|
+
return Number(midpoint);
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Get spread for a token
|
|
211
|
+
*/
|
|
212
|
+
async getSpread(tokenId) {
|
|
213
|
+
const client = await this.ensureInitialized();
|
|
214
|
+
return this.rateLimiter.execute(ApiType.CLOB_API, async () => {
|
|
215
|
+
const spread = await client.getSpread(tokenId);
|
|
216
|
+
return Number(spread);
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Get last trade price for a token
|
|
221
|
+
*/
|
|
222
|
+
async getLastTradePrice(tokenId) {
|
|
223
|
+
const client = await this.ensureInitialized();
|
|
224
|
+
return this.rateLimiter.execute(ApiType.CLOB_API, async () => {
|
|
225
|
+
const price = await client.getLastTradePrice(tokenId);
|
|
226
|
+
return Number(price);
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
// ============================================================================
|
|
230
|
+
// Unified Market Access
|
|
231
|
+
// ============================================================================
|
|
232
|
+
/**
|
|
233
|
+
* Get market by slug or condition ID
|
|
234
|
+
*/
|
|
235
|
+
async getMarket(identifier) {
|
|
236
|
+
const isConditionId = identifier.startsWith('0x') || /^\d+$/.test(identifier);
|
|
237
|
+
if (isConditionId) {
|
|
238
|
+
return this.getMarketByConditionId(identifier);
|
|
239
|
+
}
|
|
240
|
+
else {
|
|
241
|
+
return this.getMarketBySlug(identifier);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
async getMarketBySlug(slug) {
|
|
245
|
+
if (!this.gammaApi) {
|
|
246
|
+
throw new PolymarketError(ErrorCode.INVALID_CONFIG, 'GammaApiClient is required for slug-based lookups');
|
|
247
|
+
}
|
|
248
|
+
const gammaMarket = await this.gammaApi.getMarketBySlug(slug);
|
|
249
|
+
if (!gammaMarket) {
|
|
250
|
+
throw new PolymarketError(ErrorCode.MARKET_NOT_FOUND, `Market not found: ${slug}`);
|
|
251
|
+
}
|
|
252
|
+
try {
|
|
253
|
+
const clobMarket = await this.getClobMarket(gammaMarket.conditionId);
|
|
254
|
+
return this.mergeMarkets(gammaMarket, clobMarket);
|
|
255
|
+
}
|
|
256
|
+
catch {
|
|
257
|
+
return this.fromGammaMarket(gammaMarket);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
async getMarketByConditionId(conditionId) {
|
|
261
|
+
// Try to get data from both sources for best accuracy
|
|
262
|
+
let clobMarket = null;
|
|
263
|
+
let gammaMarket = null;
|
|
264
|
+
// Try CLOB first (authoritative for trading data)
|
|
265
|
+
try {
|
|
266
|
+
clobMarket = await this.getClobMarket(conditionId);
|
|
267
|
+
}
|
|
268
|
+
catch {
|
|
269
|
+
// CLOB failed, continue to try Gamma
|
|
270
|
+
}
|
|
271
|
+
// Always try Gamma for accurate slug and metadata (if available)
|
|
272
|
+
if (this.gammaApi) {
|
|
273
|
+
try {
|
|
274
|
+
gammaMarket = await this.gammaApi.getMarketByConditionId(conditionId);
|
|
275
|
+
}
|
|
276
|
+
catch {
|
|
277
|
+
// Gamma failed
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
// Merge if both available (preferred)
|
|
281
|
+
if (gammaMarket && clobMarket) {
|
|
282
|
+
return this.mergeMarkets(gammaMarket, clobMarket);
|
|
283
|
+
}
|
|
284
|
+
// Gamma only - still useful for metadata
|
|
285
|
+
if (gammaMarket) {
|
|
286
|
+
return this.fromGammaMarket(gammaMarket);
|
|
287
|
+
}
|
|
288
|
+
// CLOB only - slug might be stale, add warning
|
|
289
|
+
if (clobMarket) {
|
|
290
|
+
const market = this.fromClobMarket(clobMarket);
|
|
291
|
+
// Check if slug looks stale (doesn't match question keywords)
|
|
292
|
+
const questionWords = clobMarket.question.toLowerCase().split(/\s+/).slice(0, 3);
|
|
293
|
+
const slugWords = clobMarket.marketSlug.toLowerCase().split('-');
|
|
294
|
+
const hasMatchingWord = questionWords.some(qw => slugWords.some(sw => sw.includes(qw) || qw.includes(sw)));
|
|
295
|
+
if (!hasMatchingWord && clobMarket.marketSlug.length > 0) {
|
|
296
|
+
// Slug appears stale, use conditionId as fallback identifier
|
|
297
|
+
market.slug = `market-${conditionId.slice(0, 10)}`;
|
|
298
|
+
}
|
|
299
|
+
return market;
|
|
300
|
+
}
|
|
301
|
+
throw new PolymarketError(ErrorCode.MARKET_NOT_FOUND, `Market not found: ${conditionId}`);
|
|
302
|
+
}
|
|
303
|
+
// ===== K-Line Aggregation =====
|
|
304
|
+
/**
|
|
305
|
+
* Get K-Line candles for a market (single token)
|
|
306
|
+
*/
|
|
307
|
+
async getKLines(conditionId, interval, options) {
|
|
308
|
+
if (!this.dataApi) {
|
|
309
|
+
throw new PolymarketError(ErrorCode.INVALID_CONFIG, 'DataApiClient is required for K-Line data');
|
|
310
|
+
}
|
|
311
|
+
const trades = await this.dataApi.getTradesByMarket(conditionId, options?.limit || 1000);
|
|
312
|
+
// Filter by token/outcome if specified
|
|
313
|
+
let filteredTrades = trades;
|
|
314
|
+
if (options?.tokenId) {
|
|
315
|
+
filteredTrades = trades.filter((t) => t.asset === options.tokenId);
|
|
316
|
+
}
|
|
317
|
+
else if (options?.outcomeIndex !== undefined) {
|
|
318
|
+
filteredTrades = trades.filter((t) => t.outcomeIndex === options.outcomeIndex);
|
|
319
|
+
}
|
|
320
|
+
return this.aggregateToKLines(filteredTrades, interval);
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Get dual K-Lines (YES + NO tokens)
|
|
324
|
+
*/
|
|
325
|
+
async getDualKLines(conditionId, interval, options) {
|
|
326
|
+
if (!this.dataApi) {
|
|
327
|
+
throw new PolymarketError(ErrorCode.INVALID_CONFIG, 'DataApiClient is required for K-Line data');
|
|
328
|
+
}
|
|
329
|
+
const market = await this.getMarket(conditionId);
|
|
330
|
+
const trades = await this.dataApi.getTradesByMarket(conditionId, options?.limit || 1000);
|
|
331
|
+
// Separate trades by outcome
|
|
332
|
+
const yesTrades = trades.filter((t) => t.outcomeIndex === 0 || t.outcome === 'Yes');
|
|
333
|
+
const noTrades = trades.filter((t) => t.outcomeIndex === 1 || t.outcome === 'No');
|
|
334
|
+
const yesCandles = this.aggregateToKLines(yesTrades, interval);
|
|
335
|
+
const noCandles = this.aggregateToKLines(noTrades, interval);
|
|
336
|
+
// Get current orderbook for real-time spread analysis
|
|
337
|
+
let currentOrderbook;
|
|
338
|
+
let realtimeSpread;
|
|
339
|
+
try {
|
|
340
|
+
currentOrderbook = await this.getProcessedOrderbook(conditionId);
|
|
341
|
+
realtimeSpread = this.calculateRealtimeSpread(currentOrderbook);
|
|
342
|
+
}
|
|
343
|
+
catch {
|
|
344
|
+
// Orderbook not available
|
|
345
|
+
}
|
|
346
|
+
// Calculate historical spread from trade close prices (for backtesting)
|
|
347
|
+
const spreadAnalysis = this.analyzeHistoricalSpread(yesCandles, noCandles);
|
|
348
|
+
return {
|
|
349
|
+
conditionId,
|
|
350
|
+
interval,
|
|
351
|
+
market,
|
|
352
|
+
yes: yesCandles,
|
|
353
|
+
no: noCandles,
|
|
354
|
+
spreadAnalysis, // Historical (trade-based)
|
|
355
|
+
realtimeSpread, // Real-time (orderbook-based)
|
|
356
|
+
currentOrderbook,
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Aggregate trades into K-Line candles
|
|
361
|
+
*/
|
|
362
|
+
aggregateToKLines(trades, interval) {
|
|
363
|
+
const intervalMs = getIntervalMs(interval);
|
|
364
|
+
const buckets = new Map();
|
|
365
|
+
// Group trades into time buckets
|
|
366
|
+
for (const trade of trades) {
|
|
367
|
+
const bucketTime = Math.floor(trade.timestamp / intervalMs) * intervalMs;
|
|
368
|
+
const bucket = buckets.get(bucketTime) || [];
|
|
369
|
+
bucket.push(trade);
|
|
370
|
+
buckets.set(bucketTime, bucket);
|
|
371
|
+
}
|
|
372
|
+
// Convert buckets to candles
|
|
373
|
+
const candles = [];
|
|
374
|
+
for (const [timestamp, bucketTrades] of buckets) {
|
|
375
|
+
if (bucketTrades.length === 0)
|
|
376
|
+
continue;
|
|
377
|
+
// Sort by timestamp for correct open/close
|
|
378
|
+
bucketTrades.sort((a, b) => a.timestamp - b.timestamp);
|
|
379
|
+
const prices = bucketTrades.map((t) => t.price);
|
|
380
|
+
const buyTrades = bucketTrades.filter((t) => t.side === 'BUY');
|
|
381
|
+
const sellTrades = bucketTrades.filter((t) => t.side === 'SELL');
|
|
382
|
+
candles.push({
|
|
383
|
+
timestamp,
|
|
384
|
+
open: bucketTrades[0].price,
|
|
385
|
+
high: Math.max(...prices),
|
|
386
|
+
low: Math.min(...prices),
|
|
387
|
+
close: bucketTrades[bucketTrades.length - 1].price,
|
|
388
|
+
volume: bucketTrades.reduce((sum, t) => sum + t.size * t.price, 0),
|
|
389
|
+
tradeCount: bucketTrades.length,
|
|
390
|
+
buyVolume: buyTrades.reduce((sum, t) => sum + t.size * t.price, 0),
|
|
391
|
+
sellVolume: sellTrades.reduce((sum, t) => sum + t.size * t.price, 0),
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
return candles.sort((a, b) => a.timestamp - b.timestamp);
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Analyze historical spread from trade close prices (for backtesting)
|
|
398
|
+
*
|
|
399
|
+
* This uses trade close prices, not orderbook bid/ask.
|
|
400
|
+
* Useful for:
|
|
401
|
+
* - Historical analysis / backtesting
|
|
402
|
+
* - Understanding past price movements
|
|
403
|
+
* - Identifying patterns when orderbook data unavailable
|
|
404
|
+
*/
|
|
405
|
+
analyzeHistoricalSpread(yesCandles, noCandles) {
|
|
406
|
+
const yesMap = new Map(yesCandles.map((c) => [c.timestamp, c]));
|
|
407
|
+
const noMap = new Map(noCandles.map((c) => [c.timestamp, c]));
|
|
408
|
+
const allTimestamps = [...new Set([...yesMap.keys(), ...noMap.keys()])].sort();
|
|
409
|
+
let lastYes = 0.5;
|
|
410
|
+
let lastNo = 0.5;
|
|
411
|
+
const analysis = [];
|
|
412
|
+
for (const ts of allTimestamps) {
|
|
413
|
+
const yesCandle = yesMap.get(ts);
|
|
414
|
+
const noCandle = noMap.get(ts);
|
|
415
|
+
if (yesCandle)
|
|
416
|
+
lastYes = yesCandle.close;
|
|
417
|
+
if (noCandle)
|
|
418
|
+
lastNo = noCandle.close;
|
|
419
|
+
const priceSum = lastYes + lastNo;
|
|
420
|
+
const priceSpread = priceSum - 1;
|
|
421
|
+
// Determine arb opportunity based on price deviation
|
|
422
|
+
// Note: This is indicative only - actual arb requires orderbook analysis
|
|
423
|
+
let arbOpportunity = '';
|
|
424
|
+
if (priceSpread < -0.005)
|
|
425
|
+
arbOpportunity = 'LONG'; // Sum < 0.995
|
|
426
|
+
else if (priceSpread > 0.005)
|
|
427
|
+
arbOpportunity = 'SHORT'; // Sum > 1.005
|
|
428
|
+
analysis.push({
|
|
429
|
+
timestamp: ts,
|
|
430
|
+
yesPrice: lastYes,
|
|
431
|
+
noPrice: lastNo,
|
|
432
|
+
priceSum,
|
|
433
|
+
priceSpread,
|
|
434
|
+
arbOpportunity,
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
return analysis;
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Calculate real-time spread from orderbook (for live trading)
|
|
441
|
+
*
|
|
442
|
+
* This uses orderbook bid/ask prices for accurate arbitrage detection.
|
|
443
|
+
* Useful for:
|
|
444
|
+
* - Real-time arbitrage execution
|
|
445
|
+
* - Live trading decisions
|
|
446
|
+
* - Accurate profit calculations
|
|
447
|
+
*/
|
|
448
|
+
calculateRealtimeSpread(orderbook) {
|
|
449
|
+
const { yes, no, summary } = orderbook;
|
|
450
|
+
// Determine arbitrage opportunity
|
|
451
|
+
let arbOpportunity = '';
|
|
452
|
+
let arbProfitPercent = 0;
|
|
453
|
+
if (summary.longArbProfit > 0.001) { // > 0.1% threshold
|
|
454
|
+
arbOpportunity = 'LONG';
|
|
455
|
+
arbProfitPercent = summary.longArbProfit * 100;
|
|
456
|
+
}
|
|
457
|
+
else if (summary.shortArbProfit > 0.001) { // > 0.1% threshold
|
|
458
|
+
arbOpportunity = 'SHORT';
|
|
459
|
+
arbProfitPercent = summary.shortArbProfit * 100;
|
|
460
|
+
}
|
|
461
|
+
return {
|
|
462
|
+
timestamp: Date.now(),
|
|
463
|
+
// Orderbook prices
|
|
464
|
+
yesBid: yes.bid,
|
|
465
|
+
yesAsk: yes.ask,
|
|
466
|
+
noBid: no.bid,
|
|
467
|
+
noAsk: no.ask,
|
|
468
|
+
// Spread metrics
|
|
469
|
+
askSum: summary.askSum,
|
|
470
|
+
bidSum: summary.bidSum,
|
|
471
|
+
askSpread: summary.askSum - 1,
|
|
472
|
+
bidSpread: summary.bidSum - 1,
|
|
473
|
+
// Arbitrage
|
|
474
|
+
longArbProfit: summary.longArbProfit,
|
|
475
|
+
shortArbProfit: summary.shortArbProfit,
|
|
476
|
+
arbOpportunity,
|
|
477
|
+
arbProfitPercent,
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* Get real-time spread analysis only (without K-lines)
|
|
482
|
+
* Use this for quick arbitrage checks
|
|
483
|
+
*/
|
|
484
|
+
async getRealtimeSpread(conditionId) {
|
|
485
|
+
const orderbook = await this.getProcessedOrderbook(conditionId);
|
|
486
|
+
return this.calculateRealtimeSpread(orderbook);
|
|
487
|
+
}
|
|
488
|
+
// ===== Orderbook Analysis =====
|
|
489
|
+
/**
|
|
490
|
+
* Get processed orderbook with analytics (alias for getProcessedOrderbook)
|
|
491
|
+
*/
|
|
492
|
+
async getOrderbook(conditionId) {
|
|
493
|
+
return this.getProcessedOrderbook(conditionId);
|
|
494
|
+
}
|
|
495
|
+
/**
|
|
496
|
+
* Detect arbitrage opportunity
|
|
497
|
+
*
|
|
498
|
+
* 使用有效价格(考虑镜像订单)计算套利机会
|
|
499
|
+
* 详细原理见: docs/01-polymarket-orderbook-arbitrage.md
|
|
500
|
+
*/
|
|
501
|
+
async detectArbitrage(conditionId, threshold = 0.005) {
|
|
502
|
+
const orderbook = await this.getOrderbook(conditionId);
|
|
503
|
+
const { effectivePrices } = orderbook.summary;
|
|
504
|
+
if (orderbook.summary.longArbProfit > threshold) {
|
|
505
|
+
return {
|
|
506
|
+
type: 'long',
|
|
507
|
+
profit: orderbook.summary.longArbProfit,
|
|
508
|
+
// 使用有效价格描述实际操作
|
|
509
|
+
action: `Buy YES @ ${effectivePrices.effectiveBuyYes.toFixed(4)} + NO @ ${effectivePrices.effectiveBuyNo.toFixed(4)}, Merge for $1`,
|
|
510
|
+
expectedProfit: orderbook.summary.longArbProfit,
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
if (orderbook.summary.shortArbProfit > threshold) {
|
|
514
|
+
return {
|
|
515
|
+
type: 'short',
|
|
516
|
+
profit: orderbook.summary.shortArbProfit,
|
|
517
|
+
// 使用有效价格描述实际操作
|
|
518
|
+
action: `Split $1, Sell YES @ ${effectivePrices.effectiveSellYes.toFixed(4)} + NO @ ${effectivePrices.effectiveSellNo.toFixed(4)}`,
|
|
519
|
+
expectedProfit: orderbook.summary.shortArbProfit,
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
return null;
|
|
523
|
+
}
|
|
524
|
+
// ===== Market Discovery =====
|
|
525
|
+
/**
|
|
526
|
+
* Get trending markets
|
|
527
|
+
*/
|
|
528
|
+
async getTrendingMarkets(limit = 20) {
|
|
529
|
+
if (!this.gammaApi) {
|
|
530
|
+
throw new PolymarketError(ErrorCode.INVALID_CONFIG, 'GammaApiClient is required for trending markets');
|
|
531
|
+
}
|
|
532
|
+
return this.gammaApi.getTrendingMarkets(limit);
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* Search markets
|
|
536
|
+
*/
|
|
537
|
+
async searchMarkets(params) {
|
|
538
|
+
if (!this.gammaApi) {
|
|
539
|
+
throw new PolymarketError(ErrorCode.INVALID_CONFIG, 'GammaApiClient is required for market search');
|
|
540
|
+
}
|
|
541
|
+
return this.gammaApi.getMarkets(params);
|
|
542
|
+
}
|
|
543
|
+
// ===== Market Signal Detection =====
|
|
544
|
+
/**
|
|
545
|
+
* Detect market signals (volume surge, depth imbalance, whale trades)
|
|
546
|
+
*/
|
|
547
|
+
async detectMarketSignals(conditionId) {
|
|
548
|
+
const signals = [];
|
|
549
|
+
if (!this.dataApi) {
|
|
550
|
+
throw new PolymarketError(ErrorCode.INVALID_CONFIG, 'DataApiClient is required for signal detection');
|
|
551
|
+
}
|
|
552
|
+
const market = await this.getMarket(conditionId);
|
|
553
|
+
const orderbook = await this.getOrderbook(conditionId);
|
|
554
|
+
const trades = await this.dataApi.getTradesByMarket(conditionId, 100);
|
|
555
|
+
// Volume surge detection
|
|
556
|
+
if (market.volume24hr && market.volume > 0) {
|
|
557
|
+
const avgDaily = market.volume / 7; // Approximate
|
|
558
|
+
const ratio = market.volume24hr / avgDaily;
|
|
559
|
+
if (ratio > 2) {
|
|
560
|
+
signals.push({
|
|
561
|
+
type: 'volume_surge',
|
|
562
|
+
severity: ratio > 5 ? 'high' : ratio > 3 ? 'medium' : 'low',
|
|
563
|
+
details: { volume24hr: market.volume24hr, avgDaily, ratio },
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
// Depth imbalance detection
|
|
568
|
+
if (orderbook.summary.imbalanceRatio > 1.5 || orderbook.summary.imbalanceRatio < 0.67) {
|
|
569
|
+
const ratio = orderbook.summary.imbalanceRatio;
|
|
570
|
+
signals.push({
|
|
571
|
+
type: 'depth_imbalance',
|
|
572
|
+
severity: ratio > 3 || ratio < 0.33 ? 'high' : 'medium',
|
|
573
|
+
details: {
|
|
574
|
+
imbalanceRatio: ratio,
|
|
575
|
+
bidDepth: orderbook.summary.totalBidDepth,
|
|
576
|
+
askDepth: orderbook.summary.totalAskDepth,
|
|
577
|
+
direction: ratio > 1 ? 'BUY_PRESSURE' : 'SELL_PRESSURE',
|
|
578
|
+
},
|
|
579
|
+
});
|
|
580
|
+
}
|
|
581
|
+
// Whale trade detection
|
|
582
|
+
const recentLargeTrades = trades.filter((t) => t.size * t.price > 1000);
|
|
583
|
+
for (const trade of recentLargeTrades.slice(0, 3)) {
|
|
584
|
+
const value = trade.size * trade.price;
|
|
585
|
+
signals.push({
|
|
586
|
+
type: 'whale_trade',
|
|
587
|
+
severity: value > 10000 ? 'high' : value > 5000 ? 'medium' : 'low',
|
|
588
|
+
details: {
|
|
589
|
+
size: trade.size,
|
|
590
|
+
price: trade.price,
|
|
591
|
+
usdValue: value,
|
|
592
|
+
side: trade.side,
|
|
593
|
+
outcome: trade.outcome,
|
|
594
|
+
},
|
|
595
|
+
});
|
|
596
|
+
}
|
|
597
|
+
return signals;
|
|
598
|
+
}
|
|
599
|
+
// ===== Helper Methods =====
|
|
600
|
+
normalizeClobMarket(m) {
|
|
601
|
+
return {
|
|
602
|
+
conditionId: m.condition_id,
|
|
603
|
+
questionId: m.question_id,
|
|
604
|
+
marketSlug: m.market_slug,
|
|
605
|
+
question: m.question,
|
|
606
|
+
description: m.description,
|
|
607
|
+
tokens: m.tokens.map(t => ({
|
|
608
|
+
tokenId: t.token_id,
|
|
609
|
+
outcome: t.outcome,
|
|
610
|
+
price: t.price,
|
|
611
|
+
winner: t.winner,
|
|
612
|
+
})),
|
|
613
|
+
active: m.active,
|
|
614
|
+
closed: m.closed,
|
|
615
|
+
acceptingOrders: m.accepting_orders,
|
|
616
|
+
endDateIso: m.end_date_iso,
|
|
617
|
+
negRisk: m.neg_risk,
|
|
618
|
+
minimumOrderSize: m.minimum_order_size,
|
|
619
|
+
minimumTickSize: m.minimum_tick_size,
|
|
620
|
+
};
|
|
621
|
+
}
|
|
622
|
+
processOrderbooks(yesBook, noBook, yesTokenId, noTokenId) {
|
|
623
|
+
const yesBestBid = yesBook.bids[0]?.price || 0;
|
|
624
|
+
const yesBestAsk = yesBook.asks[0]?.price || 1;
|
|
625
|
+
const noBestBid = noBook.bids[0]?.price || 0;
|
|
626
|
+
const noBestAsk = noBook.asks[0]?.price || 1;
|
|
627
|
+
const yesBidDepth = yesBook.bids.reduce((sum, l) => sum + l.price * l.size, 0);
|
|
628
|
+
const yesAskDepth = yesBook.asks.reduce((sum, l) => sum + l.price * l.size, 0);
|
|
629
|
+
const noBidDepth = noBook.bids.reduce((sum, l) => sum + l.price * l.size, 0);
|
|
630
|
+
const noAskDepth = noBook.asks.reduce((sum, l) => sum + l.price * l.size, 0);
|
|
631
|
+
const askSum = yesBestAsk + noBestAsk;
|
|
632
|
+
const bidSum = yesBestBid + noBestBid;
|
|
633
|
+
// Effective prices (accounting for mirroring)
|
|
634
|
+
const effectivePrices = {
|
|
635
|
+
effectiveBuyYes: Math.min(yesBestAsk, 1 - noBestBid),
|
|
636
|
+
effectiveBuyNo: Math.min(noBestAsk, 1 - yesBestBid),
|
|
637
|
+
effectiveSellYes: Math.max(yesBestBid, 1 - noBestAsk),
|
|
638
|
+
effectiveSellNo: Math.max(noBestBid, 1 - yesBestAsk),
|
|
639
|
+
};
|
|
640
|
+
const effectiveLongCost = effectivePrices.effectiveBuyYes + effectivePrices.effectiveBuyNo;
|
|
641
|
+
const effectiveShortRevenue = effectivePrices.effectiveSellYes + effectivePrices.effectiveSellNo;
|
|
642
|
+
const longArbProfit = 1 - effectiveLongCost;
|
|
643
|
+
const shortArbProfit = effectiveShortRevenue - 1;
|
|
644
|
+
const yesSpread = yesBestAsk - yesBestBid;
|
|
645
|
+
return {
|
|
646
|
+
yes: {
|
|
647
|
+
bid: yesBestBid,
|
|
648
|
+
ask: yesBestAsk,
|
|
649
|
+
bidSize: yesBook.bids[0]?.size || 0,
|
|
650
|
+
askSize: yesBook.asks[0]?.size || 0,
|
|
651
|
+
bidDepth: yesBidDepth,
|
|
652
|
+
askDepth: yesAskDepth,
|
|
653
|
+
spread: yesSpread,
|
|
654
|
+
tokenId: yesTokenId,
|
|
655
|
+
},
|
|
656
|
+
no: {
|
|
657
|
+
bid: noBestBid,
|
|
658
|
+
ask: noBestAsk,
|
|
659
|
+
bidSize: noBook.bids[0]?.size || 0,
|
|
660
|
+
askSize: noBook.asks[0]?.size || 0,
|
|
661
|
+
bidDepth: noBidDepth,
|
|
662
|
+
askDepth: noAskDepth,
|
|
663
|
+
spread: noBestAsk - noBestBid,
|
|
664
|
+
tokenId: noTokenId,
|
|
665
|
+
},
|
|
666
|
+
summary: {
|
|
667
|
+
askSum,
|
|
668
|
+
bidSum,
|
|
669
|
+
effectivePrices,
|
|
670
|
+
effectiveLongCost,
|
|
671
|
+
effectiveShortRevenue,
|
|
672
|
+
longArbProfit,
|
|
673
|
+
shortArbProfit,
|
|
674
|
+
totalBidDepth: yesBidDepth + noBidDepth,
|
|
675
|
+
totalAskDepth: yesAskDepth + noAskDepth,
|
|
676
|
+
imbalanceRatio: (yesBidDepth + noBidDepth) / (yesAskDepth + noAskDepth + 0.001),
|
|
677
|
+
yesSpread,
|
|
678
|
+
},
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
mergeMarkets(gamma, clob) {
|
|
682
|
+
// Build tokens array from CLOB data, falling back to Gamma prices
|
|
683
|
+
const tokens = clob.tokens.map((t, index) => ({
|
|
684
|
+
tokenId: t.tokenId,
|
|
685
|
+
outcome: t.outcome,
|
|
686
|
+
price: t.price || gamma.outcomePrices[index] || 0.5,
|
|
687
|
+
winner: t.winner,
|
|
688
|
+
}));
|
|
689
|
+
return {
|
|
690
|
+
conditionId: clob.conditionId,
|
|
691
|
+
slug: gamma.slug,
|
|
692
|
+
question: clob.question,
|
|
693
|
+
description: clob.description || gamma.description,
|
|
694
|
+
tokens,
|
|
695
|
+
volume: gamma.volume,
|
|
696
|
+
volume24hr: gamma.volume24hr,
|
|
697
|
+
liquidity: gamma.liquidity,
|
|
698
|
+
spread: gamma.spread,
|
|
699
|
+
oneDayPriceChange: gamma.oneDayPriceChange,
|
|
700
|
+
oneWeekPriceChange: gamma.oneWeekPriceChange,
|
|
701
|
+
active: clob.active,
|
|
702
|
+
closed: clob.closed,
|
|
703
|
+
acceptingOrders: clob.acceptingOrders,
|
|
704
|
+
endDate: clob.endDateIso ? new Date(clob.endDateIso) : new Date(),
|
|
705
|
+
source: 'merged',
|
|
706
|
+
};
|
|
707
|
+
}
|
|
708
|
+
fromGammaMarket(gamma) {
|
|
709
|
+
// Create tokens from Gamma outcomes (binary market: Yes/No)
|
|
710
|
+
const tokens = [
|
|
711
|
+
{ tokenId: '', outcome: 'Yes', price: gamma.outcomePrices[0] || 0.5 },
|
|
712
|
+
{ tokenId: '', outcome: 'No', price: gamma.outcomePrices[1] || 0.5 },
|
|
713
|
+
];
|
|
714
|
+
return {
|
|
715
|
+
conditionId: gamma.conditionId,
|
|
716
|
+
slug: gamma.slug,
|
|
717
|
+
question: gamma.question,
|
|
718
|
+
description: gamma.description,
|
|
719
|
+
tokens,
|
|
720
|
+
volume: gamma.volume,
|
|
721
|
+
volume24hr: gamma.volume24hr,
|
|
722
|
+
liquidity: gamma.liquidity,
|
|
723
|
+
spread: gamma.spread,
|
|
724
|
+
oneDayPriceChange: gamma.oneDayPriceChange,
|
|
725
|
+
oneWeekPriceChange: gamma.oneWeekPriceChange,
|
|
726
|
+
active: gamma.active,
|
|
727
|
+
closed: gamma.closed,
|
|
728
|
+
acceptingOrders: !gamma.closed,
|
|
729
|
+
endDate: gamma.endDate,
|
|
730
|
+
source: 'gamma',
|
|
731
|
+
};
|
|
732
|
+
}
|
|
733
|
+
fromClobMarket(clob) {
|
|
734
|
+
// Convert CLOB tokens to UnifiedMarketToken format
|
|
735
|
+
const tokens = clob.tokens.map(t => ({
|
|
736
|
+
tokenId: t.tokenId,
|
|
737
|
+
outcome: t.outcome,
|
|
738
|
+
price: t.price,
|
|
739
|
+
winner: t.winner,
|
|
740
|
+
}));
|
|
741
|
+
return {
|
|
742
|
+
conditionId: clob.conditionId,
|
|
743
|
+
slug: clob.marketSlug,
|
|
744
|
+
question: clob.question,
|
|
745
|
+
description: clob.description,
|
|
746
|
+
tokens,
|
|
747
|
+
volume: 0,
|
|
748
|
+
volume24hr: undefined,
|
|
749
|
+
liquidity: 0,
|
|
750
|
+
spread: undefined,
|
|
751
|
+
active: clob.active,
|
|
752
|
+
closed: clob.closed,
|
|
753
|
+
acceptingOrders: clob.acceptingOrders,
|
|
754
|
+
endDate: clob.endDateIso ? new Date(clob.endDateIso) : new Date(),
|
|
755
|
+
source: 'clob',
|
|
756
|
+
};
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
// ===== Utility Functions =====
|
|
760
|
+
export function getIntervalMs(interval) {
|
|
761
|
+
const map = {
|
|
762
|
+
'30s': 30 * 1000,
|
|
763
|
+
'1m': 60 * 1000,
|
|
764
|
+
'5m': 5 * 60 * 1000,
|
|
765
|
+
'15m': 15 * 60 * 1000,
|
|
766
|
+
'30m': 30 * 60 * 1000,
|
|
767
|
+
'1h': 60 * 60 * 1000,
|
|
768
|
+
'4h': 4 * 60 * 60 * 1000,
|
|
769
|
+
'12h': 12 * 60 * 60 * 1000,
|
|
770
|
+
'1d': 24 * 60 * 60 * 1000,
|
|
771
|
+
};
|
|
772
|
+
return map[interval];
|
|
773
|
+
}
|
|
774
|
+
//# sourceMappingURL=market-service.js.map
|