Developer Guides
Step-by-step guides for beginners and advanced patterns for pro developers.
Getting Started
1Install the SDK
First, install the Polybased SDK in your project:
npm install @polybased/sdk2Fetch Your First Markets
Create a simple script to fetch active markets:
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:
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:
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:
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);Advanced Patterns
Project Structure & Environment
Organize your code for scalability and maintainability:
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.jsonUse environment variables for configuration and API keys. Never hardcode sensitive data.
Retry Logic & Exponential Backoff
Handle network failures and rate limits gracefully:
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:
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
Trading & User WebSocket
This SDK focuses on read-only market data. For trading operations and user-specific WebSocket streams, you'll need:
- āBuilder Profile credentials from Polymarket
- āA signing server for secure transaction signing
- āReference the official Polymarket documentation