Advanced

Prediction Market APIs: Live and Historical Data

Andrej Gjorgievski Andrej Gjorgievski Updated Sep 11, 2026 19 min read
Guide

Overview

Introduction

A prediction market API is a software interface that exposes event, market, outcome, price, trade, and resolution data in structured form through REST endpoints, real-time streams, or both.

The interface can support market discovery, research, monitoring, and historical analysis. It does not guarantee that every venue supplies the same objects, fields, timestamps, or access rights. Public data access also does not imply permission to trade. Collection and validation remain read-only and use official interfaces. Examples from Polymarket, Kalshi, and Manifold show how data surfaces differ across venues, while Gemini's documentation shows where the venues converge.

Key takeaways

Key takeaways

  • What it is. A prediction market API can expose discovery metadata, snapshots, real-time changes, trades, history, and resolution records through separate data surfaces.
  • Why it matters. Reliable analysis requires venue-specific identifiers, explicit time and price types, raw payloads, and a recovery path from a known snapshot.
  • Main risk or limitation. Read-only replays can test ingestion and state reconstruction, but they cannot remove feed gaps, schema changes, licensing limits, or mistakes in interpreting settlement terms.

What a Prediction Market API Exposes

A venue may split prediction market data across several interfaces. Discovery routes describe events, questions, outcome labels, rules, closing times, and stable identifiers. Market-data routes can return current quotes, order books, public trades, price history, and volume. Account routes may add positions or fills after authentication. Resolution fields report the native status, result, source, and settlement time.

Polymarket's market-data overview separates discovery, order-book, and account or analytics data. Kalshi's market-data quick start moves from series to events, markets, and books. Manifold's official API documentation uses its own contract, market, answer, and bet vocabulary.

Consuming prediction market data reliably therefore requires a client-side venue adapter. The adapter converts native objects into internal records while retaining the original structured metadata, and it must not invent an absent field. A current quote and a historical series belong in separate record types. Public trades, account balances, and terminal results carry different meanings, access controls, and update schedules.

REST and WebSocket Feeds Have Different Jobs

REST and WebSocket access are complementary. REST provides a bounded response to a request. It is normally the better surface for discovery, initial state, periodic reconciliation, and recovery. A WebSocket keeps a connection open and sends changes or events after subscription. It is useful when a monitor needs timely updates between snapshots.

ConcernRESTWebSocket
Main jobDiscover objects and fetch snapshotsReceive live changes after subscription
State modelComplete response at request timeInitial state or deltas in a sequence
Common failureStale cache, partial page, or rate limitDisconnect, missing delta, or stale heartbeat
Recovery actionRetry within a bounded policy or continue paginationStop deltas and rebuild from a fresh REST snapshot

Use REST for Discovery and Recovery

Start by finding native event, market, and outcome identifiers. Store the returned rules and status with the raw response, then normalize them. Gemini's prediction-market REST overview also frames REST as a discovery and state-recovery surface. A stream may omit fields needed to reconstruct an object, so recovery starts from a complete documented snapshot.

Use WebSockets for Live State Changes

Polymarket's market WebSocket channel describes book, price, trade, market-creation, and resolution messages. Kalshi documents an authenticated connection in its WebSocket quick start and snapshot-plus-delta handling for order-book stream updates. Authentication requirements and channel behavior differ, so verify the current venue documentation before connecting.

Map Events, Markets, Contracts and Outcomes

Titles are presentation text, not safe database keys. A compound internal key should include the venue plus every native identifier needed to distinguish the event, tradable market, and outcome. Keep slugs and titles for search and display only.

Events Group Related Markets

Polymarket documents an event that can contain several binary markets, with each market linked to outcome-token identifiers. Kalshi uses a series, event, and market hierarchy. Manifold may call a question a contract or market and a topic a group. The official Polymarket object model, Kalshi event response, and Manifold documentation show why a universal market_id field is insufficient without a venue namespace.

Here, contract refers to Manifold’s native API object label, not to a smart contract. This page also uses two related terms: settlement terms describe what a market pays against, while a schema agreement describes the fields and types exchanged between a venue and a client.

Outcomes Need Native Identifiers

Two venues may publish nearly identical titles while using different cutoffs, sources, cancellation rules, or outcome mappings. Never merge them through fuzzy title matching alone. Retain the raw question, outcome labels, close time, resolution source, and void behavior before any cross-venue comparison.

Internal fieldPolymarket exampleKalshi exampleManifold exampleNormalization rule
object_type_nativeEvent or marketSeries, event, or marketContract, market, or groupPreserve the venue’s object label
event_id_nativeEvent IDEvent tickerGroup or topic IDStore as text with venue
market_id_nativeMarket or condition IDMarket tickerContract or market IDRequired for each market record
outcome_id_nativeOutcome token IDYES or NO sideAnswer ID or outcomeRequired for quote records
slug_or_tickerEvent or market slugSeries or market tickerMarket slugSecondary lookup only
from dataclasses import dataclass

@dataclass(frozen=True)
class NativeKey:
    venue: str
    market_id_native: str
    event_id_native: str | None = None
    outcome_id_native: str | None = None

This internal type makes no network call. It preserves the identifiers already returned by official discovery data. Leave event or outcome identifiers empty when a venue does not supply them. Never synthesize them.

Normalize Quotes, Order Books and Trades

Avoid one generic field called price. A normalized price record should identify whether the value is a bid, ask, last trade, midpoint, or mark. A mark is a venue-computed reference used for valuation, not an executable quote. Candles belong to the historical series record type, which stores open, high, low, close, volume, and the aggregation interval rather than a single price. The normalized price record also needs the outcome identifier, size, book time, source event time, and local observation time. Book time is the timestamp the venue attaches to the book state. Source event time is when the venue emitted the record, and local observation time is when the client observed it. Store all three when supplied because they can differ. As crypto order book mechanics show, bids are standing offers to buy, asks are standing offers to sell, and depth records how much size is available at successive prices.

Suppose a market display shows a midpoint of 0.60, while the best ask is 0.62 for 40 units and 0.64 for the next 100. A buyer requesting 100 units cannot treat 0.60 as an executable quote. The first 40 may be available at 0.62 and the remaining 60 at 0.64, before fees. A last trade at 0.59 would be another historical observation, not a current offer.

Polymarket's order-book response separates bids, asks, sizes, a token identifier, a timestamp, and a last-trade price. Kalshi's order-book representation documents YES and NO bids instead of a universal explicit-ask layout. Its public-trade stream and trades endpoint expose trade records separately.

Each venue therefore needs its own reconstruction logic. Store the native representation before deriving a complementary ask or midpoint. The prediction market price formats cover probability and payout interpretation. Data normalization records what each field means without judging whether a quote is attractive.

Store Historical Data and Resolution State

A price array is not a complete historical dataset. Preserve contemporaneous question wording, rules, outcome labels, identifiers, status changes, resolution source, and correction history alongside quotes and trades. Otherwise a later analyst may see a series without knowing which proposition and settlement terms applied at that time.

Preserve Rules With Price History

Polymarket's historical-price API reference describes market asset IDs, time ranges, aggregation intervals, and fidelity. Kalshi separates current and older records in its historical-data workflow and documents bid, ask, price, volume, and open-interest candles through a candlestick endpoint. Manifold points bulk users toward its own download documentation.

Store raw payloads within the source's terms and retention rules. Add an adapter version and ingestion time. If rule text changes, keep the permitted earlier version or a dated rule reference instead of silently overwriting it. Onchain records can add another evidence layer, but the underlying blockchain structure does not replace venue rules.

Treat Resolution as a State Machine

The prediction market lifecycle can assign separate states and dates to closure and settlement, so preserve both instead of treating the closing time as final. Kalshi's lifecycle documentation distinguishes determination, disputes, amendments, and finalization. Polymarket can send a resolution message through its market channel. Manifold exposes resolution fields on its market objects. The onchain prediction market architecture maps how smart-contract and oracle layers can generate those native states.

Normalized stateMeaningNative evidence to retain
OpenTrading or forecasting remains activeNative status, open time, close time
ClosedNew activity has stoppedClose event and source timestamp
DeterminedA provisional result is knownNative result and determination time
DisputedResult remains contestableDispute status and notices
AmendedA published determination or record changedPrior value, revised value, notice, and amendment time
ResolvedOutcome has been declaredWinning outcome and source
Voided or canceledVenue will not settle under the ordinary outcome mappingNative reason, refund rule, and status time
SettledTerminal credits or accounting are completeFinal status and settlement time

Determined means a first published answer remains open to dispute or amendment. Resolved means the venue has declared the outcome it will pay against, while settled means the resulting credits or accounting are complete. Preserve both native and normalized states. Never infer a final result solely from a price near zero or one.

Separate Public Data From Authenticated Actions

Authentication is endpoint-specific. Polymarket says its public market data requires no API key, authentication, or wallet, while trading uses credential and signing layers in its authentication overview. Kalshi documents signed API requests and WebSocket handshakes through its API key process. Manifold combines commonly public reads with authenticated operations.

Access classTypical purposeSafe handling
Public read, unauthenticatedDiscovery, quotes, books, trades, or status where offered without credentialsApply terms, limits, validation, and caching
Public-data read, authenticatedPublic channels that require a signed request or handshake, including Kalshi WebSocketsUse read-only credentials where available and keep secrets server-side
Private account readPositions, fills, balances, or other account dataGrant the narrowest permission and separate it from public records
Authenticated writeOrders, cancellations, account changes, or other actionsExcluded from the read-only workflow

Treat account records as a separate protected dataset, even when a venue returns them beside public market data. Authentication does not by itself indicate whether the underlying data is public or private.

Keep live private keys, HMAC secrets, API secrets, and wallet credentials out of source code, notebooks, client-side applications, screenshots, logs, and AI prompts. Do not copy an old tutorial's permissions or endpoint assumptions. On Aug. 31, 2026, Kalshi's order-book explanation said the endpoint required no authentication, while its endpoint reference displayed required authentication headers. Check both current pages before relying on either representation.

Handle Rate Limits, Pagination and Time

At the venues checked, each endpoint can have its own rate limits and pagination rules. Polymarket publishes separate limits by API family in its current rate-limit documentation. Kalshi separates read and write capacity and advises exponential backoff after HTTP 429 in its rate-limit documentation.

Respect Endpoint Limits and Cursors

Cache stable discovery metadata. Bound retries, add jitter to backoff, and stop after a defined attempt or time budget. Never distribute traffic across addresses to evade a limit. Follow opaque cursors until the documented stop condition, and do not parse or increment them. Polymarket's event pagination, market pagination, and Kalshi's pagination model illustrate similar cursor concepts with venue-specific details.

Normalize Time and Decimal Precision

Convert source times to UTC integer milliseconds internally while retaining the raw value and documented unit. Record the venue event time separately from local ingestion time. Parse financial strings with decimal arithmetic instead of binary floating point. This matters because the checked Polymarket, Kalshi, and Manifold materials use different combinations of ISO strings, Unix seconds, and Unix milliseconds.

FailureDetectionResponse
HTTP 429Rate-limit statusPause with bounded backoff and jitter
Cursor reuse or expiryRepeated cursor or documented errorRestart from a stored boundary
Mixed time unitsImplausible date or schema ruleParse through a venue-specific unit map
Duplicate pageRepeated namespaced record IDDe-duplicate and retain ingestion evidence
Missing fieldSchema validation failureQuarantine the record and alert
Float roundingDecimal comparison mismatchParse the original string as a decimal

Kalshi's market ticker channel is a useful example because its documented messages can carry several time forms. Schemas and limits cited here were checked on Aug. 31, 2026 and should be verified again in current official documentation.

Recover From Disconnects and Schema Changes

A live client should treat a sequence gap, stale heartbeat, parse failure, or reconnect as loss of trust in its local state. Stop applying deltas. Fetch a fresh REST snapshot, replace the affected state, and resume only at the venue's documented boundary. Do not attempt to guess the missing update.

Detect Sequence Gaps

Persist the last accepted sequence value when the stream supplies one. A duplicate can be ignored after an idempotency check. A jump, reversal, or missing initial snapshot should trigger a rebuild. Kalshi's order-book update model documents a snapshot followed by incremental deltas and sequence values. Venues without equivalent sequencing need another documented recovery signal, such as a complete snapshot comparison.

Version Venue Adapters

Transport recovery repairs lost messages. Schema migration repairs a changed schema agreement between the venue and the client. A transport fault calls for a fresh known state. A renamed field, incompatible type, new identifier rule, or retired host calls for adapter changes and fixture tests.

Polymarket's developer changelog and Kalshi's API changelog document breaking and additive migrations. Examples include pagination changes, host migrations, price-precision updates, renamed fields, and revised messages. Manifold labels its API alpha in its official documentation. Preserve raw payloads and tolerate unknown additive fields, but fail visibly on incompatible changes. Record the adapter version that produced each normalized row.

Build a Read-Only Market Monitor

A reliable monitor can rebuild the same normalized state from a known snapshot plus accepted events.

  1. Read the current terms, access restrictions, licensing rules, and official documentation.
  2. Discover events and markets through an unauthenticated endpoint when one is available.
  3. Select native event, market, and outcome identifiers returned by that discovery response.
  4. Fetch a REST snapshot and save the complete raw payload with an ingestion timestamp, within the source's terms and retention rules.
  5. Normalize identifiers, lifecycle state, timestamps, and decimal fields through a venue adapter.
  6. Subscribe to a WebSocket only after the REST snapshot, using authentication when a public-data channel requires a signed handshake, then retain any initial stream snapshot before deltas.
  7. Validate sequence, schema, source time, and namespaced record IDs for every message.
  8. Persist accepted events append-only and reconcile the materialized state with periodic REST snapshots.
  9. Store wording, rules, labels, and the resolution source with the market record.
  10. Keep polling or listening until the venue reaches a terminal state, whether settled, voided, or canceled, then display the record in a local log or dashboard.

Reconciliation replaces diverged local state with a fresh official snapshot. Replay applies the same adapter transformations to recorded messages without a live write. Together, they make the stored state auditable.

# Executable local fixtures. No network or account access.
from decimal import Decimal

initial_snapshot = {
    "venue": "example",
    "event_id_native": "event-7",
    "market_id_native": "market-3",
    "outcome_id_native": "yes",
    "sequence": 40,
    "price_type": "best_bid",
    "price_decimal": "0.60",
    "size_decimal": "125",
    "book_time_ms": 1788134399000,
    "source_event_at_ms": 1788134400000,
    "observed_at_ms": 1788134400100,
}
recovery_snapshot = {
    **initial_snapshot,
    "sequence": 42,
    "price_decimal": "0.615",
    "book_time_ms": 1788134402000,
    "source_event_at_ms": 1788134402000,
    "observed_at_ms": 1788134402100,
}
messages = [
    {
        **initial_snapshot,
        "sequence": 41,
        "price_decimal": "0.61",
        "book_time_ms": 1788134401000,
        "source_event_at_ms": 1788134401000,
        "observed_at_ms": 1788134401100,
    },
    {
        **initial_snapshot,
        "sequence": 43,
        "price_decimal": "0.62",
        "book_time_ms": 1788134403000,
        "source_event_at_ms": 1788134403000,
        "observed_at_ms": 1788134403100,
    },
]

saved_snapshots = iter([initial_snapshot, recovery_snapshot])
rebuild_triggers = []

def load_saved_rest_snapshot():
    return next(saved_snapshots).copy()

def apply_validated_delta(current, message):
    return {
        **current,
        "sequence": message["sequence"],
        "price_type": message["price_type"],
        "price_decimal": str(Decimal(message["price_decimal"])),
        "size_decimal": str(Decimal(message["size_decimal"])),
        "book_time_ms": message["book_time_ms"],
        "source_event_at_ms": message["source_event_at_ms"],
        "observed_at_ms": message["observed_at_ms"],
    }

state = load_saved_rest_snapshot()
expected = state["sequence"] + 1
for message in messages:
    if message["sequence"] != expected:
        rebuild_triggers.append({"expected": expected, "received": message["sequence"]})
        state = load_saved_rest_snapshot()
        expected = state["sequence"] + 1
        if message["sequence"] != expected:
            continue
    state = apply_validated_delta(state, message)
    expected = state["sequence"] + 1

The example resumes only when the recorded recovery snapshot establishes the next documented sequence boundary. Production credentials, authenticated write methods, and live-order endpoints are outside scope. A monitor may record alerts or data-quality exceptions, but it should not turn them into transactions.

Paper-Test With Replays and Demo Environments

Paper testing checks parsers, state transitions, recovery, and alert logic without sending a live order. Replays are more reproducible than a live connection because the same recorded fixtures can be run against each adapter revision.

Test caseExpected result
Duplicate messageIgnore after the idempotency check
Out-of-order timestampRetain source time and flag ordering
Missing required fieldQuarantine record and alert
Sequence gapDetect the gap, halt deltas, and record a rebuild trigger
HTTP 429 fixtureApply the bounded retry budget, then surface a rate-limit exception
Corrected statusPreserve prior native state and append correction
Renamed fieldFail the fixture until the adapter is updated

Kalshi documents production and demo connections in its WebSocket quick start. Manifold documents a venue-specific dryRun option. Neither capability is a universal standard, and a local mock is safer when authenticated writes are unnecessary.

A prediction market trading bot adds order placement to the data pipeline. Read-only research stops at collection, replay, and paper testing without placing orders. Cross-venue prices may describe propositions with different rules, cutoffs, or settlement sources. Without equivalent settlement terms, the displayed prices do not support a valid cross-market arbitrage comparison. Even then, automation and arbitrage risks include feed latency, fill uncertainty, costs, and venue rules that can erase a displayed difference.

Compare Prediction Market Data Access

Polymarket's public-data and trading split separates unauthenticated market reads from credentialed actions and includes token-level price history. A comparison of platform data access must identify which product documentation governs each interface because one venue may publish separate endpoints or terms for different products.

Kalshi's authenticated API access model includes signed WebSocket handshakes, separate current and historical datasets, and documented demo connections. Manifold's public data access model includes public REST reads, but collection, storage, and redistribution still depend on its current data-use terms and bulk-download guidance.

Before choosing a source, compare documentation quality, public-data coverage, access terms, resolution fields, and change notices. Also confirm geographic restrictions before implementation, because access can differ by jurisdiction even where the schema does not.

Prediction Market API Checklist

Before treating prediction market datasets as ready for analysis, confirm that the dataset and the collection process behind it satisfy all ten checks:

  1. A current official source and permitted use.
  2. Venue-namespaced event, market, and outcome identifiers.
  3. A stored raw REST snapshot.
  4. A documented stream and sequence policy.
  5. Bounded handling for rate limits and retries.
  6. Pagination through the documented stop condition.
  7. UTC time with the raw source value retained.
  8. Decimal parsing and an explicit price type.
  9. Raw payloads, adapter versions, and replay fixtures.
  10. Native resolution state plus changelog monitoring.

The dataset is not ready for production analysis until the collection process behind it can rebuild the dataset deterministically from a known snapshot and reconcile the final recorded status with the venue's published terminal state.

Frequently Asked Questions

What prediction markets have APIs?

Polymarket, Kalshi, Manifold, and other venues publish official APIs, but the exposed objects and permissions differ. Some focus on public market data, while others split discovery, streaming, account data, and trading across separate interfaces. Check the current first-party documentation for the specific product and legal entity. Do not treat one venue’s schema as a universal model for prediction market APIs.

Is the Polymarket API free?

Polymarket exposes public market-data interfaces that can be queried without trading credentials, but its terms and rate limits still apply. Permission to redistribute the data depends on the current data-use terms. Account-specific data and order submission use authenticated surfaces. “Free” therefore does not mean unlimited, complete, or unrestricted.

Is REST or WebSocket better for live data?

WebSockets are better suited to timely changes after a known state, while REST is better suited to discovery, snapshots, reconciliation, and recovery. A reliable monitor normally uses both. It fetches a REST snapshot, applies validated stream deltas, and replaces local state from REST after a gap or reconnect.

How do you get historical prediction market data?

Use the venue’s documented history, trade, candle, or bulk-download surfaces where available. Store rules, identifiers, outcome labels, native statuses, resolution source, and corrections with the numeric series. Historical access can be partitioned from live data, as Kalshi documents, so a time range may require separate queries and an explicit merge.

Can you build a trading bot with a prediction market API?

Some venues expose authenticated write interfaces. A read-only workflow is limited to collection, monitoring, replay, and paper testing, without order routing or signing. Automation adds software, feed, access, execution, and compliance risk, and it creates no expectation of profit.