@polymarket-data/client
v0.1.1
Published
Node.js SDK for polymarket-data-collector REST API
Maintainers
Readme
@polymarket-data/client
Node.js client for the polymarket-data-collector REST API. Provides typed access to real-time and historical Polymarket market data.
Install
npm install @polymarket-data/clientRequires Node.js >= 18.
Quick Start
import { DataCollectorClient, MarketStream } from '@polymarket-data/client';
const client = new DataCollectorClient({
baseUrl: 'http://localhost:8000',
apiKey: 'your-api-key', // optional
timeout: 10000, // optional, default 10s
retries: 2, // optional, default 2
retryDelay: 1000, // optional, default 1s
});
// Get market snapshot
const snapshot = await client.market.getSnapshot(tokenId);
// Get order book
const book = await client.market.getBook(tokenId);
// Get price
const price = await client.market.getPrice(tokenId);API Reference
DataCollectorClient
Main client class. All REST requests go to {baseUrl}/api/v1.
Constructor Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| baseUrl | string | — | Required. Base URL of the data collector service |
| apiKey | string | — | API key (sent as X-API-Key header) |
| timeout | number | 10000 | Request timeout in ms |
| retries | number | 2 | Retry count for 502/503/504 and network errors |
| retryDelay | number | 1000 | Base retry delay in ms (exponential backoff) |
client.market
Market data for a single token.
| Method | Return Type | Description |
|--------|-------------|-------------|
| getSnapshot(tokenId) | MarketSnapshot \| null | Full market snapshot (price, spread, liquidity, holders, rewards, rank) |
| getBook(tokenId) | OrderBookResponse \| null | Order book with bids, asks, and depth |
| getPrice(tokenId) | PriceResponse | Current price, spread, best bid/ask |
| getMetadata(tokenId) | MetadataResponse \| null | Market metadata from Gamma API |
| getOpenInterest(tokenId) | OpenInterestResponse \| null | Open interest data |
| getHolders(tokenId) | HoldersResponse \| null | Top holders and concentration metrics |
| getRewards(tokenId) | RewardsResponse \| null | Liquidity rewards info |
| getRank(tokenId) | RankResponse \| null | Probability rank among all markets |
| getStatus(tokenId) | MarketStatus \| null | Market status (open/closed/settled) |
| getChanges(tokenId, params?) | ChangesResponse \| null | Price changes across time intervals |
| getTrend(tokenId, params?) | TrendResponse \| null | Consecutive price trend |
| getOhlc(tokenId, params?) | OhlcResponse | OHLC candlestick data |
| getTrades(tokenId, params?) | TradesResponse | Recent trades |
| getHistory(tokenId, params?) | HistoryResponse | Historical price points |
Methods returning T | null return null when the market is not found (404).
// Price changes with custom intervals
const changes = await client.market.getChanges(tokenId, {
intervals: ['5m', '1h', '24h'],
withWindowStats: true,
});
// OHLC candles
const ohlc = await client.market.getOhlc(tokenId, {
interval: '1h', // '1m' | '5m' | '15m' | '1h' | '4h' | '1d'
limit: 100,
source: 'midpoint', // 'midpoint' | 'trade'
});client.batch
Batch queries for multiple tokens (max 200 per request).
| Method | Return Type | Description |
|--------|-------------|-------------|
| snapshots(tokenIds) | BatchSnapshotResponse | Snapshots for multiple tokens |
| changes(tokenIds) | BatchChangesResponse | Price changes for multiple tokens |
const batch = await client.batch.snapshots([tokenId1, tokenId2, tokenId3]);
// batch.results: Record<tokenId, { collected_at, data }>
// batch.missing: string[]client.subscriptions
Manage data collection subscriptions.
| Method | Return Type | Description |
|--------|-------------|-------------|
| create(params) | SubscriptionCreateResponse | Create a new subscription |
| list(params?) | SubscriptionListResponse | List subscriptions |
| get(tokenId) | SubscriptionResponse \| null | Get subscription by token ID |
| update(tokenId, params) | SubscriptionResponse | Update subscription |
| delete(tokenId) | SubscriptionDeleteResponse | Delete subscription |
| batchCreate(items) | BatchSubscriptionResult | Create multiple subscriptions |
client.quality
Data quality metrics.
const quality = await client.quality.get(tokenId, { period: 'last_24h' });
// quality.completeness.completeness_rate → 0.98Periods: last_10m, last_30m, last_1h, last_6h, last_24h, last_7d, last_30d, all
client.export
Export historical data in JSON, CSV, or XLSX format.
// JSON
const ticks = await client.export.ticks({
tokenId,
start: '2026-01-01',
end: '2026-01-31',
format: 'json',
});
// CSV (returns Buffer)
const csv = await client.export.ticks({
tokenId,
start: '2026-01-01',
end: '2026-01-31',
format: 'csv',
});client.sql
Execute read-only SQL queries against the data store.
const result = await client.sql.query('SELECT * FROM ticks WHERE token_id = ? LIMIT 10');
// or with params
const result = await client.sql.query({ query: 'SELECT ...', limit: 100 });client.users
User portfolio data.
| Method | Return Type | Description |
|--------|-------------|-------------|
| list(params?) | UserListResponse | List tracked users |
| discovered(params?) | UserDiscoveredResponse | Recently discovered users |
| getProfile(userId) | UserProfileResponse \| null | User profile with PnL summary |
| getPositions(userId, params?) | UserPositionsResponse \| null | User positions |
client.status
System health.
const status = await client.status.get();
const healthy = await client.status.isHealthy(); // booleanMarketStream
Server-Sent Events (SSE) stream for real-time market updates.
import { MarketStream } from '@polymarket-data/client';
const stream = new MarketStream({ baseUrl: 'http://localhost:8000' });
for await (const event of stream.subscribe(tokenId)) {
console.log(event.snapshot); // MarketSnapshot | null
console.log(event.book); // OrderBookResponse | null
}
// Stop the stream
stream.close();Error Handling
All errors extend DataCollectorError:
| Error | Status | Description |
|-------|--------|-------------|
| NotFoundError | 404 | Resource not found |
| AuthenticationError | 401 | Invalid or missing API key |
| ForbiddenError | 403 | Insufficient permissions |
| RateLimitError | 429 | Rate limit exceeded (includes retryAfter) |
| TimeoutError | — | Request timed out |
| ConnectionError | — | Network error |
import { RateLimitError, NotFoundError } from '@polymarket-data/client';
try {
await client.market.getPrice(tokenId);
} catch (e) {
if (e instanceof RateLimitError) {
console.log(`Retry after ${e.retryAfter}s`);
}
}License
MIT
