MCPcopy Index your code
hub / github.com/cyl19970726/poly-sdk

github.com/cyl19970726/poly-sdk @main

Chat with this repo
repository ↗ · DeepWiki ↗ · + Follow
1,720 symbols 4,482 edges 204 files 536 documented · 31%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

@catalyst-team/poly-sdk

npm version License: MIT

Polymarket 统一 TypeScript SDK - 交易、市场数据、聪明钱分析和链上操作。

开发者: @hhhx402 | 项目: Catalyst.fun

请我喝杯咖啡 (Polygon): 0x58d2ff253998bc2f3b8f5bdbe9c52cad7b022739

English


目录


概览

@catalyst-team/poly-sdk 是一个全面的 TypeScript SDK,提供:

  • 交易 - 下限价单/市价单 (GTC, GTD, FOK, FAK)
  • 市场数据 - 实时价格、订单簿、K线、历史成交
  • 聪明钱分析 - 追踪顶级交易者、计算聪明分数、跟单策略
  • 链上操作 - CTF (split/merge/redeem)、授权、DEX 交换
  • 套利检测 - 实时套利扫描和执行
  • WebSocket 推送 - 实时价格和订单簿更新

核心功能

功能 描述
统一 API 单一 SDK 访问所有 Polymarket API
类型安全 完整的 TypeScript 支持和类型定义
速率限制 按 API 端点内置速率限制
缓存 基于 TTL 的缓存,支持可插拔适配器
错误处理 结构化错误和自动重试

安装

pnpm add @catalyst-team/poly-sdk

# 或
npm install @catalyst-team/poly-sdk

# 或
yarn add @catalyst-team/poly-sdk

架构

SDK 分为三层:

poly-sdk 架构
================================================================================

┌──────────────────────────────────────────────────────────────────────────────┐
│                              PolymarketSDK                                    │
│                               (入口点)                                         │
├──────────────────────────────────────────────────────────────────────────────┤
│                                                                               │
│  第三层: 高级服务 (推荐使用)                                                    │
│  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━                                      │
│  ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐                 │
│  │  TradingService │ │  MarketService  │ │ OnchainService  │                 │
│  │  ────────────── │ │  ────────────── │ │ ──────────────  │                 │
│  │  • 限价单       │ │  • K线          │ │ • Split/Merge   │                 │
│  │  • 市价单       │ │  • 订单簿       │ │ • Redeem        │                 │
│  │  • 订单管理     │ │  • 价格历史     │ │ • 授权          │                 │
│  │  • 奖励         │ │  • 套利检测     │ │ • 交换          │                 │
│  └─────────────────┘ └─────────────────┘ └─────────────────┘                 │
│                                                                               │
│  ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐                 │
│  │RealtimeServiceV2│ │  WalletService  │ │SmartMoneyService│                 │
│  │  ────────────── │ │  ────────────── │ │ ──────────────  │                 │
│  │  • WebSocket    │ │  • 用户画像     │ │ • 顶级交易者    │                 │
│  │  • 价格推送     │ │  • 聪明分数     │ │ • 跟单交易      │                 │
│  │  • 订单簿更新   │ │  • 卖出检测     │ │ • 信号检测      │                 │
│  │  • 用户事件     │ │  • PnL 计算     │ │ • 排行榜        │                 │
│  └─────────────────┘ └─────────────────┘ └─────────────────┘                 │
│                                                                               │
│  ┌─────────────────────────────────────────────────────────────────────────┐ │
│  │                        ArbitrageService                                  │ │
│  │  ─────────────────────────────────────────────────────────────────────  │ │
│  │  • 市场扫描    • 自动执行    • 再平衡器    • 智能清仓                      │ │
│  └─────────────────────────────────────────────────────────────────────────┘ │
│                                                                               │
├──────────────────────────────────────────────────────────────────────────────┤
│                                                                               │
│  第二层: 底层客户端 (高级用户 / 原始 API 访问)                                  │
│  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━                       │
│  ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│  │GammaApiClnt│ │DataApiClnt │ │SubgraphClnt│ │ CTFClient  │ │BridgeClient│ │
│  │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │
│  │ • 市场     │ │ • 持仓     │ │ • 链上数据 │ │ • Split    │ │ • 跨链     │ │
│  │ • 事件     │ │ • 交易     │ │ • PnL      │ │ • Merge    │ │   充值     │ │
│  │ • 搜索     │ │ • 活动     │ │ • OI       │ │ • Redeem   │ │            │ │
│  └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │
│                                                                               │
│  使用官方 Polymarket 客户端:                                                   │
│  • @polymarket/clob-client - 交易、订单簿、市场数据                            │
│  • @polymarket/real-time-data-client - WebSocket 实时更新                     │
│                                                                               │
├──────────────────────────────────────────────────────────────────────────────┤
│                                                                               │
│  第一层: 核心基础设施                                                          │
│  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━                                                │
│  ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│  │ 速率限制器 │ │    缓存    │ │    错误    │ │    类型    │ │  价格工具  │ │
│  │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │
│  │ • 按 API   │ │ • 基于 TTL │ │ • 重试     │ │ • 统一     │ │ • 套利计算 │ │
│  │ • Bottleneck│ │ • 可插拔   │ │ • 错误码   │ │ • K线      │ │ • 舍入     │ │
│  └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │
│                                                                               │
└──────────────────────────────────────────────────────────────────────────────┘

服务职责

服务 职责
PolymarketSDK 入口点,整合所有服务
TradingService 订单管理(下单/撤单/查询)
MarketService 市场数据(订单簿/K线/搜索)
OnchainService 链上操作(split/merge/redeem/授权/交换)
RealtimeServiceV2 WebSocket 实时数据
WalletService 钱包/交易者分析
SmartMoneyService 聪明钱跟踪
ArbitrageService 套利检测与执行

快速开始

基础用法(只读)

import { PolymarketSDK } from '@catalyst-team/poly-sdk';

// 只读操作无需认证
const sdk = new PolymarketSDK();

// 通过 slug 或 condition ID 获取市场
const market = await sdk.getMarket('will-trump-win-2024');
console.log(`${market.question}`);
console.log(`YES: ${market.tokens.find(t => t.outcome === 'Yes')?.price}`);
console.log(`NO: ${market.tokens.find(t => t.outcome === 'No')?.price}`);

// 获取处理后的订单簿(含分析数据)
const orderbook = await sdk.getOrderbook(market.conditionId);
console.log(`多头套利利润: ${orderbook.summary.longArbProfit}`);
console.log(`空头套利利润: ${orderbook.summary.shortArbProfit}`);

// 检测套利机会
const arb = await sdk.detectArbitrage(market.conditionId);
if (arb) {
  console.log(`${arb.type.toUpperCase()} 套利: ${(arb.profit * 100).toFixed(2)}% 利润`);
  console.log(arb.action);
}

带认证(交易)

import { PolymarketSDK } from '@catalyst-team/poly-sdk';

// 推荐: 使用静态工厂方法(一行代码启动)
const sdk = await PolymarketSDK.create({
  privateKey: process.env.POLYMARKET_PRIVATE_KEY!,
});
// 准备好交易 - SDK 已初始化并连接 WebSocket

// 下限价单
const order = await sdk.tradingService.createLimitOrder({
  tokenId: yesTokenId,
  side: 'BUY',
  price: 0.45,
  size: 10,
  orderType: 'GTC',
});
console.log(`订单已下: ${order.id}`);

// 获取未成交订单
const openOrders = await sdk.tradingService.getOpenOrders();
console.log(`未成交订单: ${openOrders.length}`);

// 完成后清理
sdk.stop();

服务指南

PolymarketSDK (入口)

整合所有服务的主 SDK 类。

import { PolymarketSDK } from '@catalyst-team/poly-sdk';

// ===== 方式 1: 静态工厂方法(推荐)=====
// 一行搞定: new + initialize + connect + waitForConnection
const sdk = await PolymarketSDK.create({
  privateKey: '0x...', // 可选: 用于交易
  chainId: 137,        // 可选: Polygon 主网(默认)
});

// ===== 方式 2: 使用 start() =====
// const sdk = new PolymarketSDK({ privateKey: '0x...' });
// await sdk.start();  // initialize + connect + waitForConnection

// ===== 方式 3: 手动分步(完全控制)=====
// const sdk = new PolymarketSDK({ privateKey: '0x...' });
// await sdk.initialize();       // 初始化交易服务
// sdk.connect();                // 连接 WebSocket
// await sdk.waitForConnection(); // 等待连接完成

// 访问服务
sdk.tradingService  // 交易操作
sdk.markets         // 市场数据
sdk.wallets         // 钱包分析
sdk.realtime        // WebSocket 实时数据
sdk.smartMoney      // 聪明钱跟踪和跟单交易
sdk.dataApi         // 直接访问 Data API
sdk.gammaApi        // 直接访问 Gamma API
sdk.subgraph        // 通过 Goldsky 访问链上数据

// 便捷方法
await sdk.getMarket(identifier);        // 获取统一市场
await sdk.getOrderbook(conditionId);    // 获取处理后的订单簿
await sdk.detectArbitrage(conditionId); // 检测套利机会

// 清理
sdk.stop();  // 断开所有服务

TradingService

使用 @polymarket/clob-client 进行订单管理。

import { TradingService } from '@catalyst-team/poly-sdk';

const trading = new TradingService(rateLimiter, cache, {
  privateKey: process.env.POLYMARKET_PRIVATE_KEY!,
});
await trading.initialize();

// ===== 限价单 =====

// GTC: 一直有效直到取消
const gtcOrder = await trading.createLimitOrder({
  tokenId: yesTokenId,
  side: 'BUY',
  price: 0.45,
  size: 10,
  orderType: 'GTC',
});

// GTD: 有效期至指定时间
const gtdOrder = await trading.createLimitOrder({
  tokenId: yesTokenId,
  side: 'BUY',
  price: 0.45,
  size: 10,
  orderType: 'GTD',
  expiration: Math.floor(Date.now() / 1000) + 3600, // 1 小时
});

// ===== 市价单 =====

// FOK: 全部成交或取消
const fokOrder = await trading.createMarketOrder({
  tokenId: yesTokenId,
  side: 'BUY',
  amount: 10, // $10 USDC
  orderType: 'FOK',
});

// FAK: 部分成交也可以
const fakOrder = await trading.createMarketOrder({
  tokenId: yesTokenId,
  side: 'SELL',
  amount: 10, // 10 份额
  orderType: 'FAK',
});

// ===== 订单管理 =====
const openOrders = await trading.getOpenOrders();
await trading.cancelOrder(orderId);
await trading.cancelAllOrders();

// ===== 奖励(做市激励)=====
const isScoring = await trading.isOrderScoring(orderId);
const rewards = await trading.getCurrentRewards();
const earnings = await trading.getEarnings('2024-12-07');

MarketService

市场数据、K线、订单簿分析。

import { MarketService } from '@catalyst-team/poly-sdk';

// 获取统一市场
const market = await sdk.markets.getMarket('btc-100k-2024');

// 获取价格线(来自 /prices-history API)
const prices = await sdk.markets.getKLines(conditionId, '1d');

// 获取双价格线(primary + secondary)含价差分析
const dual = await sdk.markets.getDualKLines(conditionId, '1d');
console.log(dual.primary);          // 主要结果价格点
console.log(dual.secondary);        // 次要结果价格点
console.log(dual.spreadAnalysis);   // 价差分析

// 获取 OHLCV K 线(来自成交数据聚合)
const klines = await sdk.markets.getKLinesOHLCV(conditionId, '1h', { limit: 100 });

// 获取双 OHLCV K 线(YES + NO)含价差分析
const dualOHLCV = await sdk.markets.getDualKLinesOHLCV(conditionId, '1h');
console.log(dualOHLCV.yes);              // YES 代币蜡烛图
console.log(dualOHLCV.no);               // NO 代币蜡烛图
console.log(dualOHLCV.spreadAnalysis);   // 历史价差(成交价)
console.log(dualOHLCV.realtimeSpread);   // 实时价差(订单簿)

// 获取处理后的订单簿
const orderbook = await sdk.markets.getProcessedOrderbook(conditionId);

// 快速实时价差检查
const spread = await sdk.markets.getRealtimeSpread(conditionId);
if (spread.longArbProfit > 0.005) {
  console.log(`多头套利: 买 YES@${spread.yesAsk} + NO@${spread.noAsk}`);
}

// 检测市场信号
const signals = await sdk.markets.detectMarketSignals(conditionId);

理解 Polymarket 订单簿

重要: Polymarket 订单簿有镜像特性:

买 YES @ P = 卖 NO @ (1-P)

这意味着同一订单会出现在两个订单簿中。简单相加会导致重复计算:

// 错误: 重复计算镜像订单
const askSum = YES.ask + NO.ask;  // ~1.998, 而非 ~1.0

// 正确: 使用有效价格
import { getEffectivePrices, checkArbitrage } from '@catalyst-team/poly-sdk';

const effective = getEffectivePrices(yesAsk, yesBid, noAsk, noBid);
// effective.effectiveBuyYes = min(YES.ask, 1 - NO.bid)
// effective.effectiveBuyNo = min(NO.ask, 1 - YES.bid)

const arb = checkArbitrage(yesAsk, noAsk, yesBid, noBid);
if (arb) {
  console.log(`${arb.type} 套利: ${(arb.profit * 100).toFixed(2)}% 利润`);
}

OnchainService

链上操作的统一接口:CTF + 授权 + 交换。

import { OnchainService } from '@catalyst-team/poly-sdk';

const onchain = new OnchainService({
  privateKey: process.env.POLYMARKET_PRIVATE_KEY!,
  rpcUrl: 'https://polygon-rpc.com', // 可选
});

// 检查是否准备好进行 CTF 交易
const status = await onchain.checkReadyForCTF('100');
if (!status.ready) {
  console.log('问题:', status.issues);
  await onchain.approveAll();
}

// ===== CTF 操作 =====

// Split: USDC -> YES + NO 代币
const splitResult = await onchain.split(conditionId, '100');

// Merge: YES + NO -> USDC(用于套利)
const mergeResult = await onchain.mergeByTokenIds(conditionId, tokenIds, '100');

// Redeem: 获胜代币 -> USDC(结算后)
const redeemResult = await onchain.redeemByTokenIds(conditionId, tokenIds);

// ===== DEX 交换 (QuickSwap V3) =====

// 将 MATIC 交换为 USDC.e(CTF 需要)
await onchain.swap('MATIC', 'USDC_E', '50');

// 获取余额
const balances = await onchain.getBalances();
console.log(`USDC.e: ${balances.usdcE}`);

注意: Polymarket CTF 需要 USDC.e (0x2791...),不是原生 USDC。


RealtimeServiceV2

使用 @polymarket/real-time-data-client 的 WebSocket 实时数据。

```typescript import { RealtimeServiceV2 } from '@catalyst-team/poly-sdk';

const realtime = new RealtimeServiceV2({ autoReconnect: true, pingInterval: 5000, });

// 连接并订阅 realtime.connect(); realtime.subscribeMarket([yesTokenId, noTokenId]);

// 事件 API realtime.on('priceUpdate', (update) => { c

Extension points exported contracts — how you extend this code

UnifiedCache (Interface)
(no doc) [5 implementers]
src/core/unified-cache.ts
BinanceApiError (Interface)
* Binance API error response
src/services/binance-service.ts
RealTimeDataClientInterface (Interface)
(no doc) [2 implementers]
src/realtime/types.ts
PolymarketSDKConfig (Interface)
(no doc)
src/index.ts
DecodedOrder (Interface)
(no doc)
src/utils/calldata-decoder.ts
InsiderCharacteristicsSimple (Interface)
(no doc)
src/signal/types.ts
InsiderScanServiceConfig (Interface)
(no doc)
src/insider-scan/insider-scan-service.ts
SmartMoneyWallet (Interface)
(no doc)
src/smart-money/types.ts

Core symbols most depended-on inside this repo

log
called by 4281
src/services/ctf-manager.ts
error
called by 253
src/core/logger.ts
set
called by 171
src/core/unified-cache.ts
log
called by 110
src/services/dip-arb-service.ts
log
called by 88
scripts/dip-arb/auto-trade.ts
log
called by 87
src/services/arbitrage-service.ts
get
called by 79
src/core/unified-cache.ts
log
called by 60
scripts/ordermanager/full-e2e.ts

Shape

Method 825
Interface 399
Function 385
Class 104
Enum 7

Languages

TypeScript100%

Modules by API surface

src/services/realtime-service-v2.ts96 symbols
src/services/trading-service.ts82 symbols
src/services/order-manager.ts69 symbols
src/services/dip-arb-service.ts52 symbols
src/services/market-service.ts51 symbols
src/services/onchain-service.ts50 symbols
src/clients/ctf-client.ts50 symbols
src/realtime/types.ts42 symbols
src/services/arbitrage-service.ts41 symbols
src/smart-money/types.ts37 symbols
src/services/wallet-service.ts37 symbols
src/clients/data-api.ts37 symbols

For agents

$ claude mcp add poly-sdk \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact