Developer Guides

Step-by-step guides for beginners and advanced patterns for pro developers.

Newbie Track

Getting Started

1Install the SDK

First, install the Polybased SDK in your project:

bash
npm install @polybased/sdk

2Fetch Your First Markets

Create a simple script to fetch active markets:

typescript
import { PolymarketClient } from '@polybased/sdk';

const client = new PolymarketClient();

async function fetchMarkets() {
  try {
    const markets = await client.getMarkets({ 
      closed: false, 
      limit: 5 
    });
    
    console.log('Active Markets:', markets);
  } catch (error) {
    console.error('Error fetching markets:', error);
  }
}

fetchMarkets();

3Get Recent Trades

Fetch recent trades for a specific market:

typescript
async function fetchTrades() {
  const trades = await client.getTrades({
    market: 'presidential-election-2024',
    limit: 10,
  });

  trades.forEach(trade => {
    console.log(`Trade: ${trade.outcome} @ ${trade.price}`);
  });
}

4Subscribe to Live Updates

Stream real-time orderbook updates via WebSocket:

typescript
const ws = client.subscribeToMarket('presidential-election-2024');

ws.on('book', (orderbook) => {
  console.log('Best bid:', orderbook.bids[0]);
  console.log('Best ask:', orderbook.asks[0]);
});

ws.on('trade', (trade) => {
  console.log('New trade:', trade);
});

// Remember to clean up
process.on('SIGINT', () => {
  ws.close();
  process.exit();
});

šŸ’” For Node.js environments, install ws package and add global.WebSocket = require('ws') at the top.

5Complete Starter Example

A complete example showing market data and live bid/ask updates:

typescript
import { PolymarketClient } from '@polybased/sdk';

const client = new PolymarketClient();
const marketSlug = 'presidential-election-2024';

async function main() {
  // Fetch market details
  const market = await client.getMarket(marketSlug);
  console.log('Market:', market.question);
  console.log('Current prices:', market.outcomePrices);

  // Subscribe to live updates
  const ws = client.subscribeToMarket(marketSlug);
  
  ws.on('book', (book) => {
    const bestBid = book.bids[0];
    const bestAsk = book.asks[0];
    
    console.table({
      'Best Bid': bestBid?.price || 'N/A',
      'Best Ask': bestAsk?.price || 'N/A',
      'Spread': bestAsk && bestBid 
        ? (bestAsk.price - bestBid.price).toFixed(4) 
        : 'N/A'
    });
  });

  ws.on('error', (err) => console.error('WS Error:', err));
}

main().catch(console.error);
Pro Track

Advanced Patterns

Project Structure & Environment

Organize your code for scalability and maintainability:

plaintext
project/
ā”œā”€ā”€ src/
│   ā”œā”€ā”€ clients/
│   │   └── polymarket.ts      # SDK client wrapper
│   ā”œā”€ā”€ services/
│   │   ā”œā”€ā”€ market-monitor.ts  # Market monitoring logic
│   │   └── trade-analyzer.ts  # Trade analysis
│   ā”œā”€ā”€ utils/
│   │   ā”œā”€ā”€ retry.ts           # Retry logic
│   │   └── cache.ts           # Caching layer
│   └── index.ts
ā”œā”€ā”€ .env                        # API keys, config
└── package.json

Use environment variables for configuration and API keys. Never hardcode sensitive data.

Retry Logic & Exponential Backoff

Handle network failures and rate limits gracefully:

typescript
async function fetchWithRetry<T>(
  fn: () => Promise<T>,
  retries = 3,
  delay = 1000
): Promise<T> {
  try {
    return await fn();
  } catch (error) {
    if (retries === 0) throw error;
    
    console.log(`Retrying... (${retries} attempts left)`);
    await new Promise(resolve => setTimeout(resolve, delay));
    
    return fetchWithRetry(fn, retries - 1, delay * 2);
  }
}

// Usage
const markets = await fetchWithRetry(() => 
  client.getMarkets({ limit: 100 })
);

Pagination & Async Iterators

Efficiently paginate through large datasets:

typescript
async function* getAllMarkets() {
  let offset = 0;
  const limit = 100;
  
  while (true) {
    const markets = await client.getMarkets({ limit, offset });
    
    if (markets.length === 0) break;
    
    for (const market of markets) {
      yield market;
    }
    
    offset += limit;
    
    // Rate limiting: delay between requests
    await new Promise(resolve => setTimeout(resolve, 500));
  }
}

// Usage
for await (const market of getAllMarkets()) {
  console.log(market.question);
}

Performance Optimization

• Caching: Cache market data that doesn't change frequently. Use Redis or in-memory caching for better performance.
• Batch Requests: Combine multiple API calls when possible to reduce round trips.
• Connection Pooling: Reuse WebSocket connections instead of creating new ones for each subscription.
• Error Boundaries: Implement proper error handling to prevent cascading failures.

Trading & User WebSocket

This SDK focuses on read-only market data. For trading operations and user-specific WebSocket streams, you'll need: