# List fills Source: https://docs.probalytics.io/api-reference/fills/list-fills /openapi.yaml get /api/v1/fills Returns a paginated list of trade fills (executions) from Kalshi and Polymarket. # Cypher query Source: https://docs.probalytics.io/api-reference/market-graph/cypher-query /openapi-market-graph.yaml post /api/graph/cypher One read statement per request; `COPY`, `LOAD`, `CALL`, `INSTALL`, `EXPORT`, and writes are rejected. Results are capped at 10,000 rows, queries at 10,000 characters, and execution at 30 seconds. `UNION ALL` is not supported; run separate queries instead. # Preconfigured query Source: https://docs.probalytics.io/api-reference/market-graph/preconfigured-query /openapi-market-graph.yaml get /api/graph/q/{name} - `market`: the market node with all its columns - `relations`: every relation to or from the market (`src`, `dst`, relation fields, and the peer's `peer_id`, `peer_platform`, `peer_title`, `peer_status`, `peer_url`) - `underlying`: all markets on the same underlying, with `direction`, `lo`, `hi` - `outcome_set`: all markets in the same outcome set, with the set's `kind` and `members` # List markets Source: https://docs.probalytics.io/api-reference/markets/list-markets /openapi.yaml get /api/v1/markets Returns a paginated list of prediction markets from Kalshi and Polymarket. # Errors & Request Behavior Source: https://docs.probalytics.io/docs/api-reference/errors REST API errors, validation, and retry behavior The REST API uses PocketBase-style JSON errors. An error response includes the HTTP status in both the response status code and the `status` field. ## Error response format ```json theme={null} { "data": {}, "message": "Human-readable error description.", "status": 400 } ``` | Field | Type | Description | | - | - | - | | `status` | `integer` | HTTP status code | | `message` | `string` | Human-readable summary; capitalization and exact wording can vary | | `data` | `object` | Additional details; empty when no structured details are available | Validation details are keyed by request field and contain their own `code` and `message` values: ```json theme={null} { "data": { "start_time": { "code": "validation_invalid_date", "message": "Invalid date format." } }, "message": "Invalid params.", "status": 400 } ``` Do not build program logic around the exact English wording. Use the HTTP status and structured validation keys where present. ## HTTP status codes ### 400 Bad Request Returned when a validated parameter is outside its accepted values, including: * dates that are not RFC 3339, such as `2026-03-01` without a time and timezone; * unsupported `platform`, `status`, or `taker_side` values; * numeric limits below 1 or above 1,000. Some malformed values are currently handled more permissively: * a nonnumeric `limit` falls back to the default value of 100; * a malformed pagination `cursor` is ignored and the first page is returned; * `market_id` is passed to the database without route-level UUID validation. These behaviors may become stricter in a future version. Send values matching the published OpenAPI schema rather than relying on the fallback. ### 401 Unauthorized Returned when API-key authentication fails. ```json theme={null} { "data": {}, "message": "Missing authorization header.", "status": 401 } ``` Common causes: * missing `Authorization` header; * a scheme other than the case-sensitive `Bearer` scheme; * a token that does not contain `API_KEY_ID:API_KEY_SECRET`; * an invalid, revoked, or inactive API key. Correct format: ```bash theme={null} curl -H "Authorization: Bearer api_xxx:sk_xxx" \ https://api.probalytics.io/api/v1/markets ``` ### 403 Forbidden Returned when the authenticated account cannot access the requested resource. ### 500 Internal Server Error Returned when a request could not be completed because of an internal or upstream database failure. ```json theme={null} { "data": {}, "message": "Failed to fetch markets.", "status": 500 } ``` Retry transient 5xx failures with bounded exponential backoff. If failures persist, contact support with the request parameters and UTC timestamp. ## REST limits versus ClickHouse quotas No fixed REST requests-per-second or requests-per-hour quota is currently part of the public REST contract. Operational protections can still reject abusive or unusually concurrent traffic. Direct ClickHouse credentials use separate traffic and resource limits. See [SQL access tiers](/docs/sql-guide/overview#access-tiers). A ClickHouse quota error is not a REST 429 response and does not use the JSON format on this page. ## Cursor pagination Pagination uses `cursor`; there is no `offset` parameter. A cursor is emitted whenever the current page contains exactly `limit` rows. The API does not fetch an extra row to prove another page exists, so a full final page can produce a cursor whose next request returns an empty `data` array. Continue until `data` is empty or `next_cursor` is absent: ```python theme={null} import requests url = "https://api.probalytics.io/api/v1/fills" headers = {"Authorization": "Bearer api_xxx:sk_xxx"} params = {"limit": 1000, "platform": "POLYMARKET"} all_rows = [] while True: response = requests.get(url, headers=headers, params=params, timeout=30) response.raise_for_status() payload = response.json() rows = payload["data"] if not rows: break all_rows.extend(rows) cursor = payload.get("next_cursor") if not cursor: break params["cursor"] = cursor ``` # Platform Status Source: https://docs.probalytics.io/docs/api-reference/status Public status API for service uptime and incidents The status API reports the current health of the Probalytics platform. It is public and does not require authentication. ``` GET https://status.probalytics.io/api ``` The response is a single JSON object. It covers the services that deliver data to you, including the REST API, the ClickHouse service, S3-compatible file downloads, and the data collection and processing pipelines. ## Service names Data pipeline services are grouped as `/`, for example `polymarket/markets`, `polymarket/fills`, `polymarket/orderbook`, `kalshi/markets`. Each group covers the full pipeline for that platform and dataset. Standalone services use flat names: `api` (the REST API), `clickhouse`, `s3`. ## Response format ```json theme={null} { "status": "up", "checked_at": "2026-09-05T12:00:00Z", "window_seconds": 180, "incident_days": 30, "services": [ { "name": "clickhouse", "status": "up", "last_seen": "2026-09-05T11:59:41Z", "errors": 0 }, { "name": "polymarket/orderbook", "status": "up", "last_seen": "2026-09-05T11:59:55Z", "errors": 0 } ], "incidents": [ { "service": "kalshi/fills", "started_at": "2026-08-30T02:14:00Z", "ended_at": "2026-08-30T02:39:00Z", "duration_seconds": 1500 } ] } ``` ## Top-level fields | Field | Type | Description | | - | - | - | | `status` | `string` | Overall platform status. The worst status of any monitored service, ignoring `unknown` services. `unknown` when no data is available. | | `checked_at` | `string` | RFC 3339 UTC time when the data was computed, not when you made the request. The data can be up to a few minutes old; treat `checked_at` as the freshness timestamp. | | `window_seconds` | `integer` | The silence window in seconds. A service that has not reported for longer than this window is reported as `down`. | | `incident_days` | `integer` | How many calendar days of incident history the response covers. | | `services` | `array` | One entry per monitored service, sorted by `name`. | | `incidents` | `array` | Known service outage periods within the incident window, sorted by service name and start time. | | `error` | `string` | Present only when no status data is available, with `status: "unknown"` and empty `services` and `incidents` lists. Retry after a short delay. | ## Service entries | Field | Type | Description | | - | - | - | | `name` | `string` | Service identifier. | | `status` | `string` | One of `up`, `degraded`, `down`. See definitions below. | | `last_seen` | `string` | RFC 3339 UTC time the service last reported. | | `errors` | `number` | Number of errors reported by the service in the recent error window (about the last 5 minutes). | ### Status definitions * `up`: the service is reporting normally and has no recent errors. * `degraded`: the service is running and still reporting, but it has reported recent errors. It may behave unreliably. * `down`: the service has stopped reporting. Its last report is older than `window_seconds`. The service is likely not running. * `unknown`: no status data is available, for example when the API was queried before its first data refresh. No data available is the only case that reports `unknown`. A service can only have one status. A stale report (`down`) takes precedence over reported errors (`degraded`). ## Incidents Each incident is a continuous period in which a service stopped reporting. Incidents are derived from gaps in service reporting, so the recorded duration can be slightly longer than the actual outage. | Field | Type | Description | | - | - | - | | `service` | `string` | Service identifier, same value as `services[].name`. | | `started_at` | `string` | RFC 3339 UTC time the reporting gap started. | | `ended_at` | `string` | RFC 3339 UTC time reporting resumed. | | `duration_seconds` | `integer` | Length of the gap in seconds. | ## Polling recommendations * Poll no more than once per minute. The data changes slowly and is cached. * Compare `checked_at` with your request time to know how fresh the reading is. * Treat `errors` above zero as a sign to watch the platform, not as a guaranteed failure. ## Notes * Timestamps are RFC 3339 in UTC. * This endpoint monitors the platform services that serve you. It does not report the health of your own queries, clients, or API keys. # Fills (Trades) Source: https://docs.probalytics.io/docs/datasets/fills The fills dataset shape, coverage, and venue-specific trade normalization rules ## Shape A fill is one normalized trade execution. It links to a market and one of that market's outcomes. | Field | Type | Values and meaning | | - | - | - | | `id` | `UUID` | Stable Probalytics fill ID. Generated deterministically from the venue trade or chain event. | | `market_id` | `UUID` | Probalytics market ID. Join this to `markets.id`. | | `market_platform_id` | `string` | Venue-native market identifier copied from the linked market. | | `platform` | `enum` | `POLYMARKET` or `KALSHI`. | | `platform_id` | `string` | Venue-native trade, order, or execution ID. The exact source differs by product. | | `outcome` | `Outcome` | Traded outcome containing `id` (UUID), `platform_id` (string), `name` (string), and zero-based `index` (integer). | | `size` | `decimal` | Executed quantity. Prediction markets use contracts/shares; perpetual and margin products use venue instrument units. | | `price` | `decimal` | Execution price for the stored `outcome`. Prediction-market prices are normally between `0` and `1`; perpetual prices are instrument prices. | | `normalized_price` | `decimal` | Prediction markets: execution price expressed as the price of outcome index `0`. Perpetual and margin products: same value as `price`. | | `taker_side` | `enum` | `BUY` or `SELL`. The exact mapping is product-specific and documented below. | | `taker_cash_flow` | `decimal` | Positive gross/notional value assigned to the taker. It is not signed by trade direction. | | `maker_cash_flow` | `decimal` | Positive gross/notional value assigned to the maker. It is not signed by trade direction. | | `taker_id` | `string \| null` | Taker wallet or participant ID when exposed by the source. Currently populated for Polymarket prediction-market fills. | | `maker_id` | `string \| null` | Maker wallet or participant ID when exposed by the source. Currently populated for Polymarket prediction-market fills. | | `fee` | `decimal` | Source fee amount when available. `0` is also used when the source does not expose fees. | | `source_block_number` | `integer \| null` | Chain block containing the execution. Present for Polymarket prediction-market fills. | | `source_tx_hash` | `string \| null` | Chain transaction hash when available. | | `source_log_index` | `integer \| null` | Event position within the chain transaction. | | `timestamp` | `datetime` | Source execution time in UTC. | | `indexed_at` | `datetime` | Time Probalytics wrote the fill. | | `metadata` | `object` | Product-specific annotations. Values are strings, numbers, or booleans. Usually empty for prediction-market fills. | ## Coverage by venue and product | Venue | Product | Fills | Coverage starts | | - | - | -: | - | | Polymarket | Prediction-market trades | 1,171,916,395 | 2022-11-21 | | Polymarket | Perpetual trades | 9,580,526 | 2026-05-06 | | Kalshi | Prediction-market trades | 1,360,159,691 | 2022-01-01 | | Kalshi | Combo trades (multivariate events) | 156,479,772 | 2025-09-17 | | Kalshi | Margin trades | 25,225,233 | 2026-06-03 | Counts as of 2026-08-24 17:59 UTC. Coverage starts use the earliest source `timestamp`. Prediction and perpetual/margin rows are separated using the linked market's `market_type`. Kalshi combo count as of 2026-10-17; identify combo fills by joining `market_id` to `markets.id` and filtering `market_type = 'PARLAY'`, not by ticker prefix. Fills are indexed continuously, so these counts change throughout the day. Query the data warehouse for current values: ```sql theme={null} WITH market_id IN ( SELECT id FROM markets FINAL WHERE market_type = 'PERPETUAL' ) AS is_perpetual SELECT platform, if(is_perpetual, 'PERPETUAL', 'PREDICTION') AS product, count() AS fills, min(timestamp) AS earliest_fill FROM fills GROUP BY platform, product ORDER BY platform, product; ``` ## Polymarket prediction-market trades ### Source These fills come from `OrderFilled` events emitted on Polygon by the supported CTF Exchange and Neg Risk Exchange contracts, including their V2 versions. Legacy executions can emit two related `OrderFilled` logs. Probalytics retains the maker-focused representation instead of publishing both as separate trades. ### Field mapping | Polymarket source | Probalytics field | | - | - | | Transaction hash + log index + taker address | `id` | | Outcome token's linked market | `market_id`, `market_platform_id` | | Order hash | `platform_id` | | Outcome token ID | `outcome` | | Outcome-token amount ÷ `1,000,000` | `size` | | USDC amount ÷ outcome-token amount | `price` | | `price` for outcome index `0`; otherwise `1 - price` | `normalized_price` | | Taker pays USDC | `taker_side = 'BUY'` | | Taker supplies outcome tokens | `taker_side = 'SELL'` | | USDC amount ÷ `1,000,000` | `taker_cash_flow`, `maker_cash_flow` | | Taker and maker wallet addresses | `taker_id`, `maker_id` | | Event fee ÷ `1,000,000` | `fee` | | Block number, transaction hash, log index | Source provenance fields | | Block timestamp | `timestamp` | Outcome index `0` is the reverse-alphabetically first normalized market outcome. For a typical Yes/No market, Yes is index `0` and No is index `1`. ## Polymarket perpetual trades Polymarket perpetual trades come from the perpetual product feed and link to markets with `market_type = 'PERPETUAL'`. | Polymarket perpetual source | Probalytics field | | - | - | | Instrument ID | `market_id`, `market_platform_id` through the linked market | | Trade ID | `id`, `platform_id` | | Synthetic Long outcome | `outcome` | | Quantity | `size` | | Instrument price | `price`, `normalized_price` | | `long` | `taker_side = 'BUY'` | | `short` | `taker_side = 'SELL'` | | `size × price` | `taker_cash_flow`, `maker_cash_flow` | | Source timestamp in milliseconds | `timestamp` | | Source transaction hash, when present | `metadata.tx_hash` | Participant IDs are `null`, and `fee` is `0` because the current source does not expose those values. ## Kalshi prediction-market trades ### Source These fills come from Kalshi trade records. Each record contains the market ticker, Yes and No prices, traded count, taker side, trade ID, and execution time. ### Field mapping | Kalshi source | Probalytics field | | - | - | | Market ticker | `market_id`, `market_platform_id` through the linked market | | Trade ID | `id`, `platform_id` | | `taker_side = 'yes'` | Yes `outcome`; `price = yes_price_dollars` | | `taker_side = 'no'` | No `outcome`; `price = no_price_dollars` | | `count_fp` | `size` | | `yes_price_dollars` | `normalized_price` | | Every current Kalshi prediction fill | `taker_side = 'BUY'` | | `size × price` | `taker_cash_flow`, `maker_cash_flow` | | `created_time` | `timestamp` | The source's Yes/No taker side selects which outcome was bought. It does not map to the stored BUY/SELL enum, so all current Kalshi prediction fills are stored as `BUY`. Participant IDs are `null`, and `fee` is `0` because the current trade source does not expose those values. Kalshi combo trades are indexed by a separate pipeline. It reads the same trade feed, keeps only trades whose ticker is a known [combo market](/docs/datasets/markets#kalshi-combo-markets), and applies the same mapping. Combo fills link to the combo market (`market_type = 'PARLAY'`), not to its leg markets. ## Kalshi margin trades Kalshi margin trades come from the margin product feed and link to markets with `market_type = 'PERPETUAL'`. | Kalshi margin source | Probalytics field | | - | - | | Margin ticker | `market_id`, `market_platform_id` through the linked market | | Trade ID | `id`, `platform_id` | | Synthetic Long outcome | `outcome` | | Count | `size` | | Instrument price | `price`, `normalized_price` | | `taker_side = 'bid'` | `taker_side = 'BUY'` | | `taker_side = 'ask'` | `taker_side = 'SELL'` | | `size × price` | `taker_cash_flow`, `maker_cash_flow` | | `created_time` | `timestamp` | | Product marker | `metadata.instrument_type = 'perpetual_future'` | Participant IDs are `null`, and `fee` is `0` because the current source does not expose those values. ## Reading fills across products * Join `market_id` to `markets.id` before interpreting price or size units. * Use `price` for the stored outcome's execution price. * Use `normalized_price` to create one outcome-0 price series for prediction markets. * Do not treat perpetual `normalized_price` as a probability. * Do not sum the cash-flow fields as signed P\&L; both currently store positive gross/notional values. See [Tables & Schemas](/docs/sql-guide/tables#fills) for access-specific database types and query behavior. # Markets Source: https://docs.probalytics.io/docs/datasets/markets The markets dataset shape, coverage, and venue-specific normalization rules ## Shape `markets` has one row per normalized market or instrument. Updates reuse the same `id`; in ClickHouse, `indexed_at` selects the newest version. | Field | Type | Values and meaning | | - | - | - | | `id` | `UUID` | Stable Probalytics market ID. Use this to join fills and orderbook snapshots. | | `platform` | `enum` | `POLYMARKET` or `KALSHI`. | | `platform_id` | `string` | Venue-native market identifier: Polymarket condition ID, Kalshi ticker, or perpetual instrument ID. | | `slug` | `string` | URL-friendly market name from platform metadata. For Kalshi, it is built from the platform's series title. | | `url` | `string` | Direct URL to the market on its platform. Always present. | | `title` | `string` | Market question, venue title, or instrument symbol. | | `description` | `string` | Market rules or description from platform metadata. | | `category` | `string` | Probalytics market category used for internal classification. Usually empty in the current dataset. | | `tags` | `array` | Probalytics tags used for internal classification. Usually empty in the current dataset. | | `market_type` | `enum` | `BINARY` — two-sided prediction market `SCALAR` — numeric settlement `PARLAY` — multi-leg market `PERPETUAL` — perpetual or margin instrument `MULTIPLE` — mutually exclusive multi-outcome product | | `legs` | `array` | Component selections of a `PARLAY` market. Each leg contains `market_id` (UUID), `market_platform_id` (string), `outcome_id` (UUID), and `outcome_platform_id` (string). Empty for every other market type. | | `outcomes` | `array` | All normalized outcomes. Each outcome contains `id` (UUID), `platform_id` (string), `name` (string), and zero-based `index` (integer). | | `created_at` | `datetime` | Source creation time in UTC. Perpetual and margin instruments currently use the product reference epochs documented below. | | `opened_at` | `datetime \| null` | Time trading opened. | | `closes_at` | `datetime \| null` | Time trading closes or closed. | | `resolves_at` | `datetime \| null` | Expected or recorded resolution time. | | `end_date` | `datetime \| null` | Event end/reference time. This can be the same source timestamp as `closes_at`. | | `reset_at` | `datetime \| null` | Reset or void time when supplied. | | `status` | `enum` | `PENDING`, `ACTIVE`, `PAUSED`, `CLOSED`, or `RESOLVED`. Venue mappings are listed below. | | `resolution_type` | `enum \| null` | `STANDARD`: one winning outcome. `SPLIT`: payouts divided across outcomes. `VOID`: voided/cancelled. `null`: unresolved or unavailable. | | `resolution_winning_outcome_id` | `UUID \| null` | Winning `outcomes.id` for a standard resolution. Usually `null` for split and void resolutions. | | `resolution_outcome_payouts` | `array` | Exact settlement values. Each item contains `outcome_id` (UUID) and `payout` (decimal). Empty before resolution or when payout data is unavailable. | | `resolution_resolved_by` | `string \| null` | Resolver or source identifier, such as `kalshi` or a Polymarket resolver value. | | `resolution_resolved_at` | `datetime \| null` | Recorded resolution time in UTC. | | `resolution_source_block_number` | `integer \| null` | Resolution block number when the resolution came from a chain source. API-derived resolutions can contain `0` or `null`. | | `resolution_source_tx_hash` | `string \| null` | Resolution transaction hash when supplied. Empty or `null` for API-derived resolutions. | | `source_block_number` | `integer` | Source block number. `0` for current API-derived market rows. | | `source_tx_hash` | `string` | Source transaction hash. Empty when unavailable. | | `indexed_at` | `datetime` | Time Probalytics wrote this version. The newest value wins for the same market ID. | ## Coverage by venue and product | Venue | Product | `market_type` | Markets | Coverage starts | | - | - | -: | -: | - | | Polymarket | Binary prediction markets | `BINARY` | 2,715,016 | 2020-10-02 | | Polymarket | Scalar prediction markets | `SCALAR` | 71 | 2020-10-02 | | Polymarket | Perpetuals | `PERPETUAL` | 52 | 2026-07-01 (reference epoch) | | Kalshi | Binary prediction markets | `BINARY` | 13,986,711 | 2021-07-02 | | Kalshi | Scalar prediction markets | `SCALAR` | 30,273 | 2023-11-30 | | Kalshi | Combo markets (multivariate events) | `PARLAY` | 220,314,965 | 2025-09-17 | | Kalshi | Margin instruments | `PERPETUAL` | 16 | 2026-06-17 (reference epoch) | Counts as of 2026-08-24 17:34 UTC, queried from `markets FINAL` and grouped by `platform` and `market_type`. Coverage starts use the earliest `created_at`; perpetual and margin rows currently use fixed product reference epochs. Kalshi combo count as of 2026-10-17. > [!WARNING] > > Always filter `markets` by `market_type` (and `platform`). Kalshi combo markets make up over 90% of the table, so a query without a `market_type` filter scans hundreds of millions of rows even when you only want binary markets. When joining to `markets`, filter it in a subquery first; a bare `JOIN markets` loads the whole table into memory. Markets are indexed continuously, so these counts change throughout the day. Query the data warehouse for current values: ```sql theme={null} SELECT platform, market_type, count() AS markets, min(created_at) AS earliest_created_at FROM markets FINAL GROUP BY platform, market_type ORDER BY platform, market_type; ``` ## Polymarket prediction markets ### Source Market and event metadata comes from Gamma. This supplies the question, description, URL slugs, lifecycle dates, outcome names, outcome token IDs, and settled outcome prices. ### Identity and outcomes * `platform_id` uses the condition ID. If it is missing, the Gamma market ID is used. * `id` is generated deterministically from `platform_id`. * Outcomes are sorted reverse-alphabetically before indexes are assigned. * Each outcome token ID becomes `outcomes.platform_id` and is used to generate the outcome UUID. For a typical Yes/No market, reverse-alphabetical ordering makes **Yes outcome 0** and **No outcome 1**. Read the stored outcome names and indexes instead of assuming source array order. ### Status mapping Rules are evaluated from top to bottom: | Gamma state | Probalytics `status` | | - | - | | `closed = true` | `RESOLVED` | | otherwise `archived = true` | `CLOSED` | | otherwise `active = false` | `PENDING` | | otherwise | `ACTIVE` | ### Lifecycle mapping | Gamma source | Probalytics field | | - | - | | `createdAt` | `created_at` | | `startDate` | `opened_at` | | `endDate` | `end_date` | | `endDate` | `closes_at` | | `endDate`, with resolved time as a fallback | `resolves_at` | ### Resolution mapping Gamma does not expose one normalized winner field. For a closed market, settled `outcomePrices` become payout values: | Settled payouts | Result | | - | - | | One outcome has payout `1` | `STANDARD`, with that outcome as the winner | | All payouts sum to `0` | `VOID` | | Any other payout combination | `SPLIT` | These rows come from Gamma rather than market-creation chain events, so `source_block_number` is normally `0` and `source_tx_hash` is normally empty. ## Polymarket perpetuals Polymarket perpetual instruments use a separate product feed and remain under `platform = 'POLYMARKET'`. | Field | Value or rule | | - | - | | `platform_id` | Numeric venue instrument ID as a string | | `title` | Instrument symbol; falls back to the instrument ID | | `market_type` | `PERPETUAL` | | `outcomes` | One synthetic `Long` outcome at index `0` | | `created_at` | Fixed product reference epoch: 2026-07-01 | | `status` | `ACTIVE` | | `description` | Empty | The source also provides base/quote assets, funding interval, and price/quantity decimal metadata. Those attributes are used internally but are not currently columns in the public `markets` table. ## Kalshi prediction markets ### Source Kalshi market records are enriched with event and series metadata. The result combines the market ticker and rules with the related series title, category, and URL structure. ### Identity and outcomes * The venue ticker becomes `platform_id`. * `id` is generated deterministically from the ticker. * `Yes` is always outcome index `0`; `No` is outcome index `1`. * Outcome UUIDs are generated deterministically from the market UUID and normalized side name. ### Display-field fallbacks `title` uses the first non-empty value in this order: 1. title; 2. subtitle; 3. Yes subtitle; 4. No subtitle; 5. ticker. `description` joins primary and secondary rules. `slug` comes from the series title, and the market URL is constructed from the series and market tickers. ### Type mapping | Kalshi source | Probalytics `market_type` | | - | - | | Market type or result is scalar | `SCALAR` | | Otherwise | `BINARY` | ### Status mapping | Kalshi status | Probalytics `status` | | - | - | | `active`, `open` | `ACTIVE` | | `initialized`, `inactive` | `PENDING` | | `closed` | `CLOSED` | | `determined`, `finalized`, `settled` | `RESOLVED` | | `paused`, `disputed`, `amended` | `PAUSED` | | Any other value | `PENDING` | ### Lifecycle mapping | Kalshi source | Probalytics field | | - | - | | `created_time` | `created_at` | | `open_time` | `opened_at` | | `close_time` | `closes_at` | | `close_time` | `end_date` | | `expiration_time` | `resolves_at` | ### Resolution mapping Resolution uses the most precise available source field: 1. `void` creates zero payouts and `resolution_type = 'VOID'`; 2. `settlement_value_dollars` sets the Yes payout directly and No payout to `1 - value`; 3. a Yes/No result creates `1`/`0` payouts; 4. a scalar result can be derived by comparing expiration value with the strike; 5. if the required scalar inputs are missing, payout data remains empty. `resolution_resolved_at` uses settlement time when present, otherwise expiration time. `resolution_resolved_by` is `kalshi`. Combo markets are excluded from this path and are documented in [Kalshi combo markets](#kalshi-combo-markets). ## Kalshi combo markets Kalshi combos (multivariate events) are built from a user's selection of legs inside an MVE collection. They are indexed by a dedicated pipeline and stored as `market_type = 'PARLAY'`. Identify them by `market_type`, not by ticker prefix. ### Source Each combo market record references its MVE collection. The collection supplies the series ticker, and the series supplies the title, category, and URL structure, exactly as for prediction markets. Records without a collection ticker, without a ticker, or with a leg missing its market ticker or side are dropped. ### Field mapping All fields follow the [Kalshi prediction-market](#kalshi-prediction-markets) rules, with two differences: | Field | Value or rule | | - | - | | `market_type` | Always `PARLAY` | | `legs` | One entry per selected leg, in source order | Leg mapping: | Kalshi leg field | Probalytics leg field | | - | - | | `market_ticker` | `market_platform_id` | | Generated from `market_ticker` | `market_id` (same UUID as that market's `markets.id`) | | `side`, lowercased (`yes` or `no`) | `outcome_platform_id` | | Generated from leg market ID and side | `outcome_id` (same UUID as the matching `markets.outcomes.id`) | The combo itself has the usual `Yes` (index `0`) and `No` (index `1`) outcomes. Its fills and [orderbook snapshots](/docs/datasets/orderbook#kalshi-combo-books) link to the combo's `id`, not to the leg markets. To expand a combo into its legs: ```sql theme={null} SELECT m.platform_id AS combo, leg.market_platform_id AS leg_market, leg.outcome_platform_id AS leg_side FROM markets AS m FINAL ARRAY JOIN m.legs AS leg WHERE m.platform = 'KALSHI' AND m.market_type = 'PARLAY' LIMIT 100; ``` ## Kalshi margin instruments Kalshi margin instruments use a separate product feed and remain under `platform = 'KALSHI'`. | Field | Value or rule | | - | - | | `platform_id` | Venue margin ticker | | `title` | Venue title; falls back to the ticker | | `market_type` | `PERPETUAL` | | `outcomes` | One synthetic `Long` outcome at index `0` | | `created_at` | Fixed product reference epoch: 2026-06-17 | | `description` | Empty | | `status` | Mapped from the margin product state | Margin status mapping: | Kalshi margin status | Probalytics `status` | | - | - | | `active`, `open` | `ACTIVE` | | `closed` | `CLOSED` | | `settled`, `resolved` | `RESOLVED` | | `paused`, `inactive` | `PAUSED` | | Any other value | `PENDING` | The source contract size, tick size, and fractional-trading flag are used internally but are not currently columns in the public `markets` table. ## Querying the latest market version ClickHouse replaces rows by `(platform, id)` and keeps the greatest `indexed_at` during background merges. Use `FINAL` when a query must see exactly one current version per market: ```sql theme={null} SELECT * FROM markets FINAL WHERE platform = 'KALSHI' AND market_type = 'BINARY' -- always filter by market_type; combos dominate the table LIMIT 100; ``` Join fills and orderbook snapshots with `markets.id`, filtering `markets` by `platform` and `market_type` in a subquery before the join: ```sql theme={null} SELECT f.timestamp, f.price, f.size, m.title FROM fills AS f JOIN ( SELECT id, title FROM markets WHERE platform = 'KALSHI' AND market_type = 'BINARY' ) AS m ON f.market_id = m.id WHERE f.platform = 'KALSHI' AND f.timestamp >= now() - INTERVAL 1 DAY LIMIT 100; ``` Use `platform_id` when you need the venue's native identifier. See [Tables & Schemas](/docs/sql-guide/tables#markets) for the ClickHouse column types. # Orderbook Snapshots Source: https://docs.probalytics.io/docs/datasets/orderbook The orderbook dataset shape, coverage, reconstruction, and usage rules ## Shape Each row is the complete orderbook for one market outcome at one source timestamp. It replaces both sides of the previous book; it is not a level update. Orderbook snapshots are event-driven, not sampled at a fixed interval. Probalytics processes the venue's ordered event stream, applies each change to the reconstructed book, and publishes a new complete snapshot when the book changes. `VERIFIED` snapshots are thoroughly checked and guarantee that the orderbook is correct. A quiet market can therefore have a long time between rows without any missing data. > [!NOTE] > > Orderbook reconstruction has more moving parts than our other datasets. If anything here is unclear, ask us in the [Probalytics Telegram channel](https://t.me/probalytics) or email [support@probalytics.io](mailto:support@probalytics.io). Include the `market_id`, `outcome.id`, and time range when asking about a specific series. | Field | Type | Values and meaning | | - | - | - | | `market_id` | `UUID` | Probalytics market ID. Join this to `markets.id`. | | `market_platform_id` | `string` | Venue-native market identifier copied from the linked market. | | `platform` | `enum` | `POLYMARKET` or `KALSHI`. | | `outcome` | `Outcome` | The outcome whose book is represented. Contains `id` (UUID), `platform_id` (string), `name` (string), and zero-based `index` (integer). | | `bids` | `array` | Complete bid side, sorted from highest to lowest price. Each level contains `price` (decimal) and aggregate `size` (decimal). | | `asks` | `array` | Complete ask side, sorted from lowest to highest price. Each level contains `price` (decimal) and aggregate `size` (decimal). | | `timestamp` | `datetime` | Source event time represented by the book. Different books can share the same timestamp. | | `indexed_at` | `datetime` | Time Probalytics materialized this row. Use it to inspect delivery timing and choose the newest copy of the same row identity. | | `hash` | `integer` | Probalytics content hash for row identity and deduplication. It is not a venue hash or a cryptographic proof. | | `state` | `enum` | `VERIFIED` — final snapshot in a processed update sequence; Probalytics guarantees that this orderbook snapshot was reconstructed with no loss `INTERMEDIATE` — earlier book state retained from that same sequence | | `continuity` | `enum` | `CONTIGUOUS` — proven to follow the preceding published row for this outcome `RESET` — the first published row for this outcome, or a later row whose connection to the preceding published row could not be proven. The row is still a complete orderbook and can be used on its own. | | `path_index` | `integer` | Zero-based order within one emitted path. Several rows with the same `timestamp` are ordered by this field. It is not a global sequence number. | ## Reading a snapshot Every row is a complete, independently usable orderbook. `bids` contains all bids present at that moment, and `asks` contains all asks. You do not need to apply the row to an earlier snapshot or reconstruct missing levels. An empty `bids` or `asks` array means there were no orders on that side of the book. It does not mean “unchanged.” Ordering matters when building a time series: 1. Read one `(market_id, outcome.id)` series at a time. 2. Order snapshots by `timestamp`, then `path_index`. 3. If duplicate copies of the same snapshot exist, keep the one with the latest `indexed_at`. 4. When `continuity = RESET`, treat that row as a fresh starting point. If an earlier row exists, do not calculate a change between the two rows or forward-fill values from the earlier row. Continue normally from the `RESET` row. ## State and continuity `state` and `continuity` answer different questions: * `state`: how was this row validated within its emitted path? * `continuity`: can this path be connected to the previously published dataset state? ### Ordering rows Read one `(market_id, outcome.id)` series at a time and order it by `timestamp`, then `path_index`. Several reconstructed states can share a timestamp; `path_index` orders those states and starts again at `0` for the next update sequence. `indexed_at` is not source-event order. If the same row identity was written more than once, keep the copy with the latest `indexed_at`. `RESET` means Probalytics cannot connect this row to a preceding published row. It does not describe whether the current row is final or prove that data is missing. The first published row for every outcome is always `RESET` because no earlier row exists. For a later reset, the connection to the preceding published row could not be proven. That is why the first row after a continuity break can be `INTERMEDIATE + RESET`, followed by `VERIFIED + CONTIGUOUS` in the same update sequence. | `state` | `continuity` | How to read the row | | - | - | - | | `VERIFIED` | `CONTIGUOUS` | Orderbook reconstructed without gaps, with a proven link to the preceding published state. | | `VERIFIED` | `RESET` | Orderbook reconstructed without gaps, but it cannot be connected to a preceding published row. It can be the outcome's first row or a later fresh starting point. | | `INTERMEDIATE` | `CONTIGUOUS` | Earlier retained book state from an update sequence that produced a `VERIFIED` final snapshot. | | `INTERMEDIATE` | `RESET` | First retained book state after continuity was restarted. A later row in the same update sequence can be verified and contiguous. | ### Choosing rows by use case | Use case | Rows to use | | - | - | | Latest gap-free book | Latest `VERIFIED` row for each outcome | | Final snapshots only | `state = VERIFIED` | | Every reconstructed book transition | Both `INTERMEDIATE` and `VERIFIED` | | Gap-sensitive research | Do not calculate changes across a `RESET`; continue from the reset row | | Reset or feed-quality analysis | Do not use a raw reset count as a gap count. Separate each outcome's initial reset from later resets, then investigate later resets in context. | `INTERMEDIATE` does not mean provisional or expected to disappear. These rows are published only after the final snapshot in their update sequence passes validation. ### What continuity does not mean `CONTIGUOUS` does not mean rows arrive at regular intervals. An inactive market can remain unchanged for hours and then continue with a proven transition. `RESET` marks a fresh starting point, not necessarily a data gap. Every outcome contributes one expected reset when its first snapshot is published. Later resets mean only that Probalytics could not prove the transition from the previous published state; they do not tell you whether venue events were missed or how many. Causes can include processor replacement, a source sequence gap, an update that cannot be applied, or recovery from a fresh full book. To classify a reset, check whether an earlier snapshot exists for the same `(market_id, outcome.id)`. If no earlier snapshot exists, this is the expected initialization reset. If an earlier snapshot exists, do not calculate a change between that row and the reset row. A query restricted to a date range can hide the earlier row, so it cannot classify the first reset in the result by itself. ## Timestamp, path order, and identity Several reconstructed states can share one source timestamp: ```text theme={null} timestamp=T, path_index=0, state=INTERMEDIATE timestamp=T, path_index=1, state=INTERMEDIATE timestamp=T, path_index=2, state=VERIFIED ``` Do not deduplicate by timestamp alone. Different books at the same timestamp are valid distinct rows. The logical row identity is: ```text theme={null} market_id, outcome.id, timestamp, hash, state, continuity, path_index ``` If the same identity appears more than once, keep the copy with the greatest `indexed_at`. ### `timestamp` versus `indexed_at` * Use `timestamp` to order source events. * Use `path_index` to order reconstructed states sharing one timestamp. * Use `indexed_at` as the final tiebreaker and to see when Probalytics produced the row. `indexed_at - timestamp` is observed delivery delay. It includes source-clock differences, buffering, reconstruction, and recovery—not only network time. Recovery can also publish an older source state later, so `indexed_at` must not replace event ordering. ## Hash `hash` is a Probalytics 64-bit content hash. It covers: * `market_id`; * `outcome.id`; * `timestamp`; * every published bid price and size; * every published ask price and size. It does not include `indexed_at`, `state`, `continuity`, `path_index`, or platform metadata. The stored `hash` is separate from the hash supplied by Polymarket. Polymarket verification happens before the normalized row is produced; the stored hash identifies the normalized row. ## Price and size precision Published orderbook prices and sizes are stored as decimal values with six digits after the decimal point. Use decimal values rather than binary floating point when exact level comparisons or hash reproduction matter. Prediction-market prices are normally between `0` and `1`. Perpetual and margin prices use venue instrument units. Join `market_id` to markets and inspect `market_type` before combining products. ## Coverage by venue and product | Venue | Product | Snapshots | Markets | Coverage starts | Notes | | - | - | -: | -: | - | - | | Polymarket | Prediction-market books | 83,248,715,002 | 2,380,433 | 2025-11-20 | Data before 2026-02-17 can have lower capture frequency and gaps. High-quality, high-frequency reconstruction begins 2026-02-17. | | Polymarket | Perpetual books | 1,264,049,214 | 67 | 2026-07-11 | Every published source frame is already a complete book. | | Kalshi | Prediction-market books | 51,835,309,511 | 3,426,492 | 2026-05-09 | Yes and No books are published together for each reconstructed state. | | Kalshi | Combo books | 224,563,754 | 10,165,339 | 2026-10-07 | Only combos seen with a resting order are subscribed. See [Kalshi combo books](#kalshi-combo-books). | | Kalshi | Margin books | 974,713,894 | 13 | 2026-06-19 | Full books and changes are reconstructed using source ordering. | Counts as of 2026-08-27 11:59 UTC. Coverage starts use the earliest source `timestamp`. Prediction and perpetual/margin rows are separated using the linked market's `market_type`. Kalshi combo snapshot count as of 2026-10-17, market count as of 2026-10-18. Orderbook rows are produced when a book changes, not on a fixed timer. An inactive market can therefore have long intervals with no rows. The dataset updates continuously, so these values change throughout the day. Query the data warehouse for current values: ```sql theme={null} SELECT s.platform, if(m.is_perpetual = 1, 'PERPETUAL', 'PREDICTION') AS product, count() AS snapshots, uniqExact(s.market_id) AS markets, min(s.timestamp) AS earliest_snapshot FROM orderbook_snapshots AS s LEFT ANY JOIN ( SELECT id, platform, toUInt8(1) AS is_perpetual FROM markets FINAL WHERE market_type = 'PERPETUAL' ) AS m ON s.market_id = m.id AND s.platform = m.platform GROUP BY s.platform, product ORDER BY s.platform, product; ``` ## Polymarket prediction-market books ### Source and reconstruction | Polymarket input | How Probalytics uses it | | - | - | | Full book | Initializes or replaces the reconstructed book for one outcome asset | | Price-level change | Applies the change to the reconstructed book and produces a new complete book state | | Trade or tick-size change | Advances the ordered event sequence used to reconstruct the next book state | | Venue-provided book hash | Compared with the hash calculated from the final reconstructed book | Each outcome asset has its own published row. Multiple source connections are reconstructed independently. Equivalent states are deduplicated, and a healthy source can continue publication when its state is anchored to the last published book. ### What `VERIFIED` means for Polymarket prediction markets `VERIFIED` guarantees that the orderbook was reconstructed without gaps. For Polymarket prediction markets, the final reconstructed book must reproduce the venue-provided book hash. `INTERMEDIATE` rows are earlier book states from that same verified update sequence. `continuity` remains separate. A `VERIFIED + RESET` row matches the venue hash, but its connection to the preceding published row cannot be proven. Treat it as a fresh starting point. ## Polymarket perpetual books ### Source and reconstruction Each published source frame contains the complete bid and ask book for one instrument. Probalytics publishes it against the instrument's synthetic `Long` outcome. | Polymarket perpetual input | How Probalytics uses it | | - | - | | Instrument ID | `market_id`, `market_platform_id` through the linked market | | Full bids | Complete `bids` array | | Full asks | Complete `asks` array | | Source timestamp | `timestamp` | ### What `VERIFIED` means for Polymarket perpetuals Every source frame is already a complete book, so a published frame is `VERIFIED` without reconstructing it from level changes or comparing a book hash. The first frame for an instrument starts with `continuity = RESET`; later frames are `CONTIGUOUS` while the processor retains that instrument's published state. ## Kalshi prediction-market books ### Source and reconstruction Kalshi supplies bid books for Yes and No. Probalytics publishes one conventional two-sided book for each outcome. ```text theme={null} Yes ask price = 1 - No bid price No ask price = 1 - Yes bid price ``` The size at the opposing bid becomes the size at the derived ask. Kalshi asks are therefore derived from the opposite outcome's bids, not supplied as independent ask orders. | Kalshi input | How Probalytics uses it | | - | - | | Yes bid levels in a full snapshot | Publishes them as Yes `bids` and uses them to derive No `asks` | | No bid levels in a full snapshot | Publishes them as No `bids` and uses them to derive Yes `asks` | | A Yes or No bid-level change | Applies the change, recalculates the derived ask side, and produces new complete Yes and No books | | Source sequence number | Orders source messages; a detected gap makes that source stream unhealthy until a fresh full snapshot arrives | ### What `VERIFIED` means for Kalshi prediction markets `VERIFIED` guarantees that the orderbook was reconstructed without gaps. If Probalytics detects a source sequence gap or cannot apply a change, it stops publishing from that source stream until a fresh full snapshot rebuilds the book. `continuity` answers a separate question. A `VERIFIED + RESET` row is gap-free itself, but Probalytics cannot prove that it connects to the preceding published row. Treat it as a fresh starting point. This can happen during processor redeployments, service downtime, software updates, or recovery from a fresh full book. The Yes and No rows for one reconstructed state share the same `timestamp` and `path_index`. A market-level reset therefore normally appears as two rows - one for each outcome. ## Kalshi combo books ### Which combos are captured Kalshi has about 12 million open [combo markets](/docs/datasets/markets#kalshi-combo-markets) at any time, and about 99% of them never hold an order. Probalytics therefore subscribes to a combo's orderbook only while the combo is being quoted: | Step | Rule | | - | - | | Discovery | Probalytics follows Kalshi's `ticker` channel for all markets. A combo whose ticker starts with `KXMVE` is added the first time its ticker shows a resting order: a Yes bid above `0`, or a Yes ask above `0` and below `1`. Kalshi reports a Yes ask of exactly `1` when there is no No bid. Combos with other ticker prefixes are not currently captured. | | Subscription | The combo's orderbook is subscribed about 1 second after discovery. Kalshi answers with a full snapshot, which starts the book with `continuity = RESET`. | | Retention | Each orderbook change (delta) keeps the subscription alive. The 4-hour expiry is rewritten at most once every 10 minutes per combo, so a combo is dropped between 3 hours 50 minutes and 4 hours after its last change. Snapshots and new quotes on the `ticker` channel do not extend it. | | Removal | A combo is unsubscribed when its subscription expires, or as soon as Kalshi's `multivariate_market_lifecycle` channel reports it `determined` or `settled`. | | Re-entry | A removed combo is subscribed again the next time its ticker shows a resting order. It restarts with a fresh full snapshot and `continuity = RESET`. | What this means for coverage: * A combo with no rows was never seen with a resting order. * Book activity before a combo's first row is not captured. An order placed and cancelled before the subscription takes effect has no row. * Book activity after a combo goes 4 hours without a change is captured only from its next quote, and the resumed book starts with `RESET`. ### Source and reconstruction Once subscribed, a combo book uses exactly the same source messages, Yes/No ask derivation, sequence handling, and `VERIFIED`/`continuity` rules as [Kalshi prediction-market books](#kalshi-prediction-market-books). When a sequence gap or an inapplicable change is detected, Probalytics requests a fresh full snapshot for that combo and resumes publication from it. Combo rows link to the combo itself: `market_id` is generated from the combo ticker, and the outcomes are the combo's `Yes` (index `0`) and `No` (index `1`). Leg markets do not receive rows from combo books. Rows are written without waiting for the combo's `markets` row, so a snapshot can briefly exist before its market is indexed. Use a `LEFT JOIN` to `markets` when completeness matters. ## Kalshi margin books ### Source and reconstruction Kalshi margin supplies full bid/ask books and subsequent level changes for each instrument. Probalytics publishes the reconstructed book against the instrument's synthetic `Long` outcome. | Kalshi margin input | How Probalytics uses it | | - | - | | Margin ticker | `market_id`, `market_platform_id` through the linked market | | Full bids and asks | Initializes or replaces the reconstructed book | | Bid or ask level change | Applies the change to the specified side and produces a new complete book | | Source sequence number | Orders source messages; a detected gap makes that source stream unhealthy until a fresh full snapshot arrives | ### What `VERIFIED` means for Kalshi margin Kalshi margin uses the same `VERIFIED` and `continuity` rules as Kalshi prediction-market books. ## Historical rows Some quality fields were added after the first orderbook rows were stored. Older rows can contain these compatibility values: | Field | Historical value | | - | - | | `hash` | `0` | | `path_index` | `0` | Historical `VERIFIED` rows were also checked to ensure that their orderbooks were reconstructed without gaps. The `hash = 0` and `path_index = 0` values only indicate that those fields were not recorded when the rows were originally written. See [Tables & Schemas](/docs/sql-guide/tables#orderbook_snapshots) for access-specific database types and query examples. # Datasets Source: https://docs.probalytics.io/docs/datasets/overview Coverage, construction, and interpretation of Probalytics datasets Probalytics combines venue data into four normalized datasets. Choose a dataset to see its coverage, source inputs, normalization rules, field meanings, and known limitations. > **[Markets](/docs/datasets/markets)** > > Market identity, outcomes, lifecycle, and resolution metadata > **[Fills (Trades)](/docs/datasets/fills)** > > Executions, prices, sizes, sides, participants, fees, and cash flow > **[Orderbook](/docs/datasets/orderbook)** > > Full-depth books, reconstruction, validation, and continuity > **[RFQs](/docs/datasets/rfqs)** > > Kalshi request-for-quote creation and deletion events (early access) ## Understanding coverage Each dataset page tells you: * which platforms and products are included; * when the available history begins; * where the data comes from; * how source data is transformed into Probalytics fields; * which fields or records are not available. Your plan controls which datasets you can query and how much history you can access. **All retained history** means the complete period Probalytics currently stores for that dataset. It may begin later than the exchange itself. > [!TIP] > > If your query begins later than the coverage date shown on a dataset page, your account may have a shorter history window. If you should have access to more, please contact [support@probalytics.io](mailto:support@probalytics.io). # RFQs Source: https://docs.probalytics.io/docs/datasets/rfqs Kalshi request-for-quote events: shape, coverage, and normalization rules > [!NOTE] > > RFQs are an **early access** dataset and are not included in standard plans. To request access, email [support@probalytics.io](mailto:support@probalytics.io). ## Shape `rfqs` has one row per request-for-quote lifecycle event. An RFQ is a request by a Kalshi user for quotes on a market, usually a [combo market](/docs/datasets/markets#kalshi-combo-markets). Each RFQ produces a `CREATED` row and, once it is withdrawn or expires, a `DELETED` row with the same `id`. | Field | Type | Values and meaning | | - | - | - | | `id` | `UUID` | Stable Probalytics RFQ ID, generated deterministically from the Kalshi RFQ ID. Shared by the `CREATED` and `DELETED` rows. | | `platform` | `enum` | `KALSHI`. | | `platform_id` | `string` | Kalshi RFQ ID. | | `event_type` | `enum` | `CREATED` — RFQ opened `DELETED` — RFQ removed | | `market_id` | `UUID` | Requested market. Joins to `markets.id`. | | `market_platform_id` | `string` | Requested market's Kalshi ticker. | | `creator_id` | `string` | Kalshi's identifier for the requesting user. | | `contracts` | `decimal \| null` | Requested number of contracts, when the request is sized in contracts. | | `target_cost` | `decimal \| null` | Requested cost in USD, when the request is sized in dollars. | | `timestamp` | `datetime` | Source time in UTC: creation time for `CREATED`, deletion time for `DELETED`. | | `indexed_at` | `datetime` | Time Probalytics wrote this row. | ## Coverage | Venue | Product | Rows | Coverage starts | | - | - | -: | - | | Kalshi | RFQs | 1,100,200,509 | 2026-10-14 | Count as of 2026-10-18. Each RFQ contributes one `CREATED` row and, once removed, one `DELETED` row, so the row count is roughly twice the number of RFQs. RFQs are captured live from Kalshi's communications WebSocket channel. Kalshi does not provide RFQ history, so there is no data before capture started, and RFQs created during a capture outage are not backfilled. Only RFQ creation and deletion are recorded. Quotes submitted in response to an RFQ are not included; executed trades appear in [fills](/docs/datasets/fills). ## Normalization | Kalshi source | Probalytics field | | - | - | | `id` | `platform_id`; also the input for `id` | | `market_ticker` | `market_platform_id`; also the input for `market_id` | | `creator_id` | `creator_id` | | `contracts_fp` | `contracts` | | `target_cost_dollars` | `target_cost` | | `created_ts` | `timestamp` on `CREATED` rows | | `deleted_ts` | `timestamp` on `DELETED` rows | Empty size fields become `null`. Events without the timestamp for their event type are dropped. ## Querying RFQs Pair each RFQ with its deletion to measure how long it stayed open: ```sql theme={null} SELECT id, any(market_platform_id) AS market, minIf(timestamp, event_type = 'CREATED') AS created, minIf(timestamp, event_type = 'DELETED') AS deleted, dateDiff('second', created, deleted) AS open_seconds FROM rfqs FINAL WHERE timestamp >= now() - INTERVAL 1 DAY GROUP BY id HAVING countIf(event_type = 'CREATED') > 0 AND countIf(event_type = 'DELETED') > 0 LIMIT 100; ``` Join `market_id` to `markets.id` to read the requested combo and its `legs`. An RFQ can reference a market that has not been indexed yet, so use a `LEFT JOIN` when completeness matters. See [Tables & Schemas](/docs/sql-guide/tables#rfqs) for the ClickHouse column types. # S3 Data Files Source: https://docs.probalytics.io/docs/file-downloads/overview Download bulk Parquet exports of markets, fills, and orderbook snapshots over S3 Bulk exports of the Probalytics datasets as Parquet files. They're served from an S3-compatible endpoint, so you can use the AWS CLI, boto3, curl, or any other S3 client. Use them to backfill, for local research, or to load into your own warehouse. | Dataset | Period | One file per | | - | - | - | | Markets | Monthly | Platform and calendar month of market creation | | Fills | Daily and weekly | Platform and UTC day, or Monday–Sunday week | | Orderbook snapshots | Daily | Platform and UTC day | ## Access S3 Data Files are included in paid **Pro**, **Orderbook**, and **Custom** plans. They aren't available during a trial. Your Probalytics API key is your S3 credential: | S3 setting | Value | | - | - | | Access key ID | API Key ID (`api_...`) | | Secret access key | API Key Secret (`sk_...`) | | Endpoint | `https://s3.probalytics.io` | | Region | `hel1` | | Bucket | `probalytics-data` | | Addressing | Path-style | To create a key, see the [Quickstart](/docs/quickstart). If an older key is rejected, create a new one. Access is read-only: you can list and download objects. ## Browse in the app Log into [app.probalytics.io](https://app.probalytics.io) and open **S3 Data Files**. You can filter the catalog by platform, type, and period, or search by filename. Each row shows the file's size and row count. Files are not downloaded through the browser. Click a row's download button, or select several rows and click **Download**, to get a ready-to-run cURL, AWS CLI, or Python snippet for those files. ## Object layout ``` datasets/{dataset}/{platform}/{period}/parquet/{date_path}/{filename} ``` | Dataset | Object key example | | - | - | | Fills, daily | `datasets/fills/polymarket/daily/parquet/2026/10/07/fills_polymarket_2026-10-07.parquet` | | Fills, weekly | `datasets/fills/kalshi/weekly/parquet/2026/10/fills_kalshi_2026-09-28_to_2026-10-04.parquet` | | Markets, monthly | `datasets/markets/polymarket/monthly/parquet/2026/09/markets_polymarket_2026-09-01_to_2026-09-30.parquet` | | Orderbook, daily | `datasets/orderbook_snapshots/kalshi/daily/parquet/2026/10/07/orderbook_snapshots_kalshi_2026-10-07.parquet` | * `{platform}` is `polymarket` or `kalshi`. * For daily files, `{date_path}` is `YYYY/MM/DD`. For weekly and monthly files it's `YYYY/MM`, taken from the **last** day of the period. A week that crosses a month boundary is filed under the month it ends in. * Filenames are deterministic. A daily filename contains its date. Weekly and monthly filenames contain an inclusive `start_to_end` date range. * Periods with no rows have no file. ## Download The examples set credentials once through the standard AWS environment variables: ```bash theme={null} export AWS_ACCESS_KEY_ID='api_...' export AWS_SECRET_ACCESS_KEY='sk_...' ``` **AWS CLI** ```bash theme={null} # List what's available aws s3 ls --endpoint-url https://s3.probalytics.io --region hel1 \ s3://probalytics-data/datasets/fills/polymarket/daily/parquet/2026/10/ # Download one file aws s3 cp --endpoint-url https://s3.probalytics.io --region hel1 \ s3://probalytics-data/datasets/fills/polymarket/daily/parquet/2026/10/07/fills_polymarket_2026-10-07.parquet . # Download a whole month of daily files aws s3 cp --recursive --endpoint-url https://s3.probalytics.io --region hel1 \ s3://probalytics-data/datasets/fills/polymarket/daily/parquet/2026/09/ ./fills-2026-09/ ``` **Python** ```python theme={null} import boto3 s3 = boto3.client( "s3", endpoint_url="https://s3.probalytics.io", region_name="hel1", # Reads AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY from the environment. ) bucket = "probalytics-data" prefix = "datasets/fills/polymarket/daily/parquet/2026/09/" for page in s3.get_paginator("list_objects_v2").paginate(Bucket=bucket, Prefix=prefix): for obj in page.get("Contents", []): filename = obj["Key"].rsplit("/", 1)[-1] s3.download_file(bucket, obj["Key"], filename) print(filename, obj["Size"]) ``` **cURL** Requires curl 7.75 or later for SigV4 signing. ```bash theme={null} curl --aws-sigv4 "aws:amz:hel1:s3" \ --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" \ "https://s3.probalytics.io/probalytics-data/datasets/fills/polymarket/daily/parquet/2026/10/07/fills_polymarket_2026-10-07.parquet" \ -o fills_polymarket_2026-10-07.parquet ``` ## File format Files are standard Parquet with internal ZSTD compression and no outer gzip. Any Parquet reader can open them directly. ```python theme={null} import polars as pl fills = pl.read_parquet("fills_polymarket_2026-10-07.parquet") print(fills.schema) ``` The columns match the ClickHouse tables documented in the [SQL tables reference](/docs/sql-guide/tables) and the [Datasets](/docs/datasets/overview) pages, with these differences: * UUID columns (`id`, `market_id`, and the IDs inside `outcome`, `outcomes`, `legs`, and `resolution_outcome_payouts`) are written as strings. * `outcome` and `outcomes` are Parquet structs with `id`, `platform_id`, `name`, and `index` fields. * Rows are deduplicated, so each row identity appears once. | Dataset | Rows included | Sort order | | - | - | - | | Markets | Markets whose `created_at` falls in the month | `created_at`, `id` | | Fills | Fills whose `timestamp` falls in the UTC day or week | `market_id`, `timestamp`, `id` | | Orderbook snapshots | Snapshots whose `timestamp` falls in the UTC day | `market_id`, `outcome.id`, `timestamp` | Orderbook files contain every snapshot for the platform and day, including `INTERMEDIATE` rows. See [Orderbook snapshots](/docs/datasets/orderbook) to choose which rows to keep. ## Availability and freshness Files only cover complete periods: a day, week, or month is exported after it has ended. Exports run in the early hours UTC, so files usually appear during the following day: | Dataset | Usually available | | - | - | | Orderbook snapshots, daily | Early hours UTC of the next day | | Fills, daily | From about 04:35 UTC of the next day | | Fills, weekly | From about 04:45 UTC on the Monday after the week ends | | Markets, monthly | From about 04:15 UTC on the first day of the next month | These times are not guaranteed. A large backfill or an operational issue can delay a file. > [!WARNING] > > A file is a snapshot of the data as of when it was generated, and published files are normally not regenerated. Specifically: > > * A monthly markets file keeps each market's `status` and resolution fields as of the export. Markets that resolve later still appear unresolved in older files. > * Fills or snapshots that arrive after a period was exported aren't added to that period's file. > > For current market state or late corrections, query [SQL](/docs/sql-guide/overview) or the REST API. ### History Fills and markets files start at each platform's earliest data. Orderbook snapshot files start on **2025-11-20** for Polymarket and **2026-05-09** for Kalshi. # Market Graph Source: https://docs.probalytics.io/docs/market-graph Logical relations between Kalshi and Polymarket markets, queried with Cypher over the REST API > [!NOTE] > > The market graph is an **early access** feature and is not included in standard plans. To request access, email [support@probalytics.io](mailto:support@probalytics.io). ## Shape The market graph links markets whose outcomes depend on each other, within a platform and across Kalshi and Polymarket. It covers five domains: `crypto`, `sports`, `finance`, `weather`, and `elections`. Every relation comes with a price rule that consistent prices must satisfy. ``` (:Market)-[:ASSERTS]->(:Underlying) the number the market is about (:Market)-[:MEMBER_OF]->(:OutcomeSet) options of one event that split one outcome (:Market)-[:RELATION]->(:Market) how two markets' outcomes are linked (:Underlying)-[:OF_GAME]->(:Game) sports: the game or competition ``` ### Market One node per market. `id` is the Probalytics market ID and joins to [`markets.id`](/docs/datasets/markets). | Field | Meaning | | - | - | | `id`, `platform`, `platform_id`, `slug`, `url` | Identity | | `family` | The platform's product: Kalshi series, or Polymarket event slug with numbers masked | | `domain` | `crypto`, `sports`, `finance`, `weather`, or `elections` | | `title`, `status`, `created_at`, `closes_at`, `resolved_yes` | Listing and settlement. `resolved_yes` is `null` while open. | | `underlying`, `measure` | Key of the number the market asserts and how it is observed. `null` if not modelled. | | `direction`, `lo`, `hi`, `lo_closed`, `hi_closed` | The Yes condition as an interval of that number. `direction` is `above`, `below`, `range`, `up`, or (sports) `set`. | | `coverage` | Why a market has no underlying. `null` when modelled. | | `category`, `subject`, `shape`, `stat`, `predicate`, `outcome_role`, `mechanism`, `payout` | Taxonomy labels, present on every market | Sports markets also carry `game_id`, `segment`, `unit`, `tie_push`, and settlement facts (`tie`, `postponed`, `cancelled`, `stopped`, `player_out`). A column a domain does not use is `null`. ### Underlying One observable number: `key`, `domain`, `asset`, `feed`, `measure`, `obs_start`, `obs_end`, `markets`. Markets on the same underlying ask about the same number, which is what makes exact relations possible. | Domain | Key | `asset` | | - | - | - | | crypto | `asset \| feed \| measure \| start \| end` | Coin, e.g. `BTC` | | sports | `game \| segment \| measure \| unit` | — (use the `Game` node) | | finance | `instrument \| source \| measure \| start \| end` | Instrument, e.g. `SPX`, `UST10Y`, `NVDA` | | weather | `station \| source \| measure \| start \| end` | Station or area, e.g. `KNYC`, `usdm:Texas` | | elections | `race \| source \| measure` | Race, e.g. `US\|2026\|house\|CA-38\|general` | ### OutcomeSet The options of one event. `kind` is: * `brackets` — ranges tiling a line; exactly one wins, prices sum to 1 * `selection` — options covering every outcome; exactly one wins, prices sum to 1 * `exclusive` — at most one wins; prices sum to at most 1 Also `members`, `resolved`, and `winners`. ### RELATION | Field | Meaning | | - | - | | `relation` | `IMPLIES`, `EQUIVALENT`, `MUTEX`, `INVERSE`, or `NEAR` (see below) | | `basis` | The rule that produced the edge | | `exact` | `true` when the relation holds by construction | | `cross_platform` | `true` for Kalshi ↔ Polymarket edges | | `divergence`, `divergence_n` | Share of settled pairs of this kind that resolved inconsistently, and the number of pairs measured | | `margin`, `margin_bps` | `NEAR` only: the gap between the two levels | | `holds_if` | Condition under which the edge is guaranteed (sports, elections). `null` means it always holds. | ## Relations | Relation | Meaning | Price rule | | - | - | - | | `IMPLIES` | If A resolves Yes, B resolves Yes | P(A) ≤ P(B) | | `EQUIVALENT` | A and B always resolve the same way | P(A) = P(B) | | `MUTEX` | A and B cannot both resolve Yes | P(A) + P(B) ≤ 1 | | `INVERSE` | Exactly one of A and B resolves Yes | P(A) + P(B) = 1 | | `NEAR` | Same question on different data sources (e.g. Binance vs. CF Benchmarks) | P(A) ≈ P(B), with risk given by `divergence` | `IMPLIES` edges are stored only to the nearest neighbour: a 150-rung threshold ladder is 149 edges, and the full chain is a path query. `MUTEX` edges are likewise stored to the nearest conflicting market on each side. Brackets of one event are exclusive through their `OutcomeSet`, not pairwise edges. Sports `holds_if` values: * `completed` — the platforms settle a disrupted game differently, so the edge is guaranteed when the game is played to completion * `played` — they also settle a player who does not play differently * `played_second_half` — one side is a Kalshi "(Protected)" prop Elections `holds_if` values (`seated`, `call_stands`, `official_count`, `winner_inaugurated`) mark edges where the platforms settle on different results. ## Coverage | Domain | Cross-platform edges | | - | - | | crypto | `NEAR` (different price feeds), with measured divergence | | sports | Exact (same game, same quantity), with `holds_if` for disruptions | | finance | Exact where both platforms read the same publisher (Treasury par yields, AAA gas) | | weather | `NEAR` only: Kalshi reads the NWS climate day, Polymarket a station's local calendar day; `margin` is in degrees | | elections | Exact on one race's result, with `holds_if` where settlement sources differ | The graph covers the full history of Kalshi and Polymarket markets in the five domains, open and resolved. Each Kalshi series or Polymarket event family belongs to exactly one domain, so no market appears twice. Markets outside the five domains are not included; markets inside a domain that could not be modelled are included with `coverage` set. The graph is rebuilt from the [markets](/docs/datasets/markets) dataset roughly every 30 minutes. ## Querying the graph The graph is served over the REST API with the same API key as other endpoints. Requests from accounts without access return `403`. ### Preconfigured queries ```bash theme={null} curl "https://api.probalytics.io/api/graph/q/relations?id=" \ -H "Authorization: Bearer :" ``` | Name | Returns | | - | - | | `market` | The market node | | `relations` | Every relation to or from the market, with the peer's `id`, `platform`, `title`, `status`, `url` | | `underlying` | All markets on the same underlying, with `direction`, `lo`, `hi` | | `outcome_set` | All markets in the same outcome set, with the set's `kind` and `members` | ### Cypher ```bash theme={null} curl -X POST "https://api.probalytics.io/api/graph/cypher" \ -H "Authorization: Bearer :" \ -H "Content-Type: application/json" \ -d '{"query": "MATCH (a:Market {id: $id})-[r:RELATION]-(b:Market) WHERE r.cross_platform RETURN r.relation, r.exact, r.divergence, b.platform, b.title", "params": {"id": ""}}' ``` The response is `{"rows": [...]}`. Each request runs one read-only statement and returns at most 10,000 rows. Queries time out after 30 seconds; when the server is busy with other Cypher queries it returns `429`, so retry with backoff. Example queries: ```cypher theme={null} // Everything a market implies (follows the nearest-neighbour chain) MATCH (a:Market {id: $id})-[r:RELATION* 1..30 (e, n | WHERE e.relation = 'IMPLIES')]->(b:Market) RETURN DISTINCT b.id, b.title // All markets on one instrument MATCH (m:Market)-[:ASSERTS]->(u:Underlying) WHERE u.asset = 'UST10Y' RETURN m.platform AS platform, u.measure AS measure, count(*) AS markets // Both platforms' markets for one game MATCH (g:Game {id: $game})<-[:OF_GAME]-(u:Underlying)<-[:ASSERTS]-(m:Market) RETURN m.platform, m.title, u.measure, m.lo, m.hi // Open cross-platform pairs with low divergence MATCH (a:Market)-[r:RELATION]->(b:Market) WHERE r.cross_platform AND r.divergence < 0.005 AND a.status = 'ACTIVE' AND b.status = 'ACTIVE' RETURN a.title, b.title, r.relation, r.divergence LIMIT 100 ``` `UNION ALL` is not supported; run separate queries instead. Combine graph results with [orderbook](/docs/datasets/orderbook) or [markets](/docs/datasets/markets) data in SQL by market `id` to check price rules against live prices. # Python Client Source: https://docs.probalytics.io/docs/python-client Query markets, fills, and orderbook snapshots from Python with typed models and dataframes The [`probalytics`](https://github.com/Probalytics/probalytics-python) Python client is a convenience layer over the ClickHouse database. It handles the connection, builds queries for you, and returns results as [Polars](https://pola.rs) or [pandas](https://pandas.pydata.org) dataframes — or as typed Python models. > [!NOTE] > > The client connects to ClickHouse using the same credentials as the [SQL Guide](/docs/sql-guide/overview). Create ClickHouse credentials in [app.probalytics.io](https://app.probalytics.io) → ClickHouse Credentials. ## Installation ```bash theme={null} pip install probalytics ``` Requires **Python 3.11+**. Polars is included by default. For pandas support: ```bash theme={null} pip install "probalytics[pandas]" ``` ## Connecting **From credentials** ```python theme={null} from probalytics import ProbalyticsClient client = ProbalyticsClient.from_clickhouse( host="clickhouse.probalytics.io", username="YOUR_USERNAME", password="YOUR_PASSWORD", ) ``` Advanced options: ```python theme={null} client = ProbalyticsClient.from_clickhouse( host="clickhouse.probalytics.io", port=9440, database="probalytics", username="YOUR_USERNAME", password="YOUR_PASSWORD", secure=True, frame="polars", # default dataframe backend: "polars" or "pandas" ) ``` **From environment** Set these environment variables: ```bash theme={null} export PROBALYTICS_CLICKHOUSE_HOST="clickhouse.probalytics.io" export PROBALYTICS_CLICKHOUSE_USERNAME="YOUR_USERNAME" export PROBALYTICS_CLICKHOUSE_PASSWORD="YOUR_PASSWORD" export PROBALYTICS_FRAME="polars" # optional ``` Then: ```python theme={null} from probalytics import ProbalyticsClient client = ProbalyticsClient.from_env() ``` **Context manager** The client can be used as a context manager to close the connection automatically: ```python theme={null} from probalytics import ProbalyticsClient with ProbalyticsClient.from_env() as client: markets = client.markets(platform="POLYMARKET", status="ACTIVE") ``` ## Markets Query market metadata as typed models or as a dataframe. ```python theme={null} # Typed models markets = client.markets( market_platform_id="0xmarket", platform="POLYMARKET", status="ACTIVE", limit=100, ) market = markets[0] print(market.title, market.platform, market.platform_id) # As a dataframe markets_df = client.markets_frame( platform="KALSHI", status="ACTIVE", frame="polars", ) ``` Any filter accepts a single value or a list: ```python theme={null} markets = client.markets( market_platform_id=["0xmarket", "KXBTC-26JUN-T50000"], platform=["POLYMARKET", "KALSHI"], status=["ACTIVE", "PAUSED"], ) ``` ## Fills Fetch trade fills. Scope them to a market object, a market ID, or a platform-native ID: ```python theme={null} fills = client.fills( market=market, start_time="2026-03-15T00:00:00Z", end_time="2026-03-16T00:00:00Z", ) # Equivalent ways to scope: fills = market.fills() fills = client.fills(market_id=market.id) fills = client.fills(market_platform_id=market.platform_id, platform=market.platform) ``` Filter by participant, side, and platform: ```python theme={null} fills = client.fills( platform=["POLYMARKET", "KALSHI"], taker_side=["BUY", "SELL"], trader_id="0x1234...", start_time="2026-03-15T00:00:00Z", ) ``` Return typed models instead of a dataframe with `fills_models`: ```python theme={null} fill_models = client.fills_models(market=market, start_time="2026-03-15T00:00:00Z") fill_models = market.fills_models(start_time="2026-03-15T00:00:00Z") ``` > [!WARNING] > > Interpret financial fields using the linked market's `market_type`. `normalized_price` is not a probability for perpetual products, cash-flow fields are not currently signed by trade direction, and `fee = 0` can mean fee data was unavailable. ## Orderbook snapshots Full bid/ask depth per outcome, captured when the book changes. Requires an Orderbook or Custom ClickHouse tier. ```python theme={null} book = client.orderbook_snapshots( market=market, start_time="2026-03-15T00:00:00Z", end_time="2026-03-15T00:01:00Z", state="VERIFIED", ) # Or from the market object: book = market.orderbook_snapshots( start_time="2026-03-15T00:00:00Z", end_time="2026-03-15T00:01:00Z", state="VERIFIED", ) ``` Each row is a complete replacement book for one outcome, not a level delta. Snapshot rows also expose `indexed_at`, `hash`, `state`, `continuity`, and `path_index`. * Order rows within one outcome by `timestamp`, `path_index`, then `indexed_at`. * Keep `INTERMEDIATE` rows to see every retained book state; filter to `VERIFIED` for orderbooks reconstructed without gaps. * A `RESET` row is a fresh starting point. Do not calculate changes from the preceding row or forward-fill across it. * Do not deduplicate different states by timestamp alone. See [Orderbook Snapshots](/docs/datasets/orderbook) for field semantics and venue-specific reconstruction details. ## Choosing Polars or pandas Methods return **Polars** by default. Set the backend globally when connecting, or override per call: ```python theme={null} # Global: every call returns pandas client = ProbalyticsClient.from_clickhouse(..., frame="pandas") # Per call fills_pd = client.fills(market=market, frame="pandas") ``` Valid values are `"polars"` and `"pandas"`. ## Custom SQL Run arbitrary parameterized queries and get a dataframe back: ```python theme={null} df = client.query( """ SELECT platform, count() AS fills FROM fills WHERE timestamp >= %(start_time)s GROUP BY platform ORDER BY fills DESC """, parameters={"start_time": "2026-03-15T00:00:00Z"}, ) ``` > [!WARNING] > > Always pass values via `parameters` rather than string-formatting them into the query. See the [SQL Guide](/docs/sql-guide/overview) for table schemas and query examples. ## Supported filters | Method | Filters | | - | - | | `markets` / `markets_frame` | `start_time`, `end_time`, `status`, `platform`, `market_id`, `market_platform_id`, `limit`, `max_rows` | | `fills` / `fills_models` | `start_time`, `end_time`, `platform`, `market`, `market_id`, `market_platform_id`, `taker_side`, `trader_id`, `limit`, `max_rows` | | `orderbook_snapshots` | `start_time`, `end_time`, `platform`, `market`, `market_id`, `market_platform_id`, `state`, `continuity`, `limit` | Every filter accepts a single value or a list of values. ## Resources > **[Source & README](https://github.com/Probalytics/probalytics-python)** > > Package source and usage guide (Apache-2.0) > **[SQL Guide](/docs/sql-guide/overview)** > > Table schemas and query examples # Quickstart Source: https://docs.probalytics.io/docs/quickstart Get started with Probalytics in 2 minutes Choose your access method and get working code in 2 minutes. **REST API** ## REST API Query prediction market data via HTTP with simple authentication. ### Setup (1 min) #### Step 1: Click "Create API Key" Go to [app.probalytics.io](https://app.probalytics.io) → API Keys section ![Click Create API Key](https://mintcdn.com/probalytics/XCOjsFabz4gtaVHr/public/images/quickstart/click-create-api-key.png?fit=max\&auto=format\&n=XCOjsFabz4gtaVHr\&q=85\&s=1d65c6e1db2607c1140989cd63a63f11) #### Step 2: Enter Credential Name Give your key a name (e.g., "trading-bot", "research") ![Enter API Credentials Name](https://mintcdn.com/probalytics/XCOjsFabz4gtaVHr/public/images/quickstart/insert-api-credentials-name.png?fit=max\&auto=format\&n=XCOjsFabz4gtaVHr\&q=85\&s=e4967d6ec000e5983bd16e754b73acac) #### Step 3: Copy API Key ID and API Key Secret Copy both the **API Key ID** and **API Key Secret** from the dashboard. ![Copy API Credentials](https://mintcdn.com/probalytics/XCOjsFabz4gtaVHr/public/images/quickstart/copy-api-credentials.png?fit=max\&auto=format\&n=XCOjsFabz4gtaVHr\&q=85\&s=642886a5c2ae710c704020976d04ee8d) > [!WARNING] > > Keep your API Key Secret secure. Never commit it to git or expose it publicly. ### Make Your First Request Concatenate **API Key ID** and **API Key Secret** with a colon in the `Authorization` header: ``` Authorization: Bearer API_KEY_ID:API_KEY_SECRET ``` ```python theme={null} import requests API_KEY_ID = "api_brave_cosmic_falcon" API_KEY_SECRET = "sk_life_AbCdEfGh..." API_KEY = f"{API_KEY_ID}:{API_KEY_SECRET}" headers = {"Authorization": f"Bearer {API_KEY}"} response = requests.get( "https://api.probalytics.io/api/v1/markets", headers=headers, timeout=30, ) response.raise_for_status() payload = response.json() markets = payload["data"] print(f"Found {len(markets)} markets") # A full page may include a cursor for the next request. next_cursor = payload.get("next_cursor") ``` See the REST API section in the sidebar for: * All endpoints (GET /markets, GET /fills) * Query parameters & filtering * Complete response examples **SQL (ClickHouse) — Recommended** ## SQL (ClickHouse) — Recommended Direct database access for analytics, batch operations, and complex queries. ### Setup (2 min) #### Step 1: Click "Create ClickHouse Credentials" Go to [app.probalytics.io](https://app.probalytics.io) → ClickHouse Credentials section ![Click Create ClickHouse Key](https://mintcdn.com/probalytics/XCOjsFabz4gtaVHr/public/images/quickstart/click-create-clickhouse-key.png?fit=max\&auto=format\&n=XCOjsFabz4gtaVHr\&q=85\&s=8114ac4f842deea94d926c5b061af714) #### Step 2: Enter Credential Name Give your credentials a name (e.g., "research", "dashboard") ![Enter ClickHouse Credentials Name](https://mintcdn.com/probalytics/XCOjsFabz4gtaVHr/public/images/quickstart/insert-clickhouse-credentials-name.png?fit=max\&auto=format\&n=XCOjsFabz4gtaVHr\&q=85\&s=ec8dfab4c3d6cd88ee41ddf6eed921d1) #### Step 3: Copy Username and Password Copy both the username and password generated for you. ![Copy ClickHouse Credentials](https://mintcdn.com/probalytics/XCOjsFabz4gtaVHr/public/images/quickstart/copy-clickhouse-credentials.png?fit=max\&auto=format\&n=XCOjsFabz4gtaVHr\&q=85\&s=32c684b004dbeefebdd0195f39d7995c) ### Connection Details * **Host**: `clickhouse.probalytics.io` * **Port**: `9440` (Secure TCP) or `8443` (Secure HTTPS) * **Database**: `probalytics` * **Username**: From dashboard * **Password**: From dashboard > [!NOTE] > > All connections are secured with TLS encryption. Use the secure ports and enable TLS/SSL in your client. ### Connect with CLI ```bash theme={null} clickhouse client --host=clickhouse.probalytics.io --secure --port=9440 --user=YOUR_USERNAME --password=YOUR_PASSWORD --database=probalytics ``` ### Connect with Python Install first: `pip install clickhouse-driver` ```python theme={null} from clickhouse_driver import Client client = Client( host='clickhouse.probalytics.io', port=9440, user='YOUR_USERNAME', password='YOUR_PASSWORD', database='probalytics', secure=True ) result = client.execute('SELECT count() FROM markets;') print(f"Total markets: {result[0][0]}") ``` ### First Query ```sql theme={null} SELECT count() FROM markets; ``` See [SQL Guide](/docs/sql-guide/overview) for: * More connection tools (CLI, JavaScript, Go, DBeaver) * Table schemas * Query examples * Performance tips ## Which Method Should I Use? **REST API** * ✓ Simple to integrate * ✓ Good for production applications * ✓ Markets and fills over JSON * ✗ Limited query flexibility **SQL (ClickHouse) — Recommended** * ✓ Complex queries and analytics * ✓ Aggregations and joins * ✓ Paid ClickHouse tiers have full markets/fills history; trials normally receive seven days of fills * ✓ Super fast analytics ## Next Steps > **[SQL Guide](/docs/sql-guide/overview)** > > Tables, schemas, query templates > **[REST Errors](/docs/api-reference/errors)** > > Error bodies and pagination behavior > **[S3 Data Files](/docs/file-downloads/overview)** > > Bulk Parquet exports over S3 # Common Queries Source: https://docs.probalytics.io/docs/sql-guide/common-queries Copy-paste SQL query templates for prediction market analysis Starting-point queries for common prediction market analysis tasks. Add the market, product-type, and time constraints required by your analysis before using them in production. > [!WARNING] > > `price` is the execution price for the traded outcome. For binary markets, `normalized_price` expresses the trade relative to outcome index 0 and is normally between 0 and 1. For perpetual markets, `normalized_price` is the instrument price and is not a probability. Join fills to markets and inspect `market_type` before combining products. ## Market Discovery ### Search Markets by Keyword ```sql theme={null} SELECT id, platform, title, status, created_at FROM markets WHERE platform = 'POLYMARKET' AND created_at >= now() - INTERVAL 90 DAY AND ( title ILIKE '%bitcoin%' OR title ILIKE '%btc%' ) ORDER BY created_at DESC LIMIT 50; ``` ### Markets Closing Soon Find active markets closing in the next 7 days—useful for time-sensitive analysis. ```sql theme={null} SELECT id, platform, title, closes_at, dateDiff('hour', now(), closes_at) as hours_until_close FROM markets WHERE platform = 'POLYMARKET' AND status = 'ACTIVE' AND closes_at BETWEEN now() AND now() + INTERVAL 7 DAY ORDER BY closes_at ASC LIMIT 100; ``` ### Recently Created Markets ```sql theme={null} SELECT id, platform, title, category, created_at FROM markets WHERE platform = 'POLYMARKET' AND created_at >= now() - INTERVAL 24 HOUR ORDER BY created_at DESC LIMIT 50; ``` ### Most Traded Markets (Last 7 Days) ```sql theme={null} SELECT f.market_id, m.title, m.platform, count() as fill_count, sum(f.size) as total_size, uniq(f.taker_id) as unique_takers FROM fills f JOIN ( SELECT id, title, platform FROM markets WHERE platform = 'POLYMARKET' AND market_type = 'BINARY' -- filter markets before joining ) m ON f.market_id = m.id WHERE f.platform = 'POLYMARKET' AND f.timestamp >= now() - INTERVAL 7 DAY GROUP BY f.market_id, m.title, m.platform ORDER BY total_size DESC LIMIT 25; ``` *** ## Price Analysis ### Price History for a Market Get all fills for a specific market to plot price over time. Use `price` for per-outcome charts or `normalized_price` for a single Outcome 0 chart. ```sql theme={null} SELECT timestamp, outcome.name as outcome, price, size, taker_side FROM fills WHERE platform = 'POLYMARKET' AND market_id = 'your-market-uuid-here' AND timestamp >= now() - INTERVAL 30 DAY ORDER BY timestamp ASC; ``` ### OHLC Candles (Hourly) Build candlestick data for charting. Uses `price` (the per-outcome execution price) so each outcome gets correct candles. ```sql theme={null} SELECT toStartOfHour(timestamp) as hour, outcome.name as outcome, argMin(price, timestamp) as open, max(price) as high, min(price) as low, argMax(price, timestamp) as close, sum(size) as volume, count() as fill_count FROM fills WHERE platform = 'POLYMARKET' AND market_id = 'your-market-uuid-here' AND timestamp >= now() - INTERVAL 7 DAY GROUP BY hour, outcome ORDER BY hour ASC, outcome; ``` ### OHLC Candles (Daily) ```sql theme={null} SELECT toDate(timestamp) as date, outcome.name as outcome, argMin(price, timestamp) as open, max(price) as high, min(price) as low, argMax(price, timestamp) as close, sum(size) as volume FROM fills WHERE platform = 'POLYMARKET' AND market_id = 'your-market-uuid-here' AND timestamp >= now() - INTERVAL 90 DAY GROUP BY date, outcome ORDER BY date ASC, outcome; ``` ### Volume-Weighted Average Price (VWAP) ```sql theme={null} SELECT outcome.name as outcome, sum(price * size) / sum(size) as vwap, sum(size) as total_size FROM fills WHERE platform = 'POLYMARKET' AND market_id = 'your-market-uuid-here' AND timestamp >= now() - INTERVAL 24 HOUR GROUP BY outcome; ``` ### Latest Price per Outcome Get the most recent fill price for each outcome in a market. ```sql theme={null} SELECT outcome.name as outcome, argMax(price, timestamp) as latest_price, max(timestamp) as last_fill_time FROM fills WHERE platform = 'POLYMARKET' AND market_id = 'your-market-uuid-here' AND timestamp >= now() - INTERVAL 30 DAY GROUP BY outcome; ``` *** ## Trading Activity ### Recent Fills on a Market ```sql theme={null} SELECT timestamp, outcome.name as outcome, taker_side, price, size, taker_id, maker_id FROM fills WHERE platform = 'POLYMARKET' AND market_id = 'your-market-uuid-here' ORDER BY timestamp DESC LIMIT 100; ``` ### Hourly Volume Over Time ```sql theme={null} SELECT toStartOfHour(timestamp) as hour, count() as fills, sum(size) as total_size, uniq(taker_id) as unique_takers FROM fills WHERE platform = 'POLYMARKET' AND market_id = 'your-market-uuid-here' AND timestamp >= now() - INTERVAL 7 DAY GROUP BY hour ORDER BY hour ASC; ``` ### Large Fills (Whale Watching) Find fills above a size threshold. ```sql theme={null} SELECT f.timestamp, m.title, f.outcome.name as outcome, f.taker_side, f.price, f.size, f.taker_id FROM fills f JOIN ( SELECT id, title FROM markets WHERE platform = 'POLYMARKET' AND market_type = 'BINARY' -- filter markets before joining ) m ON f.market_id = m.id WHERE f.platform = 'POLYMARKET' AND f.timestamp >= now() - INTERVAL 24 HOUR AND f.size > 1000 -- adjust threshold ORDER BY f.size DESC LIMIT 100; ``` ### Buy vs Sell Pressure ```sql theme={null} SELECT toStartOfHour(timestamp) as hour, outcome.name as outcome, sumIf(size, taker_side = 'BUY') as buy_size, sumIf(size, taker_side = 'SELL') as sell_size, sumIf(size, taker_side = 'BUY') - sumIf(size, taker_side = 'SELL') as net_flow FROM fills WHERE platform = 'POLYMARKET' AND market_id = 'your-market-uuid-here' AND timestamp >= now() - INTERVAL 7 DAY GROUP BY hour, outcome ORDER BY hour ASC; ``` ### Stored Gross Amounts and Fees The current `taker_cash_flow` and `maker_cash_flow` values are stored gross/notional amounts, not signed directional cash flows. This query summarizes the stored values; it does not calculate P\&L. A zero fee can mean fee data was unavailable. ```sql theme={null} SELECT outcome.name as outcome, taker_side, count() as fill_count, sum(taker_cash_flow) as stored_taker_gross, sum(maker_cash_flow) as stored_maker_gross, sum(fee) as total_fees FROM fills WHERE platform = 'POLYMARKET' AND market_id = 'your-market-uuid-here' AND timestamp >= now() - INTERVAL 30 DAY GROUP BY outcome, taker_side; ``` *** ## Trader Analysis ### Top Takers by Volume ```sql theme={null} SELECT taker_id, count() as fill_count, sum(size) as total_size, uniq(market_id) as markets_traded, min(timestamp) as first_fill, max(timestamp) as last_fill FROM fills WHERE platform = 'POLYMARKET' AND timestamp >= now() - INTERVAL 30 DAY AND taker_id IS NOT NULL GROUP BY taker_id ORDER BY total_size DESC LIMIT 100; ``` ### Trader Activity on a Specific Market ```sql theme={null} SELECT taker_id, count() as fills, sum(size) as total_size, sumIf(size, taker_side = 'BUY') as buy_size, sumIf(size, taker_side = 'SELL') as sell_size, avg(price) as avg_price FROM fills WHERE platform = 'POLYMARKET' AND market_id = 'your-market-uuid-here' AND taker_id IS NOT NULL GROUP BY taker_id ORDER BY total_size DESC LIMIT 50; ``` ### Taker-Side Net Contract Flow per Outcome Estimate a trader's taker-side net contract flow by summing buys minus sells. ```sql theme={null} SELECT outcome.name as outcome, sumIf(size, taker_side = 'BUY') - sumIf(size, taker_side = 'SELL') as net_contracts FROM fills WHERE platform = 'POLYMARKET' AND market_id = 'your-market-uuid-here' AND taker_id = 'trader-id-here' GROUP BY outcome; ``` This estimates only the trader's taker-side contract flow. It does not include fills where the same trader appears as maker, venue-specific settlement, fees, or signed cash P\&L. ### Trader's Recent Activity Across Markets ```sql theme={null} SELECT f.timestamp, m.title, f.outcome.name as outcome, f.taker_side, f.price, f.size FROM fills f JOIN ( SELECT id, title FROM markets WHERE platform = 'POLYMARKET' AND market_type = 'BINARY' -- filter markets before joining ) m ON f.market_id = m.id WHERE f.platform = 'POLYMARKET' AND f.taker_id = 'trader-id-here' AND f.timestamp >= now() - INTERVAL 7 DAY ORDER BY f.timestamp DESC LIMIT 100; ``` *** ## Orderbook Analysis ### Current Best Bid/Ask ```sql theme={null} SELECT outcome.id as outcome_id, outcome.name as outcome, bids[1].price as best_bid, bids[1].size as bid_size, asks[1].price as best_ask, asks[1].size as ask_size, asks[1].price - bids[1].price as spread, timestamp, continuity, path_index FROM orderbook_snapshots FINAL WHERE market_id = 'your-market-uuid-here' AND length(bids) > 0 AND length(asks) > 0 AND state = 'VERIFIED' ORDER BY timestamp DESC, path_index DESC, indexed_at DESC LIMIT 1 BY outcome.id; ``` ### Spread Over Time ```sql theme={null} SELECT toStartOfMinute(timestamp) as minute, outcome.name as outcome, avg(asks[1].price - bids[1].price) as avg_spread, min(asks[1].price - bids[1].price) as min_spread, max(asks[1].price - bids[1].price) as max_spread FROM orderbook_snapshots WHERE market_id = 'your-market-uuid-here' AND timestamp >= now() - INTERVAL 1 HOUR AND state = 'VERIFIED' AND length(bids) > 0 AND length(asks) > 0 GROUP BY minute, outcome ORDER BY minute ASC; ``` ### Orderbook at a Specific Time Get the book state at an exact point in time (e.g., to correlate with a fill event). Uses the most recent snapshot at or before the target time. ```sql theme={null} SELECT outcome.name as outcome, bids[1].price as best_bid, asks[1].price as best_ask, (bids[1].price + asks[1].price) / 2 as mid_price, bids, asks, timestamp, continuity, path_index FROM orderbook_snapshots FINAL WHERE market_id = 'your-market-uuid-here' AND outcome.id = 'your-outcome-uuid-here' AND timestamp <= '2026-03-20T14:30:00.000Z' AND state = 'VERIFIED' ORDER BY timestamp DESC, path_index DESC, indexed_at DESC LIMIT 1; ``` ### Top-N Depth Levels Extract only the top N price levels without transferring the full book. ```sql theme={null} SELECT outcome.id as outcome_id, outcome.name as outcome, arraySlice(bids, 1, 10) as top_bids, arraySlice(asks, 1, 10) as top_asks, timestamp, continuity, path_index FROM orderbook_snapshots FINAL WHERE market_id = 'your-market-uuid-here' AND state = 'VERIFIED' ORDER BY timestamp DESC, path_index DESC, indexed_at DESC LIMIT 1 BY outcome.id; ``` ### Orderbook Depth Total size available across all levels. ```sql theme={null} SELECT outcome.id as outcome_id, outcome.name as outcome, arraySum(arrayMap(b -> b.2, bids)) as total_bid_size, arraySum(arrayMap(a -> a.2, asks)) as total_ask_size, timestamp, continuity, path_index FROM orderbook_snapshots FINAL WHERE market_id = 'your-market-uuid-here' AND timestamp >= now() - INTERVAL 1 DAY AND state = 'VERIFIED' ORDER BY timestamp DESC, path_index DESC, indexed_at DESC LIMIT 1 BY outcome.id; ``` ### Tick-Level Reconstruction Before building a millisecond sampling grid, check whether the window contains any fresh starting points: ```sql theme={null} SELECT timestamp, path_index, state, continuity FROM orderbook_snapshots FINAL WHERE market_id = 'your-market-uuid-here' AND outcome.id = 'your-outcome-uuid-here' AND timestamp >= toDateTime64('2026-03-20T14:00:00.000000000', 9) AND timestamp < toDateTime64('2026-03-20T14:01:00.000000000', 9) AND continuity = 'RESET' ORDER BY timestamp, path_index; ``` If the query returns no `RESET` rows, collapse multiple verified snapshots at the same exchange timestamp to the last path state and then forward-fill: ```sql theme={null} WITH toDateTime64('2026-03-20T14:00:00.000000000', 9) AS range_start, toDateTime64('2026-03-20T14:01:00.000000000', 9) AS range_end SELECT timestamp, bids, asks FROM ( SELECT timestamp, argMax(bids, tuple(path_index, indexed_at)) AS bids, argMax(asks, tuple(path_index, indexed_at)) AS asks FROM orderbook_snapshots FINAL WHERE market_id = 'your-market-uuid-here' AND outcome.id = 'your-outcome-uuid-here' AND state = 'VERIFIED' AND timestamp >= range_start AND timestamp < range_end GROUP BY timestamp ) ORDER BY timestamp ASC WITH FILL FROM range_start TO range_end STEP toIntervalMillisecond(1) INTERPOLATE (bids, asks); ``` > [!WARNING] > > Forward-filled rows are synthetic sampling points, not exchange events. Do not use them for event counts, feed-quality measurements, or reset detection. Never fill across `RESET`. One minute at millisecond resolution produces 60,000 rows, so use a coarser grid for longer ranges. *** ## Market Resolution ### Recently Resolved Markets ```sql theme={null} SELECT id, platform, title, resolution_type, resolution_resolved_at, resolution_winning_outcome_id FROM markets WHERE platform = 'POLYMARKET' AND status = 'RESOLVED' AND resolution_resolved_at >= now() - INTERVAL 7 DAY ORDER BY resolution_resolved_at DESC LIMIT 50; ``` ### Resolution with Winning Outcome Name ```sql theme={null} SELECT m.id, m.title, m.resolution_resolved_at, m.resolution_type, winning.name as winning_outcome FROM markets m ARRAY JOIN m.outcomes as winning WHERE m.platform = 'POLYMARKET' AND m.status = 'RESOLVED' AND m.resolution_resolved_at >= now() - INTERVAL 30 DAY AND winning.id = m.resolution_winning_outcome_id ORDER BY m.resolution_resolved_at DESC LIMIT 50; ``` *** ## Aggregated Statistics ### Daily Platform Stats ```sql theme={null} SELECT toDate(timestamp) as date, platform, count() as fills, sum(size) as total_size, uniq(taker_id) as unique_takers, uniq(market_id) as active_markets FROM fills WHERE timestamp >= now() - INTERVAL 30 DAY GROUP BY date, platform ORDER BY date DESC, platform; ``` ### Markets by Category ```sql theme={null} SELECT category, count() as market_count, countIf(status = 'ACTIVE') as active_markets, countIf(status = 'RESOLVED') as resolved_markets FROM markets WHERE platform = 'POLYMARKET' AND created_at >= now() - INTERVAL 90 DAY GROUP BY category ORDER BY market_count DESC; ``` ### Outcome Count Distribution How many markets have 2 outcomes vs 3+ outcomes? ```sql theme={null} SELECT length(outcomes) as outcome_count, count() as market_count FROM markets WHERE platform = 'POLYMARKET' AND created_at >= now() - INTERVAL 90 DAY GROUP BY outcome_count ORDER BY outcome_count; ``` *** ## Advanced Patterns ### Price Movement Detection Find markets where price moved significantly in the last hour. ```sql theme={null} WITH recent_prices AS ( SELECT market_id, outcome.name as outcome, argMin(price, timestamp) as price_1h_ago, argMax(price, timestamp) as current_price FROM fills WHERE platform = 'POLYMARKET' AND timestamp >= now() - INTERVAL 1 HOUR GROUP BY market_id, outcome ) SELECT m.title, r.outcome, r.price_1h_ago, r.current_price, r.current_price - r.price_1h_ago as price_change, (r.current_price - r.price_1h_ago) / r.price_1h_ago * 100 as pct_change FROM recent_prices r JOIN ( SELECT id, title FROM markets WHERE platform = 'POLYMARKET' AND market_type = 'BINARY' -- filter markets before joining ) m ON r.market_id = m.id WHERE abs(r.current_price - r.price_1h_ago) > 0.05 -- 5+ point move ORDER BY abs(pct_change) DESC LIMIT 25; ``` ### Markets with Unusual Volume Find markets trading above their 7-day average. ```sql theme={null} WITH volume_stats AS ( SELECT market_id, sum(size) / 7 as avg_daily_size FROM fills WHERE platform = 'POLYMARKET' AND timestamp BETWEEN now() - INTERVAL 8 DAY AND now() - INTERVAL 1 DAY GROUP BY market_id ), today_volume AS ( SELECT market_id, sum(size) as today_size FROM fills WHERE platform = 'POLYMARKET' AND timestamp >= now() - INTERVAL 1 DAY GROUP BY market_id ) SELECT m.title, t.today_size, v.avg_daily_size, t.today_size / v.avg_daily_size as volume_ratio FROM today_volume t JOIN volume_stats v ON t.market_id = v.market_id JOIN ( SELECT id, title FROM markets WHERE platform = 'POLYMARKET' AND market_type = 'BINARY' -- filter markets before joining ) m ON t.market_id = m.id WHERE v.avg_daily_size > 100 -- filter low-volume markets ORDER BY volume_ratio DESC LIMIT 25; ``` ### Latest Fill Price Divergence Between Outcomes For binary markets, compare the most recent execution price for each outcome. The executions can occur at different times and are not executable bid/ask quotes, so a deviation indicates asynchronous or stale prints—not a confirmed arbitrage opportunity. ```sql theme={null} SELECT m.title, sumIf(latest_price, outcome_index = 0) as yes_price, sumIf(latest_price, outcome_index = 1) as no_price, sumIf(latest_price, outcome_index = 0) + sumIf(latest_price, outcome_index = 1) as total, abs(1 - (sumIf(latest_price, outcome_index = 0) + sumIf(latest_price, outcome_index = 1))) as distance_from_one FROM ( SELECT market_id, outcome.index as outcome_index, argMax(price, timestamp) as latest_price FROM fills WHERE platform = 'POLYMARKET' AND timestamp >= now() - INTERVAL 1 DAY GROUP BY market_id, outcome_index ) t JOIN ( SELECT id, title FROM markets WHERE platform = 'POLYMARKET' AND market_type = 'BINARY' -- filter markets before joining ) m ON t.market_id = m.id GROUP BY m.id, m.title HAVING distance_from_one > 0.02 ORDER BY distance_from_one DESC LIMIT 25; ``` ### Time-Weighted Average Price (TWAP) Weight prices by time between fills, not volume. ```sql theme={null} WITH fill_intervals AS ( SELECT timestamp, price, leadInFrame(timestamp) OVER ( ORDER BY timestamp ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING ) as next_fill_time, dateDiff('second', timestamp, leadInFrame(timestamp) OVER ( ORDER BY timestamp ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING ) ) as seconds_until_next FROM fills WHERE platform = 'POLYMARKET' AND market_id = 'your-market-uuid-here' AND outcome.name = 'Yes' AND timestamp >= now() - INTERVAL 24 HOUR ) SELECT sum(price * seconds_until_next) / sum(seconds_until_next) as twap FROM fill_intervals WHERE seconds_until_next > 0; ``` *** ## Exporting Data ### Export to CSV Format Add `FORMAT CSV` or `FORMAT CSVWithNames` to any query: ```sql theme={null} SELECT timestamp, normalized_price, size, taker_side FROM fills WHERE platform = 'POLYMARKET' AND market_id = 'your-market-uuid-here' AND timestamp >= now() - INTERVAL 30 DAY ORDER BY timestamp FORMAT CSVWithNames; ``` ### Export to JSON ```sql theme={null} SELECT id, title, status, created_at FROM markets WHERE platform = 'POLYMARKET' AND created_at >= now() - INTERVAL 7 DAY FORMAT JSONEachRow; ``` > [!NOTE] > > When using programmatic clients, the format is usually handled by the client library. These FORMAT clauses are useful for CLI exports or direct HTTP queries. # SQL Guide Source: https://docs.probalytics.io/docs/sql-guide/overview Query Probalytics data directly with SQL Query the tables available to your ClickHouse tier for advanced analytics and complex queries. ## Getting Started Already have credentials? Jump to [Connection Methods](#connection-methods). New to Probalytics? Create ClickHouse credentials in [app.probalytics.io](https://app.probalytics.io) → ClickHouse Credentials section. See [Quickstart](/docs/quickstart#sql-clickhouse) for setup. **Connection Details** * **Host**: `clickhouse.probalytics.io` * **Port**: `9440` (Secure TCP) or `8443` (Secure HTTPS) * **Database**: `probalytics` * **Authentication**: Username and password from dashboard > [!NOTE] > > All connections are secured with TLS encryption. Use the `--secure` flag for CLI or enable TLS/SSL in your client. ## Quick Exploration ### SQL Workspace (Browser) The fastest way to explore and test queries. Visit [app.probalytics.io/sql](https://app.probalytics.io/sql) and start querying immediately—no setup required. > [!WARNING] > > Large result sets will crash your browser. Keep queries focused and use LIMIT to restrict results. For bulk exports or large analytics, use programmatic connections instead. ## Connection Methods For production applications and large-scale analysis, use one of these programmatic connections: **Python - clickhouse-driver** Native ClickHouse driver for best performance. Install: `pip install clickhouse-driver` ```python theme={null} from clickhouse_driver import Client client = Client( host='clickhouse.probalytics.io', port=9440, user='YOUR_USERNAME', password='YOUR_PASSWORD', database='probalytics', secure=True ) # Test connection result = client.execute('SELECT count() FROM markets;') print(f"Total markets: {result[0][0]}") ``` **Python - clickhouse-connect** HTTP-based client, simpler setup. Install: `pip install clickhouse-connect` ```python theme={null} import clickhouse_connect client = clickhouse_connect.get_client( host='clickhouse.probalytics.io', port=8443, username='YOUR_USERNAME', password='YOUR_PASSWORD', database='probalytics' ) # Test connection result = client.query('SELECT count() FROM markets;') print(f"Total markets: {result.first_item}") ``` **JavaScript / Node.js** Install: `npm install @clickhouse/client` ```javascript theme={null} import { createClient } from '@clickhouse/client'; const client = createClient({ url: 'https://clickhouse.probalytics.io:8443', username: 'YOUR_USERNAME', password: 'YOUR_PASSWORD', database: 'probalytics' }); // Test connection const result = await client.query({ query: 'SELECT count() FROM markets;', format: 'JSONEachRow' }); const data = await result.json(); console.log(`Total markets: ${data[0].count}`); ``` **Go** Install: `go get github.com/ClickHouse/clickhouse-go/v2` ```go theme={null} package main import ( "fmt" "github.com/ClickHouse/clickhouse-go/v2" "context" "crypto/tls" ) func main() { conn, _ := clickhouse.Open(&clickhouse.Options{ Addr: []string{"clickhouse.probalytics.io:9440"}, Auth: clickhouse.Auth{ Username: "YOUR_USERNAME", Password: "YOUR_PASSWORD", }, TLS: &tls.Config{}, Settings: clickhouse.Settings{ "max_execution_time": 300, }, }) var count uint64 err := conn.QueryRow(context.Background(), "SELECT count() FROM markets;").Scan(&count) fmt.Printf("Total markets: %d\n", count) } ``` **DBeaver** Popular GUI tool for SQL queries and exploration. 1. Download [DBeaver Community](https://dbeaver.io/download/) 2. Create new connection → Search "ClickHouse" 3. Configure: * **Server Host**: clickhouse.probalytics.io * **Port**: 8443 * **Database**: probalytics * **Username**: From your dashboard * **Password**: From your dashboard * **SSL**: Enable SSL/TLS in connection settings 4. Test connection → Browse and query tables **CLI - clickhouse-client** Quick exploration and ad-hoc queries. Install: [ClickHouse Docs](https://clickhouse.com/docs/en/install) ```bash theme={null} clickhouse client --host=clickhouse.probalytics.io --secure --port=9440 --user=YOUR_USERNAME --password=YOUR_PASSWORD --database=probalytics ``` Or run a query directly: ```bash theme={null} clickhouse client \ --host clickhouse.probalytics.io \ --secure \ --port 9440 \ --user YOUR_USERNAME \ --password YOUR_PASSWORD \ --database probalytics \ --query "SELECT count() FROM markets;" ``` ## Exploring the Database ### List All Tables ```sql theme={null} SHOW TABLES FROM probalytics; ``` ### Describe Table Structure ```sql theme={null} DESCRIBE TABLE probalytics.markets; DESCRIBE TABLE probalytics.fills; DESCRIBE TABLE probalytics.orderbook_snapshots; ``` ### Test Your Connection ```sql theme={null} SELECT 'markets' as table_name, count() as row_count FROM markets UNION ALL SELECT 'fills' as table_name, count() as row_count FROM fills UNION ALL SELECT 'orderbook_snapshots' as table_name, count() as row_count FROM orderbook_snapshots; ``` ## Understanding ReplacingMergeTree Tables use the `ReplacingMergeTree` engine for efficient updates and deduplication. **How it works:** * Each table's `ORDER BY` tuple defines row identity for replacement * For duplicate identity keys, the greatest `indexed_at` version wins * Background merges consolidate duplicates asynchronously * Queries may return duplicates until merges complete **The FINAL Keyword** Use `FINAL` to force immediate deduplication: ```sql theme={null} -- May include duplicates (fast) SELECT count() FROM markets; -- Guaranteed deduplicated (slower) SELECT count() FROM markets FINAL; ``` > [!WARNING] > > `FINAL` triggers synchronous deduplication which is significantly slower. Use it only when you need guaranteed unique results. For most analytics, skip `FINAL` and rely on background merges. ## Access tiers Your tier determines which datasets a ClickHouse credential can query. Query quotas and resource limits are applied separately from REST and can vary by credential. Contact [support@probalytics.io](mailto:support@probalytics.io) if you need the effective limits for a credential. ### Paid credentials | Feature | Starter | Pro | Orderbook | Custom | | - | - | - | - | - | | **Tables** | markets, fills | markets, fills | markets, fills, orderbooks | markets, fills, orderbooks | | **Retained history** | All | All | All | All | ### Trial credentials Trials receive full market metadata but normally only the last seven days of fills and, when the tier permits it, orderbook snapshots. A per-account offer can differ from the normal trial window. "All retained history" means the complete period Probalytics currently stores for that dataset. See the [Datasets overview](/docs/datasets/overview#understanding-coverage) for coverage details. | Feature | Starter trial | Pro trial | Orderbook trial | Custom trial | | - | - | - | - | - | | **Tables** | markets, fills | markets, fills | markets, fills, orderbooks | markets, fills, orderbooks | > [!NOTE] > > Your tier is set when creating ClickHouse credentials in the dashboard. ## Available Tables ### markets Primary table for prediction market metadata. * **Available to**: All tiers * **Records**: One per market across platforms * **Key fields**: platform, title, description, outcomes, status, market\_type * See [Tables reference](/docs/sql-guide/tables) for complete schema ### fills Individual trade fill records on each market. * **Available to**: All tiers * **Records**: One per trade executed * **Key fields**: market\_id, size, price, normalized\_price, taker\_side, taker\_id, maker\_id, fee, timestamp * **Note**: Partitioned monthly by `timestamp` for performance * See [Tables reference](/docs/sql-guide/tables) for complete schema ### orderbook\_snapshots Orderbook depth snapshots per market outcome, written when the book state changes. * **Available to**: Orderbook and Custom ClickHouse tiers * **Records**: Full bid/ask states per outcome; multiple ordered states can share one timestamp * **Key fields**: market\_id, outcome, bids, asks, timestamp, hash, state, continuity, path\_index * **Note**: Partitioned daily by `timestamp`; use continuity boundaries when reconstructing time series * **Data range**: Polymarket available from November 20, 2025 (high-quality snapshots from February 17, 2026). Kalshi available from May 8, 2026. * See [Tables reference](/docs/sql-guide/tables) for complete schema ## Next Steps > **[Tables Reference](/docs/sql-guide/tables)** > > Complete field definitions and data types > **[Common Queries](/docs/sql-guide/common-queries)** > > Ready-to-run query examples > **[SQL Tips](/docs/sql-guide/tips)** > > Performance optimization strategies # Tables & Schemas Source: https://docs.probalytics.io/docs/sql-guide/tables ClickHouse table schemas and columns Complete reference for all Probalytics database tables. All tables use a `ReplacingMergeTree` with `indexed_at` as the version column. Rows are identified by each table's `ORDER BY` key; when identical keys are inserted more than once, the greatest `indexed_at` wins during background merges. ## markets Primary table containing prediction market metadata from all supported platforms. **Availability**: All ClickHouse tiers, including all retained market history during trials. See [Markets](/docs/datasets/markets) for the distinction between account access and source coverage. > [!WARNING] > > Always filter `markets` by `market_type` (and `platform`). Kalshi combo markets make up over 90% of the table, so a query without a `market_type` filter scans hundreds of millions of rows even when you only want binary markets. When joining to `markets`, filter it in a subquery first; a bare `JOIN markets` loads the whole table into memory. ### Schema | Column | Type | Description | | - | - | - | | `id` | `UUID` | Probalytics unique market identifier | | `platform` | `Enum('POLYMARKET', 'KALSHI')` | Source platform | | `platform_id` | `String` | Platform's native market ID | | `slug` | `String` | URL-friendly market identifier | | `url` | `String` | Direct link to market on platform | | `title` | `String` | Market question/title | | `description` | `String` | Full market description text | | `category` | `LowCardinality(String)` | Market category (e.g., "Politics", "Sports") | | `tags` | `Array(LowCardinality(String))` | Associated tags | | `market_type` | `Enum('BINARY', 'MULTIPLE', 'SCALAR', 'PARLAY', 'PERPETUAL')` | Type of market | | `legs` | `Array(Tuple(market_id UUID, market_platform_id String, outcome_id UUID, outcome_platform_id String))` | Component selections of a `PARLAY` market; empty otherwise | | `outcomes` | `Array(Tuple(...))` | Possible outcomes (see [Outcomes](#outcomes-structure)) | | `created_at` | `DateTime64(6)` | Source-provided creation/reference time; some perpetual products use a fixed product epoch | | `opened_at` | `Nullable(DateTime64(6))` | When trading opened | | `closes_at` | `Nullable(DateTime64(6))` | When trading closes | | `resolves_at` | `Nullable(DateTime64(6))` | Expected resolution time | | `end_date` | `Nullable(DateTime64(6))` | Market end date | | `reset_at` | `Nullable(DateTime64(6))` | Last reset timestamp | | `status` | `Enum('PENDING', 'ACTIVE', 'PAUSED', 'CLOSED', 'RESOLVED')` | Current market state | ### Resolution Fields | Column | Type | Description | | - | - | - | | `resolution_type` | `Nullable(Enum('STANDARD', 'SPLIT', 'VOID'))` | How market was resolved | | `resolution_winning_outcome_id` | `Nullable(UUID)` | ID of winning outcome | | `resolution_outcome_payouts` | `Array(Tuple(outcome_id UUID, payout Decimal128(18)))` | Payout per outcome | | `resolution_resolved_by` | `Nullable(String)` | Resolver identifier | | `resolution_resolved_at` | `Nullable(DateTime64(6))` | Resolution timestamp | | `resolution_source_block_number` | `Nullable(UInt64)` | Resolution block number when supplied; API-derived resolutions can contain `0` or no meaningful chain provenance | | `resolution_source_tx_hash` | `Nullable(String)` | Resolution transaction hash when supplied; API-derived resolutions can contain an empty/default value | ### Indexing Fields | Column | Type | Description | | - | - | - | | `source_block_number` | `UInt64` | Source block number when supplied; `0` means unavailable for current API-derived market rows | | `source_tx_hash` | `FixedString(66)` | Source transaction hash when supplied; empty/default means unavailable | | `indexed_at` | `DateTime64(9)` | When Probalytics indexed this record | ### Outcomes Structure The `outcomes` column is an array of named tuples: ```sql theme={null} Array(Tuple( id UUID, -- Probalytics outcome ID platform_id String, -- Platform's native outcome ID name String, -- Outcome name (e.g., "Yes", "No", "Trump") index UInt8 -- Position in the outcomes list )) ``` **Access fields by name:** ```sql theme={null} SELECT id, title, outcome.id as outcome_id, outcome.name as outcome_name FROM markets ARRAY JOIN outcomes as outcome WHERE platform = 'POLYMARKET' LIMIT 5; ``` ### Market Types | Type | Description | | - | - | | `BINARY` | Two outcomes: Yes/No | | `MULTIPLE` | Multiple mutually exclusive outcomes | | `SCALAR` | Numeric range market | | `PARLAY` | Combined multi-leg market | | `PERPETUAL` | Perpetual or margin instrument; prices and quantities use instrument units rather than probability units | ### Market Statuses | Status | Description | | - | - | | `PENDING` | Market created but not yet open for trading | | `ACTIVE` | Open for trading | | `PAUSED` | Trading temporarily suspended | | `CLOSED` | Trading ended, awaiting resolution | | `RESOLVED` | Final outcome determined | *** ## fills Normalized execution records from supported platform and product feeds. Participant identifiers are populated only when the source exposes them. **Availability**: All retained fill history on paid ClickHouse tiers; trials normally receive the last 7 days. This is an access entitlement, not a guarantee of complete venue history. ### Schema | Column | Type | Description | | - | - | - | | `id` | `UUID` | Probalytics unique fill identifier | | `market_id` | `UUID` | Reference to `markets.id` | | `market_platform_id` | `String` | Platform's native market ID | | `platform` | `Enum('POLYMARKET', 'KALSHI')` | Source platform | | `platform_id` | `String` | Platform's native fill/trade ID | | `outcome` | `Tuple(id UUID, platform_id String, name String, index UInt8)` | The outcome traded | | `size` | `Decimal128(18)` | Traded quantity: contracts for prediction markets, venue instrument units for perpetual products | | `price` | `Decimal128(18)` | Price per contract in platform-native units | | `normalized_price` | `Decimal128(18)` | Binary: execution price expressed relative to outcome index 0, normally 0–1. Perpetual: instrument price, not a probability | | `taker_side` | `Enum('BUY', 'SELL')` | Source-specific normalized taker side; semantics differ by platform and product | | `taker_cash_flow` | `Decimal128(18)` | Stored gross/notional amount for the taker; currently not signed by BUY/SELL direction | | `maker_cash_flow` | `Decimal128(18)` | Stored gross/notional amount for the maker; currently not signed by direction | | `taker_id` | `Nullable(String)` | Taker identifier (wallet address or platform user ID) | | `maker_id` | `Nullable(String)` | Maker identifier (wallet address or platform user ID) | | `fee` | `Decimal128(18)` | Fee amount; `0` can mean fee data was unavailable rather than no fee was charged | | `timestamp` | `DateTime64(6)` | When the fill was executed (microsecond precision) | ### Indexing Fields | Column | Type | Description | | - | - | - | | `source_block_number` | `Nullable(UInt64)` | Blockchain block number (null for non-chain fills) | | `source_tx_hash` | `Nullable(String)` | Transaction hash (null for non-chain fills) | | `source_log_index` | `Nullable(UInt32)` | Log index within the transaction | | `indexed_at` | `DateTime64(9)` | When Probalytics indexed this record | | `metadata` | `JSON` | Source- or product-specific metadata; defaults to `{}` | > [!WARNING] > > Do not interpret `normalized_price` without joining `market_id` to `markets` and checking `market_type`. Do not calculate directional P\&L by summing the current cash-flow columns: their stored values are not signed by trade direction. ### Outcome Structure The `outcome` column is a named tuple: ```sql theme={null} Tuple( id UUID, -- Probalytics outcome ID platform_id String, -- Platform's native outcome ID name String, -- Outcome name index UInt8 -- Position index ) ``` **Access fields by name:** ```sql theme={null} SELECT outcome.id as outcome_id, outcome.platform_id as platform_outcome_id, outcome.name as outcome_name, outcome.index as outcome_index, price, size FROM fills LIMIT 5; ``` ### Taker Side `taker_side` is not directly comparable across every source. In particular, current Kalshi binary fills are stored as `BUY`; the source side selects the bought Yes/No outcome. Polymarket binary fills use BUY/SELL relative to exchanging quote currency and outcome tokens. See [Fills](/docs/datasets/fills#field-derivation-by-product) before aggregating by this field. *** ## orderbook\_snapshots Orderbook depth snapshots per market outcome, written when the book state changes. Each row captures the full bid/ask ladder at a point in time. **Availability**: Orderbook and Custom ClickHouse tiers. Paid credentials receive all retained history; trials normally receive the last 7 days. > [!NOTE] > > Polymarket data is available from November 20, 2025, with high-quality, high-frequency snapshots beginning February 17, 2026; earlier data may have lower capture frequency and gaps. Kalshi orderbook data is available from May 8, 2026. Coverage dates describe observed dataset availability, not a guarantee that every transition is contiguous; use the quality fields below. ### Schema | Column | Type | Description | | - | - | - | | `market_id` | `UUID` | Reference to `markets.id` | | `market_platform_id` | `String` | Platform's native market ID | | `platform` | `Enum('POLYMARKET', 'KALSHI')` | Source platform | | `outcome` | `Tuple(id UUID, platform_id String, name String, index UInt8)` | The outcome this snapshot is for | | `bids` | `Array(Tuple(price Decimal64(6), size Decimal64(6)))` | Bid levels sorted by price descending | | `asks` | `Array(Tuple(price Decimal64(6), size Decimal64(6)))` | Ask levels sorted by price ascending | | `timestamp` | `DateTime64(9)` | Exchange event time represented by the book | | `indexed_at` | `DateTime64(9)` | When Probalytics materialized the row | | `hash` | `UInt64` | Internal non-cryptographic content identity and sorting-key tiebreaker | | `state` | `Enum8('VERIFIED', 'INTERMEDIATE')` | Whether the orderbook was reconstructed without gaps or is an earlier retained state from that update sequence | | `continuity` | `Enum8('CONTIGUOUS', 'RESET')` | Whether the row connects to the preceding published row or is a fresh starting point | | `path_index` | `UInt32` | Zero-based order of rows within an emitted path; not a global sequence number | For complete-book semantics, row ordering, quality fields, historical defaults, and venue-specific reconstruction, see [Orderbook Snapshots](/docs/datasets/orderbook). ### Bid/Ask Structure Each level in the `bids` and `asks` arrays is a named tuple: ```sql theme={null} Tuple( price Decimal64(6), -- Price level size Decimal64(6) -- Total size at this price ) ``` **Access fields by name:** ```sql theme={null} SELECT market_platform_id, outcome.name as outcome_name, bids[1].price as best_bid_price, bids[1].size as best_bid_size, asks[1].price as best_ask_price, asks[1].size as best_ask_size, timestamp, continuity, path_index FROM orderbook_snapshots FINAL WHERE market_id = 'your-market-uuid-here' AND state = 'VERIFIED' ORDER BY timestamp DESC, path_index DESC, indexed_at DESC LIMIT 10; ``` ### Computed Fields BBO, spread, and mid-price are not stored — compute them at query time: * **best\_bid** = `bids[1].price` (first level in descending bids) * **best\_ask** = `asks[1].price` (first level in ascending asks) * **spread** = `asks[1].price - bids[1].price` * **mid\_price** = `(bids[1].price + asks[1].price) / 2` ### Example: Bid-Ask Spread Over Time ```sql theme={null} SELECT toStartOfMinute(timestamp) as minute, outcome.name as outcome, avg(asks[1].price - bids[1].price) as avg_spread, avg(bids[1].size + asks[1].size) as avg_top_of_book_size FROM orderbook_snapshots WHERE market_id = 'your-market-uuid-here' AND timestamp >= now() - INTERVAL 1 HOUR AND state = 'VERIFIED' AND length(bids) > 0 AND length(asks) > 0 GROUP BY minute, outcome ORDER BY minute ASC; ``` *** ## rfqs Kalshi request-for-quote lifecycle events. See [RFQs](/docs/datasets/rfqs) for coverage and normalization. **Availability**: Early access only. Email [support@probalytics.io](mailto:support@probalytics.io) to request access. ### Schema | Column | Type | Description | | - | - | - | | `id` | `UUID` | Probalytics RFQ identifier | | `platform` | `Enum('POLYMARKET', 'KALSHI', 'PREDICTIT', 'UNKNOWN')` | Source platform; currently always `KALSHI` | | `platform_id` | `String` | Kalshi RFQ ID | | `event_type` | `Enum('CREATED', 'DELETED')` | Lifecycle event | | `market_id` | `UUID` | Requested market (references `markets.id`) | | `market_platform_id` | `String` | Requested market's Kalshi ticker | | `creator_id` | `String` | Kalshi requester identifier | | `contracts` | `Nullable(Decimal128(18))` | Requested contracts | | `target_cost` | `Nullable(Decimal128(18))` | Requested cost in USD | | `timestamp` | `DateTime64(6)` | Event time | | `indexed_at` | `DateTime64(9)` | When Probalytics indexed this row | *** ## Table Relationships | From | To | Description | | - | - | - | | `fills.market_id` | `markets.id` | Links fill to its market | | `fills.market_platform_id` | `markets.platform_id` | Platform-native market reference | | `fills.outcome` | `markets.outcomes[]` | Traded outcome matches one in the market's outcomes array | | `orderbook_snapshots.market_id` | `markets.id` | Links snapshot to its market | | `orderbook_snapshots.outcome` | `markets.outcomes[]` | Snapshot outcome matches one in the market's outcomes array | | `markets.legs[].market_id` | `markets.id` | Links a combo leg to its component market | | `rfqs.market_id` | `markets.id` | Links an RFQ to the requested market | **Join example:** ```sql theme={null} SELECT m.title, f.price, f.size, f.outcome.name FROM fills f JOIN ( SELECT id, title FROM markets WHERE platform = 'POLYMARKET' AND market_type = 'BINARY' -- filter markets before joining ) m ON f.market_id = m.id WHERE f.platform = 'POLYMARKET' LIMIT 10; ``` *** ## Ordering & Partitioning Understanding table ordering helps write efficient queries. ### markets ```sql theme={null} ORDER BY (platform, id) ``` Queries filtering by `platform` and `id` align with the sorting key. A `created_at` filter is still useful for reducing the requested range, but it is not part of the current sort key. `market_type` is not in the sort key either, but always filter on it: Kalshi `PARLAY` rows are over 90% of the table, so `market_type = 'BINARY'` skips most of the data. ### fills ```sql theme={null} ORDER BY (platform, market_id, timestamp, id) PARTITION BY toYYYYMM(timestamp) ``` * Queries filtering by `platform` + `market_id` are fastest * Monthly partitions on `timestamp` allow efficient date range pruning ### orderbook\_snapshots ```sql theme={null} ORDER BY (market_id, outcome.id, timestamp, hash, state, continuity, path_index) PARTITION BY toYYYYMMDD(timestamp) ``` * Queries filtering by `market_id` + `outcome.id` are fastest * Daily partitions on `timestamp` allow efficient date range pruning * Preserve `path_index` when ordering states that share a timestamp ### rfqs ```sql theme={null} ORDER BY (platform, market_id, timestamp, id, event_type) PARTITION BY toYYYYMM(timestamp) ``` *** ## Data Types Reference ### DateTime64(6) / DateTime64(9) Microsecond (6) or nanosecond (9) stored precision timestamps in UTC. Precision indicates storage scale, not guaranteed source-clock accuracy. ```sql theme={null} -- Filter by date range WHERE timestamp >= '2024-01-01' AND timestamp < '2024-02-01' -- Extract components SELECT toYear(timestamp), toMonth(timestamp), toDayOfWeek(timestamp) ``` ### Decimal128(18) / Decimal64(6) High-precision decimals for financial values. `Decimal128(18)` has 18 decimal places (used for fill prices/sizes). `Decimal64(6)` has 6 decimal places (used for orderbook levels). ```sql theme={null} -- Restrict probability-price analysis to non-perpetual products SELECT avg(f.normalized_price) FROM fills f JOIN ( SELECT id FROM markets WHERE platform = 'POLYMARKET' AND market_type = 'BINARY' -- filter markets before joining ) m ON f.market_id = m.id WHERE f.platform = 'POLYMARKET' -- Safe arithmetic SELECT sum(size), avg(price) ``` ### Enum Types Use enum values as strings so queries remain readable and do not depend on internal numeric assignments: ```sql theme={null} -- String comparison WHERE platform = 'POLYMARKET' ``` ### Arrays Use array functions for filtering and extraction: ```sql theme={null} -- Check if array contains value WHERE has(tags, 'politics') -- Expand array to rows using ARRAY JOIN SELECT outcome.name FROM markets ARRAY JOIN outcomes as outcome -- Array length WHERE length(outcomes) > 2 -- Access by index (1-based) SELECT bids[1].price as best_bid FROM orderbook_snapshots ``` ### Named Tuples Access tuple fields directly by name: ```sql theme={null} SELECT outcome.id, outcome.platform_id, outcome.name, outcome.index FROM fills ``` # Tips & Best Practices Source: https://docs.probalytics.io/docs/sql-guide/tips Performance optimization for Probalytics queries Performance tips and common mistakes to avoid. ## Filter by ORDER BY Fields Tables are sorted by their ORDER BY columns. Filtering on these makes queries **much faster**. **markets**: `ORDER BY (platform, id)` **fills**: `ORDER BY (platform, market_id, timestamp, id)` **orderbook\_snapshots**: `ORDER BY (market_id, outcome.id, timestamp, hash, state, continuity, path_index)` Use the leftmost applicable sort-key columns and a time bound whenever possible. Time bounds reduce work even when the time column is not part of the leading sort-key prefix. ### Examples ```sql theme={null} -- Slow: No ORDER BY filters SELECT * FROM markets WHERE title LIKE '%election%'; -- Better: Use the sort-key prefix and bound the requested period SELECT * FROM markets WHERE platform = 'POLYMARKET' AND created_at >= '2024-01-01' AND title LIKE '%election%'; ``` ## Always Filter markets by market\_type Kalshi combo markets (`market_type = 'PARLAY'`) are over 90% of the `markets` table. Any query that does not filter `market_type` reads them all. ```sql theme={null} -- Slow: Reads 200M+ combo rows you do not want SELECT count() FROM markets WHERE platform = 'KALSHI'; -- Fast: Skips the combos SELECT count() FROM markets WHERE platform = 'KALSHI' AND market_type = 'BINARY'; ``` The same applies to joins. A bare `JOIN markets` loads the whole table into memory before matching; filter it in a subquery first. ```sql theme={null} -- Slow: Builds a hash table from every market SELECT f.price, m.title FROM fills f JOIN markets m ON f.market_id = m.id WHERE f.platform = 'KALSHI' AND f.timestamp >= now() - INTERVAL 1 DAY; -- Fast: Join only the markets you need SELECT f.price, m.title FROM fills f JOIN ( SELECT id, title FROM markets WHERE platform = 'KALSHI' AND market_type = 'BINARY' ) m ON f.market_id = m.id WHERE f.platform = 'KALSHI' AND f.timestamp >= now() - INTERVAL 1 DAY; ``` ```sql theme={null} -- Slow: Scans all fills SELECT * FROM fills WHERE price > 0.9; -- Fast: Filter by ORDER BY columns SELECT * FROM fills WHERE platform = 'POLYMARKET' AND market_id = 'your-market-uuid-here' AND timestamp >= '2024-01-01' AND price > 0.9; ``` ## Common Mistakes ### Always Use LIMIT Avoid loading millions of rows unintentionally—it's slow and wastes resources. ```sql theme={null} -- Bad: Loads massive result set SELECT * FROM fills; -- Good: Quick exploration SELECT * FROM fills LIMIT 100; ``` ### Don't Overuse FINAL `FINAL` forces immediate deduplication and is **significantly slower**. Use it only for counts/aggregations where exact results matter. ```sql theme={null} -- Slow: FINAL for exploration SELECT * FROM markets FINAL LIMIT 100; -- Fast: Skip FINAL for data browsing SELECT * FROM markets LIMIT 100; -- Use FINAL for accurate counts SELECT count() FROM markets FINAL; ``` ### Select Only What You Need ```sql theme={null} -- Bad: Transfers 20+ columns unnecessarily SELECT * FROM fills; -- Good: Only needed columns SELECT timestamp, normalized_price, size, taker_side FROM fills; ``` ## Working with large datasets * Filter by date and other sorting-key columns. * Aggregate in ClickHouse before returning rows. * Split large raw-data reads into smaller time ranges. ```sql theme={null} SELECT toStartOfHour(timestamp) AS hour, avg(price) AS average_price FROM fills WHERE timestamp >= now() - INTERVAL 30 DAY GROUP BY hour ORDER BY hour; ``` ## Quick Tips **Percentiles** ```sql theme={null} SELECT quantile(0.95)(price) as p95_price FROM fills WHERE market_id = 'your-market-uuid-here'; ``` **Cardinality estimates** ```sql theme={null} SELECT uniq(taker_id) as unique_takers FROM fills; ``` **Unnest outcomes array** ```sql theme={null} SELECT outcome.name FROM markets ARRAY JOIN outcomes AS outcome WHERE platform = 'POLYMARKET'; ``` **Best bid/ask from orderbook** ```sql theme={null} SELECT bids[1].price as best_bid, asks[1].price as best_ask, asks[1].price - bids[1].price as spread FROM orderbook_snapshots WHERE market_id = 'your-market-uuid-here' AND outcome.id = 'your-outcome-uuid-here' AND state = 'VERIFIED' ORDER BY timestamp DESC, path_index DESC, indexed_at DESC LIMIT 1; ``` When `continuity` is `RESET`, use that row as a fresh starting point. Do not forward-fill from the preceding row. # Support Source: https://docs.probalytics.io/docs/support Get help and contact the team ## Contact Channels > **[Discord](https://discord.gg/probalytics)** > > Community chat and support > **[Telegram](https://t.me/probalytics)** > > Direct messaging > **[Email](mailto:support@probalytics.io)** > > [support@probalytics.io](mailto:support@probalytics.io) ## When to Use Each Channel | Channel | Best For | | - | - | | **Discord** | General questions, community discussion, feature requests | | **Telegram** | Quick questions and community discussion | | **Email** | Account issues, billing, and security concerns | ## Before Contacting Support To help us resolve your issue faster, please include: 1. **Your plan tier** (Starter, Pro, Orderbook, or Custom) 2. **Access method** (REST API or SQL) 3. **Error messages** (full text or screenshot) 4. **Query or code** that produced the error 5. **Timestamp** when the issue occurred ## Common Issues Check [Troubleshooting](/docs/troubleshooting) for solutions to frequent problems before reaching out. # Troubleshooting Source: https://docs.probalytics.io/docs/troubleshooting Common issues and solutions Quick fixes for frequent problems with Probalytics. ## Authentication Issues ### "Invalid API credentials" (401) **Cause:** Incorrect authorization header format. **Fix:** Ensure the format is `Bearer API_KEY_ID:API_KEY_SECRET`: ```bash theme={null} # Wrong curl -H "Authorization: api_xxx:sk_xxx" ... curl -H "Authorization: Bearer api_xxx" ... # Correct curl -H "Authorization: Bearer api_xxx:sk_xxx" ... ``` ### "Access denied" (403) **Cause:** Your plan doesn't have access to the requested data. **Common scenarios:** * No active or trialing subscription for the REST API * Querying `orderbook_snapshots` through ClickHouse without an Orderbook or Custom tier **Fix:** Verify the subscription and access method in the dashboard. *** ## SQL / ClickHouse Issues ### "Authentication failed" **Cause:** Wrong username/password or connection settings. **Checklist:** * Host: `clickhouse.probalytics.io` * Port: `9440` (Secure TCP) or `8443` (Secure HTTPS) * Database: `probalytics` * Username and password from dashboard (not API keys) * TLS/SSL enabled (use `--secure` flag for CLI) ### Query Times Out **Cause:** Query is too broad or inefficient. **Fix:** Add filters on ORDER BY columns: ```sql theme={null} -- Slow: No filters SELECT * FROM fills WHERE price > 0.9; -- Fast: Filter by ORDER BY columns first SELECT * FROM fills WHERE platform = 'POLYMARKET' AND market_id = 'your-market-uuid-here' AND timestamp >= now() - INTERVAL 7 DAY AND price > 0.9; ``` See [SQL Tips](/docs/sql-guide/tips) for optimization guidance. ### Truncated results ClickHouse credentials can have a maximum result size. If a large query returns fewer rows than expected, aggregate in ClickHouse or split the read into smaller time ranges. Contact [support@probalytics.io](mailto:support@probalytics.io) to confirm the effective limits for your credential. Do not assume that a successful response contains every matching row. ### "Memory limit exceeded" **Cause:** Query uses too much memory. **Fixes:** * Add stricter filters to reduce data scanned * Aggregate into a coarser time interval before returning rows: ```sql theme={null} SELECT toStartOfHour(timestamp), avg(price) FROM fills WHERE timestamp >= now() - INTERVAL 7 DAY GROUP BY 1 ``` * Break query into smaller date ranges * Upgrade tier for higher memory limits ### Duplicate Rows in Results **Cause:** `ReplacingMergeTree` hasn't merged yet. **Fix:** Add `FINAL` for exact results (slower): ```sql theme={null} SELECT count() FROM markets FINAL; ``` Skip `FINAL` only when temporary duplicate identity keys are acceptable. Use it when exact deduplication is required, especially for audits and point-in-time results. *** ## REST API Issues ### Request Rejected Under Heavy Traffic No fixed REST request quota is currently part of the public contract. Operational protections can still reject abusive or unusually concurrent traffic. **Fix:** * Reduce request frequency and batch where possible * Cache responses where possible * Retry transient 5xx responses with bounded exponential backoff > [!NOTE] > > REST and direct ClickHouse connections use separate traffic and resource limits. If ClickHouse throttles or stops a query, check the limits for that credential or contact [support@probalytics.io](mailto:support@probalytics.io). ### Empty Results **Cause:** Filters too restrictive or wrong format. **Checklist:** * Dates must be RFC3339: `2024-01-01T00:00:00Z` * Enum values are uppercase: `POLYMARKET`, `ACTIVE`, `BUY` * UUIDs must be valid format ### Slow Response Times **Cause:** Requesting too much data at once. **Fixes:** * Use cursor-based pagination with `limit` and `cursor` parameters * Add filters: `platform`, `start_time`, `end_time`, `market_id` * Request only active/recent data *** ## Data Issues ### Missing Recent Data **Cause:** Source-specific ingestion delay, source recovery, or an account time-window restriction. **Note:** Most market/fill pollers normally run on short intervals, but this is not a five-minute SLA. Recovery and upstream rate limiting can extend delays. Compare `indexed_at` with the source `timestamp` where both fields are available; the difference also includes source-clock differences and processing time. ### Price Shows 0 or Unexpected Values **Cause:** Units depend on the product, and some older/source fields may be incomplete. Perpetual prices are instrument prices and can be greater than 1. A fee of `0` can mean the fee was unavailable. **Fix:** Join fills to markets and interpret values using `market_type`: ```sql theme={null} SELECT f.*, m.market_type FROM fills f JOIN ( SELECT id, market_type FROM markets WHERE id = 'your-market-uuid-here' -- filter markets before joining ) m ON f.market_id = m.id WHERE f.market_id = 'your-market-uuid-here' ``` ### Market Not Found **Cause:** Market may be: * Too new (not indexed yet) * From an unsupported platform * Using wrong ID format **Tip:** Use `platform_id` for platform-native IDs, `id` for Probalytics UUIDs. *** ## Connection Issues ### Can't Connect to ClickHouse **Checklist:** 1. Firewall allows outbound port 9440 (Secure TCP) or 8443 (Secure HTTPS) 2. Using correct host: `clickhouse.probalytics.io` 3. Credentials are for ClickHouse (not API keys) 4. TLS/SSL is enabled in your client (use `--secure` flag for CLI) 5. Try HTTPS port (8443) if TCP (9440) is blocked ### SSL/TLS Errors **Fix:** All connections require TLS. Ensure your client is configured for secure connections: ```bash theme={null} # CLI - use --secure flag clickhouse client --host=clickhouse.probalytics.io --secure --port=9440 --user=YOUR_USERNAME --password=YOUR_PASSWORD --database=probalytics ``` ```python theme={null} # clickhouse-driver - use secure=True and port 9440 client = Client(host='clickhouse.probalytics.io', port=9440, secure=True, ...) # clickhouse-connect - use port 8443 (HTTPS) client = clickhouse_connect.get_client(host='clickhouse.probalytics.io', port=8443, ...) ``` *** ## Still Stuck? If none of these solutions work: 1. Check [Discord](https://discord.gg/probalytics) for similar issues 2. Contact [support](/docs/support) with: * Error message (full text) * Query or code * Timestamp * Your tier # Introduction Source: https://docs.probalytics.io/introduction Unified prediction market data platform # Probalytics Clean, unified prediction market data. One API. Multiple access methods. Aggregate data from Polymarket, Kalshi, and more into a single normalized dataset. Choose how you access it: REST API, raw SQL, the Python client, or bulk S3 exports. > **[REST API](/docs/quickstart#rest-api)** > > Query via HTTP with auth > **[SQL (ClickHouse)](/docs/quickstart#sql-clickhouse)** > > Direct database connection > **[Python Client](/docs/python-client)** > > Typed models and dataframes > **[S3 Data Files](/docs/file-downloads/overview)** > > Bulk Parquet exports over S3 > **[Status API](/docs/api-reference/status)** > > Query uptime and incidents via HTTP (no auth required) ## The Problem > [!WARNING] > > Prediction market data is fragmented across exchanges with different APIs, formats, and schemas. Polymarket needs blockchain indexing. Kalshi has its own REST API. Building cross-platform analysis means maintaining multiple integrations and handling data inconsistencies. What we solved: * ✓ Unified API across exchanges * ✓ Normalized data schema * ✓ Dataset-specific historical coverage with source timestamps * ✓ Continuous updates * ✓ Multiple access methods for your workflow ## Data Available Three core datasets, continuously updated: > **[Markets](/docs/datasets/markets)** > > Market metadata: title, outcomes, category, status, lifecycle timestamps, and resolution data > **[Fills](/docs/datasets/fills)** > > Recorded executions: price, size, taker side, timestamp, and available participant IDs > **[Orderbook snapshots](/docs/datasets/orderbook)** > > Full bid/ask depth per outcome for Orderbook and Custom ClickHouse tiers Prediction markets and perpetual instruments share these datasets. Join fills to markets and inspect `market_type` before interpreting units: perpetual prices are instrument prices, not probabilities. > [!TIP] > > Coverage depends on dataset, source, product, and access tier. "All retained history" means all retained rows available to the account, not guaranteed coverage back to venue launch. See the [Datasets overview](/docs/datasets/overview) for coverage, normalization rules, and known exclusions. ## Supported Exchanges | Exchange | Type | Coverage | Status | | - | - | - | - | | **Polymarket** | Blockchain (Polygon) | Markets, fills, orderbook snapshots | Live ✓ | | **Kalshi** | US-regulated | Markets, fills, orderbook snapshots | Live ✓ | ## Access Methods Choose what fits your workflow: ### REST API Query via HTTP with simple authentication. Best for: production applications, quick integrations. * Authentication: API key in header * Resources: markets and fills * Operational traffic protections may apply; no fixed REST request quota is currently published * Response format: JSON ### SQL (ClickHouse) Direct database connection. Best for: data analysis, batch operations, complex queries, dashboards. * Connect from: Python, Node.js, Go, DBeaver, etc. * Full SQL support: aggregations, joins, window functions * Performance: optimized for analytics ### S3 Data Files Bulk Parquet exports over S3. Best for: backfills, local analysis, research, data science pipelines. * Format: Parquet, downloaded with any S3 client using your API key * Frequency: daily and weekly (fills), daily (orderbook snapshots), monthly (markets) * See [S3 Data Files](/docs/file-downloads/overview) ## Use Cases > **Trading** > > Build bots, alerts, dashboards. Track prices across platforms. Detect opportunities. > **Research** > > Market efficiency analysis. Forecast accuracy studies. Information aggregation patterns. > **Arbitrage** > > Find price spreads. Match markets across exchanges. Identify inefficiencies. > **Backtesting** > > Test strategies against historical data. Validate models. Performance analysis. ## Next Steps > **[Quickstart](/docs/quickstart)** > > Get working code in 2 minutes > **[Datasets](/docs/datasets/overview)** > > Coverage, provenance, normalization, and known limitations > **[SQL Guide](/docs/sql-guide/overview)** > > Tables, schemas, queries > **[S3 Data Files](/docs/file-downloads/overview)** > > Bulk Parquet exports > **[Common Queries](/docs/sql-guide/common-queries)** > > Query patterns for markets, fills, and orderbooks ## Need Help? * **Quick question?** Check [Troubleshooting](/docs/troubleshooting) * **Still stuck?** Email [support@probalytics.io](mailto:support@probalytics.io) or join our [Discord](https://discord.gg/probalytics) * **Found a bug?** Contact [support](/docs/support) with the request, timestamp, and full error