Skip to content

Repository files navigation

@catalyst-team/poly-sdk

npm versionLicense: MIT

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

@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

FeatureDescription
Unified APISingle SDK for all Polymarket APIs
Type SafetyFull TypeScript support with comprehensive types
Rate LimitingBuilt-in rate limiting per API endpoint
CachingTTL-based caching with pluggable adapters
Error HandlingStructured errors with auto-retry

Installation

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:

poly-sdk Architecture
================================================================================
┌──────────────────────────────────────────────────────────────────────────────┐
│ PolymarketSDK │
│ (Entry Point) │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 3: High-Level Services (Recommended) │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ TradingService │ │ MarketService │ │ OnchainService │ │
│ │ ────────────── │ │ ────────────── │ │ ────────────── │ │
│ │ • Limit orders │ │ • K-lines │ │ • Split/Merge │ │
│ │ • Market orders│ │ • Orderbook │ │ • Redeem │ │
│ │ • Order mgmt │ │ • Price history│ │ • Approvals │ │
│ │ • Rewards │ │ • Arbitrage │ │ • Swaps │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │RealtimeServiceV2│ │ WalletService │ │SmartMoneyService│ │
│ │ ────────────── │ │ ────────────── │ │ ────────────── │ │
│ │ • WebSocket │ │ • Profiles │ │ • Top traders │ │
│ │ • Price feeds │ │ • Smart scores │ │ • Copy trading │ │
│ │ • Book updates │ │ • Sell detect │ │ • Signal detect │ │
│ │ • User events │ │ • PnL calc │ │ • Leaderboard │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ ArbitrageService │ │
│ │ ───────────────────────────────────────────────────────────────────── │ │
│ │ • Market scanning • Auto execution • Rebalancer • Smart clearing │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ DipArbService │ │
│ │ ───────────────────────────────────────────────────────────────────── │ │
│ │ • 15m crypto UP/DOWN • Dip detection • Auto-rotate • Background redeem│
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 2: Low-Level Clients (Advanced Users / Raw API Access) │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │GammaApiClnt│ │DataApiClnt │ │SubgraphClnt│ │ CTFClient │ │BridgeClient│ │
│ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │
│ │ • Markets │ │ • Positions│ │ • On-chain │ │ • Split │ │ • Cross- │ │
│ │ • Events │ │ • Trades │ │ • PnL │ │ • Merge │ │ chain │ │
│ │ • Search │ │ • Activity │ │ • OI │ │ • Redeem │ │ • Deposits │ │
│ └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │
│ │
│ Uses Official Polymarket Clients: │
│ • @polymarket/clob-client - Trading, orderbook, market data │
│ • @polymarket/real-time-data-client - WebSocket real-time updates │
│ │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 1: Core Infrastructure │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │RateLimiter │ │ Cache │ │ Errors │ │ Types │ │Price Utils │ │
│ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │
│ │ • Per-API │ │ • TTL-based│ │ • Retry │ │ • Unified │ │ • Arb calc │ │
│ │ • Bottleneck│ │ • Pluggable│ │ • Codes │ │ • K-lines │ │ • Rounding │ │
│ └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │
│ │
└──────────────────────────────────────────────────────────────────────────────┘

Service Responsibilities

ServiceResponsibility
PolymarketSDKEntry point, integrates all services
TradingServiceOrder management (place/cancel/query)
MarketServiceMarket data (orderbook/K-lines/search)
OnchainServiceOn-chain ops (split/merge/redeem/approve/swap)
RealtimeServiceV2WebSocket real-time data
WalletServiceWallet/trader analysis
SmartMoneyServiceSmart money tracking
ArbitrageServiceArbitrage detection & execution
DipArbServiceDip arbitrage for 15m crypto markets

Quick Start

Basic Usage (Read-Only)

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// No authentication needed for read operationsconstsdk=newPolymarketSDK();// Get market by slug or condition IDconstmarket=awaitsdk.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}`);// Get processed orderbook with analyticsconstorderbook=awaitsdk.getOrderbook(market.conditionId);console.log(`Long Arb Profit: ${orderbook.summary.longArbProfit}`);console.log(`Short Arb Profit: ${orderbook.summary.shortArbProfit}`);// Detect arbitrage opportunitiesconstarb=awaitsdk.detectArbitrage(market.conditionId);if(arb){console.log(`${arb.type.toUpperCase()} ARB: ${(arb.profit*100).toFixed(2)}% profit`);console.log(arb.action);}

With Authentication (Trading)

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// Recommended: Use static factory method (one line to get started)constsdk=awaitPolymarketSDK.create({privateKey: process.env.POLYMARKET_PRIVATE_KEY!,});// Ready to trade - SDK is initialized and WebSocket connected// Place a limit orderconstorder=awaitsdk.tradingService.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTC',});console.log(`Order placed: ${order.id}`);// Get open ordersconstopenOrders=awaitsdk.tradingService.getOpenOrders();console.log(`Open orders: ${openOrders.length}`);// Clean up when donesdk.stop();

Services Guide

PolymarketSDK (Entry Point)

The main SDK class that integrates all services.

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// ===== Method 1: Static Factory (Recommended) =====// One line: new + initialize + connect + waitForConnectionconstsdk=awaitPolymarketSDK.create({privateKey: '0x...',// Optional: for tradingchainId: 137,// Optional: Polygon mainnet (default)});// ===== Method 2: Using start() =====// const sdk = new PolymarketSDK({ privateKey: '0x...' });// await sdk.start(); // initialize + connect + waitForConnection// ===== Method 3: Manual Step-by-Step (Full Control) =====// const sdk = new PolymarketSDK({ privateKey: '0x...' });// await sdk.initialize(); // Initialize trading service// sdk.connect(); // Connect WebSocket// await sdk.waitForConnection(); // Wait for connection// Access servicessdk.tradingService// Trading operationssdk.markets// Market datasdk.wallets// Wallet analysissdk.realtime// WebSocket real-time datasdk.smartMoney// Smart money tracking & copy tradingsdk.dipArb// Dip arbitrage for 15m crypto marketssdk.dataApi// Direct Data API accesssdk.gammaApi// Direct Gamma API accesssdk.subgraph// On-chain data via Goldsky// Convenience methodsawaitsdk.getMarket(identifier);// Get unified marketawaitsdk.getOrderbook(conditionId);// Get processed orderbookawaitsdk.detectArbitrage(conditionId);// Detect arb opportunity// Clean upsdk.stop();// Disconnect 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
import{TradingService,MIN_ORDER_SIZE_SHARES,MIN_ORDER_VALUE_USDC}from'@catalyst-team/poly-sdk';consttrading=newTradingService(rateLimiter,cache,{privateKey: process.env.POLYMARKET_PRIVATE_KEY!,});awaittrading.initialize();// ===== Limit Orders =====// GTC: Good Till CancelledconstgtcOrder=awaittrading.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTC',});// GTD: Good Till Date (expires at timestamp)constgtdOrder=awaittrading.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTD',expiration: Math.floor(Date.now()/1000)+3600,// 1 hour});// ===== Market Orders =====// FOK: Fill Or Kill (fill entirely or cancel)constfokOrder=awaittrading.createMarketOrder({tokenId: yesTokenId,side: 'BUY',amount: 10,// $10 USDCorderType: 'FOK',});// FAK: Fill And Kill (partial fill ok)constfakOrder=awaittrading.createMarketOrder({tokenId: yesTokenId,side: 'SELL',amount: 10,// 10 sharesorderType: 'FAK',});// ===== Order Management =====constopenOrders=awaittrading.getOpenOrders();awaittrading.cancelOrder(orderId);awaittrading.cancelAllOrders();// ===== Rewards (Market Making Incentives) =====constisScoring=awaittrading.isOrderScoring(orderId);constrewards=awaittrading.getCurrentRewards();constearnings=awaittrading.getEarnings('2024-12-07');

MarketService

Market data, K-lines, orderbook analysis.

import{MarketService}from'@catalyst-team/poly-sdk';// Get unified marketconstmarket=awaitsdk.markets.getMarket('btc-100k-2024');// Get price lines (from /prices-history API)constprices=awaitsdk.markets.getKLines(conditionId,'1d');// Get dual price lines (primary + secondary) with spread analysisconstdual=awaitsdk.markets.getDualKLines(conditionId,'1d');console.log(dual.primary);// Primary outcome price pointsconsole.log(dual.secondary);// Secondary outcome price pointsconsole.log(dual.spreadAnalysis);// Spread analysis// Get OHLCV candles (from trade data aggregation)constklines=awaitsdk.markets.getKLinesOHLCV(conditionId,'1h',{limit: 100});// Get dual OHLCV K-Lines (YES + NO) with spread analysisconstdualOHLCV=awaitsdk.markets.getDualKLinesOHLCV(conditionId,'1h');console.log(dualOHLCV.yes);// YES token candlesconsole.log(dualOHLCV.no);// NO token candlesconsole.log(dualOHLCV.spreadAnalysis);// Historical spread (trade prices)console.log(dualOHLCV.realtimeSpread);// Real-time spread (orderbook)// Get processed orderbookconstorderbook=awaitsdk.markets.getProcessedOrderbook(conditionId);// Quick real-time spread checkconstspread=awaitsdk.markets.getRealtimeSpread(conditionId);if(spread.longArbProfit>0.005){console.log(`Long arb: buy YES@${spread.yesAsk} + NO@${spread.noAsk}`);}// Detect market signalsconstsignals=awaitsdk.markets.detectMarketSignals(conditionId);

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:

// WRONG: Double counts mirror ordersconstaskSum=YES.ask+NO.ask;// ~1.998, not ~1.0// CORRECT: Use effective pricesimport{getEffectivePrices,checkArbitrage}from'@catalyst-team/poly-sdk';consteffective=getEffectivePrices(yesAsk,yesBid,noAsk,noBid);// effective.effectiveBuyYes = min(YES.ask, 1 - NO.bid)// effective.effectiveBuyNo = min(NO.ask, 1 - YES.bid)constarb=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.

import{OnchainService}from'@catalyst-team/poly-sdk';constonchain=newOnchainService({privateKey: process.env.POLYMARKET_PRIVATE_KEY!,rpcUrl: 'https://polygon-rpc.com',// optional});// Check if ready for CTF tradingconststatus=awaitonchain.checkReadyForCTF('100');if(!status.ready){console.log('Issues:',status.issues);awaitonchain.approveAll();}// ===== CTF Operations =====// Split: USDC -> YES + NO tokensconstsplitResult=awaitonchain.split(conditionId,'100');// Merge: YES + NO -> USDC (for arbitrage)constmergeResult=awaitonchain.mergeByTokenIds(conditionId,tokenIds,'100');// Redeem: Winning tokens -> USDC (after resolution)constredeemResult=awaitonchain.redeemByTokenIds(conditionId,tokenIds);// ===== DEX Swaps (QuickSwap V3) =====// Swap MATIC to USDC.e (required for CTF)awaitonchain.swap('MATIC','USDC_E','50');// Get balancesconstbalances=awaitonchain.getBalances();console.log(`USDC.e: ${balances.usdcE}`);

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


RealtimeServiceV2

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

import{RealtimeServiceV2}from'@catalyst-team/poly-sdk';constrealtime=newRealtimeServiceV2({autoReconnect: true,pingInterval: 5000,});// Connect and subscriberealtime.connect();realtime.subscribeMarket([yesTokenId,noTokenId]);// Event-based APIrealtime.on('priceUpdate',(update)=>{console.log(`${update.assetId}: ${update.price}`);console.log(`Midpoint: ${update.midpoint}, Spread: ${update.spread}`);});realtime.on('bookUpdate',(update)=>{// Orderbook is auto-normalized:// bids: descending (best first), asks: ascending (best first)console.log(`Best bid: ${update.bids[0]?.price}`);console.log(`Best ask: ${update.asks[0]?.price}`);});realtime.on('lastTrade',(trade)=>{console.log(`Trade: ${trade.side}${trade.size} @ ${trade.price}`);});// Get cached pricesconstprice=realtime.getPrice(yesTokenId);constbook=realtime.getBook(yesTokenId);// Cleanuprealtime.disconnect();

WalletService

Wallet analysis and smart money scoring.

// Get top tradersconsttraders=awaitsdk.wallets.getTopTraders(10);// Get wallet profile with smart scoreconstprofile=awaitsdk.wallets.getWalletProfile('0x...');console.log(`Smart Score: ${profile.smartScore}/100`);console.log(`Win Rate: ${profile.winRate}%`);console.log(`Total PnL: $${profile.totalPnL}`);// Detect sell activity (for follow-wallet strategy)constsellResult=awaitsdk.wallets.detectSellActivity('0x...',conditionId,Date.now()-24*60*60*1000// since 24h ago);if(sellResult.isSelling){console.log(`Sold ${sellResult.percentageSold}%`);}// Track group sell ratioconstgroupSell=awaitsdk.wallets.trackGroupSellRatio(['0x...','0x...'],conditionId,peakValue,sinceTimestamp);

SmartMoneyService

Smart money detection and real-time auto copy trading.

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// One line to get started (recommended)constsdk=awaitPolymarketSDK.create({privateKey: '0x...'});// SDK is initialized and WebSocket connected// Get smart money walletsconstwallets=awaitsdk.smartMoney.getSmartMoneyList(50);// Check if address is smart moneyconstisSmartMoney=awaitsdk.smartMoney.isSmartMoney('0x...');// Subscribe to smart money tradesconstsub=sdk.smartMoney.subscribeSmartMoneyTrades((trade)=>{console.log(`${trade.traderName}${trade.side}${trade.outcome} @ $${trade.price}`);},{filterAddresses: ['0x...'],minSize: 10});// ===== Auto Copy Trading =====// Real-time copy trading - when smart money trades, copy immediatelyconstsubscription=awaitsdk.smartMoney.startAutoCopyTrading({// Target selectiontopN: 50,// Follow top 50 traders from leaderboard// targetAddresses: ['0x...'], // Or specify addresses directly// Order settingssizeScale: 0.1,// Copy 10% of their trade sizemaxSizePerTrade: 10,// Max $10 per trademaxSlippage: 0.03,// 3% slippage toleranceorderType: 'FOK',// FOK or FAK// FiltersminTradeSize: 5,// Only copy trades > $5sideFilter: 'BUY',// Only copy BUY trades (optional)// TestingdryRun: true,// Set false for real trades// CallbacksonTrade: (trade,result)=>{console.log(`Copied ${trade.traderName}: ${result.success ? '✅' : '❌'}`);},onError: (error)=>console.error(error),});console.log(`Tracking ${subscription.targetAddresses.length} wallets`);// Get statsconststats=subscription.getStats();console.log(`Detected: ${stats.tradesDetected}, Executed: ${stats.tradesExecuted}`);// Stopsubscription.stop();sdk.stop();

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.

import{ArbitrageService}from'@catalyst-team/poly-sdk';constarbService=newArbitrageService({privateKey: process.env.POLY_PRIVKEY,profitThreshold: 0.005,// 0.5% minimum profitminTradeSize: 5,// $5 minimummaxTradeSize: 100,// $100 maximumautoExecute: true,// Auto-execute opportunities// Rebalancer: auto-maintain USDC/token ratioenableRebalancer: true,minUsdcRatio: 0.2,// Min 20% USDCmaxUsdcRatio: 0.8,// Max 80% USDCtargetUsdcRatio: 0.5,// Target when rebalancing// Execution safetysizeSafetyFactor: 0.8,// Use 80% of orderbook depthautoFixImbalance: true,// Auto-fix partial fills});// Listen for eventsarbService.on('opportunity',(opp)=>{console.log(`${opp.type.toUpperCase()} ARB: ${opp.profitPercent.toFixed(2)}%`);});arbService.on('execution',(result)=>{if(result.success){console.log(`Executed: $${result.profit.toFixed(2)} profit`);}});// ===== Workflow =====// 1. Scan markets for opportunitiesconstresults=awaitarbService.scanMarkets({minVolume24h: 5000},0.005);// 2. Start monitoring best marketconstbest=awaitarbService.findAndStart(0.005);console.log(`Started: ${best.market.name} (+${best.profitPercent.toFixed(2)}%)`);// 3. Run for a while...awaitnewPromise(r=>setTimeout(r,60*60*1000));// 1 hour// 4. Stop and clear positionsawaitarbService.stop();constclearResult=awaitarbService.clearPositions(best.market,true);console.log(`Recovered: $${clearResult.totalUsdcRecovered.toFixed(2)}`);

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

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

Features

FeatureDescription
Dip DetectionDetects 15%+ price drops within 10s sliding window
Two-Leg ExecutionLeg1 (buy dip) + Leg2 (buy opposite when cost < target)
Auto-RotateAutomatically switches to next market when current ends
Background RedeemWaits for Oracle resolution (~5min) then redeems winning positions
WebSocket ReconnectAuto re-subscribes on disconnect

Programmatic Usage

import{PolymarketSDK}from'@catalyst-team/poly-sdk';constsdk=newPolymarketSDK({privateKey: '0x...'});// Configure strategysdk.dipArb.updateConfig({shares: 10,// Shares per tradesumTarget: 0.9,// Leg2 triggers when cost ≤ 0.9 (11% profit)dipThreshold: 0.15,// 15% dip triggers Leg1windowMinutes: 14,// Trade window after round startautoExecute: true,// Auto-execute signals});// Listen to eventssdk.dipArb.on('signal',(signal)=>{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 monitoringconstmarket=awaitsdk.dipArb.findAndStart({coin: 'ETH',preferDuration: '15m',});// Enable auto-rotate with redemptionsdk.dipArb.enableAutoRotate({enabled: true,underlyings: ['ETH'],duration: '15m',settleStrategy: 'redeem',redeemWaitMinutes: 5,});// Get statsconststats=sdk.dipArb.getStats();console.log(`Signals: ${stats.signalsDetected}, L1: ${stats.leg1Filled}, L2: ${stats.leg2Filled}`);// Cleanupawaitsdk.dipArb.stop();sdk.stop();

Events

EventDataDescription
startedDipArbMarketConfigStarted monitoring market
stopped-Stopped monitoring
newRound{ roundId, upOpen, downOpen }New trading round
signalDipArbSignalEventLeg1/Leg2 signal detected
executionDipArbExecutionResultTrade execution result
roundComplete{ profit, profitRate }Round finished
rotate{ reason, newMarket }Switched to new market
settled{ success, amountReceived }Position redeemed

Scripts

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

import{DataApiClient,// Positions, trades, leaderboardGammaApiClient,// Markets, events, searchSubgraphClient,// On-chain data via GoldskyCTFClient,// CTF contract operationsBridgeClient,// Cross-chain depositsSwapService,// DEX swaps on Polygon}from'@catalyst-team/poly-sdk';// Data APIconstpositions=awaitsdk.dataApi.getPositions('0x...');consttrades=awaitsdk.dataApi.getTrades('0x...');constleaderboard=awaitsdk.dataApi.getLeaderboard();// Gamma APIconstmarkets=awaitsdk.gammaApi.searchMarkets({query: 'bitcoin'});consttrending=awaitsdk.gammaApi.getTrendingMarkets(10);constevents=awaitsdk.gammaApi.getEvents({limit: 20});// Subgraph (on-chain data)constuserPositions=awaitsdk.subgraph.getUserPositions(address);constisResolved=awaitsdk.subgraph.isConditionResolved(conditionId);constglobalOI=awaitsdk.subgraph.getGlobalOpenInterest();

Breaking Changes (v0.3.0)

UnifiedMarket.tokens is now an Array

Before (v0.2.x):

// Object with yes/no propertiesconstyesPrice=market.tokens.yes.price;constnoPrice=market.tokens.no.price;

After (v0.3.0):

// Array of MarketToken objectsconstyesToken=market.tokens.find(t=>t.outcome==='Yes');constnoToken=market.tokens.find(t=>t.outcome==='No');constyesPrice=yesToken?.price;constnoPrice=noToken?.price;

Migration Guide

// Helper function for migrationfunctiongetTokenPrice(market: UnifiedMarket,outcome: 'Yes'|'No'): number{returnmarket.tokens.find(t=>t.outcome===outcome)?.price??0;}// UsageconstyesPrice=getTokenPrice(market,'Yes');constnoPrice=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:

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
ExampleDescription
01-basic-usage.tsGet markets, orderbooks, detect arbitrage
02-smart-money.tsTop traders, wallet profiles, smart scores
03-market-analysis.tsMarket signals, volume analysis
04-kline-aggregation.tsBuild OHLCV candles from trades
05-follow-wallet-strategy.tsTrack smart money, detect exits
06-services-demo.tsAll SDK services in action
07-realtime-websocket.tsLive price feeds, orderbook updates
08-trading-orders.tsGTC, GTD, FOK, FAK order types
09-rewards-tracking.tsMarket maker incentives, earnings
10-ctf-operations.tsSplit, merge, redeem tokens
11-live-arbitrage-scan.tsScan markets for opportunities
12-trending-arb-monitor.tsReal-time trending monitor
13-arbitrage-service.tsFull arbitrage workflow
14-dip-arb-service.tsDip arbitrage for 15m crypto

DipArb Scripts (in scripts/dip-arb/):

ScriptDescription
auto-trade.tsOne-click auto trading with rotation
redeem-positions.tsRedeem ended market positions

API Reference

For detailed API documentation, see:

Type Exports

importtype{// Core typesUnifiedMarket,MarketToken,ProcessedOrderbook,ArbitrageOpportunity,EffectivePrices,// TradingSide,OrderType,Order,OrderResult,LimitOrderParams,MarketOrderParams,// K-LinesKLineInterval,KLineCandle,DualKLineData,SpreadDataPoint,// WebSocketPriceUpdate,BookUpdate,OrderbookSnapshot,// WalletWalletProfile,SellActivityResult,// Smart MoneySmartMoneyWallet,SmartMoneyTrade,AutoCopyTradingOptions,AutoCopyTradingStats,AutoCopyTradingSubscription,// CTFSplitResult,MergeResult,RedeemResult,// ArbitrageArbitrageMarketConfig,ArbitrageServiceConfig,ScanResult,ClearPositionResult,// DipArbDipArbServiceConfig,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

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
GitHub - fruitlollipop/poly-sdk · GitHub
Skip to content

Repository files navigation

@catalyst-team/poly-sdk

npm versionLicense: MIT

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

@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

FeatureDescription
Unified APISingle SDK for all Polymarket APIs
Type SafetyFull TypeScript support with comprehensive types
Rate LimitingBuilt-in rate limiting per API endpoint
CachingTTL-based caching with pluggable adapters
Error HandlingStructured errors with auto-retry

Installation

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:

poly-sdk Architecture
================================================================================
┌──────────────────────────────────────────────────────────────────────────────┐
│ PolymarketSDK │
│ (Entry Point) │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 3: High-Level Services (Recommended) │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ TradingService │ │ MarketService │ │ OnchainService │ │
│ │ ────────────── │ │ ────────────── │ │ ────────────── │ │
│ │ • Limit orders │ │ • K-lines │ │ • Split/Merge │ │
│ │ • Market orders│ │ • Orderbook │ │ • Redeem │ │
│ │ • Order mgmt │ │ • Price history│ │ • Approvals │ │
│ │ • Rewards │ │ • Arbitrage │ │ • Swaps │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │RealtimeServiceV2│ │ WalletService │ │SmartMoneyService│ │
│ │ ────────────── │ │ ────────────── │ │ ────────────── │ │
│ │ • WebSocket │ │ • Profiles │ │ • Top traders │ │
│ │ • Price feeds │ │ • Smart scores │ │ • Copy trading │ │
│ │ • Book updates │ │ • Sell detect │ │ • Signal detect │ │
│ │ • User events │ │ • PnL calc │ │ • Leaderboard │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ ArbitrageService │ │
│ │ ───────────────────────────────────────────────────────────────────── │ │
│ │ • Market scanning • Auto execution • Rebalancer • Smart clearing │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ DipArbService │ │
│ │ ───────────────────────────────────────────────────────────────────── │ │
│ │ • 15m crypto UP/DOWN • Dip detection • Auto-rotate • Background redeem│
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 2: Low-Level Clients (Advanced Users / Raw API Access) │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │GammaApiClnt│ │DataApiClnt │ │SubgraphClnt│ │ CTFClient │ │BridgeClient│ │
│ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │
│ │ • Markets │ │ • Positions│ │ • On-chain │ │ • Split │ │ • Cross- │ │
│ │ • Events │ │ • Trades │ │ • PnL │ │ • Merge │ │ chain │ │
│ │ • Search │ │ • Activity │ │ • OI │ │ • Redeem │ │ • Deposits │ │
│ └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │
│ │
│ Uses Official Polymarket Clients: │
│ • @polymarket/clob-client - Trading, orderbook, market data │
│ • @polymarket/real-time-data-client - WebSocket real-time updates │
│ │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 1: Core Infrastructure │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │RateLimiter │ │ Cache │ │ Errors │ │ Types │ │Price Utils │ │
│ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │
│ │ • Per-API │ │ • TTL-based│ │ • Retry │ │ • Unified │ │ • Arb calc │ │
│ │ • Bottleneck│ │ • Pluggable│ │ • Codes │ │ • K-lines │ │ • Rounding │ │
│ └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │
│ │
└──────────────────────────────────────────────────────────────────────────────┘

Service Responsibilities

ServiceResponsibility
PolymarketSDKEntry point, integrates all services
TradingServiceOrder management (place/cancel/query)
MarketServiceMarket data (orderbook/K-lines/search)
OnchainServiceOn-chain ops (split/merge/redeem/approve/swap)
RealtimeServiceV2WebSocket real-time data
WalletServiceWallet/trader analysis
SmartMoneyServiceSmart money tracking
ArbitrageServiceArbitrage detection & execution
DipArbServiceDip arbitrage for 15m crypto markets

Quick Start

Basic Usage (Read-Only)

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// No authentication needed for read operationsconstsdk=newPolymarketSDK();// Get market by slug or condition IDconstmarket=awaitsdk.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}`);// Get processed orderbook with analyticsconstorderbook=awaitsdk.getOrderbook(market.conditionId);console.log(`Long Arb Profit: ${orderbook.summary.longArbProfit}`);console.log(`Short Arb Profit: ${orderbook.summary.shortArbProfit}`);// Detect arbitrage opportunitiesconstarb=awaitsdk.detectArbitrage(market.conditionId);if(arb){console.log(`${arb.type.toUpperCase()} ARB: ${(arb.profit*100).toFixed(2)}% profit`);console.log(arb.action);}

With Authentication (Trading)

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// Recommended: Use static factory method (one line to get started)constsdk=awaitPolymarketSDK.create({privateKey: process.env.POLYMARKET_PRIVATE_KEY!,});// Ready to trade - SDK is initialized and WebSocket connected// Place a limit orderconstorder=awaitsdk.tradingService.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTC',});console.log(`Order placed: ${order.id}`);// Get open ordersconstopenOrders=awaitsdk.tradingService.getOpenOrders();console.log(`Open orders: ${openOrders.length}`);// Clean up when donesdk.stop();

Services Guide

PolymarketSDK (Entry Point)

The main SDK class that integrates all services.

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// ===== Method 1: Static Factory (Recommended) =====// One line: new + initialize + connect + waitForConnectionconstsdk=awaitPolymarketSDK.create({privateKey: '0x...',// Optional: for tradingchainId: 137,// Optional: Polygon mainnet (default)});// ===== Method 2: Using start() =====// const sdk = new PolymarketSDK({ privateKey: '0x...' });// await sdk.start(); // initialize + connect + waitForConnection// ===== Method 3: Manual Step-by-Step (Full Control) =====// const sdk = new PolymarketSDK({ privateKey: '0x...' });// await sdk.initialize(); // Initialize trading service// sdk.connect(); // Connect WebSocket// await sdk.waitForConnection(); // Wait for connection// Access servicessdk.tradingService// Trading operationssdk.markets// Market datasdk.wallets// Wallet analysissdk.realtime// WebSocket real-time datasdk.smartMoney// Smart money tracking & copy tradingsdk.dipArb// Dip arbitrage for 15m crypto marketssdk.dataApi// Direct Data API accesssdk.gammaApi// Direct Gamma API accesssdk.subgraph// On-chain data via Goldsky// Convenience methodsawaitsdk.getMarket(identifier);// Get unified marketawaitsdk.getOrderbook(conditionId);// Get processed orderbookawaitsdk.detectArbitrage(conditionId);// Detect arb opportunity// Clean upsdk.stop();// Disconnect 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
import{TradingService,MIN_ORDER_SIZE_SHARES,MIN_ORDER_VALUE_USDC}from'@catalyst-team/poly-sdk';consttrading=newTradingService(rateLimiter,cache,{privateKey: process.env.POLYMARKET_PRIVATE_KEY!,});awaittrading.initialize();// ===== Limit Orders =====// GTC: Good Till CancelledconstgtcOrder=awaittrading.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTC',});// GTD: Good Till Date (expires at timestamp)constgtdOrder=awaittrading.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTD',expiration: Math.floor(Date.now()/1000)+3600,// 1 hour});// ===== Market Orders =====// FOK: Fill Or Kill (fill entirely or cancel)constfokOrder=awaittrading.createMarketOrder({tokenId: yesTokenId,side: 'BUY',amount: 10,// $10 USDCorderType: 'FOK',});// FAK: Fill And Kill (partial fill ok)constfakOrder=awaittrading.createMarketOrder({tokenId: yesTokenId,side: 'SELL',amount: 10,// 10 sharesorderType: 'FAK',});// ===== Order Management =====constopenOrders=awaittrading.getOpenOrders();awaittrading.cancelOrder(orderId);awaittrading.cancelAllOrders();// ===== Rewards (Market Making Incentives) =====constisScoring=awaittrading.isOrderScoring(orderId);constrewards=awaittrading.getCurrentRewards();constearnings=awaittrading.getEarnings('2024-12-07');

MarketService

Market data, K-lines, orderbook analysis.

import{MarketService}from'@catalyst-team/poly-sdk';// Get unified marketconstmarket=awaitsdk.markets.getMarket('btc-100k-2024');// Get price lines (from /prices-history API)constprices=awaitsdk.markets.getKLines(conditionId,'1d');// Get dual price lines (primary + secondary) with spread analysisconstdual=awaitsdk.markets.getDualKLines(conditionId,'1d');console.log(dual.primary);// Primary outcome price pointsconsole.log(dual.secondary);// Secondary outcome price pointsconsole.log(dual.spreadAnalysis);// Spread analysis// Get OHLCV candles (from trade data aggregation)constklines=awaitsdk.markets.getKLinesOHLCV(conditionId,'1h',{limit: 100});// Get dual OHLCV K-Lines (YES + NO) with spread analysisconstdualOHLCV=awaitsdk.markets.getDualKLinesOHLCV(conditionId,'1h');console.log(dualOHLCV.yes);// YES token candlesconsole.log(dualOHLCV.no);// NO token candlesconsole.log(dualOHLCV.spreadAnalysis);// Historical spread (trade prices)console.log(dualOHLCV.realtimeSpread);// Real-time spread (orderbook)// Get processed orderbookconstorderbook=awaitsdk.markets.getProcessedOrderbook(conditionId);// Quick real-time spread checkconstspread=awaitsdk.markets.getRealtimeSpread(conditionId);if(spread.longArbProfit>0.005){console.log(`Long arb: buy YES@${spread.yesAsk} + NO@${spread.noAsk}`);}// Detect market signalsconstsignals=awaitsdk.markets.detectMarketSignals(conditionId);

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:

// WRONG: Double counts mirror ordersconstaskSum=YES.ask+NO.ask;// ~1.998, not ~1.0// CORRECT: Use effective pricesimport{getEffectivePrices,checkArbitrage}from'@catalyst-team/poly-sdk';consteffective=getEffectivePrices(yesAsk,yesBid,noAsk,noBid);// effective.effectiveBuyYes = min(YES.ask, 1 - NO.bid)// effective.effectiveBuyNo = min(NO.ask, 1 - YES.bid)constarb=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.

import{OnchainService}from'@catalyst-team/poly-sdk';constonchain=newOnchainService({privateKey: process.env.POLYMARKET_PRIVATE_KEY!,rpcUrl: 'https://polygon-rpc.com',// optional});// Check if ready for CTF tradingconststatus=awaitonchain.checkReadyForCTF('100');if(!status.ready){console.log('Issues:',status.issues);awaitonchain.approveAll();}// ===== CTF Operations =====// Split: USDC -> YES + NO tokensconstsplitResult=awaitonchain.split(conditionId,'100');// Merge: YES + NO -> USDC (for arbitrage)constmergeResult=awaitonchain.mergeByTokenIds(conditionId,tokenIds,'100');// Redeem: Winning tokens -> USDC (after resolution)constredeemResult=awaitonchain.redeemByTokenIds(conditionId,tokenIds);// ===== DEX Swaps (QuickSwap V3) =====// Swap MATIC to USDC.e (required for CTF)awaitonchain.swap('MATIC','USDC_E','50');// Get balancesconstbalances=awaitonchain.getBalances();console.log(`USDC.e: ${balances.usdcE}`);

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


RealtimeServiceV2

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

import{RealtimeServiceV2}from'@catalyst-team/poly-sdk';constrealtime=newRealtimeServiceV2({autoReconnect: true,pingInterval: 5000,});// Connect and subscriberealtime.connect();realtime.subscribeMarket([yesTokenId,noTokenId]);// Event-based APIrealtime.on('priceUpdate',(update)=>{console.log(`${update.assetId}: ${update.price}`);console.log(`Midpoint: ${update.midpoint}, Spread: ${update.spread}`);});realtime.on('bookUpdate',(update)=>{// Orderbook is auto-normalized:// bids: descending (best first), asks: ascending (best first)console.log(`Best bid: ${update.bids[0]?.price}`);console.log(`Best ask: ${update.asks[0]?.price}`);});realtime.on('lastTrade',(trade)=>{console.log(`Trade: ${trade.side}${trade.size} @ ${trade.price}`);});// Get cached pricesconstprice=realtime.getPrice(yesTokenId);constbook=realtime.getBook(yesTokenId);// Cleanuprealtime.disconnect();

WalletService

Wallet analysis and smart money scoring.

// Get top tradersconsttraders=awaitsdk.wallets.getTopTraders(10);// Get wallet profile with smart scoreconstprofile=awaitsdk.wallets.getWalletProfile('0x...');console.log(`Smart Score: ${profile.smartScore}/100`);console.log(`Win Rate: ${profile.winRate}%`);console.log(`Total PnL: $${profile.totalPnL}`);// Detect sell activity (for follow-wallet strategy)constsellResult=awaitsdk.wallets.detectSellActivity('0x...',conditionId,Date.now()-24*60*60*1000// since 24h ago);if(sellResult.isSelling){console.log(`Sold ${sellResult.percentageSold}%`);}// Track group sell ratioconstgroupSell=awaitsdk.wallets.trackGroupSellRatio(['0x...','0x...'],conditionId,peakValue,sinceTimestamp);

SmartMoneyService

Smart money detection and real-time auto copy trading.

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// One line to get started (recommended)constsdk=awaitPolymarketSDK.create({privateKey: '0x...'});// SDK is initialized and WebSocket connected// Get smart money walletsconstwallets=awaitsdk.smartMoney.getSmartMoneyList(50);// Check if address is smart moneyconstisSmartMoney=awaitsdk.smartMoney.isSmartMoney('0x...');// Subscribe to smart money tradesconstsub=sdk.smartMoney.subscribeSmartMoneyTrades((trade)=>{console.log(`${trade.traderName}${trade.side}${trade.outcome} @ $${trade.price}`);},{filterAddresses: ['0x...'],minSize: 10});// ===== Auto Copy Trading =====// Real-time copy trading - when smart money trades, copy immediatelyconstsubscription=awaitsdk.smartMoney.startAutoCopyTrading({// Target selectiontopN: 50,// Follow top 50 traders from leaderboard// targetAddresses: ['0x...'], // Or specify addresses directly// Order settingssizeScale: 0.1,// Copy 10% of their trade sizemaxSizePerTrade: 10,// Max $10 per trademaxSlippage: 0.03,// 3% slippage toleranceorderType: 'FOK',// FOK or FAK// FiltersminTradeSize: 5,// Only copy trades > $5sideFilter: 'BUY',// Only copy BUY trades (optional)// TestingdryRun: true,// Set false for real trades// CallbacksonTrade: (trade,result)=>{console.log(`Copied ${trade.traderName}: ${result.success ? '✅' : '❌'}`);},onError: (error)=>console.error(error),});console.log(`Tracking ${subscription.targetAddresses.length} wallets`);// Get statsconststats=subscription.getStats();console.log(`Detected: ${stats.tradesDetected}, Executed: ${stats.tradesExecuted}`);// Stopsubscription.stop();sdk.stop();

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.

import{ArbitrageService}from'@catalyst-team/poly-sdk';constarbService=newArbitrageService({privateKey: process.env.POLY_PRIVKEY,profitThreshold: 0.005,// 0.5% minimum profitminTradeSize: 5,// $5 minimummaxTradeSize: 100,// $100 maximumautoExecute: true,// Auto-execute opportunities// Rebalancer: auto-maintain USDC/token ratioenableRebalancer: true,minUsdcRatio: 0.2,// Min 20% USDCmaxUsdcRatio: 0.8,// Max 80% USDCtargetUsdcRatio: 0.5,// Target when rebalancing// Execution safetysizeSafetyFactor: 0.8,// Use 80% of orderbook depthautoFixImbalance: true,// Auto-fix partial fills});// Listen for eventsarbService.on('opportunity',(opp)=>{console.log(`${opp.type.toUpperCase()} ARB: ${opp.profitPercent.toFixed(2)}%`);});arbService.on('execution',(result)=>{if(result.success){console.log(`Executed: $${result.profit.toFixed(2)} profit`);}});// ===== Workflow =====// 1. Scan markets for opportunitiesconstresults=awaitarbService.scanMarkets({minVolume24h: 5000},0.005);// 2. Start monitoring best marketconstbest=awaitarbService.findAndStart(0.005);console.log(`Started: ${best.market.name} (+${best.profitPercent.toFixed(2)}%)`);// 3. Run for a while...awaitnewPromise(r=>setTimeout(r,60*60*1000));// 1 hour// 4. Stop and clear positionsawaitarbService.stop();constclearResult=awaitarbService.clearPositions(best.market,true);console.log(`Recovered: $${clearResult.totalUsdcRecovered.toFixed(2)}`);

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

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

Features

FeatureDescription
Dip DetectionDetects 15%+ price drops within 10s sliding window
Two-Leg ExecutionLeg1 (buy dip) + Leg2 (buy opposite when cost < target)
Auto-RotateAutomatically switches to next market when current ends
Background RedeemWaits for Oracle resolution (~5min) then redeems winning positions
WebSocket ReconnectAuto re-subscribes on disconnect

Programmatic Usage

import{PolymarketSDK}from'@catalyst-team/poly-sdk';constsdk=newPolymarketSDK({privateKey: '0x...'});// Configure strategysdk.dipArb.updateConfig({shares: 10,// Shares per tradesumTarget: 0.9,// Leg2 triggers when cost ≤ 0.9 (11% profit)dipThreshold: 0.15,// 15% dip triggers Leg1windowMinutes: 14,// Trade window after round startautoExecute: true,// Auto-execute signals});// Listen to eventssdk.dipArb.on('signal',(signal)=>{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 monitoringconstmarket=awaitsdk.dipArb.findAndStart({coin: 'ETH',preferDuration: '15m',});// Enable auto-rotate with redemptionsdk.dipArb.enableAutoRotate({enabled: true,underlyings: ['ETH'],duration: '15m',settleStrategy: 'redeem',redeemWaitMinutes: 5,});// Get statsconststats=sdk.dipArb.getStats();console.log(`Signals: ${stats.signalsDetected}, L1: ${stats.leg1Filled}, L2: ${stats.leg2Filled}`);// Cleanupawaitsdk.dipArb.stop();sdk.stop();

Events

EventDataDescription
startedDipArbMarketConfigStarted monitoring market
stopped-Stopped monitoring
newRound{ roundId, upOpen, downOpen }New trading round
signalDipArbSignalEventLeg1/Leg2 signal detected
executionDipArbExecutionResultTrade execution result
roundComplete{ profit, profitRate }Round finished
rotate{ reason, newMarket }Switched to new market
settled{ success, amountReceived }Position redeemed

Scripts

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

import{DataApiClient,// Positions, trades, leaderboardGammaApiClient,// Markets, events, searchSubgraphClient,// On-chain data via GoldskyCTFClient,// CTF contract operationsBridgeClient,// Cross-chain depositsSwapService,// DEX swaps on Polygon}from'@catalyst-team/poly-sdk';// Data APIconstpositions=awaitsdk.dataApi.getPositions('0x...');consttrades=awaitsdk.dataApi.getTrades('0x...');constleaderboard=awaitsdk.dataApi.getLeaderboard();// Gamma APIconstmarkets=awaitsdk.gammaApi.searchMarkets({query: 'bitcoin'});consttrending=awaitsdk.gammaApi.getTrendingMarkets(10);constevents=awaitsdk.gammaApi.getEvents({limit: 20});// Subgraph (on-chain data)constuserPositions=awaitsdk.subgraph.getUserPositions(address);constisResolved=awaitsdk.subgraph.isConditionResolved(conditionId);constglobalOI=awaitsdk.subgraph.getGlobalOpenInterest();

Breaking Changes (v0.3.0)

UnifiedMarket.tokens is now an Array

Before (v0.2.x):

// Object with yes/no propertiesconstyesPrice=market.tokens.yes.price;constnoPrice=market.tokens.no.price;

After (v0.3.0):

// Array of MarketToken objectsconstyesToken=market.tokens.find(t=>t.outcome==='Yes');constnoToken=market.tokens.find(t=>t.outcome==='No');constyesPrice=yesToken?.price;constnoPrice=noToken?.price;

Migration Guide

// Helper function for migrationfunctiongetTokenPrice(market: UnifiedMarket,outcome: 'Yes'|'No'): number{returnmarket.tokens.find(t=>t.outcome===outcome)?.price??0;}// UsageconstyesPrice=getTokenPrice(market,'Yes');constnoPrice=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:

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
ExampleDescription
01-basic-usage.tsGet markets, orderbooks, detect arbitrage
02-smart-money.tsTop traders, wallet profiles, smart scores
03-market-analysis.tsMarket signals, volume analysis
04-kline-aggregation.tsBuild OHLCV candles from trades
05-follow-wallet-strategy.tsTrack smart money, detect exits
06-services-demo.tsAll SDK services in action
07-realtime-websocket.tsLive price feeds, orderbook updates
08-trading-orders.tsGTC, GTD, FOK, FAK order types
09-rewards-tracking.tsMarket maker incentives, earnings
10-ctf-operations.tsSplit, merge, redeem tokens
11-live-arbitrage-scan.tsScan markets for opportunities
12-trending-arb-monitor.tsReal-time trending monitor
13-arbitrage-service.tsFull arbitrage workflow
14-dip-arb-service.tsDip arbitrage for 15m crypto

DipArb Scripts (in scripts/dip-arb/):

ScriptDescription
auto-trade.tsOne-click auto trading with rotation
redeem-positions.tsRedeem ended market positions

API Reference

For detailed API documentation, see:

Type Exports

importtype{// Core typesUnifiedMarket,MarketToken,ProcessedOrderbook,ArbitrageOpportunity,EffectivePrices,// TradingSide,OrderType,Order,OrderResult,LimitOrderParams,MarketOrderParams,// K-LinesKLineInterval,KLineCandle,DualKLineData,SpreadDataPoint,// WebSocketPriceUpdate,BookUpdate,OrderbookSnapshot,// WalletWalletProfile,SellActivityResult,// Smart MoneySmartMoneyWallet,SmartMoneyTrade,AutoCopyTradingOptions,AutoCopyTradingStats,AutoCopyTradingSubscription,// CTFSplitResult,MergeResult,RedeemResult,// ArbitrageArbitrageMarketConfig,ArbitrageServiceConfig,ScanResult,ClearPositionResult,// DipArbDipArbServiceConfig,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

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - fruitlollipop/poly-sdk · GitHub
Skip to content

Repository files navigation

@catalyst-team/poly-sdk

npm versionLicense: MIT

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

@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

FeatureDescription
Unified APISingle SDK for all Polymarket APIs
Type SafetyFull TypeScript support with comprehensive types
Rate LimitingBuilt-in rate limiting per API endpoint
CachingTTL-based caching with pluggable adapters
Error HandlingStructured errors with auto-retry

Installation

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:

poly-sdk Architecture
================================================================================
┌──────────────────────────────────────────────────────────────────────────────┐
│ PolymarketSDK │
│ (Entry Point) │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 3: High-Level Services (Recommended) │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ TradingService │ │ MarketService │ │ OnchainService │ │
│ │ ────────────── │ │ ────────────── │ │ ────────────── │ │
│ │ • Limit orders │ │ • K-lines │ │ • Split/Merge │ │
│ │ • Market orders│ │ • Orderbook │ │ • Redeem │ │
│ │ • Order mgmt │ │ • Price history│ │ • Approvals │ │
│ │ • Rewards │ │ • Arbitrage │ │ • Swaps │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │RealtimeServiceV2│ │ WalletService │ │SmartMoneyService│ │
│ │ ────────────── │ │ ────────────── │ │ ────────────── │ │
│ │ • WebSocket │ │ • Profiles │ │ • Top traders │ │
│ │ • Price feeds │ │ • Smart scores │ │ • Copy trading │ │
│ │ • Book updates │ │ • Sell detect │ │ • Signal detect │ │
│ │ • User events │ │ • PnL calc │ │ • Leaderboard │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ ArbitrageService │ │
│ │ ───────────────────────────────────────────────────────────────────── │ │
│ │ • Market scanning • Auto execution • Rebalancer • Smart clearing │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ DipArbService │ │
│ │ ───────────────────────────────────────────────────────────────────── │ │
│ │ • 15m crypto UP/DOWN • Dip detection • Auto-rotate • Background redeem│
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 2: Low-Level Clients (Advanced Users / Raw API Access) │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │GammaApiClnt│ │DataApiClnt │ │SubgraphClnt│ │ CTFClient │ │BridgeClient│ │
│ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │
│ │ • Markets │ │ • Positions│ │ • On-chain │ │ • Split │ │ • Cross- │ │
│ │ • Events │ │ • Trades │ │ • PnL │ │ • Merge │ │ chain │ │
│ │ • Search │ │ • Activity │ │ • OI │ │ • Redeem │ │ • Deposits │ │
│ └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │
│ │
│ Uses Official Polymarket Clients: │
│ • @polymarket/clob-client - Trading, orderbook, market data │
│ • @polymarket/real-time-data-client - WebSocket real-time updates │
│ │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 1: Core Infrastructure │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │RateLimiter │ │ Cache │ │ Errors │ │ Types │ │Price Utils │ │
│ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │
│ │ • Per-API │ │ • TTL-based│ │ • Retry │ │ • Unified │ │ • Arb calc │ │
│ │ • Bottleneck│ │ • Pluggable│ │ • Codes │ │ • K-lines │ │ • Rounding │ │
│ └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │
│ │
└──────────────────────────────────────────────────────────────────────────────┘

Service Responsibilities

ServiceResponsibility
PolymarketSDKEntry point, integrates all services
TradingServiceOrder management (place/cancel/query)
MarketServiceMarket data (orderbook/K-lines/search)
OnchainServiceOn-chain ops (split/merge/redeem/approve/swap)
RealtimeServiceV2WebSocket real-time data
WalletServiceWallet/trader analysis
SmartMoneyServiceSmart money tracking
ArbitrageServiceArbitrage detection & execution
DipArbServiceDip arbitrage for 15m crypto markets

Quick Start

Basic Usage (Read-Only)

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// No authentication needed for read operationsconstsdk=newPolymarketSDK();// Get market by slug or condition IDconstmarket=awaitsdk.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}`);// Get processed orderbook with analyticsconstorderbook=awaitsdk.getOrderbook(market.conditionId);console.log(`Long Arb Profit: ${orderbook.summary.longArbProfit}`);console.log(`Short Arb Profit: ${orderbook.summary.shortArbProfit}`);// Detect arbitrage opportunitiesconstarb=awaitsdk.detectArbitrage(market.conditionId);if(arb){console.log(`${arb.type.toUpperCase()} ARB: ${(arb.profit*100).toFixed(2)}% profit`);console.log(arb.action);}

With Authentication (Trading)

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// Recommended: Use static factory method (one line to get started)constsdk=awaitPolymarketSDK.create({privateKey: process.env.POLYMARKET_PRIVATE_KEY!,});// Ready to trade - SDK is initialized and WebSocket connected// Place a limit orderconstorder=awaitsdk.tradingService.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTC',});console.log(`Order placed: ${order.id}`);// Get open ordersconstopenOrders=awaitsdk.tradingService.getOpenOrders();console.log(`Open orders: ${openOrders.length}`);// Clean up when donesdk.stop();

Services Guide

PolymarketSDK (Entry Point)

The main SDK class that integrates all services.

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// ===== Method 1: Static Factory (Recommended) =====// One line: new + initialize + connect + waitForConnectionconstsdk=awaitPolymarketSDK.create({privateKey: '0x...',// Optional: for tradingchainId: 137,// Optional: Polygon mainnet (default)});// ===== Method 2: Using start() =====// const sdk = new PolymarketSDK({ privateKey: '0x...' });// await sdk.start(); // initialize + connect + waitForConnection// ===== Method 3: Manual Step-by-Step (Full Control) =====// const sdk = new PolymarketSDK({ privateKey: '0x...' });// await sdk.initialize(); // Initialize trading service// sdk.connect(); // Connect WebSocket// await sdk.waitForConnection(); // Wait for connection// Access servicessdk.tradingService// Trading operationssdk.markets// Market datasdk.wallets// Wallet analysissdk.realtime// WebSocket real-time datasdk.smartMoney// Smart money tracking & copy tradingsdk.dipArb// Dip arbitrage for 15m crypto marketssdk.dataApi// Direct Data API accesssdk.gammaApi// Direct Gamma API accesssdk.subgraph// On-chain data via Goldsky// Convenience methodsawaitsdk.getMarket(identifier);// Get unified marketawaitsdk.getOrderbook(conditionId);// Get processed orderbookawaitsdk.detectArbitrage(conditionId);// Detect arb opportunity// Clean upsdk.stop();// Disconnect 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
import{TradingService,MIN_ORDER_SIZE_SHARES,MIN_ORDER_VALUE_USDC}from'@catalyst-team/poly-sdk';consttrading=newTradingService(rateLimiter,cache,{privateKey: process.env.POLYMARKET_PRIVATE_KEY!,});awaittrading.initialize();// ===== Limit Orders =====// GTC: Good Till CancelledconstgtcOrder=awaittrading.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTC',});// GTD: Good Till Date (expires at timestamp)constgtdOrder=awaittrading.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTD',expiration: Math.floor(Date.now()/1000)+3600,// 1 hour});// ===== Market Orders =====// FOK: Fill Or Kill (fill entirely or cancel)constfokOrder=awaittrading.createMarketOrder({tokenId: yesTokenId,side: 'BUY',amount: 10,// $10 USDCorderType: 'FOK',});// FAK: Fill And Kill (partial fill ok)constfakOrder=awaittrading.createMarketOrder({tokenId: yesTokenId,side: 'SELL',amount: 10,// 10 sharesorderType: 'FAK',});// ===== Order Management =====constopenOrders=awaittrading.getOpenOrders();awaittrading.cancelOrder(orderId);awaittrading.cancelAllOrders();// ===== Rewards (Market Making Incentives) =====constisScoring=awaittrading.isOrderScoring(orderId);constrewards=awaittrading.getCurrentRewards();constearnings=awaittrading.getEarnings('2024-12-07');

MarketService

Market data, K-lines, orderbook analysis.

import{MarketService}from'@catalyst-team/poly-sdk';// Get unified marketconstmarket=awaitsdk.markets.getMarket('btc-100k-2024');// Get price lines (from /prices-history API)constprices=awaitsdk.markets.getKLines(conditionId,'1d');// Get dual price lines (primary + secondary) with spread analysisconstdual=awaitsdk.markets.getDualKLines(conditionId,'1d');console.log(dual.primary);// Primary outcome price pointsconsole.log(dual.secondary);// Secondary outcome price pointsconsole.log(dual.spreadAnalysis);// Spread analysis// Get OHLCV candles (from trade data aggregation)constklines=awaitsdk.markets.getKLinesOHLCV(conditionId,'1h',{limit: 100});// Get dual OHLCV K-Lines (YES + NO) with spread analysisconstdualOHLCV=awaitsdk.markets.getDualKLinesOHLCV(conditionId,'1h');console.log(dualOHLCV.yes);// YES token candlesconsole.log(dualOHLCV.no);// NO token candlesconsole.log(dualOHLCV.spreadAnalysis);// Historical spread (trade prices)console.log(dualOHLCV.realtimeSpread);// Real-time spread (orderbook)// Get processed orderbookconstorderbook=awaitsdk.markets.getProcessedOrderbook(conditionId);// Quick real-time spread checkconstspread=awaitsdk.markets.getRealtimeSpread(conditionId);if(spread.longArbProfit>0.005){console.log(`Long arb: buy YES@${spread.yesAsk} + NO@${spread.noAsk}`);}// Detect market signalsconstsignals=awaitsdk.markets.detectMarketSignals(conditionId);

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:

// WRONG: Double counts mirror ordersconstaskSum=YES.ask+NO.ask;// ~1.998, not ~1.0// CORRECT: Use effective pricesimport{getEffectivePrices,checkArbitrage}from'@catalyst-team/poly-sdk';consteffective=getEffectivePrices(yesAsk,yesBid,noAsk,noBid);// effective.effectiveBuyYes = min(YES.ask, 1 - NO.bid)// effective.effectiveBuyNo = min(NO.ask, 1 - YES.bid)constarb=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.

import{OnchainService}from'@catalyst-team/poly-sdk';constonchain=newOnchainService({privateKey: process.env.POLYMARKET_PRIVATE_KEY!,rpcUrl: 'https://polygon-rpc.com',// optional});// Check if ready for CTF tradingconststatus=awaitonchain.checkReadyForCTF('100');if(!status.ready){console.log('Issues:',status.issues);awaitonchain.approveAll();}// ===== CTF Operations =====// Split: USDC -> YES + NO tokensconstsplitResult=awaitonchain.split(conditionId,'100');// Merge: YES + NO -> USDC (for arbitrage)constmergeResult=awaitonchain.mergeByTokenIds(conditionId,tokenIds,'100');// Redeem: Winning tokens -> USDC (after resolution)constredeemResult=awaitonchain.redeemByTokenIds(conditionId,tokenIds);// ===== DEX Swaps (QuickSwap V3) =====// Swap MATIC to USDC.e (required for CTF)awaitonchain.swap('MATIC','USDC_E','50');// Get balancesconstbalances=awaitonchain.getBalances();console.log(`USDC.e: ${balances.usdcE}`);

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


RealtimeServiceV2

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

import{RealtimeServiceV2}from'@catalyst-team/poly-sdk';constrealtime=newRealtimeServiceV2({autoReconnect: true,pingInterval: 5000,});// Connect and subscriberealtime.connect();realtime.subscribeMarket([yesTokenId,noTokenId]);// Event-based APIrealtime.on('priceUpdate',(update)=>{console.log(`${update.assetId}: ${update.price}`);console.log(`Midpoint: ${update.midpoint}, Spread: ${update.spread}`);});realtime.on('bookUpdate',(update)=>{// Orderbook is auto-normalized:// bids: descending (best first), asks: ascending (best first)console.log(`Best bid: ${update.bids[0]?.price}`);console.log(`Best ask: ${update.asks[0]?.price}`);});realtime.on('lastTrade',(trade)=>{console.log(`Trade: ${trade.side}${trade.size} @ ${trade.price}`);});// Get cached pricesconstprice=realtime.getPrice(yesTokenId);constbook=realtime.getBook(yesTokenId);// Cleanuprealtime.disconnect();

WalletService

Wallet analysis and smart money scoring.

// Get top tradersconsttraders=awaitsdk.wallets.getTopTraders(10);// Get wallet profile with smart scoreconstprofile=awaitsdk.wallets.getWalletProfile('0x...');console.log(`Smart Score: ${profile.smartScore}/100`);console.log(`Win Rate: ${profile.winRate}%`);console.log(`Total PnL: $${profile.totalPnL}`);// Detect sell activity (for follow-wallet strategy)constsellResult=awaitsdk.wallets.detectSellActivity('0x...',conditionId,Date.now()-24*60*60*1000// since 24h ago);if(sellResult.isSelling){console.log(`Sold ${sellResult.percentageSold}%`);}// Track group sell ratioconstgroupSell=awaitsdk.wallets.trackGroupSellRatio(['0x...','0x...'],conditionId,peakValue,sinceTimestamp);

SmartMoneyService

Smart money detection and real-time auto copy trading.

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// One line to get started (recommended)constsdk=awaitPolymarketSDK.create({privateKey: '0x...'});// SDK is initialized and WebSocket connected// Get smart money walletsconstwallets=awaitsdk.smartMoney.getSmartMoneyList(50);// Check if address is smart moneyconstisSmartMoney=awaitsdk.smartMoney.isSmartMoney('0x...');// Subscribe to smart money tradesconstsub=sdk.smartMoney.subscribeSmartMoneyTrades((trade)=>{console.log(`${trade.traderName}${trade.side}${trade.outcome} @ $${trade.price}`);},{filterAddresses: ['0x...'],minSize: 10});// ===== Auto Copy Trading =====// Real-time copy trading - when smart money trades, copy immediatelyconstsubscription=awaitsdk.smartMoney.startAutoCopyTrading({// Target selectiontopN: 50,// Follow top 50 traders from leaderboard// targetAddresses: ['0x...'], // Or specify addresses directly// Order settingssizeScale: 0.1,// Copy 10% of their trade sizemaxSizePerTrade: 10,// Max $10 per trademaxSlippage: 0.03,// 3% slippage toleranceorderType: 'FOK',// FOK or FAK// FiltersminTradeSize: 5,// Only copy trades > $5sideFilter: 'BUY',// Only copy BUY trades (optional)// TestingdryRun: true,// Set false for real trades// CallbacksonTrade: (trade,result)=>{console.log(`Copied ${trade.traderName}: ${result.success ? '✅' : '❌'}`);},onError: (error)=>console.error(error),});console.log(`Tracking ${subscription.targetAddresses.length} wallets`);// Get statsconststats=subscription.getStats();console.log(`Detected: ${stats.tradesDetected}, Executed: ${stats.tradesExecuted}`);// Stopsubscription.stop();sdk.stop();

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.

import{ArbitrageService}from'@catalyst-team/poly-sdk';constarbService=newArbitrageService({privateKey: process.env.POLY_PRIVKEY,profitThreshold: 0.005,// 0.5% minimum profitminTradeSize: 5,// $5 minimummaxTradeSize: 100,// $100 maximumautoExecute: true,// Auto-execute opportunities// Rebalancer: auto-maintain USDC/token ratioenableRebalancer: true,minUsdcRatio: 0.2,// Min 20% USDCmaxUsdcRatio: 0.8,// Max 80% USDCtargetUsdcRatio: 0.5,// Target when rebalancing// Execution safetysizeSafetyFactor: 0.8,// Use 80% of orderbook depthautoFixImbalance: true,// Auto-fix partial fills});// Listen for eventsarbService.on('opportunity',(opp)=>{console.log(`${opp.type.toUpperCase()} ARB: ${opp.profitPercent.toFixed(2)}%`);});arbService.on('execution',(result)=>{if(result.success){console.log(`Executed: $${result.profit.toFixed(2)} profit`);}});// ===== Workflow =====// 1. Scan markets for opportunitiesconstresults=awaitarbService.scanMarkets({minVolume24h: 5000},0.005);// 2. Start monitoring best marketconstbest=awaitarbService.findAndStart(0.005);console.log(`Started: ${best.market.name} (+${best.profitPercent.toFixed(2)}%)`);// 3. Run for a while...awaitnewPromise(r=>setTimeout(r,60*60*1000));// 1 hour// 4. Stop and clear positionsawaitarbService.stop();constclearResult=awaitarbService.clearPositions(best.market,true);console.log(`Recovered: $${clearResult.totalUsdcRecovered.toFixed(2)}`);

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

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

Features

FeatureDescription
Dip DetectionDetects 15%+ price drops within 10s sliding window
Two-Leg ExecutionLeg1 (buy dip) + Leg2 (buy opposite when cost < target)
Auto-RotateAutomatically switches to next market when current ends
Background RedeemWaits for Oracle resolution (~5min) then redeems winning positions
WebSocket ReconnectAuto re-subscribes on disconnect

Programmatic Usage

import{PolymarketSDK}from'@catalyst-team/poly-sdk';constsdk=newPolymarketSDK({privateKey: '0x...'});// Configure strategysdk.dipArb.updateConfig({shares: 10,// Shares per tradesumTarget: 0.9,// Leg2 triggers when cost ≤ 0.9 (11% profit)dipThreshold: 0.15,// 15% dip triggers Leg1windowMinutes: 14,// Trade window after round startautoExecute: true,// Auto-execute signals});// Listen to eventssdk.dipArb.on('signal',(signal)=>{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 monitoringconstmarket=awaitsdk.dipArb.findAndStart({coin: 'ETH',preferDuration: '15m',});// Enable auto-rotate with redemptionsdk.dipArb.enableAutoRotate({enabled: true,underlyings: ['ETH'],duration: '15m',settleStrategy: 'redeem',redeemWaitMinutes: 5,});// Get statsconststats=sdk.dipArb.getStats();console.log(`Signals: ${stats.signalsDetected}, L1: ${stats.leg1Filled}, L2: ${stats.leg2Filled}`);// Cleanupawaitsdk.dipArb.stop();sdk.stop();

Events

EventDataDescription
startedDipArbMarketConfigStarted monitoring market
stopped-Stopped monitoring
newRound{ roundId, upOpen, downOpen }New trading round
signalDipArbSignalEventLeg1/Leg2 signal detected
executionDipArbExecutionResultTrade execution result
roundComplete{ profit, profitRate }Round finished
rotate{ reason, newMarket }Switched to new market
settled{ success, amountReceived }Position redeemed

Scripts

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

import{DataApiClient,// Positions, trades, leaderboardGammaApiClient,// Markets, events, searchSubgraphClient,// On-chain data via GoldskyCTFClient,// CTF contract operationsBridgeClient,// Cross-chain depositsSwapService,// DEX swaps on Polygon}from'@catalyst-team/poly-sdk';// Data APIconstpositions=awaitsdk.dataApi.getPositions('0x...');consttrades=awaitsdk.dataApi.getTrades('0x...');constleaderboard=awaitsdk.dataApi.getLeaderboard();// Gamma APIconstmarkets=awaitsdk.gammaApi.searchMarkets({query: 'bitcoin'});consttrending=awaitsdk.gammaApi.getTrendingMarkets(10);constevents=awaitsdk.gammaApi.getEvents({limit: 20});// Subgraph (on-chain data)constuserPositions=awaitsdk.subgraph.getUserPositions(address);constisResolved=awaitsdk.subgraph.isConditionResolved(conditionId);constglobalOI=awaitsdk.subgraph.getGlobalOpenInterest();

Breaking Changes (v0.3.0)

UnifiedMarket.tokens is now an Array

Before (v0.2.x):

// Object with yes/no propertiesconstyesPrice=market.tokens.yes.price;constnoPrice=market.tokens.no.price;

After (v0.3.0):

// Array of MarketToken objectsconstyesToken=market.tokens.find(t=>t.outcome==='Yes');constnoToken=market.tokens.find(t=>t.outcome==='No');constyesPrice=yesToken?.price;constnoPrice=noToken?.price;

Migration Guide

// Helper function for migrationfunctiongetTokenPrice(market: UnifiedMarket,outcome: 'Yes'|'No'): number{returnmarket.tokens.find(t=>t.outcome===outcome)?.price??0;}// UsageconstyesPrice=getTokenPrice(market,'Yes');constnoPrice=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:

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
ExampleDescription
01-basic-usage.tsGet markets, orderbooks, detect arbitrage
02-smart-money.tsTop traders, wallet profiles, smart scores
03-market-analysis.tsMarket signals, volume analysis
04-kline-aggregation.tsBuild OHLCV candles from trades
05-follow-wallet-strategy.tsTrack smart money, detect exits
06-services-demo.tsAll SDK services in action
07-realtime-websocket.tsLive price feeds, orderbook updates
08-trading-orders.tsGTC, GTD, FOK, FAK order types
09-rewards-tracking.tsMarket maker incentives, earnings
10-ctf-operations.tsSplit, merge, redeem tokens
11-live-arbitrage-scan.tsScan markets for opportunities
12-trending-arb-monitor.tsReal-time trending monitor
13-arbitrage-service.tsFull arbitrage workflow
14-dip-arb-service.tsDip arbitrage for 15m crypto

DipArb Scripts (in scripts/dip-arb/):

ScriptDescription
auto-trade.tsOne-click auto trading with rotation
redeem-positions.tsRedeem ended market positions

API Reference

For detailed API documentation, see:

Type Exports

importtype{// Core typesUnifiedMarket,MarketToken,ProcessedOrderbook,ArbitrageOpportunity,EffectivePrices,// TradingSide,OrderType,Order,OrderResult,LimitOrderParams,MarketOrderParams,// K-LinesKLineInterval,KLineCandle,DualKLineData,SpreadDataPoint,// WebSocketPriceUpdate,BookUpdate,OrderbookSnapshot,// WalletWalletProfile,SellActivityResult,// Smart MoneySmartMoneyWallet,SmartMoneyTrade,AutoCopyTradingOptions,AutoCopyTradingStats,AutoCopyTradingSubscription,// CTFSplitResult,MergeResult,RedeemResult,// ArbitrageArbitrageMarketConfig,ArbitrageServiceConfig,ScanResult,ClearPositionResult,// DipArbDipArbServiceConfig,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

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - fruitlollipop/poly-sdk · GitHub
Skip to content

Repository files navigation

@catalyst-team/poly-sdk

npm versionLicense: MIT

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

@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

FeatureDescription
Unified APISingle SDK for all Polymarket APIs
Type SafetyFull TypeScript support with comprehensive types
Rate LimitingBuilt-in rate limiting per API endpoint
CachingTTL-based caching with pluggable adapters
Error HandlingStructured errors with auto-retry

Installation

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:

poly-sdk Architecture
================================================================================
┌──────────────────────────────────────────────────────────────────────────────┐
│ PolymarketSDK │
│ (Entry Point) │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 3: High-Level Services (Recommended) │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ TradingService │ │ MarketService │ │ OnchainService │ │
│ │ ────────────── │ │ ────────────── │ │ ────────────── │ │
│ │ • Limit orders │ │ • K-lines │ │ • Split/Merge │ │
│ │ • Market orders│ │ • Orderbook │ │ • Redeem │ │
│ │ • Order mgmt │ │ • Price history│ │ • Approvals │ │
│ │ • Rewards │ │ • Arbitrage │ │ • Swaps │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │RealtimeServiceV2│ │ WalletService │ │SmartMoneyService│ │
│ │ ────────────── │ │ ────────────── │ │ ────────────── │ │
│ │ • WebSocket │ │ • Profiles │ │ • Top traders │ │
│ │ • Price feeds │ │ • Smart scores │ │ • Copy trading │ │
│ │ • Book updates │ │ • Sell detect │ │ • Signal detect │ │
│ │ • User events │ │ • PnL calc │ │ • Leaderboard │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ ArbitrageService │ │
│ │ ───────────────────────────────────────────────────────────────────── │ │
│ │ • Market scanning • Auto execution • Rebalancer • Smart clearing │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ DipArbService │ │
│ │ ───────────────────────────────────────────────────────────────────── │ │
│ │ • 15m crypto UP/DOWN • Dip detection • Auto-rotate • Background redeem│
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 2: Low-Level Clients (Advanced Users / Raw API Access) │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │GammaApiClnt│ │DataApiClnt │ │SubgraphClnt│ │ CTFClient │ │BridgeClient│ │
│ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │
│ │ • Markets │ │ • Positions│ │ • On-chain │ │ • Split │ │ • Cross- │ │
│ │ • Events │ │ • Trades │ │ • PnL │ │ • Merge │ │ chain │ │
│ │ • Search │ │ • Activity │ │ • OI │ │ • Redeem │ │ • Deposits │ │
│ └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │
│ │
│ Uses Official Polymarket Clients: │
│ • @polymarket/clob-client - Trading, orderbook, market data │
│ • @polymarket/real-time-data-client - WebSocket real-time updates │
│ │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 1: Core Infrastructure │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │RateLimiter │ │ Cache │ │ Errors │ │ Types │ │Price Utils │ │
│ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │
│ │ • Per-API │ │ • TTL-based│ │ • Retry │ │ • Unified │ │ • Arb calc │ │
│ │ • Bottleneck│ │ • Pluggable│ │ • Codes │ │ • K-lines │ │ • Rounding │ │
│ └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │
│ │
└──────────────────────────────────────────────────────────────────────────────┘

Service Responsibilities

ServiceResponsibility
PolymarketSDKEntry point, integrates all services
TradingServiceOrder management (place/cancel/query)
MarketServiceMarket data (orderbook/K-lines/search)
OnchainServiceOn-chain ops (split/merge/redeem/approve/swap)
RealtimeServiceV2WebSocket real-time data
WalletServiceWallet/trader analysis
SmartMoneyServiceSmart money tracking
ArbitrageServiceArbitrage detection & execution
DipArbServiceDip arbitrage for 15m crypto markets

Quick Start

Basic Usage (Read-Only)

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// No authentication needed for read operationsconstsdk=newPolymarketSDK();// Get market by slug or condition IDconstmarket=awaitsdk.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}`);// Get processed orderbook with analyticsconstorderbook=awaitsdk.getOrderbook(market.conditionId);console.log(`Long Arb Profit: ${orderbook.summary.longArbProfit}`);console.log(`Short Arb Profit: ${orderbook.summary.shortArbProfit}`);// Detect arbitrage opportunitiesconstarb=awaitsdk.detectArbitrage(market.conditionId);if(arb){console.log(`${arb.type.toUpperCase()} ARB: ${(arb.profit*100).toFixed(2)}% profit`);console.log(arb.action);}

With Authentication (Trading)

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// Recommended: Use static factory method (one line to get started)constsdk=awaitPolymarketSDK.create({privateKey: process.env.POLYMARKET_PRIVATE_KEY!,});// Ready to trade - SDK is initialized and WebSocket connected// Place a limit orderconstorder=awaitsdk.tradingService.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTC',});console.log(`Order placed: ${order.id}`);// Get open ordersconstopenOrders=awaitsdk.tradingService.getOpenOrders();console.log(`Open orders: ${openOrders.length}`);// Clean up when donesdk.stop();

Services Guide

PolymarketSDK (Entry Point)

The main SDK class that integrates all services.

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// ===== Method 1: Static Factory (Recommended) =====// One line: new + initialize + connect + waitForConnectionconstsdk=awaitPolymarketSDK.create({privateKey: '0x...',// Optional: for tradingchainId: 137,// Optional: Polygon mainnet (default)});// ===== Method 2: Using start() =====// const sdk = new PolymarketSDK({ privateKey: '0x...' });// await sdk.start(); // initialize + connect + waitForConnection// ===== Method 3: Manual Step-by-Step (Full Control) =====// const sdk = new PolymarketSDK({ privateKey: '0x...' });// await sdk.initialize(); // Initialize trading service// sdk.connect(); // Connect WebSocket// await sdk.waitForConnection(); // Wait for connection// Access servicessdk.tradingService// Trading operationssdk.markets// Market datasdk.wallets// Wallet analysissdk.realtime// WebSocket real-time datasdk.smartMoney// Smart money tracking & copy tradingsdk.dipArb// Dip arbitrage for 15m crypto marketssdk.dataApi// Direct Data API accesssdk.gammaApi// Direct Gamma API accesssdk.subgraph// On-chain data via Goldsky// Convenience methodsawaitsdk.getMarket(identifier);// Get unified marketawaitsdk.getOrderbook(conditionId);// Get processed orderbookawaitsdk.detectArbitrage(conditionId);// Detect arb opportunity// Clean upsdk.stop();// Disconnect 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
import{TradingService,MIN_ORDER_SIZE_SHARES,MIN_ORDER_VALUE_USDC}from'@catalyst-team/poly-sdk';consttrading=newTradingService(rateLimiter,cache,{privateKey: process.env.POLYMARKET_PRIVATE_KEY!,});awaittrading.initialize();// ===== Limit Orders =====// GTC: Good Till CancelledconstgtcOrder=awaittrading.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTC',});// GTD: Good Till Date (expires at timestamp)constgtdOrder=awaittrading.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTD',expiration: Math.floor(Date.now()/1000)+3600,// 1 hour});// ===== Market Orders =====// FOK: Fill Or Kill (fill entirely or cancel)constfokOrder=awaittrading.createMarketOrder({tokenId: yesTokenId,side: 'BUY',amount: 10,// $10 USDCorderType: 'FOK',});// FAK: Fill And Kill (partial fill ok)constfakOrder=awaittrading.createMarketOrder({tokenId: yesTokenId,side: 'SELL',amount: 10,// 10 sharesorderType: 'FAK',});// ===== Order Management =====constopenOrders=awaittrading.getOpenOrders();awaittrading.cancelOrder(orderId);awaittrading.cancelAllOrders();// ===== Rewards (Market Making Incentives) =====constisScoring=awaittrading.isOrderScoring(orderId);constrewards=awaittrading.getCurrentRewards();constearnings=awaittrading.getEarnings('2024-12-07');

MarketService

Market data, K-lines, orderbook analysis.

import{MarketService}from'@catalyst-team/poly-sdk';// Get unified marketconstmarket=awaitsdk.markets.getMarket('btc-100k-2024');// Get price lines (from /prices-history API)constprices=awaitsdk.markets.getKLines(conditionId,'1d');// Get dual price lines (primary + secondary) with spread analysisconstdual=awaitsdk.markets.getDualKLines(conditionId,'1d');console.log(dual.primary);// Primary outcome price pointsconsole.log(dual.secondary);// Secondary outcome price pointsconsole.log(dual.spreadAnalysis);// Spread analysis// Get OHLCV candles (from trade data aggregation)constklines=awaitsdk.markets.getKLinesOHLCV(conditionId,'1h',{limit: 100});// Get dual OHLCV K-Lines (YES + NO) with spread analysisconstdualOHLCV=awaitsdk.markets.getDualKLinesOHLCV(conditionId,'1h');console.log(dualOHLCV.yes);// YES token candlesconsole.log(dualOHLCV.no);// NO token candlesconsole.log(dualOHLCV.spreadAnalysis);// Historical spread (trade prices)console.log(dualOHLCV.realtimeSpread);// Real-time spread (orderbook)// Get processed orderbookconstorderbook=awaitsdk.markets.getProcessedOrderbook(conditionId);// Quick real-time spread checkconstspread=awaitsdk.markets.getRealtimeSpread(conditionId);if(spread.longArbProfit>0.005){console.log(`Long arb: buy YES@${spread.yesAsk} + NO@${spread.noAsk}`);}// Detect market signalsconstsignals=awaitsdk.markets.detectMarketSignals(conditionId);

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:

// WRONG: Double counts mirror ordersconstaskSum=YES.ask+NO.ask;// ~1.998, not ~1.0// CORRECT: Use effective pricesimport{getEffectivePrices,checkArbitrage}from'@catalyst-team/poly-sdk';consteffective=getEffectivePrices(yesAsk,yesBid,noAsk,noBid);// effective.effectiveBuyYes = min(YES.ask, 1 - NO.bid)// effective.effectiveBuyNo = min(NO.ask, 1 - YES.bid)constarb=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.

import{OnchainService}from'@catalyst-team/poly-sdk';constonchain=newOnchainService({privateKey: process.env.POLYMARKET_PRIVATE_KEY!,rpcUrl: 'https://polygon-rpc.com',// optional});// Check if ready for CTF tradingconststatus=awaitonchain.checkReadyForCTF('100');if(!status.ready){console.log('Issues:',status.issues);awaitonchain.approveAll();}// ===== CTF Operations =====// Split: USDC -> YES + NO tokensconstsplitResult=awaitonchain.split(conditionId,'100');// Merge: YES + NO -> USDC (for arbitrage)constmergeResult=awaitonchain.mergeByTokenIds(conditionId,tokenIds,'100');// Redeem: Winning tokens -> USDC (after resolution)constredeemResult=awaitonchain.redeemByTokenIds(conditionId,tokenIds);// ===== DEX Swaps (QuickSwap V3) =====// Swap MATIC to USDC.e (required for CTF)awaitonchain.swap('MATIC','USDC_E','50');// Get balancesconstbalances=awaitonchain.getBalances();console.log(`USDC.e: ${balances.usdcE}`);

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


RealtimeServiceV2

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

import{RealtimeServiceV2}from'@catalyst-team/poly-sdk';constrealtime=newRealtimeServiceV2({autoReconnect: true,pingInterval: 5000,});// Connect and subscriberealtime.connect();realtime.subscribeMarket([yesTokenId,noTokenId]);// Event-based APIrealtime.on('priceUpdate',(update)=>{console.log(`${update.assetId}: ${update.price}`);console.log(`Midpoint: ${update.midpoint}, Spread: ${update.spread}`);});realtime.on('bookUpdate',(update)=>{// Orderbook is auto-normalized:// bids: descending (best first), asks: ascending (best first)console.log(`Best bid: ${update.bids[0]?.price}`);console.log(`Best ask: ${update.asks[0]?.price}`);});realtime.on('lastTrade',(trade)=>{console.log(`Trade: ${trade.side}${trade.size} @ ${trade.price}`);});// Get cached pricesconstprice=realtime.getPrice(yesTokenId);constbook=realtime.getBook(yesTokenId);// Cleanuprealtime.disconnect();

WalletService

Wallet analysis and smart money scoring.

// Get top tradersconsttraders=awaitsdk.wallets.getTopTraders(10);// Get wallet profile with smart scoreconstprofile=awaitsdk.wallets.getWalletProfile('0x...');console.log(`Smart Score: ${profile.smartScore}/100`);console.log(`Win Rate: ${profile.winRate}%`);console.log(`Total PnL: $${profile.totalPnL}`);// Detect sell activity (for follow-wallet strategy)constsellResult=awaitsdk.wallets.detectSellActivity('0x...',conditionId,Date.now()-24*60*60*1000// since 24h ago);if(sellResult.isSelling){console.log(`Sold ${sellResult.percentageSold}%`);}// Track group sell ratioconstgroupSell=awaitsdk.wallets.trackGroupSellRatio(['0x...','0x...'],conditionId,peakValue,sinceTimestamp);

SmartMoneyService

Smart money detection and real-time auto copy trading.

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// One line to get started (recommended)constsdk=awaitPolymarketSDK.create({privateKey: '0x...'});// SDK is initialized and WebSocket connected// Get smart money walletsconstwallets=awaitsdk.smartMoney.getSmartMoneyList(50);// Check if address is smart moneyconstisSmartMoney=awaitsdk.smartMoney.isSmartMoney('0x...');// Subscribe to smart money tradesconstsub=sdk.smartMoney.subscribeSmartMoneyTrades((trade)=>{console.log(`${trade.traderName}${trade.side}${trade.outcome} @ $${trade.price}`);},{filterAddresses: ['0x...'],minSize: 10});// ===== Auto Copy Trading =====// Real-time copy trading - when smart money trades, copy immediatelyconstsubscription=awaitsdk.smartMoney.startAutoCopyTrading({// Target selectiontopN: 50,// Follow top 50 traders from leaderboard// targetAddresses: ['0x...'], // Or specify addresses directly// Order settingssizeScale: 0.1,// Copy 10% of their trade sizemaxSizePerTrade: 10,// Max $10 per trademaxSlippage: 0.03,// 3% slippage toleranceorderType: 'FOK',// FOK or FAK// FiltersminTradeSize: 5,// Only copy trades > $5sideFilter: 'BUY',// Only copy BUY trades (optional)// TestingdryRun: true,// Set false for real trades// CallbacksonTrade: (trade,result)=>{console.log(`Copied ${trade.traderName}: ${result.success ? '✅' : '❌'}`);},onError: (error)=>console.error(error),});console.log(`Tracking ${subscription.targetAddresses.length} wallets`);// Get statsconststats=subscription.getStats();console.log(`Detected: ${stats.tradesDetected}, Executed: ${stats.tradesExecuted}`);// Stopsubscription.stop();sdk.stop();

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.

import{ArbitrageService}from'@catalyst-team/poly-sdk';constarbService=newArbitrageService({privateKey: process.env.POLY_PRIVKEY,profitThreshold: 0.005,// 0.5% minimum profitminTradeSize: 5,// $5 minimummaxTradeSize: 100,// $100 maximumautoExecute: true,// Auto-execute opportunities// Rebalancer: auto-maintain USDC/token ratioenableRebalancer: true,minUsdcRatio: 0.2,// Min 20% USDCmaxUsdcRatio: 0.8,// Max 80% USDCtargetUsdcRatio: 0.5,// Target when rebalancing// Execution safetysizeSafetyFactor: 0.8,// Use 80% of orderbook depthautoFixImbalance: true,// Auto-fix partial fills});// Listen for eventsarbService.on('opportunity',(opp)=>{console.log(`${opp.type.toUpperCase()} ARB: ${opp.profitPercent.toFixed(2)}%`);});arbService.on('execution',(result)=>{if(result.success){console.log(`Executed: $${result.profit.toFixed(2)} profit`);}});// ===== Workflow =====// 1. Scan markets for opportunitiesconstresults=awaitarbService.scanMarkets({minVolume24h: 5000},0.005);// 2. Start monitoring best marketconstbest=awaitarbService.findAndStart(0.005);console.log(`Started: ${best.market.name} (+${best.profitPercent.toFixed(2)}%)`);// 3. Run for a while...awaitnewPromise(r=>setTimeout(r,60*60*1000));// 1 hour// 4. Stop and clear positionsawaitarbService.stop();constclearResult=awaitarbService.clearPositions(best.market,true);console.log(`Recovered: $${clearResult.totalUsdcRecovered.toFixed(2)}`);

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

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

Features

FeatureDescription
Dip DetectionDetects 15%+ price drops within 10s sliding window
Two-Leg ExecutionLeg1 (buy dip) + Leg2 (buy opposite when cost < target)
Auto-RotateAutomatically switches to next market when current ends
Background RedeemWaits for Oracle resolution (~5min) then redeems winning positions
WebSocket ReconnectAuto re-subscribes on disconnect

Programmatic Usage

import{PolymarketSDK}from'@catalyst-team/poly-sdk';constsdk=newPolymarketSDK({privateKey: '0x...'});// Configure strategysdk.dipArb.updateConfig({shares: 10,// Shares per tradesumTarget: 0.9,// Leg2 triggers when cost ≤ 0.9 (11% profit)dipThreshold: 0.15,// 15% dip triggers Leg1windowMinutes: 14,// Trade window after round startautoExecute: true,// Auto-execute signals});// Listen to eventssdk.dipArb.on('signal',(signal)=>{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 monitoringconstmarket=awaitsdk.dipArb.findAndStart({coin: 'ETH',preferDuration: '15m',});// Enable auto-rotate with redemptionsdk.dipArb.enableAutoRotate({enabled: true,underlyings: ['ETH'],duration: '15m',settleStrategy: 'redeem',redeemWaitMinutes: 5,});// Get statsconststats=sdk.dipArb.getStats();console.log(`Signals: ${stats.signalsDetected}, L1: ${stats.leg1Filled}, L2: ${stats.leg2Filled}`);// Cleanupawaitsdk.dipArb.stop();sdk.stop();

Events

EventDataDescription
startedDipArbMarketConfigStarted monitoring market
stopped-Stopped monitoring
newRound{ roundId, upOpen, downOpen }New trading round
signalDipArbSignalEventLeg1/Leg2 signal detected
executionDipArbExecutionResultTrade execution result
roundComplete{ profit, profitRate }Round finished
rotate{ reason, newMarket }Switched to new market
settled{ success, amountReceived }Position redeemed

Scripts

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

import{DataApiClient,// Positions, trades, leaderboardGammaApiClient,// Markets, events, searchSubgraphClient,// On-chain data via GoldskyCTFClient,// CTF contract operationsBridgeClient,// Cross-chain depositsSwapService,// DEX swaps on Polygon}from'@catalyst-team/poly-sdk';// Data APIconstpositions=awaitsdk.dataApi.getPositions('0x...');consttrades=awaitsdk.dataApi.getTrades('0x...');constleaderboard=awaitsdk.dataApi.getLeaderboard();// Gamma APIconstmarkets=awaitsdk.gammaApi.searchMarkets({query: 'bitcoin'});consttrending=awaitsdk.gammaApi.getTrendingMarkets(10);constevents=awaitsdk.gammaApi.getEvents({limit: 20});// Subgraph (on-chain data)constuserPositions=awaitsdk.subgraph.getUserPositions(address);constisResolved=awaitsdk.subgraph.isConditionResolved(conditionId);constglobalOI=awaitsdk.subgraph.getGlobalOpenInterest();

Breaking Changes (v0.3.0)

UnifiedMarket.tokens is now an Array

Before (v0.2.x):

// Object with yes/no propertiesconstyesPrice=market.tokens.yes.price;constnoPrice=market.tokens.no.price;

After (v0.3.0):

// Array of MarketToken objectsconstyesToken=market.tokens.find(t=>t.outcome==='Yes');constnoToken=market.tokens.find(t=>t.outcome==='No');constyesPrice=yesToken?.price;constnoPrice=noToken?.price;

Migration Guide

// Helper function for migrationfunctiongetTokenPrice(market: UnifiedMarket,outcome: 'Yes'|'No'): number{returnmarket.tokens.find(t=>t.outcome===outcome)?.price??0;}// UsageconstyesPrice=getTokenPrice(market,'Yes');constnoPrice=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:

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
ExampleDescription
01-basic-usage.tsGet markets, orderbooks, detect arbitrage
02-smart-money.tsTop traders, wallet profiles, smart scores
03-market-analysis.tsMarket signals, volume analysis
04-kline-aggregation.tsBuild OHLCV candles from trades
05-follow-wallet-strategy.tsTrack smart money, detect exits
06-services-demo.tsAll SDK services in action
07-realtime-websocket.tsLive price feeds, orderbook updates
08-trading-orders.tsGTC, GTD, FOK, FAK order types
09-rewards-tracking.tsMarket maker incentives, earnings
10-ctf-operations.tsSplit, merge, redeem tokens
11-live-arbitrage-scan.tsScan markets for opportunities
12-trending-arb-monitor.tsReal-time trending monitor
13-arbitrage-service.tsFull arbitrage workflow
14-dip-arb-service.tsDip arbitrage for 15m crypto

DipArb Scripts (in scripts/dip-arb/):

ScriptDescription
auto-trade.tsOne-click auto trading with rotation
redeem-positions.tsRedeem ended market positions

API Reference

For detailed API documentation, see:

Type Exports

importtype{// Core typesUnifiedMarket,MarketToken,ProcessedOrderbook,ArbitrageOpportunity,EffectivePrices,// TradingSide,OrderType,Order,OrderResult,LimitOrderParams,MarketOrderParams,// K-LinesKLineInterval,KLineCandle,DualKLineData,SpreadDataPoint,// WebSocketPriceUpdate,BookUpdate,OrderbookSnapshot,// WalletWalletProfile,SellActivityResult,// Smart MoneySmartMoneyWallet,SmartMoneyTrade,AutoCopyTradingOptions,AutoCopyTradingStats,AutoCopyTradingSubscription,// CTFSplitResult,MergeResult,RedeemResult,// ArbitrageArbitrageMarketConfig,ArbitrageServiceConfig,ScanResult,ClearPositionResult,// DipArbDipArbServiceConfig,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

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' GitHub - fruitlollipop/poly-sdk · GitHub
Skip to content

Repository files navigation

@catalyst-team/poly-sdk

npm versionLicense: MIT

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

@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

FeatureDescription
Unified APISingle SDK for all Polymarket APIs
Type SafetyFull TypeScript support with comprehensive types
Rate LimitingBuilt-in rate limiting per API endpoint
CachingTTL-based caching with pluggable adapters
Error HandlingStructured errors with auto-retry

Installation

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:

poly-sdk Architecture
================================================================================
┌──────────────────────────────────────────────────────────────────────────────┐
│ PolymarketSDK │
│ (Entry Point) │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 3: High-Level Services (Recommended) │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ TradingService │ │ MarketService │ │ OnchainService │ │
│ │ ────────────── │ │ ────────────── │ │ ────────────── │ │
│ │ • Limit orders │ │ • K-lines │ │ • Split/Merge │ │
│ │ • Market orders│ │ • Orderbook │ │ • Redeem │ │
│ │ • Order mgmt │ │ • Price history│ │ • Approvals │ │
│ │ • Rewards │ │ • Arbitrage │ │ • Swaps │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │RealtimeServiceV2│ │ WalletService │ │SmartMoneyService│ │
│ │ ────────────── │ │ ────────────── │ │ ────────────── │ │
│ │ • WebSocket │ │ • Profiles │ │ • Top traders │ │
│ │ • Price feeds │ │ • Smart scores │ │ • Copy trading │ │
│ │ • Book updates │ │ • Sell detect │ │ • Signal detect │ │
│ │ • User events │ │ • PnL calc │ │ • Leaderboard │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ ArbitrageService │ │
│ │ ───────────────────────────────────────────────────────────────────── │ │
│ │ • Market scanning • Auto execution • Rebalancer • Smart clearing │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ DipArbService │ │
│ │ ───────────────────────────────────────────────────────────────────── │ │
│ │ • 15m crypto UP/DOWN • Dip detection • Auto-rotate • Background redeem│
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 2: Low-Level Clients (Advanced Users / Raw API Access) │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │GammaApiClnt│ │DataApiClnt │ │SubgraphClnt│ │ CTFClient │ │BridgeClient│ │
│ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │
│ │ • Markets │ │ • Positions│ │ • On-chain │ │ • Split │ │ • Cross- │ │
│ │ • Events │ │ • Trades │ │ • PnL │ │ • Merge │ │ chain │ │
│ │ • Search │ │ • Activity │ │ • OI │ │ • Redeem │ │ • Deposits │ │
│ └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │
│ │
│ Uses Official Polymarket Clients: │
│ • @polymarket/clob-client - Trading, orderbook, market data │
│ • @polymarket/real-time-data-client - WebSocket real-time updates │
│ │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 1: Core Infrastructure │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │RateLimiter │ │ Cache │ │ Errors │ │ Types │ │Price Utils │ │
│ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │
│ │ • Per-API │ │ • TTL-based│ │ • Retry │ │ • Unified │ │ • Arb calc │ │
│ │ • Bottleneck│ │ • Pluggable│ │ • Codes │ │ • K-lines │ │ • Rounding │ │
│ └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │
│ │
└──────────────────────────────────────────────────────────────────────────────┘

Service Responsibilities

ServiceResponsibility
PolymarketSDKEntry point, integrates all services
TradingServiceOrder management (place/cancel/query)
MarketServiceMarket data (orderbook/K-lines/search)
OnchainServiceOn-chain ops (split/merge/redeem/approve/swap)
RealtimeServiceV2WebSocket real-time data
WalletServiceWallet/trader analysis
SmartMoneyServiceSmart money tracking
ArbitrageServiceArbitrage detection & execution
DipArbServiceDip arbitrage for 15m crypto markets

Quick Start

Basic Usage (Read-Only)

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// No authentication needed for read operationsconstsdk=newPolymarketSDK();// Get market by slug or condition IDconstmarket=awaitsdk.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}`);// Get processed orderbook with analyticsconstorderbook=awaitsdk.getOrderbook(market.conditionId);console.log(`Long Arb Profit: ${orderbook.summary.longArbProfit}`);console.log(`Short Arb Profit: ${orderbook.summary.shortArbProfit}`);// Detect arbitrage opportunitiesconstarb=awaitsdk.detectArbitrage(market.conditionId);if(arb){console.log(`${arb.type.toUpperCase()} ARB: ${(arb.profit*100).toFixed(2)}% profit`);console.log(arb.action);}

With Authentication (Trading)

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// Recommended: Use static factory method (one line to get started)constsdk=awaitPolymarketSDK.create({privateKey: process.env.POLYMARKET_PRIVATE_KEY!,});// Ready to trade - SDK is initialized and WebSocket connected// Place a limit orderconstorder=awaitsdk.tradingService.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTC',});console.log(`Order placed: ${order.id}`);// Get open ordersconstopenOrders=awaitsdk.tradingService.getOpenOrders();console.log(`Open orders: ${openOrders.length}`);// Clean up when donesdk.stop();

Services Guide

PolymarketSDK (Entry Point)

The main SDK class that integrates all services.

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// ===== Method 1: Static Factory (Recommended) =====// One line: new + initialize + connect + waitForConnectionconstsdk=awaitPolymarketSDK.create({privateKey: '0x...',// Optional: for tradingchainId: 137,// Optional: Polygon mainnet (default)});// ===== Method 2: Using start() =====// const sdk = new PolymarketSDK({ privateKey: '0x...' });// await sdk.start(); // initialize + connect + waitForConnection// ===== Method 3: Manual Step-by-Step (Full Control) =====// const sdk = new PolymarketSDK({ privateKey: '0x...' });// await sdk.initialize(); // Initialize trading service// sdk.connect(); // Connect WebSocket// await sdk.waitForConnection(); // Wait for connection// Access servicessdk.tradingService// Trading operationssdk.markets// Market datasdk.wallets// Wallet analysissdk.realtime// WebSocket real-time datasdk.smartMoney// Smart money tracking & copy tradingsdk.dipArb// Dip arbitrage for 15m crypto marketssdk.dataApi// Direct Data API accesssdk.gammaApi// Direct Gamma API accesssdk.subgraph// On-chain data via Goldsky// Convenience methodsawaitsdk.getMarket(identifier);// Get unified marketawaitsdk.getOrderbook(conditionId);// Get processed orderbookawaitsdk.detectArbitrage(conditionId);// Detect arb opportunity// Clean upsdk.stop();// Disconnect 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
import{TradingService,MIN_ORDER_SIZE_SHARES,MIN_ORDER_VALUE_USDC}from'@catalyst-team/poly-sdk';consttrading=newTradingService(rateLimiter,cache,{privateKey: process.env.POLYMARKET_PRIVATE_KEY!,});awaittrading.initialize();// ===== Limit Orders =====// GTC: Good Till CancelledconstgtcOrder=awaittrading.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTC',});// GTD: Good Till Date (expires at timestamp)constgtdOrder=awaittrading.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTD',expiration: Math.floor(Date.now()/1000)+3600,// 1 hour});// ===== Market Orders =====// FOK: Fill Or Kill (fill entirely or cancel)constfokOrder=awaittrading.createMarketOrder({tokenId: yesTokenId,side: 'BUY',amount: 10,// $10 USDCorderType: 'FOK',});// FAK: Fill And Kill (partial fill ok)constfakOrder=awaittrading.createMarketOrder({tokenId: yesTokenId,side: 'SELL',amount: 10,// 10 sharesorderType: 'FAK',});// ===== Order Management =====constopenOrders=awaittrading.getOpenOrders();awaittrading.cancelOrder(orderId);awaittrading.cancelAllOrders();// ===== Rewards (Market Making Incentives) =====constisScoring=awaittrading.isOrderScoring(orderId);constrewards=awaittrading.getCurrentRewards();constearnings=awaittrading.getEarnings('2024-12-07');

MarketService

Market data, K-lines, orderbook analysis.

import{MarketService}from'@catalyst-team/poly-sdk';// Get unified marketconstmarket=awaitsdk.markets.getMarket('btc-100k-2024');// Get price lines (from /prices-history API)constprices=awaitsdk.markets.getKLines(conditionId,'1d');// Get dual price lines (primary + secondary) with spread analysisconstdual=awaitsdk.markets.getDualKLines(conditionId,'1d');console.log(dual.primary);// Primary outcome price pointsconsole.log(dual.secondary);// Secondary outcome price pointsconsole.log(dual.spreadAnalysis);// Spread analysis// Get OHLCV candles (from trade data aggregation)constklines=awaitsdk.markets.getKLinesOHLCV(conditionId,'1h',{limit: 100});// Get dual OHLCV K-Lines (YES + NO) with spread analysisconstdualOHLCV=awaitsdk.markets.getDualKLinesOHLCV(conditionId,'1h');console.log(dualOHLCV.yes);// YES token candlesconsole.log(dualOHLCV.no);// NO token candlesconsole.log(dualOHLCV.spreadAnalysis);// Historical spread (trade prices)console.log(dualOHLCV.realtimeSpread);// Real-time spread (orderbook)// Get processed orderbookconstorderbook=awaitsdk.markets.getProcessedOrderbook(conditionId);// Quick real-time spread checkconstspread=awaitsdk.markets.getRealtimeSpread(conditionId);if(spread.longArbProfit>0.005){console.log(`Long arb: buy YES@${spread.yesAsk} + NO@${spread.noAsk}`);}// Detect market signalsconstsignals=awaitsdk.markets.detectMarketSignals(conditionId);

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:

// WRONG: Double counts mirror ordersconstaskSum=YES.ask+NO.ask;// ~1.998, not ~1.0// CORRECT: Use effective pricesimport{getEffectivePrices,checkArbitrage}from'@catalyst-team/poly-sdk';consteffective=getEffectivePrices(yesAsk,yesBid,noAsk,noBid);// effective.effectiveBuyYes = min(YES.ask, 1 - NO.bid)// effective.effectiveBuyNo = min(NO.ask, 1 - YES.bid)constarb=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.

import{OnchainService}from'@catalyst-team/poly-sdk';constonchain=newOnchainService({privateKey: process.env.POLYMARKET_PRIVATE_KEY!,rpcUrl: 'https://polygon-rpc.com',// optional});// Check if ready for CTF tradingconststatus=awaitonchain.checkReadyForCTF('100');if(!status.ready){console.log('Issues:',status.issues);awaitonchain.approveAll();}// ===== CTF Operations =====// Split: USDC -> YES + NO tokensconstsplitResult=awaitonchain.split(conditionId,'100');// Merge: YES + NO -> USDC (for arbitrage)constmergeResult=awaitonchain.mergeByTokenIds(conditionId,tokenIds,'100');// Redeem: Winning tokens -> USDC (after resolution)constredeemResult=awaitonchain.redeemByTokenIds(conditionId,tokenIds);// ===== DEX Swaps (QuickSwap V3) =====// Swap MATIC to USDC.e (required for CTF)awaitonchain.swap('MATIC','USDC_E','50');// Get balancesconstbalances=awaitonchain.getBalances();console.log(`USDC.e: ${balances.usdcE}`);

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


RealtimeServiceV2

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

import{RealtimeServiceV2}from'@catalyst-team/poly-sdk';constrealtime=newRealtimeServiceV2({autoReconnect: true,pingInterval: 5000,});// Connect and subscriberealtime.connect();realtime.subscribeMarket([yesTokenId,noTokenId]);// Event-based APIrealtime.on('priceUpdate',(update)=>{console.log(`${update.assetId}: ${update.price}`);console.log(`Midpoint: ${update.midpoint}, Spread: ${update.spread}`);});realtime.on('bookUpdate',(update)=>{// Orderbook is auto-normalized:// bids: descending (best first), asks: ascending (best first)console.log(`Best bid: ${update.bids[0]?.price}`);console.log(`Best ask: ${update.asks[0]?.price}`);});realtime.on('lastTrade',(trade)=>{console.log(`Trade: ${trade.side}${trade.size} @ ${trade.price}`);});// Get cached pricesconstprice=realtime.getPrice(yesTokenId);constbook=realtime.getBook(yesTokenId);// Cleanuprealtime.disconnect();

WalletService

Wallet analysis and smart money scoring.

// Get top tradersconsttraders=awaitsdk.wallets.getTopTraders(10);// Get wallet profile with smart scoreconstprofile=awaitsdk.wallets.getWalletProfile('0x...');console.log(`Smart Score: ${profile.smartScore}/100`);console.log(`Win Rate: ${profile.winRate}%`);console.log(`Total PnL: $${profile.totalPnL}`);// Detect sell activity (for follow-wallet strategy)constsellResult=awaitsdk.wallets.detectSellActivity('0x...',conditionId,Date.now()-24*60*60*1000// since 24h ago);if(sellResult.isSelling){console.log(`Sold ${sellResult.percentageSold}%`);}// Track group sell ratioconstgroupSell=awaitsdk.wallets.trackGroupSellRatio(['0x...','0x...'],conditionId,peakValue,sinceTimestamp);

SmartMoneyService

Smart money detection and real-time auto copy trading.

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// One line to get started (recommended)constsdk=awaitPolymarketSDK.create({privateKey: '0x...'});// SDK is initialized and WebSocket connected// Get smart money walletsconstwallets=awaitsdk.smartMoney.getSmartMoneyList(50);// Check if address is smart moneyconstisSmartMoney=awaitsdk.smartMoney.isSmartMoney('0x...');// Subscribe to smart money tradesconstsub=sdk.smartMoney.subscribeSmartMoneyTrades((trade)=>{console.log(`${trade.traderName}${trade.side}${trade.outcome} @ $${trade.price}`);},{filterAddresses: ['0x...'],minSize: 10});// ===== Auto Copy Trading =====// Real-time copy trading - when smart money trades, copy immediatelyconstsubscription=awaitsdk.smartMoney.startAutoCopyTrading({// Target selectiontopN: 50,// Follow top 50 traders from leaderboard// targetAddresses: ['0x...'], // Or specify addresses directly// Order settingssizeScale: 0.1,// Copy 10% of their trade sizemaxSizePerTrade: 10,// Max $10 per trademaxSlippage: 0.03,// 3% slippage toleranceorderType: 'FOK',// FOK or FAK// FiltersminTradeSize: 5,// Only copy trades > $5sideFilter: 'BUY',// Only copy BUY trades (optional)// TestingdryRun: true,// Set false for real trades// CallbacksonTrade: (trade,result)=>{console.log(`Copied ${trade.traderName}: ${result.success ? '✅' : '❌'}`);},onError: (error)=>console.error(error),});console.log(`Tracking ${subscription.targetAddresses.length} wallets`);// Get statsconststats=subscription.getStats();console.log(`Detected: ${stats.tradesDetected}, Executed: ${stats.tradesExecuted}`);// Stopsubscription.stop();sdk.stop();

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.

import{ArbitrageService}from'@catalyst-team/poly-sdk';constarbService=newArbitrageService({privateKey: process.env.POLY_PRIVKEY,profitThreshold: 0.005,// 0.5% minimum profitminTradeSize: 5,// $5 minimummaxTradeSize: 100,// $100 maximumautoExecute: true,// Auto-execute opportunities// Rebalancer: auto-maintain USDC/token ratioenableRebalancer: true,minUsdcRatio: 0.2,// Min 20% USDCmaxUsdcRatio: 0.8,// Max 80% USDCtargetUsdcRatio: 0.5,// Target when rebalancing// Execution safetysizeSafetyFactor: 0.8,// Use 80% of orderbook depthautoFixImbalance: true,// Auto-fix partial fills});// Listen for eventsarbService.on('opportunity',(opp)=>{console.log(`${opp.type.toUpperCase()} ARB: ${opp.profitPercent.toFixed(2)}%`);});arbService.on('execution',(result)=>{if(result.success){console.log(`Executed: $${result.profit.toFixed(2)} profit`);}});// ===== Workflow =====// 1. Scan markets for opportunitiesconstresults=awaitarbService.scanMarkets({minVolume24h: 5000},0.005);// 2. Start monitoring best marketconstbest=awaitarbService.findAndStart(0.005);console.log(`Started: ${best.market.name} (+${best.profitPercent.toFixed(2)}%)`);// 3. Run for a while...awaitnewPromise(r=>setTimeout(r,60*60*1000));// 1 hour// 4. Stop and clear positionsawaitarbService.stop();constclearResult=awaitarbService.clearPositions(best.market,true);console.log(`Recovered: $${clearResult.totalUsdcRecovered.toFixed(2)}`);

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

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

Features

FeatureDescription
Dip DetectionDetects 15%+ price drops within 10s sliding window
Two-Leg ExecutionLeg1 (buy dip) + Leg2 (buy opposite when cost < target)
Auto-RotateAutomatically switches to next market when current ends
Background RedeemWaits for Oracle resolution (~5min) then redeems winning positions
WebSocket ReconnectAuto re-subscribes on disconnect

Programmatic Usage

import{PolymarketSDK}from'@catalyst-team/poly-sdk';constsdk=newPolymarketSDK({privateKey: '0x...'});// Configure strategysdk.dipArb.updateConfig({shares: 10,// Shares per tradesumTarget: 0.9,// Leg2 triggers when cost ≤ 0.9 (11% profit)dipThreshold: 0.15,// 15% dip triggers Leg1windowMinutes: 14,// Trade window after round startautoExecute: true,// Auto-execute signals});// Listen to eventssdk.dipArb.on('signal',(signal)=>{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 monitoringconstmarket=awaitsdk.dipArb.findAndStart({coin: 'ETH',preferDuration: '15m',});// Enable auto-rotate with redemptionsdk.dipArb.enableAutoRotate({enabled: true,underlyings: ['ETH'],duration: '15m',settleStrategy: 'redeem',redeemWaitMinutes: 5,});// Get statsconststats=sdk.dipArb.getStats();console.log(`Signals: ${stats.signalsDetected}, L1: ${stats.leg1Filled}, L2: ${stats.leg2Filled}`);// Cleanupawaitsdk.dipArb.stop();sdk.stop();

Events

EventDataDescription
startedDipArbMarketConfigStarted monitoring market
stopped-Stopped monitoring
newRound{ roundId, upOpen, downOpen }New trading round
signalDipArbSignalEventLeg1/Leg2 signal detected
executionDipArbExecutionResultTrade execution result
roundComplete{ profit, profitRate }Round finished
rotate{ reason, newMarket }Switched to new market
settled{ success, amountReceived }Position redeemed

Scripts

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

import{DataApiClient,// Positions, trades, leaderboardGammaApiClient,// Markets, events, searchSubgraphClient,// On-chain data via GoldskyCTFClient,// CTF contract operationsBridgeClient,// Cross-chain depositsSwapService,// DEX swaps on Polygon}from'@catalyst-team/poly-sdk';// Data APIconstpositions=awaitsdk.dataApi.getPositions('0x...');consttrades=awaitsdk.dataApi.getTrades('0x...');constleaderboard=awaitsdk.dataApi.getLeaderboard();// Gamma APIconstmarkets=awaitsdk.gammaApi.searchMarkets({query: 'bitcoin'});consttrending=awaitsdk.gammaApi.getTrendingMarkets(10);constevents=awaitsdk.gammaApi.getEvents({limit: 20});// Subgraph (on-chain data)constuserPositions=awaitsdk.subgraph.getUserPositions(address);constisResolved=awaitsdk.subgraph.isConditionResolved(conditionId);constglobalOI=awaitsdk.subgraph.getGlobalOpenInterest();

Breaking Changes (v0.3.0)

UnifiedMarket.tokens is now an Array

Before (v0.2.x):

// Object with yes/no propertiesconstyesPrice=market.tokens.yes.price;constnoPrice=market.tokens.no.price;

After (v0.3.0):

// Array of MarketToken objectsconstyesToken=market.tokens.find(t=>t.outcome==='Yes');constnoToken=market.tokens.find(t=>t.outcome==='No');constyesPrice=yesToken?.price;constnoPrice=noToken?.price;

Migration Guide

// Helper function for migrationfunctiongetTokenPrice(market: UnifiedMarket,outcome: 'Yes'|'No'): number{returnmarket.tokens.find(t=>t.outcome===outcome)?.price??0;}// UsageconstyesPrice=getTokenPrice(market,'Yes');constnoPrice=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:

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
ExampleDescription
01-basic-usage.tsGet markets, orderbooks, detect arbitrage
02-smart-money.tsTop traders, wallet profiles, smart scores
03-market-analysis.tsMarket signals, volume analysis
04-kline-aggregation.tsBuild OHLCV candles from trades
05-follow-wallet-strategy.tsTrack smart money, detect exits
06-services-demo.tsAll SDK services in action
07-realtime-websocket.tsLive price feeds, orderbook updates
08-trading-orders.tsGTC, GTD, FOK, FAK order types
09-rewards-tracking.tsMarket maker incentives, earnings
10-ctf-operations.tsSplit, merge, redeem tokens
11-live-arbitrage-scan.tsScan markets for opportunities
12-trending-arb-monitor.tsReal-time trending monitor
13-arbitrage-service.tsFull arbitrage workflow
14-dip-arb-service.tsDip arbitrage for 15m crypto

DipArb Scripts (in scripts/dip-arb/):

ScriptDescription
auto-trade.tsOne-click auto trading with rotation
redeem-positions.tsRedeem ended market positions

API Reference

For detailed API documentation, see:

Type Exports

importtype{// Core typesUnifiedMarket,MarketToken,ProcessedOrderbook,ArbitrageOpportunity,EffectivePrices,// TradingSide,OrderType,Order,OrderResult,LimitOrderParams,MarketOrderParams,// K-LinesKLineInterval,KLineCandle,DualKLineData,SpreadDataPoint,// WebSocketPriceUpdate,BookUpdate,OrderbookSnapshot,// WalletWalletProfile,SellActivityResult,// Smart MoneySmartMoneyWallet,SmartMoneyTrade,AutoCopyTradingOptions,AutoCopyTradingStats,AutoCopyTradingSubscription,// CTFSplitResult,MergeResult,RedeemResult,// ArbitrageArbitrageMarketConfig,ArbitrageServiceConfig,ScanResult,ClearPositionResult,// DipArbDipArbServiceConfig,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

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - fruitlollipop/poly-sdk · GitHub
Skip to content

Repository files navigation

@catalyst-team/poly-sdk

npm versionLicense: MIT

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

@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

FeatureDescription
Unified APISingle SDK for all Polymarket APIs
Type SafetyFull TypeScript support with comprehensive types
Rate LimitingBuilt-in rate limiting per API endpoint
CachingTTL-based caching with pluggable adapters
Error HandlingStructured errors with auto-retry

Installation

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:

poly-sdk Architecture
================================================================================
┌──────────────────────────────────────────────────────────────────────────────┐
│ PolymarketSDK │
│ (Entry Point) │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 3: High-Level Services (Recommended) │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ TradingService │ │ MarketService │ │ OnchainService │ │
│ │ ────────────── │ │ ────────────── │ │ ────────────── │ │
│ │ • Limit orders │ │ • K-lines │ │ • Split/Merge │ │
│ │ • Market orders│ │ • Orderbook │ │ • Redeem │ │
│ │ • Order mgmt │ │ • Price history│ │ • Approvals │ │
│ │ • Rewards │ │ • Arbitrage │ │ • Swaps │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │RealtimeServiceV2│ │ WalletService │ │SmartMoneyService│ │
│ │ ────────────── │ │ ────────────── │ │ ────────────── │ │
│ │ • WebSocket │ │ • Profiles │ │ • Top traders │ │
│ │ • Price feeds │ │ • Smart scores │ │ • Copy trading │ │
│ │ • Book updates │ │ • Sell detect │ │ • Signal detect │ │
│ │ • User events │ │ • PnL calc │ │ • Leaderboard │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ ArbitrageService │ │
│ │ ───────────────────────────────────────────────────────────────────── │ │
│ │ • Market scanning • Auto execution • Rebalancer • Smart clearing │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ DipArbService │ │
│ │ ───────────────────────────────────────────────────────────────────── │ │
│ │ • 15m crypto UP/DOWN • Dip detection • Auto-rotate • Background redeem│
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 2: Low-Level Clients (Advanced Users / Raw API Access) │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │GammaApiClnt│ │DataApiClnt │ │SubgraphClnt│ │ CTFClient │ │BridgeClient│ │
│ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │
│ │ • Markets │ │ • Positions│ │ • On-chain │ │ • Split │ │ • Cross- │ │
│ │ • Events │ │ • Trades │ │ • PnL │ │ • Merge │ │ chain │ │
│ │ • Search │ │ • Activity │ │ • OI │ │ • Redeem │ │ • Deposits │ │
│ └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │
│ │
│ Uses Official Polymarket Clients: │
│ • @polymarket/clob-client - Trading, orderbook, market data │
│ • @polymarket/real-time-data-client - WebSocket real-time updates │
│ │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 1: Core Infrastructure │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │RateLimiter │ │ Cache │ │ Errors │ │ Types │ │Price Utils │ │
│ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │
│ │ • Per-API │ │ • TTL-based│ │ • Retry │ │ • Unified │ │ • Arb calc │ │
│ │ • Bottleneck│ │ • Pluggable│ │ • Codes │ │ • K-lines │ │ • Rounding │ │
│ └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │
│ │
└──────────────────────────────────────────────────────────────────────────────┘

Service Responsibilities

ServiceResponsibility
PolymarketSDKEntry point, integrates all services
TradingServiceOrder management (place/cancel/query)
MarketServiceMarket data (orderbook/K-lines/search)
OnchainServiceOn-chain ops (split/merge/redeem/approve/swap)
RealtimeServiceV2WebSocket real-time data
WalletServiceWallet/trader analysis
SmartMoneyServiceSmart money tracking
ArbitrageServiceArbitrage detection & execution
DipArbServiceDip arbitrage for 15m crypto markets

Quick Start

Basic Usage (Read-Only)

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// No authentication needed for read operationsconstsdk=newPolymarketSDK();// Get market by slug or condition IDconstmarket=awaitsdk.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}`);// Get processed orderbook with analyticsconstorderbook=awaitsdk.getOrderbook(market.conditionId);console.log(`Long Arb Profit: ${orderbook.summary.longArbProfit}`);console.log(`Short Arb Profit: ${orderbook.summary.shortArbProfit}`);// Detect arbitrage opportunitiesconstarb=awaitsdk.detectArbitrage(market.conditionId);if(arb){console.log(`${arb.type.toUpperCase()} ARB: ${(arb.profit*100).toFixed(2)}% profit`);console.log(arb.action);}

With Authentication (Trading)

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// Recommended: Use static factory method (one line to get started)constsdk=awaitPolymarketSDK.create({privateKey: process.env.POLYMARKET_PRIVATE_KEY!,});// Ready to trade - SDK is initialized and WebSocket connected// Place a limit orderconstorder=awaitsdk.tradingService.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTC',});console.log(`Order placed: ${order.id}`);// Get open ordersconstopenOrders=awaitsdk.tradingService.getOpenOrders();console.log(`Open orders: ${openOrders.length}`);// Clean up when donesdk.stop();

Services Guide

PolymarketSDK (Entry Point)

The main SDK class that integrates all services.

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// ===== Method 1: Static Factory (Recommended) =====// One line: new + initialize + connect + waitForConnectionconstsdk=awaitPolymarketSDK.create({privateKey: '0x...',// Optional: for tradingchainId: 137,// Optional: Polygon mainnet (default)});// ===== Method 2: Using start() =====// const sdk = new PolymarketSDK({ privateKey: '0x...' });// await sdk.start(); // initialize + connect + waitForConnection// ===== Method 3: Manual Step-by-Step (Full Control) =====// const sdk = new PolymarketSDK({ privateKey: '0x...' });// await sdk.initialize(); // Initialize trading service// sdk.connect(); // Connect WebSocket// await sdk.waitForConnection(); // Wait for connection// Access servicessdk.tradingService// Trading operationssdk.markets// Market datasdk.wallets// Wallet analysissdk.realtime// WebSocket real-time datasdk.smartMoney// Smart money tracking & copy tradingsdk.dipArb// Dip arbitrage for 15m crypto marketssdk.dataApi// Direct Data API accesssdk.gammaApi// Direct Gamma API accesssdk.subgraph// On-chain data via Goldsky// Convenience methodsawaitsdk.getMarket(identifier);// Get unified marketawaitsdk.getOrderbook(conditionId);// Get processed orderbookawaitsdk.detectArbitrage(conditionId);// Detect arb opportunity// Clean upsdk.stop();// Disconnect 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
import{TradingService,MIN_ORDER_SIZE_SHARES,MIN_ORDER_VALUE_USDC}from'@catalyst-team/poly-sdk';consttrading=newTradingService(rateLimiter,cache,{privateKey: process.env.POLYMARKET_PRIVATE_KEY!,});awaittrading.initialize();// ===== Limit Orders =====// GTC: Good Till CancelledconstgtcOrder=awaittrading.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTC',});// GTD: Good Till Date (expires at timestamp)constgtdOrder=awaittrading.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTD',expiration: Math.floor(Date.now()/1000)+3600,// 1 hour});// ===== Market Orders =====// FOK: Fill Or Kill (fill entirely or cancel)constfokOrder=awaittrading.createMarketOrder({tokenId: yesTokenId,side: 'BUY',amount: 10,// $10 USDCorderType: 'FOK',});// FAK: Fill And Kill (partial fill ok)constfakOrder=awaittrading.createMarketOrder({tokenId: yesTokenId,side: 'SELL',amount: 10,// 10 sharesorderType: 'FAK',});// ===== Order Management =====constopenOrders=awaittrading.getOpenOrders();awaittrading.cancelOrder(orderId);awaittrading.cancelAllOrders();// ===== Rewards (Market Making Incentives) =====constisScoring=awaittrading.isOrderScoring(orderId);constrewards=awaittrading.getCurrentRewards();constearnings=awaittrading.getEarnings('2024-12-07');

MarketService

Market data, K-lines, orderbook analysis.

import{MarketService}from'@catalyst-team/poly-sdk';// Get unified marketconstmarket=awaitsdk.markets.getMarket('btc-100k-2024');// Get price lines (from /prices-history API)constprices=awaitsdk.markets.getKLines(conditionId,'1d');// Get dual price lines (primary + secondary) with spread analysisconstdual=awaitsdk.markets.getDualKLines(conditionId,'1d');console.log(dual.primary);// Primary outcome price pointsconsole.log(dual.secondary);// Secondary outcome price pointsconsole.log(dual.spreadAnalysis);// Spread analysis// Get OHLCV candles (from trade data aggregation)constklines=awaitsdk.markets.getKLinesOHLCV(conditionId,'1h',{limit: 100});// Get dual OHLCV K-Lines (YES + NO) with spread analysisconstdualOHLCV=awaitsdk.markets.getDualKLinesOHLCV(conditionId,'1h');console.log(dualOHLCV.yes);// YES token candlesconsole.log(dualOHLCV.no);// NO token candlesconsole.log(dualOHLCV.spreadAnalysis);// Historical spread (trade prices)console.log(dualOHLCV.realtimeSpread);// Real-time spread (orderbook)// Get processed orderbookconstorderbook=awaitsdk.markets.getProcessedOrderbook(conditionId);// Quick real-time spread checkconstspread=awaitsdk.markets.getRealtimeSpread(conditionId);if(spread.longArbProfit>0.005){console.log(`Long arb: buy YES@${spread.yesAsk} + NO@${spread.noAsk}`);}// Detect market signalsconstsignals=awaitsdk.markets.detectMarketSignals(conditionId);

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:

// WRONG: Double counts mirror ordersconstaskSum=YES.ask+NO.ask;// ~1.998, not ~1.0// CORRECT: Use effective pricesimport{getEffectivePrices,checkArbitrage}from'@catalyst-team/poly-sdk';consteffective=getEffectivePrices(yesAsk,yesBid,noAsk,noBid);// effective.effectiveBuyYes = min(YES.ask, 1 - NO.bid)// effective.effectiveBuyNo = min(NO.ask, 1 - YES.bid)constarb=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.

import{OnchainService}from'@catalyst-team/poly-sdk';constonchain=newOnchainService({privateKey: process.env.POLYMARKET_PRIVATE_KEY!,rpcUrl: 'https://polygon-rpc.com',// optional});// Check if ready for CTF tradingconststatus=awaitonchain.checkReadyForCTF('100');if(!status.ready){console.log('Issues:',status.issues);awaitonchain.approveAll();}// ===== CTF Operations =====// Split: USDC -> YES + NO tokensconstsplitResult=awaitonchain.split(conditionId,'100');// Merge: YES + NO -> USDC (for arbitrage)constmergeResult=awaitonchain.mergeByTokenIds(conditionId,tokenIds,'100');// Redeem: Winning tokens -> USDC (after resolution)constredeemResult=awaitonchain.redeemByTokenIds(conditionId,tokenIds);// ===== DEX Swaps (QuickSwap V3) =====// Swap MATIC to USDC.e (required for CTF)awaitonchain.swap('MATIC','USDC_E','50');// Get balancesconstbalances=awaitonchain.getBalances();console.log(`USDC.e: ${balances.usdcE}`);

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


RealtimeServiceV2

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

import{RealtimeServiceV2}from'@catalyst-team/poly-sdk';constrealtime=newRealtimeServiceV2({autoReconnect: true,pingInterval: 5000,});// Connect and subscriberealtime.connect();realtime.subscribeMarket([yesTokenId,noTokenId]);// Event-based APIrealtime.on('priceUpdate',(update)=>{console.log(`${update.assetId}: ${update.price}`);console.log(`Midpoint: ${update.midpoint}, Spread: ${update.spread}`);});realtime.on('bookUpdate',(update)=>{// Orderbook is auto-normalized:// bids: descending (best first), asks: ascending (best first)console.log(`Best bid: ${update.bids[0]?.price}`);console.log(`Best ask: ${update.asks[0]?.price}`);});realtime.on('lastTrade',(trade)=>{console.log(`Trade: ${trade.side}${trade.size} @ ${trade.price}`);});// Get cached pricesconstprice=realtime.getPrice(yesTokenId);constbook=realtime.getBook(yesTokenId);// Cleanuprealtime.disconnect();

WalletService

Wallet analysis and smart money scoring.

// Get top tradersconsttraders=awaitsdk.wallets.getTopTraders(10);// Get wallet profile with smart scoreconstprofile=awaitsdk.wallets.getWalletProfile('0x...');console.log(`Smart Score: ${profile.smartScore}/100`);console.log(`Win Rate: ${profile.winRate}%`);console.log(`Total PnL: $${profile.totalPnL}`);// Detect sell activity (for follow-wallet strategy)constsellResult=awaitsdk.wallets.detectSellActivity('0x...',conditionId,Date.now()-24*60*60*1000// since 24h ago);if(sellResult.isSelling){console.log(`Sold ${sellResult.percentageSold}%`);}// Track group sell ratioconstgroupSell=awaitsdk.wallets.trackGroupSellRatio(['0x...','0x...'],conditionId,peakValue,sinceTimestamp);

SmartMoneyService

Smart money detection and real-time auto copy trading.

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// One line to get started (recommended)constsdk=awaitPolymarketSDK.create({privateKey: '0x...'});// SDK is initialized and WebSocket connected// Get smart money walletsconstwallets=awaitsdk.smartMoney.getSmartMoneyList(50);// Check if address is smart moneyconstisSmartMoney=awaitsdk.smartMoney.isSmartMoney('0x...');// Subscribe to smart money tradesconstsub=sdk.smartMoney.subscribeSmartMoneyTrades((trade)=>{console.log(`${trade.traderName}${trade.side}${trade.outcome} @ $${trade.price}`);},{filterAddresses: ['0x...'],minSize: 10});// ===== Auto Copy Trading =====// Real-time copy trading - when smart money trades, copy immediatelyconstsubscription=awaitsdk.smartMoney.startAutoCopyTrading({// Target selectiontopN: 50,// Follow top 50 traders from leaderboard// targetAddresses: ['0x...'], // Or specify addresses directly// Order settingssizeScale: 0.1,// Copy 10% of their trade sizemaxSizePerTrade: 10,// Max $10 per trademaxSlippage: 0.03,// 3% slippage toleranceorderType: 'FOK',// FOK or FAK// FiltersminTradeSize: 5,// Only copy trades > $5sideFilter: 'BUY',// Only copy BUY trades (optional)// TestingdryRun: true,// Set false for real trades// CallbacksonTrade: (trade,result)=>{console.log(`Copied ${trade.traderName}: ${result.success ? '✅' : '❌'}`);},onError: (error)=>console.error(error),});console.log(`Tracking ${subscription.targetAddresses.length} wallets`);// Get statsconststats=subscription.getStats();console.log(`Detected: ${stats.tradesDetected}, Executed: ${stats.tradesExecuted}`);// Stopsubscription.stop();sdk.stop();

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.

import{ArbitrageService}from'@catalyst-team/poly-sdk';constarbService=newArbitrageService({privateKey: process.env.POLY_PRIVKEY,profitThreshold: 0.005,// 0.5% minimum profitminTradeSize: 5,// $5 minimummaxTradeSize: 100,// $100 maximumautoExecute: true,// Auto-execute opportunities// Rebalancer: auto-maintain USDC/token ratioenableRebalancer: true,minUsdcRatio: 0.2,// Min 20% USDCmaxUsdcRatio: 0.8,// Max 80% USDCtargetUsdcRatio: 0.5,// Target when rebalancing// Execution safetysizeSafetyFactor: 0.8,// Use 80% of orderbook depthautoFixImbalance: true,// Auto-fix partial fills});// Listen for eventsarbService.on('opportunity',(opp)=>{console.log(`${opp.type.toUpperCase()} ARB: ${opp.profitPercent.toFixed(2)}%`);});arbService.on('execution',(result)=>{if(result.success){console.log(`Executed: $${result.profit.toFixed(2)} profit`);}});// ===== Workflow =====// 1. Scan markets for opportunitiesconstresults=awaitarbService.scanMarkets({minVolume24h: 5000},0.005);// 2. Start monitoring best marketconstbest=awaitarbService.findAndStart(0.005);console.log(`Started: ${best.market.name} (+${best.profitPercent.toFixed(2)}%)`);// 3. Run for a while...awaitnewPromise(r=>setTimeout(r,60*60*1000));// 1 hour// 4. Stop and clear positionsawaitarbService.stop();constclearResult=awaitarbService.clearPositions(best.market,true);console.log(`Recovered: $${clearResult.totalUsdcRecovered.toFixed(2)}`);

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

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

Features

FeatureDescription
Dip DetectionDetects 15%+ price drops within 10s sliding window
Two-Leg ExecutionLeg1 (buy dip) + Leg2 (buy opposite when cost < target)
Auto-RotateAutomatically switches to next market when current ends
Background RedeemWaits for Oracle resolution (~5min) then redeems winning positions
WebSocket ReconnectAuto re-subscribes on disconnect

Programmatic Usage

import{PolymarketSDK}from'@catalyst-team/poly-sdk';constsdk=newPolymarketSDK({privateKey: '0x...'});// Configure strategysdk.dipArb.updateConfig({shares: 10,// Shares per tradesumTarget: 0.9,// Leg2 triggers when cost ≤ 0.9 (11% profit)dipThreshold: 0.15,// 15% dip triggers Leg1windowMinutes: 14,// Trade window after round startautoExecute: true,// Auto-execute signals});// Listen to eventssdk.dipArb.on('signal',(signal)=>{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 monitoringconstmarket=awaitsdk.dipArb.findAndStart({coin: 'ETH',preferDuration: '15m',});// Enable auto-rotate with redemptionsdk.dipArb.enableAutoRotate({enabled: true,underlyings: ['ETH'],duration: '15m',settleStrategy: 'redeem',redeemWaitMinutes: 5,});// Get statsconststats=sdk.dipArb.getStats();console.log(`Signals: ${stats.signalsDetected}, L1: ${stats.leg1Filled}, L2: ${stats.leg2Filled}`);// Cleanupawaitsdk.dipArb.stop();sdk.stop();

Events

EventDataDescription
startedDipArbMarketConfigStarted monitoring market
stopped-Stopped monitoring
newRound{ roundId, upOpen, downOpen }New trading round
signalDipArbSignalEventLeg1/Leg2 signal detected
executionDipArbExecutionResultTrade execution result
roundComplete{ profit, profitRate }Round finished
rotate{ reason, newMarket }Switched to new market
settled{ success, amountReceived }Position redeemed

Scripts

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

import{DataApiClient,// Positions, trades, leaderboardGammaApiClient,// Markets, events, searchSubgraphClient,// On-chain data via GoldskyCTFClient,// CTF contract operationsBridgeClient,// Cross-chain depositsSwapService,// DEX swaps on Polygon}from'@catalyst-team/poly-sdk';// Data APIconstpositions=awaitsdk.dataApi.getPositions('0x...');consttrades=awaitsdk.dataApi.getTrades('0x...');constleaderboard=awaitsdk.dataApi.getLeaderboard();// Gamma APIconstmarkets=awaitsdk.gammaApi.searchMarkets({query: 'bitcoin'});consttrending=awaitsdk.gammaApi.getTrendingMarkets(10);constevents=awaitsdk.gammaApi.getEvents({limit: 20});// Subgraph (on-chain data)constuserPositions=awaitsdk.subgraph.getUserPositions(address);constisResolved=awaitsdk.subgraph.isConditionResolved(conditionId);constglobalOI=awaitsdk.subgraph.getGlobalOpenInterest();

Breaking Changes (v0.3.0)

UnifiedMarket.tokens is now an Array

Before (v0.2.x):

// Object with yes/no propertiesconstyesPrice=market.tokens.yes.price;constnoPrice=market.tokens.no.price;

After (v0.3.0):

// Array of MarketToken objectsconstyesToken=market.tokens.find(t=>t.outcome==='Yes');constnoToken=market.tokens.find(t=>t.outcome==='No');constyesPrice=yesToken?.price;constnoPrice=noToken?.price;

Migration Guide

// Helper function for migrationfunctiongetTokenPrice(market: UnifiedMarket,outcome: 'Yes'|'No'): number{returnmarket.tokens.find(t=>t.outcome===outcome)?.price??0;}// UsageconstyesPrice=getTokenPrice(market,'Yes');constnoPrice=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:

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
ExampleDescription
01-basic-usage.tsGet markets, orderbooks, detect arbitrage
02-smart-money.tsTop traders, wallet profiles, smart scores
03-market-analysis.tsMarket signals, volume analysis
04-kline-aggregation.tsBuild OHLCV candles from trades
05-follow-wallet-strategy.tsTrack smart money, detect exits
06-services-demo.tsAll SDK services in action
07-realtime-websocket.tsLive price feeds, orderbook updates
08-trading-orders.tsGTC, GTD, FOK, FAK order types
09-rewards-tracking.tsMarket maker incentives, earnings
10-ctf-operations.tsSplit, merge, redeem tokens
11-live-arbitrage-scan.tsScan markets for opportunities
12-trending-arb-monitor.tsReal-time trending monitor
13-arbitrage-service.tsFull arbitrage workflow
14-dip-arb-service.tsDip arbitrage for 15m crypto

DipArb Scripts (in scripts/dip-arb/):

ScriptDescription
auto-trade.tsOne-click auto trading with rotation
redeem-positions.tsRedeem ended market positions

API Reference

For detailed API documentation, see:

Type Exports

importtype{// Core typesUnifiedMarket,MarketToken,ProcessedOrderbook,ArbitrageOpportunity,EffectivePrices,// TradingSide,OrderType,Order,OrderResult,LimitOrderParams,MarketOrderParams,// K-LinesKLineInterval,KLineCandle,DualKLineData,SpreadDataPoint,// WebSocketPriceUpdate,BookUpdate,OrderbookSnapshot,// WalletWalletProfile,SellActivityResult,// Smart MoneySmartMoneyWallet,SmartMoneyTrade,AutoCopyTradingOptions,AutoCopyTradingStats,AutoCopyTradingSubscription,// CTFSplitResult,MergeResult,RedeemResult,// ArbitrageArbitrageMarketConfig,ArbitrageServiceConfig,ScanResult,ClearPositionResult,// DipArbDipArbServiceConfig,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

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - fruitlollipop/poly-sdk · GitHub
Skip to content

Repository files navigation

@catalyst-team/poly-sdk

npm versionLicense: MIT

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

@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

FeatureDescription
Unified APISingle SDK for all Polymarket APIs
Type SafetyFull TypeScript support with comprehensive types
Rate LimitingBuilt-in rate limiting per API endpoint
CachingTTL-based caching with pluggable adapters
Error HandlingStructured errors with auto-retry

Installation

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:

poly-sdk Architecture
================================================================================
┌──────────────────────────────────────────────────────────────────────────────┐
│ PolymarketSDK │
│ (Entry Point) │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 3: High-Level Services (Recommended) │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ TradingService │ │ MarketService │ │ OnchainService │ │
│ │ ────────────── │ │ ────────────── │ │ ────────────── │ │
│ │ • Limit orders │ │ • K-lines │ │ • Split/Merge │ │
│ │ • Market orders│ │ • Orderbook │ │ • Redeem │ │
│ │ • Order mgmt │ │ • Price history│ │ • Approvals │ │
│ │ • Rewards │ │ • Arbitrage │ │ • Swaps │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │RealtimeServiceV2│ │ WalletService │ │SmartMoneyService│ │
│ │ ────────────── │ │ ────────────── │ │ ────────────── │ │
│ │ • WebSocket │ │ • Profiles │ │ • Top traders │ │
│ │ • Price feeds │ │ • Smart scores │ │ • Copy trading │ │
│ │ • Book updates │ │ • Sell detect │ │ • Signal detect │ │
│ │ • User events │ │ • PnL calc │ │ • Leaderboard │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ ArbitrageService │ │
│ │ ───────────────────────────────────────────────────────────────────── │ │
│ │ • Market scanning • Auto execution • Rebalancer • Smart clearing │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ DipArbService │ │
│ │ ───────────────────────────────────────────────────────────────────── │ │
│ │ • 15m crypto UP/DOWN • Dip detection • Auto-rotate • Background redeem│
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 2: Low-Level Clients (Advanced Users / Raw API Access) │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │GammaApiClnt│ │DataApiClnt │ │SubgraphClnt│ │ CTFClient │ │BridgeClient│ │
│ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │
│ │ • Markets │ │ • Positions│ │ • On-chain │ │ • Split │ │ • Cross- │ │
│ │ • Events │ │ • Trades │ │ • PnL │ │ • Merge │ │ chain │ │
│ │ • Search │ │ • Activity │ │ • OI │ │ • Redeem │ │ • Deposits │ │
│ └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │
│ │
│ Uses Official Polymarket Clients: │
│ • @polymarket/clob-client - Trading, orderbook, market data │
│ • @polymarket/real-time-data-client - WebSocket real-time updates │
│ │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 1: Core Infrastructure │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │RateLimiter │ │ Cache │ │ Errors │ │ Types │ │Price Utils │ │
│ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │
│ │ • Per-API │ │ • TTL-based│ │ • Retry │ │ • Unified │ │ • Arb calc │ │
│ │ • Bottleneck│ │ • Pluggable│ │ • Codes │ │ • K-lines │ │ • Rounding │ │
│ └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │
│ │
└──────────────────────────────────────────────────────────────────────────────┘

Service Responsibilities

ServiceResponsibility
PolymarketSDKEntry point, integrates all services
TradingServiceOrder management (place/cancel/query)
MarketServiceMarket data (orderbook/K-lines/search)
OnchainServiceOn-chain ops (split/merge/redeem/approve/swap)
RealtimeServiceV2WebSocket real-time data
WalletServiceWallet/trader analysis
SmartMoneyServiceSmart money tracking
ArbitrageServiceArbitrage detection & execution
DipArbServiceDip arbitrage for 15m crypto markets

Quick Start

Basic Usage (Read-Only)

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// No authentication needed for read operationsconstsdk=newPolymarketSDK();// Get market by slug or condition IDconstmarket=awaitsdk.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}`);// Get processed orderbook with analyticsconstorderbook=awaitsdk.getOrderbook(market.conditionId);console.log(`Long Arb Profit: ${orderbook.summary.longArbProfit}`);console.log(`Short Arb Profit: ${orderbook.summary.shortArbProfit}`);// Detect arbitrage opportunitiesconstarb=awaitsdk.detectArbitrage(market.conditionId);if(arb){console.log(`${arb.type.toUpperCase()} ARB: ${(arb.profit*100).toFixed(2)}% profit`);console.log(arb.action);}

With Authentication (Trading)

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// Recommended: Use static factory method (one line to get started)constsdk=awaitPolymarketSDK.create({privateKey: process.env.POLYMARKET_PRIVATE_KEY!,});// Ready to trade - SDK is initialized and WebSocket connected// Place a limit orderconstorder=awaitsdk.tradingService.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTC',});console.log(`Order placed: ${order.id}`);// Get open ordersconstopenOrders=awaitsdk.tradingService.getOpenOrders();console.log(`Open orders: ${openOrders.length}`);// Clean up when donesdk.stop();

Services Guide

PolymarketSDK (Entry Point)

The main SDK class that integrates all services.

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// ===== Method 1: Static Factory (Recommended) =====// One line: new + initialize + connect + waitForConnectionconstsdk=awaitPolymarketSDK.create({privateKey: '0x...',// Optional: for tradingchainId: 137,// Optional: Polygon mainnet (default)});// ===== Method 2: Using start() =====// const sdk = new PolymarketSDK({ privateKey: '0x...' });// await sdk.start(); // initialize + connect + waitForConnection// ===== Method 3: Manual Step-by-Step (Full Control) =====// const sdk = new PolymarketSDK({ privateKey: '0x...' });// await sdk.initialize(); // Initialize trading service// sdk.connect(); // Connect WebSocket// await sdk.waitForConnection(); // Wait for connection// Access servicessdk.tradingService// Trading operationssdk.markets// Market datasdk.wallets// Wallet analysissdk.realtime// WebSocket real-time datasdk.smartMoney// Smart money tracking & copy tradingsdk.dipArb// Dip arbitrage for 15m crypto marketssdk.dataApi// Direct Data API accesssdk.gammaApi// Direct Gamma API accesssdk.subgraph// On-chain data via Goldsky// Convenience methodsawaitsdk.getMarket(identifier);// Get unified marketawaitsdk.getOrderbook(conditionId);// Get processed orderbookawaitsdk.detectArbitrage(conditionId);// Detect arb opportunity// Clean upsdk.stop();// Disconnect 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
import{TradingService,MIN_ORDER_SIZE_SHARES,MIN_ORDER_VALUE_USDC}from'@catalyst-team/poly-sdk';consttrading=newTradingService(rateLimiter,cache,{privateKey: process.env.POLYMARKET_PRIVATE_KEY!,});awaittrading.initialize();// ===== Limit Orders =====// GTC: Good Till CancelledconstgtcOrder=awaittrading.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTC',});// GTD: Good Till Date (expires at timestamp)constgtdOrder=awaittrading.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTD',expiration: Math.floor(Date.now()/1000)+3600,// 1 hour});// ===== Market Orders =====// FOK: Fill Or Kill (fill entirely or cancel)constfokOrder=awaittrading.createMarketOrder({tokenId: yesTokenId,side: 'BUY',amount: 10,// $10 USDCorderType: 'FOK',});// FAK: Fill And Kill (partial fill ok)constfakOrder=awaittrading.createMarketOrder({tokenId: yesTokenId,side: 'SELL',amount: 10,// 10 sharesorderType: 'FAK',});// ===== Order Management =====constopenOrders=awaittrading.getOpenOrders();awaittrading.cancelOrder(orderId);awaittrading.cancelAllOrders();// ===== Rewards (Market Making Incentives) =====constisScoring=awaittrading.isOrderScoring(orderId);constrewards=awaittrading.getCurrentRewards();constearnings=awaittrading.getEarnings('2024-12-07');

MarketService

Market data, K-lines, orderbook analysis.

import{MarketService}from'@catalyst-team/poly-sdk';// Get unified marketconstmarket=awaitsdk.markets.getMarket('btc-100k-2024');// Get price lines (from /prices-history API)constprices=awaitsdk.markets.getKLines(conditionId,'1d');// Get dual price lines (primary + secondary) with spread analysisconstdual=awaitsdk.markets.getDualKLines(conditionId,'1d');console.log(dual.primary);// Primary outcome price pointsconsole.log(dual.secondary);// Secondary outcome price pointsconsole.log(dual.spreadAnalysis);// Spread analysis// Get OHLCV candles (from trade data aggregation)constklines=awaitsdk.markets.getKLinesOHLCV(conditionId,'1h',{limit: 100});// Get dual OHLCV K-Lines (YES + NO) with spread analysisconstdualOHLCV=awaitsdk.markets.getDualKLinesOHLCV(conditionId,'1h');console.log(dualOHLCV.yes);// YES token candlesconsole.log(dualOHLCV.no);// NO token candlesconsole.log(dualOHLCV.spreadAnalysis);// Historical spread (trade prices)console.log(dualOHLCV.realtimeSpread);// Real-time spread (orderbook)// Get processed orderbookconstorderbook=awaitsdk.markets.getProcessedOrderbook(conditionId);// Quick real-time spread checkconstspread=awaitsdk.markets.getRealtimeSpread(conditionId);if(spread.longArbProfit>0.005){console.log(`Long arb: buy YES@${spread.yesAsk} + NO@${spread.noAsk}`);}// Detect market signalsconstsignals=awaitsdk.markets.detectMarketSignals(conditionId);

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:

// WRONG: Double counts mirror ordersconstaskSum=YES.ask+NO.ask;// ~1.998, not ~1.0// CORRECT: Use effective pricesimport{getEffectivePrices,checkArbitrage}from'@catalyst-team/poly-sdk';consteffective=getEffectivePrices(yesAsk,yesBid,noAsk,noBid);// effective.effectiveBuyYes = min(YES.ask, 1 - NO.bid)// effective.effectiveBuyNo = min(NO.ask, 1 - YES.bid)constarb=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.

import{OnchainService}from'@catalyst-team/poly-sdk';constonchain=newOnchainService({privateKey: process.env.POLYMARKET_PRIVATE_KEY!,rpcUrl: 'https://polygon-rpc.com',// optional});// Check if ready for CTF tradingconststatus=awaitonchain.checkReadyForCTF('100');if(!status.ready){console.log('Issues:',status.issues);awaitonchain.approveAll();}// ===== CTF Operations =====// Split: USDC -> YES + NO tokensconstsplitResult=awaitonchain.split(conditionId,'100');// Merge: YES + NO -> USDC (for arbitrage)constmergeResult=awaitonchain.mergeByTokenIds(conditionId,tokenIds,'100');// Redeem: Winning tokens -> USDC (after resolution)constredeemResult=awaitonchain.redeemByTokenIds(conditionId,tokenIds);// ===== DEX Swaps (QuickSwap V3) =====// Swap MATIC to USDC.e (required for CTF)awaitonchain.swap('MATIC','USDC_E','50');// Get balancesconstbalances=awaitonchain.getBalances();console.log(`USDC.e: ${balances.usdcE}`);

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


RealtimeServiceV2

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

import{RealtimeServiceV2}from'@catalyst-team/poly-sdk';constrealtime=newRealtimeServiceV2({autoReconnect: true,pingInterval: 5000,});// Connect and subscriberealtime.connect();realtime.subscribeMarket([yesTokenId,noTokenId]);// Event-based APIrealtime.on('priceUpdate',(update)=>{console.log(`${update.assetId}: ${update.price}`);console.log(`Midpoint: ${update.midpoint}, Spread: ${update.spread}`);});realtime.on('bookUpdate',(update)=>{// Orderbook is auto-normalized:// bids: descending (best first), asks: ascending (best first)console.log(`Best bid: ${update.bids[0]?.price}`);console.log(`Best ask: ${update.asks[0]?.price}`);});realtime.on('lastTrade',(trade)=>{console.log(`Trade: ${trade.side}${trade.size} @ ${trade.price}`);});// Get cached pricesconstprice=realtime.getPrice(yesTokenId);constbook=realtime.getBook(yesTokenId);// Cleanuprealtime.disconnect();

WalletService

Wallet analysis and smart money scoring.

// Get top tradersconsttraders=awaitsdk.wallets.getTopTraders(10);// Get wallet profile with smart scoreconstprofile=awaitsdk.wallets.getWalletProfile('0x...');console.log(`Smart Score: ${profile.smartScore}/100`);console.log(`Win Rate: ${profile.winRate}%`);console.log(`Total PnL: $${profile.totalPnL}`);// Detect sell activity (for follow-wallet strategy)constsellResult=awaitsdk.wallets.detectSellActivity('0x...',conditionId,Date.now()-24*60*60*1000// since 24h ago);if(sellResult.isSelling){console.log(`Sold ${sellResult.percentageSold}%`);}// Track group sell ratioconstgroupSell=awaitsdk.wallets.trackGroupSellRatio(['0x...','0x...'],conditionId,peakValue,sinceTimestamp);

SmartMoneyService

Smart money detection and real-time auto copy trading.

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// One line to get started (recommended)constsdk=awaitPolymarketSDK.create({privateKey: '0x...'});// SDK is initialized and WebSocket connected// Get smart money walletsconstwallets=awaitsdk.smartMoney.getSmartMoneyList(50);// Check if address is smart moneyconstisSmartMoney=awaitsdk.smartMoney.isSmartMoney('0x...');// Subscribe to smart money tradesconstsub=sdk.smartMoney.subscribeSmartMoneyTrades((trade)=>{console.log(`${trade.traderName}${trade.side}${trade.outcome} @ $${trade.price}`);},{filterAddresses: ['0x...'],minSize: 10});// ===== Auto Copy Trading =====// Real-time copy trading - when smart money trades, copy immediatelyconstsubscription=awaitsdk.smartMoney.startAutoCopyTrading({// Target selectiontopN: 50,// Follow top 50 traders from leaderboard// targetAddresses: ['0x...'], // Or specify addresses directly// Order settingssizeScale: 0.1,// Copy 10% of their trade sizemaxSizePerTrade: 10,// Max $10 per trademaxSlippage: 0.03,// 3% slippage toleranceorderType: 'FOK',// FOK or FAK// FiltersminTradeSize: 5,// Only copy trades > $5sideFilter: 'BUY',// Only copy BUY trades (optional)// TestingdryRun: true,// Set false for real trades// CallbacksonTrade: (trade,result)=>{console.log(`Copied ${trade.traderName}: ${result.success ? '✅' : '❌'}`);},onError: (error)=>console.error(error),});console.log(`Tracking ${subscription.targetAddresses.length} wallets`);// Get statsconststats=subscription.getStats();console.log(`Detected: ${stats.tradesDetected}, Executed: ${stats.tradesExecuted}`);// Stopsubscription.stop();sdk.stop();

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.

import{ArbitrageService}from'@catalyst-team/poly-sdk';constarbService=newArbitrageService({privateKey: process.env.POLY_PRIVKEY,profitThreshold: 0.005,// 0.5% minimum profitminTradeSize: 5,// $5 minimummaxTradeSize: 100,// $100 maximumautoExecute: true,// Auto-execute opportunities// Rebalancer: auto-maintain USDC/token ratioenableRebalancer: true,minUsdcRatio: 0.2,// Min 20% USDCmaxUsdcRatio: 0.8,// Max 80% USDCtargetUsdcRatio: 0.5,// Target when rebalancing// Execution safetysizeSafetyFactor: 0.8,// Use 80% of orderbook depthautoFixImbalance: true,// Auto-fix partial fills});// Listen for eventsarbService.on('opportunity',(opp)=>{console.log(`${opp.type.toUpperCase()} ARB: ${opp.profitPercent.toFixed(2)}%`);});arbService.on('execution',(result)=>{if(result.success){console.log(`Executed: $${result.profit.toFixed(2)} profit`);}});// ===== Workflow =====// 1. Scan markets for opportunitiesconstresults=awaitarbService.scanMarkets({minVolume24h: 5000},0.005);// 2. Start monitoring best marketconstbest=awaitarbService.findAndStart(0.005);console.log(`Started: ${best.market.name} (+${best.profitPercent.toFixed(2)}%)`);// 3. Run for a while...awaitnewPromise(r=>setTimeout(r,60*60*1000));// 1 hour// 4. Stop and clear positionsawaitarbService.stop();constclearResult=awaitarbService.clearPositions(best.market,true);console.log(`Recovered: $${clearResult.totalUsdcRecovered.toFixed(2)}`);

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

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

Features

FeatureDescription
Dip DetectionDetects 15%+ price drops within 10s sliding window
Two-Leg ExecutionLeg1 (buy dip) + Leg2 (buy opposite when cost < target)
Auto-RotateAutomatically switches to next market when current ends
Background RedeemWaits for Oracle resolution (~5min) then redeems winning positions
WebSocket ReconnectAuto re-subscribes on disconnect

Programmatic Usage

import{PolymarketSDK}from'@catalyst-team/poly-sdk';constsdk=newPolymarketSDK({privateKey: '0x...'});// Configure strategysdk.dipArb.updateConfig({shares: 10,// Shares per tradesumTarget: 0.9,// Leg2 triggers when cost ≤ 0.9 (11% profit)dipThreshold: 0.15,// 15% dip triggers Leg1windowMinutes: 14,// Trade window after round startautoExecute: true,// Auto-execute signals});// Listen to eventssdk.dipArb.on('signal',(signal)=>{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 monitoringconstmarket=awaitsdk.dipArb.findAndStart({coin: 'ETH',preferDuration: '15m',});// Enable auto-rotate with redemptionsdk.dipArb.enableAutoRotate({enabled: true,underlyings: ['ETH'],duration: '15m',settleStrategy: 'redeem',redeemWaitMinutes: 5,});// Get statsconststats=sdk.dipArb.getStats();console.log(`Signals: ${stats.signalsDetected}, L1: ${stats.leg1Filled}, L2: ${stats.leg2Filled}`);// Cleanupawaitsdk.dipArb.stop();sdk.stop();

Events

EventDataDescription
startedDipArbMarketConfigStarted monitoring market
stopped-Stopped monitoring
newRound{ roundId, upOpen, downOpen }New trading round
signalDipArbSignalEventLeg1/Leg2 signal detected
executionDipArbExecutionResultTrade execution result
roundComplete{ profit, profitRate }Round finished
rotate{ reason, newMarket }Switched to new market
settled{ success, amountReceived }Position redeemed

Scripts

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

import{DataApiClient,// Positions, trades, leaderboardGammaApiClient,// Markets, events, searchSubgraphClient,// On-chain data via GoldskyCTFClient,// CTF contract operationsBridgeClient,// Cross-chain depositsSwapService,// DEX swaps on Polygon}from'@catalyst-team/poly-sdk';// Data APIconstpositions=awaitsdk.dataApi.getPositions('0x...');consttrades=awaitsdk.dataApi.getTrades('0x...');constleaderboard=awaitsdk.dataApi.getLeaderboard();// Gamma APIconstmarkets=awaitsdk.gammaApi.searchMarkets({query: 'bitcoin'});consttrending=awaitsdk.gammaApi.getTrendingMarkets(10);constevents=awaitsdk.gammaApi.getEvents({limit: 20});// Subgraph (on-chain data)constuserPositions=awaitsdk.subgraph.getUserPositions(address);constisResolved=awaitsdk.subgraph.isConditionResolved(conditionId);constglobalOI=awaitsdk.subgraph.getGlobalOpenInterest();

Breaking Changes (v0.3.0)

UnifiedMarket.tokens is now an Array

Before (v0.2.x):

// Object with yes/no propertiesconstyesPrice=market.tokens.yes.price;constnoPrice=market.tokens.no.price;

After (v0.3.0):

// Array of MarketToken objectsconstyesToken=market.tokens.find(t=>t.outcome==='Yes');constnoToken=market.tokens.find(t=>t.outcome==='No');constyesPrice=yesToken?.price;constnoPrice=noToken?.price;

Migration Guide

// Helper function for migrationfunctiongetTokenPrice(market: UnifiedMarket,outcome: 'Yes'|'No'): number{returnmarket.tokens.find(t=>t.outcome===outcome)?.price??0;}// UsageconstyesPrice=getTokenPrice(market,'Yes');constnoPrice=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:

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
ExampleDescription
01-basic-usage.tsGet markets, orderbooks, detect arbitrage
02-smart-money.tsTop traders, wallet profiles, smart scores
03-market-analysis.tsMarket signals, volume analysis
04-kline-aggregation.tsBuild OHLCV candles from trades
05-follow-wallet-strategy.tsTrack smart money, detect exits
06-services-demo.tsAll SDK services in action
07-realtime-websocket.tsLive price feeds, orderbook updates
08-trading-orders.tsGTC, GTD, FOK, FAK order types
09-rewards-tracking.tsMarket maker incentives, earnings
10-ctf-operations.tsSplit, merge, redeem tokens
11-live-arbitrage-scan.tsScan markets for opportunities
12-trending-arb-monitor.tsReal-time trending monitor
13-arbitrage-service.tsFull arbitrage workflow
14-dip-arb-service.tsDip arbitrage for 15m crypto

DipArb Scripts (in scripts/dip-arb/):

ScriptDescription
auto-trade.tsOne-click auto trading with rotation
redeem-positions.tsRedeem ended market positions

API Reference

For detailed API documentation, see:

Type Exports

importtype{// Core typesUnifiedMarket,MarketToken,ProcessedOrderbook,ArbitrageOpportunity,EffectivePrices,// TradingSide,OrderType,Order,OrderResult,LimitOrderParams,MarketOrderParams,// K-LinesKLineInterval,KLineCandle,DualKLineData,SpreadDataPoint,// WebSocketPriceUpdate,BookUpdate,OrderbookSnapshot,// WalletWalletProfile,SellActivityResult,// Smart MoneySmartMoneyWallet,SmartMoneyTrade,AutoCopyTradingOptions,AutoCopyTradingStats,AutoCopyTradingSubscription,// CTFSplitResult,MergeResult,RedeemResult,// ArbitrageArbitrageMarketConfig,ArbitrageServiceConfig,ScanResult,ClearPositionResult,// DipArbDipArbServiceConfig,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

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); GitHub - fruitlollipop/poly-sdk · GitHub
Skip to content

Repository files navigation

@catalyst-team/poly-sdk

npm versionLicense: MIT

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

@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

FeatureDescription
Unified APISingle SDK for all Polymarket APIs
Type SafetyFull TypeScript support with comprehensive types
Rate LimitingBuilt-in rate limiting per API endpoint
CachingTTL-based caching with pluggable adapters
Error HandlingStructured errors with auto-retry

Installation

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:

poly-sdk Architecture
================================================================================
┌──────────────────────────────────────────────────────────────────────────────┐
│ PolymarketSDK │
│ (Entry Point) │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 3: High-Level Services (Recommended) │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │ TradingService │ │ MarketService │ │ OnchainService │ │
│ │ ────────────── │ │ ────────────── │ │ ────────────── │ │
│ │ • Limit orders │ │ • K-lines │ │ • Split/Merge │ │
│ │ • Market orders│ │ • Orderbook │ │ • Redeem │ │
│ │ • Order mgmt │ │ • Price history│ │ • Approvals │ │
│ │ • Rewards │ │ • Arbitrage │ │ • Swaps │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │
│ │RealtimeServiceV2│ │ WalletService │ │SmartMoneyService│ │
│ │ ────────────── │ │ ────────────── │ │ ────────────── │ │
│ │ • WebSocket │ │ • Profiles │ │ • Top traders │ │
│ │ • Price feeds │ │ • Smart scores │ │ • Copy trading │ │
│ │ • Book updates │ │ • Sell detect │ │ • Signal detect │ │
│ │ • User events │ │ • PnL calc │ │ • Leaderboard │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ ArbitrageService │ │
│ │ ───────────────────────────────────────────────────────────────────── │ │
│ │ • Market scanning • Auto execution • Rebalancer • Smart clearing │ │
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────────────────────┐ │
│ │ DipArbService │ │
│ │ ───────────────────────────────────────────────────────────────────── │ │
│ │ • 15m crypto UP/DOWN • Dip detection • Auto-rotate • Background redeem│
│ └─────────────────────────────────────────────────────────────────────────┘ │
│ │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 2: Low-Level Clients (Advanced Users / Raw API Access) │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │GammaApiClnt│ │DataApiClnt │ │SubgraphClnt│ │ CTFClient │ │BridgeClient│ │
│ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │
│ │ • Markets │ │ • Positions│ │ • On-chain │ │ • Split │ │ • Cross- │ │
│ │ • Events │ │ • Trades │ │ • PnL │ │ • Merge │ │ chain │ │
│ │ • Search │ │ • Activity │ │ • OI │ │ • Redeem │ │ • Deposits │ │
│ └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │
│ │
│ Uses Official Polymarket Clients: │
│ • @polymarket/clob-client - Trading, orderbook, market data │
│ • @polymarket/real-time-data-client - WebSocket real-time updates │
│ │
├──────────────────────────────────────────────────────────────────────────────┤
│ │
│ Layer 1: Core Infrastructure │
│ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━ │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │RateLimiter │ │ Cache │ │ Errors │ │ Types │ │Price Utils │ │
│ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │ ────────── │ │
│ │ • Per-API │ │ • TTL-based│ │ • Retry │ │ • Unified │ │ • Arb calc │ │
│ │ • Bottleneck│ │ • Pluggable│ │ • Codes │ │ • K-lines │ │ • Rounding │ │
│ └────────────┘ └────────────┘ └────────────┘ └────────────┘ └────────────┘ │
│ │
└──────────────────────────────────────────────────────────────────────────────┘

Service Responsibilities

ServiceResponsibility
PolymarketSDKEntry point, integrates all services
TradingServiceOrder management (place/cancel/query)
MarketServiceMarket data (orderbook/K-lines/search)
OnchainServiceOn-chain ops (split/merge/redeem/approve/swap)
RealtimeServiceV2WebSocket real-time data
WalletServiceWallet/trader analysis
SmartMoneyServiceSmart money tracking
ArbitrageServiceArbitrage detection & execution
DipArbServiceDip arbitrage for 15m crypto markets

Quick Start

Basic Usage (Read-Only)

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// No authentication needed for read operationsconstsdk=newPolymarketSDK();// Get market by slug or condition IDconstmarket=awaitsdk.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}`);// Get processed orderbook with analyticsconstorderbook=awaitsdk.getOrderbook(market.conditionId);console.log(`Long Arb Profit: ${orderbook.summary.longArbProfit}`);console.log(`Short Arb Profit: ${orderbook.summary.shortArbProfit}`);// Detect arbitrage opportunitiesconstarb=awaitsdk.detectArbitrage(market.conditionId);if(arb){console.log(`${arb.type.toUpperCase()} ARB: ${(arb.profit*100).toFixed(2)}% profit`);console.log(arb.action);}

With Authentication (Trading)

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// Recommended: Use static factory method (one line to get started)constsdk=awaitPolymarketSDK.create({privateKey: process.env.POLYMARKET_PRIVATE_KEY!,});// Ready to trade - SDK is initialized and WebSocket connected// Place a limit orderconstorder=awaitsdk.tradingService.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTC',});console.log(`Order placed: ${order.id}`);// Get open ordersconstopenOrders=awaitsdk.tradingService.getOpenOrders();console.log(`Open orders: ${openOrders.length}`);// Clean up when donesdk.stop();

Services Guide

PolymarketSDK (Entry Point)

The main SDK class that integrates all services.

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// ===== Method 1: Static Factory (Recommended) =====// One line: new + initialize + connect + waitForConnectionconstsdk=awaitPolymarketSDK.create({privateKey: '0x...',// Optional: for tradingchainId: 137,// Optional: Polygon mainnet (default)});// ===== Method 2: Using start() =====// const sdk = new PolymarketSDK({ privateKey: '0x...' });// await sdk.start(); // initialize + connect + waitForConnection// ===== Method 3: Manual Step-by-Step (Full Control) =====// const sdk = new PolymarketSDK({ privateKey: '0x...' });// await sdk.initialize(); // Initialize trading service// sdk.connect(); // Connect WebSocket// await sdk.waitForConnection(); // Wait for connection// Access servicessdk.tradingService// Trading operationssdk.markets// Market datasdk.wallets// Wallet analysissdk.realtime// WebSocket real-time datasdk.smartMoney// Smart money tracking & copy tradingsdk.dipArb// Dip arbitrage for 15m crypto marketssdk.dataApi// Direct Data API accesssdk.gammaApi// Direct Gamma API accesssdk.subgraph// On-chain data via Goldsky// Convenience methodsawaitsdk.getMarket(identifier);// Get unified marketawaitsdk.getOrderbook(conditionId);// Get processed orderbookawaitsdk.detectArbitrage(conditionId);// Detect arb opportunity// Clean upsdk.stop();// Disconnect 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
import{TradingService,MIN_ORDER_SIZE_SHARES,MIN_ORDER_VALUE_USDC}from'@catalyst-team/poly-sdk';consttrading=newTradingService(rateLimiter,cache,{privateKey: process.env.POLYMARKET_PRIVATE_KEY!,});awaittrading.initialize();// ===== Limit Orders =====// GTC: Good Till CancelledconstgtcOrder=awaittrading.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTC',});// GTD: Good Till Date (expires at timestamp)constgtdOrder=awaittrading.createLimitOrder({tokenId: yesTokenId,side: 'BUY',price: 0.45,size: 10,orderType: 'GTD',expiration: Math.floor(Date.now()/1000)+3600,// 1 hour});// ===== Market Orders =====// FOK: Fill Or Kill (fill entirely or cancel)constfokOrder=awaittrading.createMarketOrder({tokenId: yesTokenId,side: 'BUY',amount: 10,// $10 USDCorderType: 'FOK',});// FAK: Fill And Kill (partial fill ok)constfakOrder=awaittrading.createMarketOrder({tokenId: yesTokenId,side: 'SELL',amount: 10,// 10 sharesorderType: 'FAK',});// ===== Order Management =====constopenOrders=awaittrading.getOpenOrders();awaittrading.cancelOrder(orderId);awaittrading.cancelAllOrders();// ===== Rewards (Market Making Incentives) =====constisScoring=awaittrading.isOrderScoring(orderId);constrewards=awaittrading.getCurrentRewards();constearnings=awaittrading.getEarnings('2024-12-07');

MarketService

Market data, K-lines, orderbook analysis.

import{MarketService}from'@catalyst-team/poly-sdk';// Get unified marketconstmarket=awaitsdk.markets.getMarket('btc-100k-2024');// Get price lines (from /prices-history API)constprices=awaitsdk.markets.getKLines(conditionId,'1d');// Get dual price lines (primary + secondary) with spread analysisconstdual=awaitsdk.markets.getDualKLines(conditionId,'1d');console.log(dual.primary);// Primary outcome price pointsconsole.log(dual.secondary);// Secondary outcome price pointsconsole.log(dual.spreadAnalysis);// Spread analysis// Get OHLCV candles (from trade data aggregation)constklines=awaitsdk.markets.getKLinesOHLCV(conditionId,'1h',{limit: 100});// Get dual OHLCV K-Lines (YES + NO) with spread analysisconstdualOHLCV=awaitsdk.markets.getDualKLinesOHLCV(conditionId,'1h');console.log(dualOHLCV.yes);// YES token candlesconsole.log(dualOHLCV.no);// NO token candlesconsole.log(dualOHLCV.spreadAnalysis);// Historical spread (trade prices)console.log(dualOHLCV.realtimeSpread);// Real-time spread (orderbook)// Get processed orderbookconstorderbook=awaitsdk.markets.getProcessedOrderbook(conditionId);// Quick real-time spread checkconstspread=awaitsdk.markets.getRealtimeSpread(conditionId);if(spread.longArbProfit>0.005){console.log(`Long arb: buy YES@${spread.yesAsk} + NO@${spread.noAsk}`);}// Detect market signalsconstsignals=awaitsdk.markets.detectMarketSignals(conditionId);

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:

// WRONG: Double counts mirror ordersconstaskSum=YES.ask+NO.ask;// ~1.998, not ~1.0// CORRECT: Use effective pricesimport{getEffectivePrices,checkArbitrage}from'@catalyst-team/poly-sdk';consteffective=getEffectivePrices(yesAsk,yesBid,noAsk,noBid);// effective.effectiveBuyYes = min(YES.ask, 1 - NO.bid)// effective.effectiveBuyNo = min(NO.ask, 1 - YES.bid)constarb=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.

import{OnchainService}from'@catalyst-team/poly-sdk';constonchain=newOnchainService({privateKey: process.env.POLYMARKET_PRIVATE_KEY!,rpcUrl: 'https://polygon-rpc.com',// optional});// Check if ready for CTF tradingconststatus=awaitonchain.checkReadyForCTF('100');if(!status.ready){console.log('Issues:',status.issues);awaitonchain.approveAll();}// ===== CTF Operations =====// Split: USDC -> YES + NO tokensconstsplitResult=awaitonchain.split(conditionId,'100');// Merge: YES + NO -> USDC (for arbitrage)constmergeResult=awaitonchain.mergeByTokenIds(conditionId,tokenIds,'100');// Redeem: Winning tokens -> USDC (after resolution)constredeemResult=awaitonchain.redeemByTokenIds(conditionId,tokenIds);// ===== DEX Swaps (QuickSwap V3) =====// Swap MATIC to USDC.e (required for CTF)awaitonchain.swap('MATIC','USDC_E','50');// Get balancesconstbalances=awaitonchain.getBalances();console.log(`USDC.e: ${balances.usdcE}`);

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


RealtimeServiceV2

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

import{RealtimeServiceV2}from'@catalyst-team/poly-sdk';constrealtime=newRealtimeServiceV2({autoReconnect: true,pingInterval: 5000,});// Connect and subscriberealtime.connect();realtime.subscribeMarket([yesTokenId,noTokenId]);// Event-based APIrealtime.on('priceUpdate',(update)=>{console.log(`${update.assetId}: ${update.price}`);console.log(`Midpoint: ${update.midpoint}, Spread: ${update.spread}`);});realtime.on('bookUpdate',(update)=>{// Orderbook is auto-normalized:// bids: descending (best first), asks: ascending (best first)console.log(`Best bid: ${update.bids[0]?.price}`);console.log(`Best ask: ${update.asks[0]?.price}`);});realtime.on('lastTrade',(trade)=>{console.log(`Trade: ${trade.side}${trade.size} @ ${trade.price}`);});// Get cached pricesconstprice=realtime.getPrice(yesTokenId);constbook=realtime.getBook(yesTokenId);// Cleanuprealtime.disconnect();

WalletService

Wallet analysis and smart money scoring.

// Get top tradersconsttraders=awaitsdk.wallets.getTopTraders(10);// Get wallet profile with smart scoreconstprofile=awaitsdk.wallets.getWalletProfile('0x...');console.log(`Smart Score: ${profile.smartScore}/100`);console.log(`Win Rate: ${profile.winRate}%`);console.log(`Total PnL: $${profile.totalPnL}`);// Detect sell activity (for follow-wallet strategy)constsellResult=awaitsdk.wallets.detectSellActivity('0x...',conditionId,Date.now()-24*60*60*1000// since 24h ago);if(sellResult.isSelling){console.log(`Sold ${sellResult.percentageSold}%`);}// Track group sell ratioconstgroupSell=awaitsdk.wallets.trackGroupSellRatio(['0x...','0x...'],conditionId,peakValue,sinceTimestamp);

SmartMoneyService

Smart money detection and real-time auto copy trading.

import{PolymarketSDK}from'@catalyst-team/poly-sdk';// One line to get started (recommended)constsdk=awaitPolymarketSDK.create({privateKey: '0x...'});// SDK is initialized and WebSocket connected// Get smart money walletsconstwallets=awaitsdk.smartMoney.getSmartMoneyList(50);// Check if address is smart moneyconstisSmartMoney=awaitsdk.smartMoney.isSmartMoney('0x...');// Subscribe to smart money tradesconstsub=sdk.smartMoney.subscribeSmartMoneyTrades((trade)=>{console.log(`${trade.traderName}${trade.side}${trade.outcome} @ $${trade.price}`);},{filterAddresses: ['0x...'],minSize: 10});// ===== Auto Copy Trading =====// Real-time copy trading - when smart money trades, copy immediatelyconstsubscription=awaitsdk.smartMoney.startAutoCopyTrading({// Target selectiontopN: 50,// Follow top 50 traders from leaderboard// targetAddresses: ['0x...'], // Or specify addresses directly// Order settingssizeScale: 0.1,// Copy 10% of their trade sizemaxSizePerTrade: 10,// Max $10 per trademaxSlippage: 0.03,// 3% slippage toleranceorderType: 'FOK',// FOK or FAK// FiltersminTradeSize: 5,// Only copy trades > $5sideFilter: 'BUY',// Only copy BUY trades (optional)// TestingdryRun: true,// Set false for real trades// CallbacksonTrade: (trade,result)=>{console.log(`Copied ${trade.traderName}: ${result.success ? '✅' : '❌'}`);},onError: (error)=>console.error(error),});console.log(`Tracking ${subscription.targetAddresses.length} wallets`);// Get statsconststats=subscription.getStats();console.log(`Detected: ${stats.tradesDetected}, Executed: ${stats.tradesExecuted}`);// Stopsubscription.stop();sdk.stop();

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.

import{ArbitrageService}from'@catalyst-team/poly-sdk';constarbService=newArbitrageService({privateKey: process.env.POLY_PRIVKEY,profitThreshold: 0.005,// 0.5% minimum profitminTradeSize: 5,// $5 minimummaxTradeSize: 100,// $100 maximumautoExecute: true,// Auto-execute opportunities// Rebalancer: auto-maintain USDC/token ratioenableRebalancer: true,minUsdcRatio: 0.2,// Min 20% USDCmaxUsdcRatio: 0.8,// Max 80% USDCtargetUsdcRatio: 0.5,// Target when rebalancing// Execution safetysizeSafetyFactor: 0.8,// Use 80% of orderbook depthautoFixImbalance: true,// Auto-fix partial fills});// Listen for eventsarbService.on('opportunity',(opp)=>{console.log(`${opp.type.toUpperCase()} ARB: ${opp.profitPercent.toFixed(2)}%`);});arbService.on('execution',(result)=>{if(result.success){console.log(`Executed: $${result.profit.toFixed(2)} profit`);}});// ===== Workflow =====// 1. Scan markets for opportunitiesconstresults=awaitarbService.scanMarkets({minVolume24h: 5000},0.005);// 2. Start monitoring best marketconstbest=awaitarbService.findAndStart(0.005);console.log(`Started: ${best.market.name} (+${best.profitPercent.toFixed(2)}%)`);// 3. Run for a while...awaitnewPromise(r=>setTimeout(r,60*60*1000));// 1 hour// 4. Stop and clear positionsawaitarbService.stop();constclearResult=awaitarbService.clearPositions(best.market,true);console.log(`Recovered: $${clearResult.totalUsdcRecovered.toFixed(2)}`);

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

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

Features

FeatureDescription
Dip DetectionDetects 15%+ price drops within 10s sliding window
Two-Leg ExecutionLeg1 (buy dip) + Leg2 (buy opposite when cost < target)
Auto-RotateAutomatically switches to next market when current ends
Background RedeemWaits for Oracle resolution (~5min) then redeems winning positions
WebSocket ReconnectAuto re-subscribes on disconnect

Programmatic Usage

import{PolymarketSDK}from'@catalyst-team/poly-sdk';constsdk=newPolymarketSDK({privateKey: '0x...'});// Configure strategysdk.dipArb.updateConfig({shares: 10,// Shares per tradesumTarget: 0.9,// Leg2 triggers when cost ≤ 0.9 (11% profit)dipThreshold: 0.15,// 15% dip triggers Leg1windowMinutes: 14,// Trade window after round startautoExecute: true,// Auto-execute signals});// Listen to eventssdk.dipArb.on('signal',(signal)=>{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 monitoringconstmarket=awaitsdk.dipArb.findAndStart({coin: 'ETH',preferDuration: '15m',});// Enable auto-rotate with redemptionsdk.dipArb.enableAutoRotate({enabled: true,underlyings: ['ETH'],duration: '15m',settleStrategy: 'redeem',redeemWaitMinutes: 5,});// Get statsconststats=sdk.dipArb.getStats();console.log(`Signals: ${stats.signalsDetected}, L1: ${stats.leg1Filled}, L2: ${stats.leg2Filled}`);// Cleanupawaitsdk.dipArb.stop();sdk.stop();

Events

EventDataDescription
startedDipArbMarketConfigStarted monitoring market
stopped-Stopped monitoring
newRound{ roundId, upOpen, downOpen }New trading round
signalDipArbSignalEventLeg1/Leg2 signal detected
executionDipArbExecutionResultTrade execution result
roundComplete{ profit, profitRate }Round finished
rotate{ reason, newMarket }Switched to new market
settled{ success, amountReceived }Position redeemed

Scripts

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

import{DataApiClient,// Positions, trades, leaderboardGammaApiClient,// Markets, events, searchSubgraphClient,// On-chain data via GoldskyCTFClient,// CTF contract operationsBridgeClient,// Cross-chain depositsSwapService,// DEX swaps on Polygon}from'@catalyst-team/poly-sdk';// Data APIconstpositions=awaitsdk.dataApi.getPositions('0x...');consttrades=awaitsdk.dataApi.getTrades('0x...');constleaderboard=awaitsdk.dataApi.getLeaderboard();// Gamma APIconstmarkets=awaitsdk.gammaApi.searchMarkets({query: 'bitcoin'});consttrending=awaitsdk.gammaApi.getTrendingMarkets(10);constevents=awaitsdk.gammaApi.getEvents({limit: 20});// Subgraph (on-chain data)constuserPositions=awaitsdk.subgraph.getUserPositions(address);constisResolved=awaitsdk.subgraph.isConditionResolved(conditionId);constglobalOI=awaitsdk.subgraph.getGlobalOpenInterest();

Breaking Changes (v0.3.0)

UnifiedMarket.tokens is now an Array

Before (v0.2.x):

// Object with yes/no propertiesconstyesPrice=market.tokens.yes.price;constnoPrice=market.tokens.no.price;

After (v0.3.0):

// Array of MarketToken objectsconstyesToken=market.tokens.find(t=>t.outcome==='Yes');constnoToken=market.tokens.find(t=>t.outcome==='No');constyesPrice=yesToken?.price;constnoPrice=noToken?.price;

Migration Guide

// Helper function for migrationfunctiongetTokenPrice(market: UnifiedMarket,outcome: 'Yes'|'No'): number{returnmarket.tokens.find(t=>t.outcome===outcome)?.price??0;}// UsageconstyesPrice=getTokenPrice(market,'Yes');constnoPrice=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:

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
ExampleDescription
01-basic-usage.tsGet markets, orderbooks, detect arbitrage
02-smart-money.tsTop traders, wallet profiles, smart scores
03-market-analysis.tsMarket signals, volume analysis
04-kline-aggregation.tsBuild OHLCV candles from trades
05-follow-wallet-strategy.tsTrack smart money, detect exits
06-services-demo.tsAll SDK services in action
07-realtime-websocket.tsLive price feeds, orderbook updates
08-trading-orders.tsGTC, GTD, FOK, FAK order types
09-rewards-tracking.tsMarket maker incentives, earnings
10-ctf-operations.tsSplit, merge, redeem tokens
11-live-arbitrage-scan.tsScan markets for opportunities
12-trending-arb-monitor.tsReal-time trending monitor
13-arbitrage-service.tsFull arbitrage workflow
14-dip-arb-service.tsDip arbitrage for 15m crypto

DipArb Scripts (in scripts/dip-arb/):

ScriptDescription
auto-trade.tsOne-click auto trading with rotation
redeem-positions.tsRedeem ended market positions

API Reference

For detailed API documentation, see:

Type Exports

importtype{// Core typesUnifiedMarket,MarketToken,ProcessedOrderbook,ArbitrageOpportunity,EffectivePrices,// TradingSide,OrderType,Order,OrderResult,LimitOrderParams,MarketOrderParams,// K-LinesKLineInterval,KLineCandle,DualKLineData,SpreadDataPoint,// WebSocketPriceUpdate,BookUpdate,OrderbookSnapshot,// WalletWalletProfile,SellActivityResult,// Smart MoneySmartMoneyWallet,SmartMoneyTrade,AutoCopyTradingOptions,AutoCopyTradingStats,AutoCopyTradingSubscription,// CTFSplitResult,MergeResult,RedeemResult,// ArbitrageArbitrageMarketConfig,ArbitrageServiceConfig,ScanResult,ClearPositionResult,// DipArbDipArbServiceConfig,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

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages