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
- Overview
- Installation
- Architecture
- Quick Start
- Services Guide
- Low-Level Clients
- Breaking Changes (v0.3.0)
- Examples
- API Reference
- License
@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
| Feature | Description |
|---|---|
| Unified API | Single SDK for all Polymarket APIs |
| Type Safety | Full TypeScript support with comprehensive types |
| Rate Limiting | Built-in rate limiting per API endpoint |
| Caching | TTL-based caching with pluggable adapters |
| Error Handling | Structured errors with auto-retry |
pnpm add @catalyst-team/poly-sdk
# or
npm install @catalyst-team/poly-sdk
# or
yarn add @catalyst-team/poly-sdkThe 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 | Responsibility |
|---|---|
| PolymarketSDK | Entry point, integrates all services |
| TradingService | Order management (place/cancel/query) |
| MarketService | Market data (orderbook/K-lines/search) |
| OnchainService | On-chain ops (split/merge/redeem/approve/swap) |
| RealtimeServiceV2 | WebSocket real-time data |
| WalletService | Wallet/trader analysis |
| SmartMoneyService | Smart money tracking |
| ArbitrageService | Arbitrage detection & execution |
| DipArbService | Dip arbitrage for 15m crypto markets |
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);}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();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 servicesOrder 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');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);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`);}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.
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();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);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 trading05-auto-copy-simple.ts- Simplified SDK usage06-real-copy-test.ts- Real trading test
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)}`);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)
# One command to start auto trading
PRIVATE_KEY=0x... npx tsx scripts/dip-arb/auto-trade.ts| Feature | Description |
|---|---|
| Dip Detection | Detects 15%+ price drops within 10s sliding window |
| Two-Leg Execution | Leg1 (buy dip) + Leg2 (buy opposite when cost < target) |
| Auto-Rotate | Automatically switches to next market when current ends |
| Background Redeem | Waits for Oracle resolution (~5min) then redeems winning positions |
| WebSocket Reconnect | Auto re-subscribes on disconnect |
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();| Event | Data | Description |
|---|---|---|
started | DipArbMarketConfig | Started monitoring market |
stopped | - | Stopped monitoring |
newRound | { roundId, upOpen, downOpen } | New trading round |
signal | DipArbSignalEvent | Leg1/Leg2 signal detected |
execution | DipArbExecutionResult | Trade execution result |
roundComplete | { profit, profitRate } | Round finished |
rotate | { reason, newMarket } | Switched to new market |
settled | { success, amountReceived } | Position redeemed |
# 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.tsFor 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();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;// 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.
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| Example | Description |
|---|---|
| 01-basic-usage.ts | Get markets, orderbooks, detect arbitrage |
| 02-smart-money.ts | Top traders, wallet profiles, smart scores |
| 03-market-analysis.ts | Market signals, volume analysis |
| 04-kline-aggregation.ts | Build OHLCV candles from trades |
| 05-follow-wallet-strategy.ts | Track smart money, detect exits |
| 06-services-demo.ts | All SDK services in action |
| 07-realtime-websocket.ts | Live price feeds, orderbook updates |
| 08-trading-orders.ts | GTC, GTD, FOK, FAK order types |
| 09-rewards-tracking.ts | Market maker incentives, earnings |
| 10-ctf-operations.ts | Split, merge, redeem tokens |
| 11-live-arbitrage-scan.ts | Scan markets for opportunities |
| 12-trending-arb-monitor.ts | Real-time trending monitor |
| 13-arbitrage-service.ts | Full arbitrage workflow |
| 14-dip-arb-service.ts | Dip arbitrage for 15m crypto |
DipArb Scripts (in scripts/dip-arb/):
| Script | Description |
|---|---|
| auto-trade.ts | One-click auto trading with rotation |
| redeem-positions.ts | Redeem ended market positions |
For detailed API documentation, see:
- docs/00-design.md - Architecture design
- docs/02-API.md - Complete API reference
- docs/01-polymarket-orderbook-arbitrage.md - Orderbook mirror & arbitrage
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';@polymarket/clob-client- Official CLOB trading client@polymarket/real-time-data-client- Official WebSocket clientethers@5- Blockchain interactionsbottleneck- Rate limiting
MIT