Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
P

poly-sdk

> 编程语言
Open source

@catalyst-team/poly-sdk Unified TypeScript SDK for Polymarket - Trading, market data, smart money analysis, and on-chain operations. Builde…

1.3K stars0 likes0 views
WebsiteGitHub

About

@catalyst-team/poly-sdk Unified TypeScript SDK for Polymarket - Trading, market data, smart money analysis, and on-chain operations. Builde…

@catalyst-team/poly-sdk

Unified TypeScript SDK for Polymarket - Trading, market data, smart money analysis, and on-chain operations.

Builder: @hhhx402 | Project: Catalyst.fun

☕ Buy Me a Coffee (Polygon): 0x58d2ff253998bc2f3b8f5bdbe9c52cad7b022739

中文文档


Table of Contents

  • Overview
  • Installation
  • Architecture
  • Quick Start
  • Services Guide
    • PolymarketSDK (Entry Point)
    • TradingService
    • MarketService
    • OnchainService
    • RealtimeServiceV2
    • WalletService
    • SmartMoneyService
    • ArbitrageService
    • DipArbService
  • Low-Level Clients
  • Breaking Changes (v0.3.0)
  • Examples
  • API Reference
  • License

Overview

@catalyst-team/poly-sdk is a comprehensive TypeScript SDK that provides:

  • Trading - Place limit/market orders (GTC, GTD, FOK, FAK)
  • Market Data - Real-time prices, orderbooks, K-lines, historical trades
  • Smart Money Analysis - Track top traders, calculate smart scores, follow wallet strategies
  • On-chain Operations - CTF (split/merge/redeem), approvals, DEX swaps
  • Arbitrage Detection - Real-time arbitrage scanning and execution
  • WebSocket Streaming - Live price feeds and orderbook updates

Key Features

Feature Description
Unified API Single SDK for all Polymarket APIs
Type Safety Full TypeScript support with comprehensive types
Rate Limiting Built-in rate limiting per API endpoint
Caching TTL-based caching with pluggable adapters
Error Handling Structured errors with auto-retry

Installation

bash
pnpm add @catalyst-team/poly-sdk

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

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

Architecture

The SDK is organized into three layers:

…

Service Responsibilities

Service Responsibility
PolymarketSDK Entry point, integrates all services
TradingService Order management (place/cancel/query)
MarketService Market data (orderbook/K-lines/search)
OnchainService On-chain ops (split/merge/redeem/approve/swap)
RealtimeServiceV2 WebSocket real-time data
WalletService Wallet/trader analysis
SmartMoneyService Smart money tracking
ArbitrageService Arbitrage detection & execution
DipArbService Dip arbitrage for 15m crypto markets

Quick Start

Basic Usage (Read-Only)

…

With Authentication (Trading)

…

Services Guide

PolymarketSDK (Entry Point)

The main SDK class that integrates all services.

…

TradingService

Order management using @polymarket/clob-client.

Important: Polymarket Order Minimums

  • Minimum order size: 5 shares (MIN_ORDER_SIZE_SHARES)
  • Minimum order value: $1 USDC (MIN_ORDER_VALUE_USDC)
  • Orders below these limits are validated and rejected before sending to API
…

MarketService

Market data, K-lines, orderbook analysis.

…

Understanding Polymarket Orderbook

Important: Polymarket orderbooks have a mirror property:

Buy YES @ P = Sell NO @ (1-P)

This means the same order appears in both orderbooks. Simple addition causes double-counting:

typescript
// WRONG: Double counts mirror orders
const askSum = YES.ask + NO.ask;  // ~1.998, not ~1.0

// CORRECT: Use effective prices
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: ${(arb.profit * 100).toFixed(2)}% profit`);
}

OnchainService

Unified interface for all on-chain operations: CTF + Approvals + Swaps.

…

Note: Polymarket CTF requires USDC.e (0x2791...), not native USDC.


RealtimeServiceV2

WebSocket real-time data using @polymarket/real-time-data-client.

…

WalletService

Wallet analysis and smart money scoring.

…

SmartMoneyService

Smart money detection and real-time auto copy trading.

…

Note: Polymarket minimum order size is $1. Orders below $1 will be automatically skipped.

Full examples: See scripts/smart-money/ for complete working scripts:

  • 04-auto-copy-trading.ts - Full-featured auto copy trading
  • 05-auto-copy-simple.ts - Simplified SDK usage
  • 06-real-copy-test.ts - Real trading test

ArbitrageService

Real-time arbitrage detection, execution, and position management.

…

DipArbService

Dip Arbitrage for Polymarket 15-minute crypto UP/DOWN markets (BTC, ETH, SOL, XRP).

Strategy: Detect sudden price dips → Buy dipped side (Leg1) → Wait for opposite to drop → Buy opposite (Leg2) → Lock profit (UP + DOWN = $1)

Quick Start

bash
# One command to start auto trading
PRIVATE_KEY=0x... npx tsx scripts/dip-arb/auto-trade.ts

Features

Feature Description
Dip Detection Detects 15%+ price drops within 10s sliding window
Two-Leg Execution Leg1 (buy dip) + Leg2 (buy opposite when cost {
console.log(${signal.type}: ${signal.side} @ ${signal.price});
});

sdk.dipArb.on('execution', (result) => { console.log(${result.leg} ${result.success ? '✅' : '❌'}); });

sdk.dipArb.on('roundComplete', (result) => { console.log(Profit: $${result.profit?.toFixed(2)}); });

// Find and start monitoring const market = await sdk.dipArb.findAndStart({ coin: 'ETH', preferDuration: '15m', });

// Enable auto-rotate with redemption sdk.dipArb.enableAutoRotate({ enabled: true, underlyings: ['ETH'], duration: '15m', settleStrategy: 'redeem', redeemWaitMinutes: 5, });

// Get stats const stats = sdk.dipArb.getStats(); console.log(Signals: ${stats.signalsDetected}, L1: ${stats.leg1Filled}, L2: ${stats.leg2Filled});

// Cleanup await sdk.dipArb.stop(); sdk.stop();


#### Events

| Event | Data | Description |
|-------|------|-------------|
| `started` | `DipArbMarketConfig` | Started monitoring market |
| `stopped` | - | Stopped monitoring |
| `newRound` | `{ roundId, upOpen, downOpen }` | New trading round |
| `signal` | `DipArbSignalEvent` | Leg1/Leg2 signal detected |
| `execution` | `DipArbExecutionResult` | Trade execution result |
| `roundComplete` | `{ profit, profitRate }` | Round finished |
| `rotate` | `{ reason, newMarket }` | Switched to new market |
| `settled` | `{ success, amountReceived }` | Position redeemed |

#### Scripts

```bash
# Auto trading (monitors + trades)
PRIVATE_KEY=0x... npx tsx scripts/dip-arb/auto-trade.ts

# Redeem ended positions
PRIVATE_KEY=0x... npx tsx scripts/dip-arb/redeem-positions.ts

Low-Level Clients

For advanced users who need direct API access:

typescript
import {
  DataApiClient,    // Positions, trades, leaderboard
  GammaApiClient,   // Markets, events, search
  SubgraphClient,   // On-chain data via Goldsky
  CTFClient,        // CTF contract operations
  BridgeClient,     // Cross-chain deposits
  SwapService,      // DEX swaps on Polygon
} from '@catalyst-team/poly-sdk';

// Data API
const positions = await sdk.dataApi.getPositions('0x...');
const trades = await sdk.dataApi.getTrades('0x...');
const leaderboard = await sdk.dataApi.getLeaderboard();

// Gamma API
const markets = await sdk.gammaApi.searchMarkets({ query: 'bitcoin' });
const trending = await sdk.gammaApi.getTrendingMarkets(10);
const events = await sdk.gammaApi.getEvents({ limit: 20 });

// Subgraph (on-chain data)
const userPositions = await sdk.subgraph.getUserPositions(address);
const isResolved = await sdk.subgraph.isConditionResolved(conditionId);
const globalOI = await sdk.subgraph.getGlobalOpenInterest();

Breaking Changes (v0.3.0)

UnifiedMarket.tokens is now an Array

Before (v0.2.x):

typescript
// Object with yes/no properties
const yesPrice = market.tokens.yes.price;
const noPrice = market.tokens.no.price;

After (v0.3.0):

typescript
// Array of MarketToken objects
const yesToken = market.tokens.find(t => t.outcome === 'Yes');
const noToken = market.tokens.find(t => t.outcome === 'No');

const yesPrice = yesToken?.price;
const noPrice = noToken?.price;

Migration Guide

typescript
// Helper function for migration
function getTokenPrice(market: UnifiedMarket, outcome: 'Yes' | 'No'): number {
  return market.tokens.find(t => t.outcome === outcome)?.price ?? 0;
}

// Usage
const yesPrice = getTokenPrice(market, 'Yes');
const noPrice = getTokenPrice(market, 'No');

Why the change? The array format better supports multi-outcome markets and is more consistent with the Polymarket API response format.


Examples

Run examples with:

bash
pnpm example:basic        # Basic usage
pnpm example:smart-money  # Smart money analysis
pnpm example:trading      # Trading orders
pnpm example:realtime     # WebSocket feeds
pnpm example:arb-service  # Arbitrage service

…

typescript
import type {
  // Core types
  UnifiedMarket,
  MarketToken,
  ProcessedOrderbook,
  ArbitrageOpportunity,
  EffectivePrices,

  // Trading
  Side,
  OrderType,
  Order,
  OrderResult,
  LimitOrderParams,
  MarketOrderParams,

  // K-Lines
  KLineInterval,
  KLineCandle,
  DualKLineData,
  SpreadDataPoint,

  // WebSocket
  PriceUpdate,
  BookUpdate,
  OrderbookSnapshot,

  // Wallet
  WalletProfile,
  SellActivityResult,

  // Smart Money
  SmartMoneyWallet,
  SmartMoneyTrade,
  AutoCopyTradingOptions,
  AutoCopyTradingStats,
  AutoCopyTradingSubscription,

  // CTF
  SplitResult,
  MergeResult,
  RedeemResult,

  // Arbitrage
  ArbitrageMarketConfig,
  ArbitrageServiceConfig,
  ScanResult,
  ClearPositionResult,

  // DipArb
  DipArbServiceConfig,
  DipArbMarketConfig,
  DipArbSignalEvent,
  DipArbExecutionResult,
  DipArbRoundState,
  DipArbStats,
} from '@catalyst-team/poly-sdk';

Dependencies

  • @polymarket/clob-client - Official CLOB trading client
  • @polymarket/real-time-data-client - Official WebSocket client
  • ethers@5 - Blockchain interactions
  • bottleneck - Rate limiting

License

MIT

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言