API

Caching Polymarket API responses locally

Historical book data is immutable: a snapshot from last week is the same today as it was then. That makes it a perfect caching target, and caching is the easiest way to fit a research workflow inside a request quota.

What this guide covers

  • Historical book and price data for a fixed window never changes
  • Cache key should include slug, start, end and resolution
  • A content-addressed file cache survives across sessions and reruns
  • Only unresolved-market or live-window queries are unsafe to cache long-term

What is safe to cache

Historical windows are safe to cache indefinitely: the archive stores what happened, and what happened does not change. The exception is a window that includes the present, because new snapshots may still be arriving. Only cache windows whose end timestamp is safely in the past.

The key must include every input that changes the response: the market id or slug, the start and end timestamps, and the resolution. Omit any of them and you will serve the wrong cached data.

Cache key design

A stable cache key is a hash of the endpoint plus the sorted query parameters. That way the same request always maps to the same file, and different windows never collide. Store the response body verbatim so decoding is unchanged.

Write new entries atomically - to a temp file, then rename - so an interrupted write cannot leave a corrupt cache entry that fails later. This matters for long crawls that you may interrupt.

When to invalidate

You mostly do not need to invalidate immutable history. The exception is data near the present: a window that was partially captured when first fetched can gain rows later. Give recent windows a short time-to-live and treat older ones as permanent.

A simple rule: cache windows older than a few minutes indefinitely, and either skip caching or short-cache anything fresher. That captures the quota savings on history without serving stale near-real-time data.

Managing cache size

A cache that only grows will eventually fill the disk. Store entries under a directory you can prune, and give each entry a modification time so you can delete old files by age when the cache crosses a size threshold.

Because historical data is immutable, pruning is low-risk: a deleted old entry is simply re-fetched if needed, and near-real-time entries are the ones you would refresh anyway. Set the threshold generously so the common case never re-fetches.

Track hits and misses so you can see whether the cache is earning its keep. A low hit rate means your keys are too specific or the workload is genuinely fetching new windows each time, and both are worth knowing.

Code examples

import hashlib
import json
import os
from pathlib import Path

from polyorderbooks import PolyOrderbooksClient

CACHE = Path("./cache")
CACHE.mkdir(exist_ok=True)


def cache_path_for(**params):
    raw = json.dumps(params, sort_keys=True)
    digest = hashlib.sha256(raw.encode()).hexdigest()
    return CACHE / f"{digest}.json"


with PolyOrderbooksClient(api_key=os.environ["POLYORDERBOOKS_API_KEY"]) as c:
    call = dict(
        market="btc-updown-5m-1787486400",
        start="2026-10-17T07:00:00Z",
        end="2026-10-17T08:00:00Z",
        resolution="60s",
    )
    path = cache_path_for(**call)
    if path.exists():
        data = json.loads(path.read_text())
    else:
        data = c.get_market_books(
            call["market"],
            start_ts=call["start"],
            end_ts=call["end"],
            resolution=call["resolution"],
        )
        tmp = path.with_suffix(".tmp")
        tmp.write_text(json.dumps(data))
        tmp.replace(path)  # atomic rename
    print("snapshots:", sum(len(v) for v in data["data"].values()))

Free tier

The Starter plan is free, includes order books, prices, and metrics at 250ms resolution, with 3 days of history, 60 requests/min, 1,000/day, 1 free AI backtest, and 3 strategy backtests. No credit card required.

Paid data windows from $19/mo extend history to 30–120 days at higher throughput. Backtest AI add-on is +$19/mo or standalone at $29/mo.

FAQ

Is historical Polymarket data safe to cache?

Yes. A captured window does not change, so caching it on disk saves quota with no staleness risk - except for windows near the present.

What should a cache key include?

The endpoint plus all query parameters that affect the response: slug, start, end and resolution. Different windows must never share a key.

When should I invalidate?

Rarely for old history. Short-cache or skip caching for recent windows that may still gain rows as capture continues.

Why write the cache atomically?

A temp file plus rename prevents an interrupted write from leaving a corrupt entry that breaks later reads.