TypeScript SDK
@polytest/sdk is the official TypeScript client for the PolyTest API. It reads historical Polymarket markets, snapshots and order books on Node 20 or newer. Types ship with the package, and it has no runtime dependencies.
Python and Go SDKs are planned. Until they ship, the Quickstart shows each request in curl and Python.
Install
Install the package from npm and put your API key in the POLYTEST_KEY environment variable.
npm install @polytest/sdk
export POLYTEST_KEY="pt_live_your_key_here"First request
polytest() reads your key from POLYTEST_KEY. This example lists BTC 5m markets, prints five snapshots from one that has resolved, then fetches the first of those moments again with both order books.
import { polytest } from "@polytest/sdk"
const api = polytest() // reads POLYTEST_KEY
// The newest BTC 5m markets, then the first one that has resolved
const markets = await api.markets({ market_type: "5m", coin: "btc", limit: 10 })
const market = markets.items.find((m) => m.winner !== null)
if (!market) throw new Error("No resolved market on this page")
console.log(market.slug, market.winner)
// Its first five snapshots
const page = await api.snapshots(market.market_id, { limit: 5 })
for (const shot of page.items) {
console.log(shot.time, shot.price_up, shot.price_down)
}
// The first moment again, now with both order books
const [first] = page.items
if (first) {
const { snapshot } = await api.snapshotAt(market.market_id, {
timestamp: first.time,
include_orderbook: true,
})
console.log(snapshot.orderbook_up?.bids, snapshot.orderbook_up?.asks)
}Configure the client
polytest() accepts four options. You can leave any of them out.
| Option | Default | What it does |
|---|---|---|
| key | process.env.POLYTEST_KEY | Your API key, sent as X-API-Key. Spaces and tabs at either end are removed. |
| origin | https://api.polytest.io | Where requests go. It must use https (or http on localhost) and cannot include a path. |
| fetch | globalThis.fetch | A custom fetch function. The timeout still applies when it ignores its abort signal. |
| timeoutMs | 30000 | Time limit for each request in milliseconds, body included. A call that runs over throws network. null turns the limit off. |
import { polytest } from "@polytest/sdk"
const api = polytest({
key: "pt_live_your_key_here",
timeoutMs: 10_000,
})health() works without a key. With no key set, every other method throws PolyTestFailure of kind config before it sends anything.
The client never follows a redirect, so your key only goes to the origin you set. A 3xx answer throws http.
Methods
Every method returns a promise, and every result includes meta (see response meta).
| Method | Fields | Returns |
|---|---|---|
| health() | status (ok or degraded) and timestamp. Sends no key. | |
| limits() | Your plan's limits: tier, rate_limits, concurrency, data_access, api_keys and trial_budget. | |
| markets(query) | market_type, coin?, limit?, offset?, start_time?, end_time? | A page of markets, newest first. |
| market(ref) | market_id | slug | One market, by market_id or slug. |
| snapshots(market_id, query?) | limit?, offset?, start_time?, end_time?, include_orderbook? | A page of snapshots, oldest first. |
| snapshotAt(market_id, query) | timestamp, include_orderbook? | The snapshot closest to timestamp, up to two seconds either side. |
market_typeis5m,15m,1hr,4hror24hr. The list is exported asMARKET_TYPES.- Write
coinin lowercase, such asbtc,ethorsol. Without it, the server returnsbtcmarkets. start_time,end_timeandtimestamptake ISO 8601. A time with no zone is read as UTC, and a space can stand in for theT.- Arguments are checked before the request: a bad one throws
bad_requestand nothing is sent. Leave an optional field out to skip it, becausenullthrows.
Pages
markets and snapshots return a page. The rows are in items, and stop tells you whether more follow. page.next() fetches the next page, or returns null when there is none.
| stop | Meaning | next() |
|---|---|---|
| more | Another page follows at nextOffset. | Fetches the next page. |
| end | This is the last page. | Returns null without a request. |
| tier_window | You reached the end of the data your plan includes. | Returns null without a request. |
| snapshot_offset_cap | The walk reached the snapshot offset cap of 100000. | Returns null without a request. |
import { polytest, type Page, type Snapshot } from "@polytest/sdk"
const api = polytest()
const marketId = "1496946"
let page: Page<Snapshot> | null = await api.snapshots(marketId, { limit: 500 })
let rows = 0
while (page) {
rows += page.items.length
if (page.stop !== "more") console.log(rows, "rows, stopped by", page.stop)
page = await page.next()
}Rows the client cannot read are left out of items and counted in skipped. The next offset still counts them, so a skipped row never ends the walk early.
total is the server's estimate. Keep paging until stop is something other than more.
A snapshot offset above 100000 throws bad_request before the request. To read further into a long market, narrow the range with start_time and end_time.
Order books
Pass include_orderbook: true to snapshots or snapshotAt. Each snapshot then has orderbook_up and orderbook_down, and each book has bids and asks.
import { polytest } from "@polytest/sdk"
const api = polytest()
const marketId = "1496946"
const page = await api.snapshots(marketId, { limit: 100, include_orderbook: true })
for (const shot of page.items) {
if (shot.orderbook_up_invalid) continue // the client could not read this book
for (const { price, size } of shot.orderbook_up?.asks ?? []) {
console.log(shot.time, price, size)
}
}Every level is an object with price and size, including when the API sends a [price, size] pair. Extra book fields such as depth are kept.
A book the client cannot read comes back as null, with orderbook_up_invalid or orderbook_down_invalid set to true. A null book without the flag was absent. The rest of the snapshot is kept either way.
With a literal true, the rows are typed as SnapshotWithBooks. A boolean variable gives Snapshot or SnapshotWithBooks.
Errors and retries
Methods throw PolyTestFailure. Branch on error.failure.kind. error.status is the HTTP status, and error.meta is the response meta, or null when no response arrived.
| Kind | When |
|---|---|
| config | Bad options or a missing key, before any request. |
| network | No response arrived: the connection failed or the request timed out. The original error is at error.cause. |
| unauthorized | HTTP 401. The API rejected the key. |
| trial_exhausted | HTTP 402. A trial budget ran out. Has dimension and limit. |
| subscription_inactive | HTTP 403. The subscription is not active. |
| forbidden | HTTP 403. The data is outside your plan. Has tier. |
| rate_limited | HTTP 429. You went over the rate limit. Has retry_after when the server sends one. |
| concurrency_limited | HTTP 429. Too many of your requests were in flight at once. Has max_concurrent. |
| bad_request | HTTP 400, or an argument the client rejected before sending. |
| not_found | HTTP 404. No such market, or no snapshot near that time. |
| unavailable | HTTP 502 or 503. Can include retry_after. |
| server | Any other 5xx, or a 200 body the client could not read. |
| http | Any other response, including a redirect. |
isRetryable(error) returns true for rate_limited, concurrency_limited, unavailable and network, for server from an HTTP 5xx, and for http from 408 or 425. Every SDK request is a GET, so repeating one is safe.
retryDelayMs(error) returns the wait in milliseconds, capped at one hour. It uses retry_after when the server sent one. For rate_limited without it, it waits until your rate limit resets. Otherwise it returns null, which is always the case for concurrency_limited, so fall back to your own delay. Neither function sleeps.
import { polytest, isRetryable, retryDelayMs, PolyTestFailure } from "@polytest/sdk"
const api = polytest()
async function marketBySlug(slug: string) {
try {
return await api.market({ slug })
} catch (error) {
if (error instanceof PolyTestFailure && error.failure.kind === "not_found") return null
if (!isRetryable(error)) throw error
await new Promise((resolve) => setTimeout(resolve, retryDelayMs(error) ?? 1000))
return api.market({ slug })
}
}
const market = await marketBySlug("btc-updown-5m-1772689200")
console.log(market?.winner)Cancel a request
Every method takes an optional last argument with a signal, and so does page.next(). When the signal aborts, the call rejects with signal.reason, as fetch does. That value is not a PolyTestFailure, and isRetryable returns false for it.
import { polytest } from "@polytest/sdk"
const api = polytest()
const controller = new AbortController()
setTimeout(() => controller.abort(), 5_000)
const page = await api.markets({ market_type: "15m" }, { signal: controller.signal })
const nextPage = await page.next({ signal: controller.signal })timeoutMs still runs alongside your signal. Whichever fires first ends the call, and a timeout throws network.
Response meta
Every result has meta. A failure built from an HTTP response carries the same object at error.meta, so a 429 still shows your rate limit.
| Field | Headers | Contents |
|---|---|---|
| rate_limit | X-RateLimit-LimitX-RateLimit-RemainingX-RateLimit-Reset | limit, remaining and reset_unix (seconds). null unless all three headers are numbers. |
| trial_remaining_before | X-Trial-Budget-*-Remaining | During a trial, the requests, records and bytes left before this request. Otherwise null. |
| server_clamp | X-Limit-Clamped | requested, applied and max when the server lowered your limit. Otherwise null. |
import { polytest } from "@polytest/sdk"
const api = polytest()
const page = await api.markets({ market_type: "5m", limit: 100 })
console.log(page.meta.rate_limit?.remaining) // requests left in this window
console.log(page.meta.server_clamp) // null unless the server lowered limitRuntime
The package is an ES module.
| Setup | Needs |
|---|---|
| import | Node 20 or newer |
| require() | Node 20.19, or Node 22.12 or newer |
| TypeScript compiled to CommonJS | TypeScript 5.8 or newer, with "module": "nodenext" |