poly-sdk Documentation

repository·copy-trading·Indexed 22 days ago

https://github.com/cyl19970726/poly-sdk

A 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.

Tokens
99.2K
Snippets
182
Records
379
Agent score
78%

What's inside @catalyst-team/poly-sdk

  1. Overview of @catalyst-team/poly-sdk features

    copy-trading

    The @catalyst-team/poly-sdk is 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.

  2. Overview of @catalyst-team/poly-sdk

    copy-trading

    The @catalyst-team/poly-sdk is 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.
  3. Explore the poly-sdk documentation structure

    copy-trading

    The 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.
  4. Overview of PolymarketSDK Core Clients

    copy-trading

    The PolymarketSDK provides 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.
  5. Manage multiple markets with CTFManager

    copy-trading

    Each CTFManager instance is bound to a single market (one conditionId and its associated tokens). To monitor multiple markets simultaneously, instantiate a separate CTFManager for 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()));
  6. Understand the DipArb Strategy concept

    copy-trading

    DipArb 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:

    1. Signal Detection: The strategy monitors the order book for an "instantaneous dip" (e.g., a $\ge$15% drop within a 3-second window).
    2. Leg 1 (The Dip): Once a signal is detected, the strategy buys the side that has dropped (e.g., the UP side).
    3. 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 the sumTarget.
    4. Settlement: Once both sides are held, the profit is calculated as $1 - totalCost.
  7. Market Making and Arbitrage Strategy

    copy-trading

    A 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.
  8. Distinguish between Standard CTF and NegRisk CTF market types

    copy-trading

    Polymarket 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), and Redeem (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 NO share in one market can be converted into YES shares of all other competing markets via the NegRisk Adapter. For example, in a presidential election, buying Trump NO is equivalent to betting on Harris YES + Biden YES + all other candidates.
    • Example: 2024 US Presidential Election.
  9. CTF Operations: Split and Merge

    copy-trading

    The 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.
  10. How the Conditional Token Framework (CTF) works

    copy-trading

    The 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

    OperationInputOutputDescription
    Split1 USDC1 YES + 1 NOMints new outcome tokens
    Merge1 YES + 1 NO1 USDCMerges tokens back into USDC
    Redeem1 winning token1 USDCRedeems 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.
  11. Understand the Order Lifecycle State Machine

    copy-trading

    The poly-sdk uses a 7-state internal OrderStatus enum 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.