poly-sdk Documentation
repository·copy-trading·Indexed 22 days ago
https://github.com/cyl19970726/poly-sdkA unified TypeScript SDK for Polymarket (v0.5.0) providing tools for prediction market trading, real-time market data via WebSockets, smart money analysis, and on-chain CTF operations. It includes specialized services for order management (TradingService), arbitrage detection (ArbitrageService), and wallet profiling (WalletService), with specific support for USDC.e and the CLOB API.
What's inside @catalyst-team/poly-sdk
- The CTFManager test suite provides a set of scripts to verify CTF (Conditional Token Framework) operations by listening to on-chain events. The suite is designed to be cost-effective by using Split/Merge cycles which are 1:1 equivalent exchanges with minimal gas costs and no slippage.
Overview of @catalyst-team/poly-sdk features
copy-tradingThe
@catalyst-team/poly-sdkis a comprehensive TypeScript SDK designed for interacting with Polymarket. It provides several core capabilities:- Trading: Support for limit and market orders with various instruction types (GTC, GTD, FOK, FAK).
- Market Data: Access to real-time prices, orderbooks, K-lines, and historical trades.
- Smart Money Analysis: Tools to track top traders, calculate smart scores, and follow wallet strategies.
- On-chain Operations: Management of CTF (split/merge/redeem), approvals, and DEX swaps.
- Arbitrage Detection: Real-time scanning and execution of arbitrage opportunities.
- WebSocket Streaming: Live feeds for prices and orderbook updates.
Key technical features include a unified API, full TypeScript type safety, built-in rate limiting per endpoint, TTL-based caching with pluggable adapters, and structured error handling with auto-retry.
Overview of @catalyst-team/poly-sdk
copy-tradingThe
@catalyst-team/poly-sdkis a comprehensive TypeScript SDK for Polymarket. It provides a unified interface for trading, accessing market data, analyzing 'smart money' movements, performing on-chain operations, and detecting arbitrage opportunities.Key features include:
- Unified API: Single access point for all Polymarket functionalities.
- Type Safety: Full TypeScript support and definitions.
- Rate Limiting: Built-in rate limiting per API endpoint.
- Caching: TTL-based caching with pluggable adapters.
- Error Handling: Structured error codes and automatic retries.
- WebSocket Support: Real-time price and order book updates via
RealtimeServiceV2.
Explore the poly-sdk documentation structure
copy-tradingThe documentation is organized into several functional areas to help you navigate from learning to contributing:
- Concepts: Deep dives into Polymarket principles and mental models.
- API Reference: Detailed documentation of the available SDK methods and interfaces.
- Practical Guides: Implementation recipes for tasks like copy trading and arbitrage.
- Architecture: Internal details regarding service layers, WebSockets, and data models for contributors.
- Arbitrage: Specialized documentation for arbitrage mechanics and testing.
Overview of PolymarketSDK Core Clients
copy-tradingThe
PolymarketSDKprovides access to several specialized clients for different parts of the Polymarket ecosystem:PolymarketSDK: The main entry point.ClobApiClient: For interacting with the Central Limit Order Book (CLOB).GammaApiClient: For accessing Gamma-related market data.DataApiClient: For general data retrieval.TradingClient: For executing trades.BridgeClient: For bridge-related operations.CTFClient: For Conditional Token Framework operations.WebSocketManager: For managing real-time WebSocket connections.
Manage multiple markets with CTFManager
copy-tradingEach
CTFManagerinstance is bound to a single market (oneconditionIdand its associated tokens). To monitor multiple markets simultaneously, instantiate a separateCTFManagerfor each market and start them all.const markets = [ { conditionId: '0x...', primary: '123...', secondary: '456...' }, { conditionId: '0x...', primary: '789...', secondary: 'abc...' }, ]; const managers = markets.map(market => new CTFManager({ privateKey: '0x...', conditionId: market.conditionId, primaryTokenId: market.primary, secondaryTokenId: market.secondary, })); await Promise.all(managers.map(m => m.start()));Understand the DipArb Strategy concept
copy-tradingDipArb is a structural arbitrage strategy designed for Polymarket 15-minute UP/DOWN markets. It exploits the market rule where the sum of the settlement prices for UP and DOWN tokens always equals $1.
Core Principle: If you can purchase both the UP and DOWN sides for a total cost of less than $1, you lock in a risk-free profit regardless of the outcome.
How it works:
- Signal Detection: The strategy monitors the order book for an "instantaneous dip" (e.g., a $\ge$15% drop within a 3-second window).
- Leg 1 (The Dip): Once a signal is detected, the strategy buys the side that has dropped (e.g., the UP side).
- Leg 2 (The Hedge): The strategy then waits for the opposite side (e.g., DOWN) to reach a price that ensures the
totalCost(Leg 1 price + Leg 2 price) is below thesumTarget. - Settlement: Once both sides are held, the profit is calculated as
$1 - totalCost.
Market Making and Arbitrage Strategy
copy-tradingA high-capital strategy where the trader provides liquidity by holding equal amounts of 'Yes' and 'No' positions in the same market. The goal is not to predict the outcome, but to profit from the bid-ask spread.
Core Mechanics:
- Dual-Sided Positions: Holding equal amounts of 'Yes' and 'No' (e.g., $701,000 in 'Yes' and $701,000 in 'No').
- Spread Capture: Profiting from the difference between the buy and sell price (e.g., buying at 0.49 and selling at 0.51).
- Extreme Diversification: Spreading capital across a vast number of markets (e.g., 99+ positions) and diverse sectors (NBA, NFL, NHL, Soccer, Politics, Esports).
Requirements/Warnings:
- Requires significant capital (e.g., $1.4M+).
- Requires rapid execution capabilities.
- Not recommended for retail players due to the focus on spread mechanics rather than outcome prediction.
Distinguish between Standard CTF and NegRisk CTF market types
copy-tradingPolymarket utilizes two distinct Conditional Token Framework (CTF) contract architectures. Understanding which one a market uses is critical for arbitrage strategies, as they handle token conversions differently.
Standard CTF (Standard Binary Markets)
Used for simple Yes/No binary markets where each market is independent. Tokens (YES and NO) only have meaning within that specific market.
- Contract Address:
0x4D97DCd97eC945f40cF65F87097ACe5EA0476045 - Operations:
Split(USDC to YES + NO),Merge(YES + NO to USDC), andRedeem(Winning tokens to USDC after settlement). - Example: "Will BTC reach $100k by year-end?"
NegRisk CTF (Winner-Take-All Events)
Used for multi-outcome events where one winner takes all. This system allows for high capital efficiency through the NegRisk Adapter.
- CTF Contract:
0x4bFb41d5B3570DeFd03C39a9A4D8dE6Bd8B8982E - CTF Exchange:
0xC5d563A36AE78145C45a50134d48A1215220f80a - Neg Adapter:
0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296 - Key Feature: A
NOshare in one market can be converted intoYESshares of all other competing markets via the NegRisk Adapter. For example, in a presidential election, buyingTrump NOis equivalent to betting onHarris YES+Biden YES+ all other candidates. - Example: 2024 US Presidential Election.
- Contract Address:
CTF Operations: Split and Merge
copy-tradingThe SDK supports Conditional Token Framework (CTF) operations for managing liquidity in arbitrage:
- Split: Converts USDC into paired YES and NO tokens for a specific market condition.
- Merge: Converts paired YES and NO tokens back into USDC.
Operational Notes:
- Gas Costs: On Polygon, Split and Merge operations are highly efficient, typically costing ~100k gas (~$0.03 USD).
- Slippage: Testing shows successful round-trips ($5 → tokens → $5) with zero slippage in controlled environments.
How the Conditional Token Framework (CTF) works
copy-tradingThe CTF is based on the Gnosis Conditional Tokens framework. It allows for the creation of outcome-based tokens where the sum of all possible outcomes equals the collateral amount (e.g., 1 USDC).
Core Constraint
YES + NO = 1 USDC(before market settlement).Token Operations
Operation Input Output Description Split 1 USDC 1 YES + 1 NO Mints new outcome tokens Merge 1 YES + 1 NO 1 USDC Merges tokens back into USDC Redeem 1 winning token 1 USDC Redeems the winning outcome after settlement Key Implications
- If the price of a YES token is 0.65, the NO token price must be approximately 0.35.
- Arbitrage opportunities exist when
YES + NO ≠ 1.
Understand the Order Lifecycle State Machine
copy-tradingThe
poly-sdkuses a 7-state internalOrderStatusenum to track orders from creation to settlement. These states are categorized into Active States (can transition to other states) and Terminal States (final states).Active States
pending: Order created locally, not yet submitted.open: Order is in the orderbook, awaiting fills.partially_filled: Order has been partially filled; the remainder is still in the orderbook.
Terminal States
filled: Order is completely filled.cancelled: Order was cancelled by the user or the system.expired: A GTD (Good-Til-Date) order reached its expiration time.rejected: Order failed validation before it could be submitted.