Skip to main content

Python client for PredictionData API - streaming market data for Polymarket

Project description

PredictionData Python Client

A Python library for streaming historical market data from the PredictionData API. Access order books, trades, and on-chain fills for Polymarket prediction markets.

Installation

pip install predictiondata

Quick Start

from predictiondata import PredictionDataClient, Channel

# Initialize client with your API key
client = PredictionDataClient(api_key="<YOUR_API_KEY>")

# Stream historical data
messages = client.replay(
    exchange="polymarket",
    from_date="2024-11-01",
    to_date="2024-11-15",
    filters=[Channel(name="trades", symbols=["will-trump-win-2024/YES"])]
)

    async for exchange_timestamp, message in messages:
        print(f"Time: {exchange_timestamp}ms, Trade: {message}")

Features

  • Async streaming - Efficiently stream large amounts of historical data
  • Multiple data types - Access order books, trades, and on-chain fills
  • Flexible filtering - Filter by market slug or token ID
  • Type-safe - Full type hints for better IDE support

Data Types

Order Books

Incremental order book reconstructions with bid/ask prices and sizes.

Channel(name="books", symbols=["will-trump-win-2024/YES"])

Schema:

  • exchange_timestamp (int): Exchange timestamp in milliseconds
  • local_timestamp (int): Server capture timestamp in milliseconds
  • ask_prices (str): Comma-separated ask prices
  • ask_sizes (str): Comma-separated ask sizes
  • bid_prices (str): Comma-separated bid prices
  • bid_sizes (str): Comma-separated bid sizes

Trades

Executed trades from the order book.

Channel(name="trades", symbols=["will-trump-win-2024/YES"])

Schema:

  • exchange_timestamp (int): Exchange timestamp in milliseconds
  • local_timestamp (int): Server capture timestamp in milliseconds
  • side (str): "BUY" or "SELL"
  • size (float): Trade size
  • price (float): Trade price

On-chain Fills

On-chain settlement data from the Polygon blockchain.

Channel(name="onchain_fills", symbols=["will-trump-win-2024/YES"])

Schema:

  • block_number (int): Blockchain block number
  • block_timestamp (int): Block timestamp in milliseconds
  • side (str): "BUY" or "SELL"
  • size (float): Fill size
  • price (float): Fill price
  • maker (str): Maker address
  • taker (str): Taker address

Usage Examples

Stream Multiple Markets

from predictiondata import PredictionDataClient, Channel

async def main():
    client = PredictionDataClient(api_key="your_api_key")
    
    messages = client.replay(
        exchange="polymarket",
        from_date="2024-11-01",
        to_date="2024-11-15",
        filters=[
            Channel(name="trades", symbols=[
                "will-trump-win-2024/YES",
                "will-biden-win-2024/YES"
            ])
        ]
    )
    
    async for exchange_timestamp, message in messages:
        print(f"Market: {message['_symbol']}")
        print(f"Side: {message['side']}, Size: {message['size']}, Price: {message['price']}")
    
    await client.close()

# Run with asyncio
import asyncio
asyncio.run(main())

Use Token IDs Instead of Slugs

Channel(name="onchain_fills", token_ids=["0x1234567890abcdef..."])

Fetch Single Day

For non-streaming use cases, fetch a complete day of data:

async def fetch_example():
    client = PredictionDataClient(api_key="your_api_key")
    
    data = await client.fetch_day(
        exchange="polymarket",
        data_type="trades",
        identifier="will-trump-win-2024/YES",
        date="2024-11-15"
    )
    
    print(f"Found {len(data)} trades")
    await client.close()

Context Manager

Use async context manager for automatic cleanup:

async def main():
    async with PredictionDataClient(api_key="your_api_key") as client:
        messages = client.replay(
            exchange="polymarket",
            from_date="2024-11-01",
            to_date="2024-11-15",
            filters=[Channel(name="books", symbols=["btc-above-100k/YES"])]
        )
        
        async for exchange_timestamp, message in messages:
            # Process messages
            pass

API Reference

PredictionDataClient

Main client class for accessing the PredictionData API.

Constructor:

PredictionDataClient(api_key: str, base_url: str = "http://datasets.predictiondata.dev")

Methods:

  • replay(exchange, from_date, to_date, filters) - Stream historical data

    • Returns: AsyncIterator[Tuple[int, Dict[str, Any]]] (yields exchange_timestamp, message)
  • fetch_day(exchange, data_type, identifier, date, use_slug=True) - Fetch single day

    • Returns: List[Dict[str, Any]]
  • close() - Close the client session

Channel

Represents a data channel filter.

Constructor:

Channel(name: str, symbols: List[str] = None, token_ids: List[str] = None)
  • name: Data type - "books", "trades", or "onchain_fills"
  • symbols: List of market slugs (format: "event-slug/OUTCOME")
  • token_ids: List of token IDs (alternative to symbols)

Market Identifiers

Markets can be identified by either:

  1. Slug (format: event-slug/OUTCOME):

    • Example: will-trump-win-2024/YES
    • Use for human-readable queries
  2. Token ID (contract address):

    • Example: 0x1234567890abcdef...
    • Use for programmatic queries

Error Handling

The client handles missing data gracefully:

async for exchange_timestamp, message in client.replay(...):
    try:
        # Process message
        pass
    except Exception as e:
        print(f"Error processing message: {e}")

Missing data files (404 responses) are skipped automatically.

Development

Install Development Dependencies

pip install -e ".[dev]"

Run Tests

pytest

Format Code

black predictiondata/

License

MIT License

Support

Changelog

0.1.0 (2025-11-17)

  • Initial release
  • Support for books, trades, and on-chain fills
  • Async streaming API
  • Market filtering by slug or token ID

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

predictiondata-0.1.0.tar.gz (12.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

predictiondata-0.1.0-py3-none-any.whl (8.9 kB view details)

Uploaded Python 3

File details

Details for the file predictiondata-0.1.0.tar.gz.

File metadata

  • Download URL: predictiondata-0.1.0.tar.gz
  • Upload date:
  • Size: 12.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for predictiondata-0.1.0.tar.gz
Algorithm Hash digest
SHA256 0aa681deb21c59548cae363ac931b189fae0caea655f9cbff3d0872a706dd95f
MD5 7478342ca1f155df1b0c04e380ee16b3
BLAKE2b-256 deb52ffca3ce8c4189250633e14ccf45cc4d59f10719eb235674bd31c9bc7a30

See more details on using hashes here.

File details

Details for the file predictiondata-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: predictiondata-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 8.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.7

File hashes

Hashes for predictiondata-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8d896931df1ec3539ba8daecea07cae11a699ac47656db5d1a6cbbbb1bd54fe6
MD5 e9e28733cdfd8dc67a5f1432d15653e9
BLAKE2b-256 99a4206fad4e2553aabec5e76bb196e35e5ff8d29fc6a9ba29fa8ce5a497c2a8

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page