### Install Telonex SDK Source: https://telonex.io/docs/sdk/python Instructions for installing the Telonex package via pip, including optional dependencies for pandas and polars DataFrame support. ```bash pip install telonex # pandas support pip install telonex[dataframe] # polars support pip install telonex[polars] # both pip install telonex[all] ``` -------------------------------- ### Example API Request (Python SDK) Source: https://telonex.io/docs/introduction/authentication Example of using the Telonex Python SDK to download data, which handles authentication internally. ```APIDOC ## Example API Request (Python SDK) ### Description This example demonstrates how to use the Telonex Python SDK to download data. The SDK handles the API key authentication and request construction internally. ### Method SDK Function Call ### Endpoint (Handled by SDK) ### Parameters - **api_key** (string) - Required - Your Telonex API key. - **exchange** (string) - Required - The exchange name (e.g., `polymarket`). - **channel** (string) - Required - The data channel (e.g., `quotes`). - **from_date** (string) - Required - The start date for the data range (YYYY-MM-DD). - **to_date** (string) - Required - The end date for the data range (YYYY-MM-DD). - **slug** (string) - Required - The slug for the market data. - **outcome** (string) - Required - The specific outcome for the market data. ### Request Example ```python from telonex import download files = download( api_key="YOUR_API_KEY", exchange="polymarket", channel="quotes", from_date="2025-01-01", to_date="2025-01-07", slug="will-trump-win-2024", outcome="Yes", ) ``` ``` -------------------------------- ### Example API Request (Python requests) Source: https://telonex.io/docs/introduction/authentication Example of how to make an authenticated API request using the Python `requests` library, including the Authorization header and query parameters. ```APIDOC ## Example API Request (Python requests) ### Description This example shows how to authenticate and make a GET request to the Telonex API using the Python `requests` library. It includes setting the `Authorization` header and passing query parameters. ### Method GET ### Endpoint `https://api.telonex.io/v1/downloads/polymarket/quotes/2025-01-01` ### Query Parameters - **slug** (string) - Required - The slug for the market data. - **outcome** (string) - Required - The specific outcome for the market data. ### Headers - **Authorization** (string) - Required - The API key prefixed with `Bearer ` (e.g., `Bearer YOUR_API_KEY`) ### Request Example ```python import requests API_KEY = "YOUR_API_KEY" response = requests.get( "https://api.telonex.io/v1/downloads/polymarket/quotes/2025-01-01", headers={"Authorization": f"Bearer {API_KEY}"}, params={"slug": "will-trump-win-2024", "outcome": "Yes"} ) ``` ``` -------------------------------- ### Example API Request (cURL) Source: https://telonex.io/docs/introduction/authentication Example of how to make an authenticated API request using cURL, including the Authorization header. ```APIDOC ## Example API Request (cURL) ### Description This example demonstrates how to make an authenticated request to the Telonex API using cURL. It includes the necessary `Authorization` header and specifies query parameters and an output file. ### Method GET ### Endpoint `https://api.telonex.io/v1/downloads/polymarket/quotes/2025-01-01` ### Query Parameters - **slug** (string) - Required - The slug for the market data. - **outcome** (string) - Required - The specific outcome for the market data. ### Headers - **Authorization** (string) - Required - The API key prefixed with `Bearer ` (e.g., `Bearer YOUR_API_KEY`) ### Request Example ```bash curl -L -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.telonex.io/v1/downloads/polymarket/quotes/2025-01-01?slug=will-trump-win-2024&outcome=Yes" \ -o quotes.parquet ``` ``` -------------------------------- ### GET /datasets/markets Source: https://telonex.io/docs/sdk/python Download or load market metadata datasets. ```APIDOC ## GET /datasets/markets ### Description Download the markets dataset containing all market metadata or load it directly into a DataFrame. ### Method GET ### Parameters #### Query Parameters - **exchange** (str) - Required - Exchange name - **download_dir** (str) - Optional - Output directory (default: "./datasets") - **engine** (str) - Optional - DataFrame engine: "pandas" or "polars" ### Response #### Success Response (200) - **path** (str) - Path to downloaded parquet file or DataFrame object ``` -------------------------------- ### Asynchronous Data Downloading Source: https://telonex.io/docs/sdk/python Provides an example of using download_async to perform non-blocking market data downloads within an asynchronous Python context. ```python import asyncio from telonex import download_async async def main(): files = await download_async( api_key="YOUR_API_KEY", exchange="polymarket", channel="quotes", from_date="2025-01-01", to_date="2025-01-07", slug="will-the-us-strike-iran-next-433", outcome="Yes", ) print(f"Downloaded {len(files)} files") asyncio.run(main()) ``` -------------------------------- ### Fetch Data via Telonex API Source: https://telonex.io/docs/introduction/authentication Shows how to perform a GET request to the Telonex API to download market data. Includes examples using standard cURL, the Python requests library, and the official Telonex Python SDK. ```bash curl -L -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.telonex.io/v1/downloads/polymarket/quotes/2025-01-01?slug=will-trump-win-2024&outcome=Yes" \ -o quotes.parquet ``` ```python import requests API_KEY = "YOUR_API_KEY" response = requests.get( "https://api.telonex.io/v1/downloads/polymarket/quotes/2025-01-01", headers={"Authorization": f"Bearer {API_KEY}"}, params={"slug": "will-trump-win-2024", "outcome": "Yes"} ) ``` ```python from telonex import download files = download( api_key="YOUR_API_KEY", exchange="polymarket", channel="quotes", from_date="2025-01-01", to_date="2025-01-07", slug="will-trump-win-2024", outcome="Yes", ) ``` -------------------------------- ### GET /datasets/tags Source: https://telonex.io/docs/sdk/python Download or load tags metadata datasets. ```APIDOC ## GET /datasets/tags ### Description Download the tags dataset or load it directly into a DataFrame. ### Method GET ### Parameters #### Query Parameters - **exchange** (str) - Required - Exchange name - **download_dir** (str) - Optional - Output directory (default: "./datasets") - **engine** (str) - Optional - DataFrame engine: "pandas" or "polars" ### Response #### Success Response (200) - **path** (str) - Path to downloaded parquet file or DataFrame object ``` -------------------------------- ### Quick Start Data Retrieval Source: https://telonex.io/docs/sdk/python Demonstrates basic usage of the Telonex SDK to download market data files to disk or load them directly into a pandas DataFrame for analysis. ```python from telonex import download, get_dataframe, get_availability # Download data files to disk files = download( api_key="YOUR_API_KEY", exchange="polymarket", channel="quotes", from_date="2026-01-20", to_date="2026-01-21", slug="will-the-us-strike-iran-next-433", outcome="Yes", ) print(f"Downloaded {len(files)} files") # Or load directly into a pandas DataFrame df = get_dataframe( api_key="YOUR_API_KEY", exchange="polymarket", channel="quotes", from_date="2026-01-20", to_date="2026-01-21", slug="will-the-us-strike-iran-next-433", outcome="Yes", ) print(f"Loaded {len(df)} rows") # Binance spot data — no outcome needed btc = get_dataframe( api_key="YOUR_API_KEY", exchange="binance", channel="trades", from_date="2026-02-19", to_date="2026-02-20", slug="btcusdt", ) ``` -------------------------------- ### Download Binance Historical Data via Python and cURL Source: https://telonex.io/docs/exchanges/binance Examples for retrieving historical market data from Binance using the Telonex Python SDK and direct REST API calls. The Python example demonstrates fetching dataframes by slug or asset_id, while the cURL example shows how to download parquet files directly. ```python from telonex import get_dataframe # By slug (recommended) df = get_dataframe( api_key="YOUR_API_KEY", exchange="binance", channel="trades", from_date="2026-02-19", to_date="2026-02-20", slug="btcusdt", ) # By asset_id (equivalent) df = get_dataframe( api_key="YOUR_API_KEY", exchange="binance", channel="quotes", from_date="2026-02-19", to_date="2026-02-20", asset_id="btcusdt", ) ``` ```bash curl -L "https://api.telonex.io/v1/downloads/binance/trades/2026-02-19?slug=btcusdt" \ -H "Authorization: Bearer YOUR_API_KEY" \ -o btcusdt_trades.parquet ``` -------------------------------- ### API Authentication Header Example Source: https://telonex.io/docs/api/overview Demonstrates how to include the API key in the Authorization header for authenticated requests. Replace 'YOUR_API_KEY' with your actual API key. ```http Authorization: Bearer YOUR_API_KEY ``` -------------------------------- ### List All Tags Source: https://telonex.io/docs/schemas/tags-dataset Example showing how to extract and display specific columns from the tags DataFrame. ```python from telonex import get_tags_dataframe tags = get_tags_dataframe(exchange="polymarket") print(tags[['tag_slug', 'tag_label']].to_string()) ``` -------------------------------- ### Download Datasets via API Source: https://telonex.io/docs/api/datasets-endpoint Demonstrates how to fetch dataset files from the Telonex API. Includes a curl command for direct downloads and a Python example using pandas to read the Parquet format directly. ```bash curl -L "https://api.telonex.io/v1/datasets/polymarket/markets" -o markets.parquet ``` ```python import pandas as pd df = pd.read_parquet("https://api.telonex.io/v1/datasets/polymarket/markets") print(f"Found {len(df)} markets") ``` -------------------------------- ### GET /download Source: https://telonex.io/docs/sdk/python Downloads historical market data for a specified exchange, channel, and time range. ```APIDOC ## GET /download ### Description Retrieves historical market data files based on exchange, channel, and date range. Supports filtering by market ID or slug and specific outcomes. ### Method GET ### Endpoint download() ### Parameters #### Query Parameters - **api_key** (string) - Required - Your Telonex API key. - **exchange** (string) - Required - The exchange name (e.g., "polymarket"). - **channel** (string) - Required - Data channel (trades, quotes, book_snapshot_5, book_snapshot_25, book_snapshot_full, onchain_fills). - **from_date** (string) - Required - Start date in YYYY-MM-DD format. - **to_date** (string) - Required - End date in YYYY-MM-DD format. - **market_id** (string) - Optional - Unique identifier for the market. - **slug** (string) - Optional - Human-readable market identifier. - **outcome** (string) - Optional - The specific outcome to filter by. - **verbose** (boolean) - Optional - Enable to show download progress. ### Request Example ```python download( api_key="YOUR_API_KEY", exchange="polymarket", channel="quotes", from_date="2026-01-20", to_date="2026-01-21", market_id="0x285908f7d6ef04ca37e4650ebb8ba9b6d323bbe5ab3e33d8162a80906a552e5f", outcome="Yes" ) ``` ### Response #### Success Response (200) - **files** (list) - A list of file paths or objects containing the requested market data. #### Response Example ```json ["data_2026-01-20.csv", "data_2026-01-21.csv"] ``` ``` -------------------------------- ### GET /availability Source: https://telonex.io/docs/sdk/python Check the available date range for specific assets on an exchange. ```APIDOC ## GET /availability ### Description Check data availability for an asset. Returns the available date range for each channel. ### Method GET ### Parameters #### Query Parameters - **exchange** (str) - Required - Exchange name (e.g., "polymarket") - **slug** (str) - Optional - Market slug identifier - **outcome** (str) - Optional - Outcome name ### Response #### Success Response (200) - **exchange** (str) - Exchange name - **asset_id** (str) - Unique asset identifier - **channels** (dict) - Available date ranges per channel ### Response Example { "exchange": "polymarket", "asset_id": "21742633...", "channels": { "trades": {"from_date": "2024-01-15", "to_date": "2024-11-06"} } } ``` -------------------------------- ### Get Redirect URL without Following (Python requests) Source: https://telonex.io/docs/api/download-endpoint This Python example illustrates how to obtain the redirect URL without automatically following it, using `allow_redirects=False` with the `requests` library. This is useful if you need to inspect the redirect URL or handle the download process manually. The code checks for a 302 status code and extracts the `Location` header. ```python import requests # Use allow_redirects=False to get the redirect URL response = requests.get( "https://api.telonex.io/v1/downloads/polymarket/trades/2026-01-20", params={"slug": "will-the-us-strike-iran-next-433", "outcome": "Yes"}, allow_redirects=False ) if response.status_code == 302: download_url = response.headers["Location"] print(f"Download URL: {download_url}") # Load from the URL df = pd.read_parquet(download_url) ``` -------------------------------- ### Querying Binance Markets Source: https://telonex.io/docs/api/identifier-options Demonstrates how to query single-asset markets like Binance where outcomes are not required. Includes both cURL and Telonex SDK examples. ```bash curl -L "https://api.telonex.io/v1/downloads/binance/trades/2026-02-19?slug=btcusdt" -H "Authorization: Bearer YOUR_API_KEY" -o trades.parquet ``` ```python from telonex import get_dataframe df = get_dataframe( api_key="YOUR_API_KEY", exchange="binance", channel="trades", from_date="2026-02-19", to_date="2026-02-20", slug="btcusdt" ) ``` -------------------------------- ### Download Historical Data with curl Source: https://telonex.io/docs/api/download-endpoint This example demonstrates how to download historical market data using the curl command-line tool. The `-L` flag ensures that curl follows the redirect to the actual download URL. The output is saved to a file named `trades.parquet`. ```shell # -L follows the redirect to the download URL curl -L "https://api.telonex.io/v1/downloads/polymarket/trades/2026-01-20?slug=will-the-us-strike-iran-next-433&outcome=Yes" \ -o trades.parquet ``` -------------------------------- ### GET /v1/datasets/{exchange}/{dataset} Source: https://telonex.io/docs/api/overview Download a dataset file for a specific exchange and dataset. No authentication is required for this endpoint. ```APIDOC ## GET /v1/datasets/{exchange}/{dataset} ### Description Download dataset file (no auth required) ### Method GET ### Endpoint `/v1/datasets/{exchange}/{dataset}` ### Parameters #### Path Parameters - **exchange** (string) - Required - The name of the exchange. - **dataset** (string) - Required - The name of the dataset. ### Response #### Success Response (200) - This endpoint returns the dataset file. ``` -------------------------------- ### Handle API Errors with Telonex Library (Python) Source: https://telonex.io/docs/sdk/python This Python example shows how to handle various errors that can occur when using the Telonex download function. It imports specific exception classes from the telonex library to catch and report issues like authentication failures, not found data, rate limits, entitlement errors, and validation problems. ```python from telonex import ( download, AuthenticationError, NotFoundError, RateLimitError, EntitlementError, ValidationError, ) try: files = download( api_key="YOUR_API_KEY", exchange="polymarket", channel="quotes", from_date="2025-01-01", to_date="2025-01-07", slug="will-the-us-strike-iran-next-433", outcome="Yes", ) except AuthenticationError: print("Invalid API key") except NotFoundError as e: print(f"Data not found for date: {e.date}") except RateLimitError as e: print(f"Rate limited, retry after {e.retry_after} seconds") except EntitlementError as e: print(f"Download limit exceeded. Remaining: {e.downloads_remaining}") except ValidationError as e: print(f"Invalid parameters: {e}") ``` -------------------------------- ### Download Historical Data using Telonex Python SDK Source: https://telonex.io/docs/api/download-endpoint This example showcases how to download historical market data using the `telonex` Python SDK. The `get_dataframe` function simplifies the process by handling the API request and data loading directly into a pandas DataFrame. This method supports specifying data by slug and outcome. ```python from telonex import get_dataframe # Download by slug - returns DataFrame directly df = get_dataframe( exchange="polymarket", channel="trades", from_date="2026-01-20", to_date="2026-01-21", slug="will-the-us-strike-iran-next-433", outcome="Yes", ) print(f"Loaded {len(df)} trades") ``` -------------------------------- ### GET /v1/downloads/{exchange}/{channel}/{date} Source: https://telonex.io/docs/api/overview Download data file for a specific exchange, channel, and date. This endpoint returns a 302 redirect to a pre-signed S3 URL. ```APIDOC ## GET /v1/downloads/{exchange}/{channel}/{date} ### Description Download data file (returns redirect) ### Method GET ### Endpoint `/v1/downloads/{exchange}/{channel}/{date}` ### Parameters #### Path Parameters - **exchange** (string) - Required - The name of the exchange. - **channel** (string) - Required - The name of the channel. - **date** (string) - Required - The date for the data file (e.g., YYYY-MM-DD). ### Response #### Success Response (302) - This endpoint returns a 302 redirect to a pre-signed S3 URL. ``` -------------------------------- ### Check Availability with Python Source: https://telonex.io/docs/api/availability Demonstrates how to check data availability using Python's requests library. It makes a GET request to the availability endpoint and processes the JSON response to print asset details and channel date ranges. ```python import requests response = requests.get( "https://api.telonex.io/v1/availability/polymarket", params={ "slug": "xrp-updown-15m-1764246600", "outcome": "Up" } ) data = response.json() print(f"Asset: {data['slug']} - {data['outcome']}") for channel, dates in data["channels"].items(): print(f" {channel}: {dates['from_date']} to {dates['to_date']}") ``` -------------------------------- ### Check Availability with Curl Source: https://telonex.io/docs/api/availability Example of how to check data availability using curl. This command sends a GET request to the availability endpoint with specified query parameters for market slug and outcome. ```shell curl "https://api.telonex.io/v1/availability/polymarket?slug=xrp-updown-15m-1764246600&outcome=Up" ``` -------------------------------- ### Download Market Data to Disk Source: https://telonex.io/docs/sdk/python Detailed usage of the download function to fetch market data files, supporting optional parameters like download directory, logging, and concurrency. ```python from telonex import download files = download( api_key="YOUR_API_KEY", exchange="polymarket", channel="quotes", from_date="2026-01-20", to_date="2026-01-21", slug="will-the-us-strike-iran-next-433", outcome="Yes", download_dir="./datasets", # optional, default: "./datasets" verbose=False, # optional, enable logging concurrency=5, # optional, max concurrent downloads ) ``` -------------------------------- ### Process Flattened Snapshots with Pandas Source: https://telonex.io/docs/schemas/book-snapshot Demonstrates how to load a flattened Parquet snapshot, convert string-based price and size fields to floats, and perform basic liquidity calculations like spread and depth. ```python import pandas as pd df = pd.read_parquet("book_snapshot_5.parquet") # Convert string prices/sizes to float for calculations price_cols = [f'{side}_price_{i}' for side in ['bid', 'ask'] for i in range(5)] size_cols = [f'{side}_size_{i}' for side in ['bid', 'ask'] for i in range(5)] for col in price_cols + size_cols: if col in df.columns: df[col] = df[col].astype(float) # Extract best bid/ask df['best_bid'] = df['bid_price_0'] df['best_ask'] = df['ask_price_0'] df['spread'] = df['best_ask'] - df['best_bid'] # Calculate depth at top 3 levels df['bid_depth_3'] = df['bid_size_0'] + df['bid_size_1'] + df['bid_size_2'] df['ask_depth_3'] = df['ask_size_0'] + df['ask_size_1'] + df['ask_size_2'] ``` -------------------------------- ### GET /v1/availability/{exchange} Source: https://telonex.io/docs/api/overview Check data availability for a specific exchange. No authentication is required for this endpoint. ```APIDOC ## GET /v1/availability/{exchange} ### Description Check data availability (no auth required) ### Method GET ### Endpoint `/v1/availability/{exchange}` ### Parameters #### Path Parameters - **exchange** (string) - Required - The name of the exchange. ### Response #### Success Response (200) - **detail** (string) - Information about data availability. ``` -------------------------------- ### GET /v1/datasets/polymarket/tags Source: https://telonex.io/docs/exchanges/polymarket Retrieves tag definitions used for categorizing markets on the Polymarket platform. ```APIDOC ## GET /v1/datasets/polymarket/tags ### Description Returns a dataset containing tag definitions for market categorization. ### Method GET ### Endpoint /v1/datasets/polymarket/tags ### Response #### Success Response (200) - **data** (parquet) - A parquet file containing tag mappings. #### Response Example ```python import pandas as pd tags = pd.read_parquet("https://api.telonex.io/v1/datasets/polymarket/tags") ``` ``` -------------------------------- ### Process Full Book Snapshots with Pandas Source: https://telonex.io/docs/schemas/book-snapshot Shows how to handle the nested structure of full book snapshots where bids and asks are stored as lists of dictionaries, requiring iteration to access individual price levels. ```python import pandas as pd df = pd.read_parquet("book_snapshot_full.parquet") # Each row has 'bids' and 'asks' as lists of dicts # Note: price and size are strings, convert as needed for idx, row in df.head(1).iterrows(): print("Bids:") for level in row['bids'][:5]: price = float(level['price']) size = float(level['size']) print(f" {price}: {size}") print("Asks:") for level in row['asks'][:5]: price = float(level['price']) size = float(level['size']) print(f" {price}: {size}") ``` -------------------------------- ### GET /v1/datasets/polymarket/markets Source: https://telonex.io/docs/exchanges/polymarket Retrieves the full list of market metadata for Polymarket, including data availability status for each market. ```APIDOC ## GET /v1/datasets/polymarket/markets ### Description Returns a dataset containing all market metadata, including identifiers and data availability windows. ### Method GET ### Endpoint /v1/datasets/polymarket/markets ### Response #### Success Response (200) - **data** (parquet) - A parquet file containing market definitions, slugs, and market_ids. #### Response Example ```python import pandas as pd markets = pd.read_parquet("https://api.telonex.io/v1/datasets/polymarket/markets") ``` ``` -------------------------------- ### Calculate Volume by Wallet with Pandas Source: https://telonex.io/docs/schemas/onchain-fills Calculates the notional volume traded by each maker using pandas. It filters for direct trades, computes the notional value for each trade, and then groups by maker to sum their total notional volume. ```python direct = df[~df['mirrored']].copy() direct['notional'] = direct['amount'] * direct['price'] maker_vol = direct.groupby('maker')['notional'].sum().sort_values(ascending=False) print("Top 5 makers by notional volume:") print(maker_vol.head()) ``` -------------------------------- ### Download Datasets via Python SDK Source: https://telonex.io/docs/api/datasets-endpoint Demonstrates how to use the official Telonex Python SDK to retrieve market data. This method abstracts the API call and returns a pandas DataFrame directly. ```python from telonex import get_markets_dataframe df = get_markets_dataframe(exchange="polymarket") print(df[['slug', 'question']].head()) ``` -------------------------------- ### GET /v1/availability/{exchange} Source: https://telonex.io/docs/api/availability Retrieves the available date range for specific assets on a given exchange. This endpoint is public and does not require authentication. ```APIDOC ## GET /v1/availability/{exchange} ### Description Check data availability for a specific asset. Returns the available date range for each channel (e.g., trades, quotes). ### Method GET ### Endpoint /v1/availability/{exchange} ### Parameters #### Path Parameters - **exchange** (string) - Required - The exchange name (e.g., polymarket) #### Query Parameters - **asset_id** (string) - Optional - Unique asset/token ID - **market_id** (string) - Optional - Market ID - **outcome** (string) - Optional - Outcome label (e.g., "Yes", "No") - **outcome_id** (integer) - Optional - Outcome index (0 or 1) - **slug** (string) - Optional - Market slug ### Request Example curl "https://api.telonex.io/v1/availability/polymarket?slug=xrp-updown-15m-1764246600&outcome=Up" ### Response #### Success Response (200) - **exchange** (string) - Exchange name - **asset_id** (string) - Asset/token ID - **market_id** (string) - Market ID - **slug** (string) - Market slug - **outcome** (string) - Outcome label - **outcome_id** (integer) - Outcome index - **channels** (object) - Map of channel names to date ranges #### Response Example { "exchange": "polymarket", "asset_id": "21742633143463906290569050155826241533067272736897614950488156847949938836455", "channels": { "trades": { "from_date": "2024-01-15", "to_date": "2024-11-06" } } } ``` -------------------------------- ### Enable Verbose Mode for Debugging Downloads (Python) Source: https://telonex.io/docs/sdk/python This Python code illustrates how to enable verbose mode in the Telonex `download` function. Setting `verbose=True` provides detailed output, such as download progress, which is useful for debugging and monitoring data retrieval operations. ```python files = download( api_key="YOUR_API_KEY", exchange="polymarket", channel="quotes", from_date="2026-01-20", to_date="2026-01-21", slug="will-the-us-strike-iran-next-433", outcome="Yes", verbose=True, # Shows download progress ) ``` -------------------------------- ### On-Chain Fills Schema Details Source: https://telonex.io/docs/schemas/onchain-fills This section details the schema for the onchain_fills channel, including field names, data types, and descriptions. It also explains partitioning and mirroring strategies for trade data. ```APIDOC ## On-Chain Fills Schema ### Description The `onchain_fills` channel contains executed trades scraped directly from the Polygon blockchain. Data goes back to November 2022. Each row represents one maker fill. ### Schema | Field | Type | Description | Partition Key | |-----------------------|---------|---------------------------------------------------------------------------|---------------| | `block_number` | int64 | Block number where trade was settled | | | `block_timestamp_us` | int64 | Block timestamp in microseconds since epoch | | | `tx_hash` | string | Transaction hash (hex with 0x prefix) | | | `transaction_index` | int32 | Transaction index within block | | | `log_index` | int32 | Event log index within transaction | | | `exchange` | string | Exchange identifier (`polymarket`) | | | `chain_id` | int32 | Blockchain ID (137 for Polygon) | | | `asset_id` | string | Outcome token this row belongs to | **Yes** | | `sibling_asset_id` | string | Complementary outcome token in the binary pair | | | `maker_asset_id` | string | Outcome token the maker was trading | | | `taker_asset_id` | string | Outcome token the taker was trading | | | `market_id` | string | Condition ID (hex) identifying the market | | | `order_hash` | string | Unique order hash for the maker's order | | | `maker` | string | Maker wallet address | | | `taker` | string | Taker wallet address | | | `mirrored` | bool | `false` if `asset_id == maker_asset_id` (direct row), `true` otherwise | | | `maker_side` | string | `buy` or `sell` — maker's action relative to `maker_asset_id` | | | `taker_side` | string | `buy` or `sell` — taker's action relative to `taker_asset_id` | | | `amount` | string | Trade size in shares (decimal string) | | | `price` | string | USDC per share of the row's `asset_id` token (decimal string, 0 to 1) | | ### Notes - The `price` and `amount` fields are stored as strings to preserve decimal precision. Convert to float/Decimal for calculations. ### Deduplication Rows are uniquely identified by `(tx_hash, log_index)` within each `asset_id` partition. To avoid double-counting trades, filter to `mirrored == false` or work within a single asset partition. ### Partitioning and Mirroring Data is partitioned by `asset_id`. Each fill produces two rows: a direct row (`mirrored=false`) and a mirrored row (`mirrored=true`). | Row Type | Partition | `mirrored` | Price | |----------|------------------|------------|-------------------| | Direct | maker_asset_id | `false` | Original | | Mirrored | sibling_asset_id | `true` | `1 - direct_price`| **Caution**: When merging YES and NO partitions, filter on `mirrored == false` to avoid double-counting. Within a single partition, every row's `price` already represents the same token's price. ### Exchange Contract Events Polymarket's exchange contracts emit `OrderFilled` and `OrdersMatched` events. The pipeline filters for `OrderFilled` events where the `taker` is not the exchange contract itself, ensuring one row per maker fill. `OrdersMatched` events are used to determine taker details, especially for cross-token trades. ``` -------------------------------- ### GET /v1/downloads/{exchange}/{channel}/{date} Source: https://telonex.io/docs/api/download-endpoint Download historical market data. This endpoint returns a redirect to a pre-signed download URL for the requested data. ```APIDOC ## GET /v1/downloads/{exchange}/{channel}/{date} ### Description Download historical market data. Returns a redirect to a pre-signed download URL. ### Method GET ### Endpoint `/v1/downloads/{exchange}/{channel}/{date}` ### Parameters #### Path Parameters - **exchange** (string) - Required - Exchange name (e.g., `polymarket`) - **channel** (string) - Required - Data channel (e.g., `trades`, `quotes`, `book_snapshot_5`, `book_snapshot_25`, `book_snapshot_full`, `onchain_fills`) - **date** (string) - Required - Date in `YYYY-MM-DD` format #### Query Parameters *Specify the asset using one of the following methods:* - **asset_id** (string) - Required (if not using market/slug parameters) - Unique asset/token ID - **market_id** (string) - Required (if not using asset_id/slug parameters) - Market ID - **outcome** (string) - Required (if using market_id or slug) - Outcome label (e.g., "Yes", "No") - **outcome_id** (integer) - Required (if using market_id or slug) - Outcome index (0 or 1) - **slug** (string) - Required (if not using asset_id/market_id parameters) - Market slug ### Request Example ```bash curl -L "https://api.telonex.io/v1/downloads/polymarket/trades/2026-01-20?slug=will-the-us-strike-iran-next-433&outcome=Yes" -o trades.parquet ``` ### Response #### Success Response (302 Redirect) The endpoint returns an HTTP 302 redirect to a pre-signed S3 URL. The download URL is in the `Location` header. ``` HTTP/1.1 302 Found Location: https://s3.amazonaws.com/bucket/file.parquet?X-Amz-Signature=...&X-Amz-Expires=900 ``` * The pre-signed URL expires in **15 minutes**. * The `Content-Disposition` header on the S3 response forces a download. #### Error Responses - **400 Bad Request**: Missing or invalid parameters. - **403 Forbidden**: Download limit exceeded or subscription required. Includes `X-Downloads-Remaining` header. - **404 Not Found**: No data available for the specified parameters. - **422 Validation Error**: Invalid channel or date format. ``` -------------------------------- ### Use Environment Variables for API Key (Python) Source: https://telonex.io/docs/sdk/python This Python snippet demonstrates a best practice for securely managing API keys by using environment variables. It imports the `os` module to access the `TELONEX_API_KEY` environment variable for the `download` function, avoiding hardcoding sensitive credentials. ```python import os from telonex import download files = download( api_key=os.environ["TELONEX_API_KEY"], exchange="polymarket", channel="quotes", from_date="2026-01-20", to_date="2026-01-21", slug="will-the-us-strike-iran-next-433", outcome="Yes", ) ``` -------------------------------- ### Fetch On-Chain Fills with Pandas Source: https://telonex.io/docs/schemas/onchain-fills Fetches on-chain fill data for a specific market and outcome from Telonex IO using the `telonex` library and pandas. It includes type conversions and filtering for direct trades. ```python from telonex import get_dataframe import pandas as pd df = get_dataframe( api_key="YOUR_API_KEY", exchange="polymarket", channel="onchain_fills", slug="will-donald-trump-win-the-2024-us-presidential-election", outcome="Yes", from_date="2024-11-05", to_date="2024-11-06", ) # Convert types df['price'] = df['price'].astype(float) df['amount'] = df['amount'].astype(float) df['timestamp'] = pd.to_datetime(df['block_timestamp_us'], unit='us') # Filter to direct rows only (avoid double-counting) direct = df[~df['mirrored']] print(f"Total fills: {len(direct)}") print(f"Unique makers: {direct['maker'].nunique()}") print(f"Unique takers: {direct['taker'].nunique()}") ``` -------------------------------- ### GET /v1/datasets/{exchange}/{dataset} Source: https://telonex.io/docs/api/datasets-endpoint Downloads metadata datasets. Returns a redirect to a pre-signed download URL for Apache Parquet files. Datasets are updated daily after midnight UTC. ```APIDOC ## GET /v1/datasets/{exchange}/{dataset} ### Description Download metadata datasets. Returns a redirect to a pre-signed download URL. Datasets are regenerated daily after midnight UTC and are not real-time. ### Method GET ### Endpoint `/v1/datasets/{exchange}/{dataset}` ### Parameters #### Path Parameters - **exchange** (string) - Required - Exchange name (e.g., `polymarket`) - **dataset** (string) - Required - Dataset name. Available datasets include `markets` (Market metadata) and `tags` (Tag definitions). ### Response #### Success Response (302 Redirect) Returns an HTTP 302 redirect to a pre-signed S3 URL. The file is in Apache Parquet format. #### Error Response (404 Not Found) - **error** (string) - Description - Unknown exchange or dataset ### Examples #### Download with curl ```bash curl -L "https://api.telonex.io/v1/datasets/polymarket/markets" -o markets.parquet ``` #### Download with Python ```python import pandas as pd df = pd.read_parquet("https://api.telonex.io/v1/datasets/polymarket/markets") print(f"Found {len(df)} markets") ``` #### Using the Python SDK ```python from telonex import get_markets_dataframe df = get_markets_dataframe(exchange="polymarket") print(df[['slug', 'question']].head()) ``` ``` -------------------------------- ### Load Data into DataFrames Source: https://telonex.io/docs/sdk/python Demonstrates how to use get_dataframe to retrieve market data into either pandas or polars DataFrames by specifying the engine parameter. ```python from telonex import get_dataframe # Pandas DataFrame (default) df = get_dataframe( api_key="YOUR_API_KEY", exchange="polymarket", channel="quotes", from_date="2026-01-20", to_date="2026-01-21", slug="will-the-us-strike-iran-next-433", outcome="Yes", ) # Polars DataFrame df = get_dataframe( api_key="YOUR_API_KEY", exchange="polymarket", channel="quotes", from_date="2026-01-20", to_date="2026-01-21", slug="will-the-us-strike-iran-next-433", outcome="Yes", engine="polars", ) ``` -------------------------------- ### Calculate USD Per Share for Trades (Python) Source: https://telonex.io/docs/schemas/onchain-fills Computes the actual USD cost per share for both the maker and taker, accounting for whether they traded the row's primary token or its sibling. This is essential for accurate volume and P&L calculations. ```python import numpy as np # USD per share for the maker df['maker_usd_per_share'] = np.where( df['maker_asset_id'] == df['asset_id'], df['price'], # Trading the row's token 1 - df['price'] # Trading the sibling ) # USD per share for the taker df['taker_usd_per_share'] = np.where( df['taker_asset_id'] == df['asset_id'], df['price'], 1 - df['price'] ) ``` -------------------------------- ### GET /downloads/binance/trades/{date} - Binance Identification Source: https://telonex.io/docs/api/identifier-options Retrieves trade data for Binance markets. For Binance, `slug`, `market_id`, and `asset_id` are the same (e.g., 'btcusdt'). An outcome is not needed as Binance markets are single-asset. ```APIDOC ## GET /downloads/binance/trades/{date} ### Description Retrieves trade data for Binance markets. For Binance, `slug`, `market_id`, and `asset_id` are the same (e.g., 'btcusdt'). An outcome is not needed as Binance markets are single-asset. ### Method GET ### Endpoint `/downloads/binance/trades/{date}` ### Parameters #### Query Parameters - **slug** (string) - Required - The symbol for the Binance market (e.g., 'btcusdt'). - **asset_id** (string) - Required - The symbol for the Binance market (e.g., 'btcusdt'). ### Request Example ```bash # By slug curl -L "https://api.telonex.io/v1/downloads/binance/trades/2026-02-19?slug=btcusdt" \ -H "Authorization: Bearer YOUR_API_KEY" \ -o trades.parquet ``` ### Response #### Success Response (200) - **data** (file) - Parquet file containing trade data. #### Response Example (Binary data for parquet file) ``` -------------------------------- ### GET /book_snapshot_{depth} Source: https://telonex.io/docs/schemas/book-snapshot Retrieves order book snapshots at specific depth levels. The 5 and 25 level snapshots use a flattened schema, while the full snapshot provides a nested structure. ```APIDOC ## GET /book_snapshot_{depth} ### Description Provides event-driven order book snapshots. `book_snapshot_5` and `book_snapshot_25` provide fixed-depth snapshots, while `book_snapshot_full` provides the complete order book state. ### Method GET ### Endpoint /book_snapshot_{depth} ### Parameters #### Path Parameters - **depth** (string) - Required - The depth level: 5, 25, or full. ### Response #### Success Response (200) - **timestamp_us** (int64) - Exchange timestamp in microseconds - **local_timestamp_us** (int64) - Collector receipt time in microseconds - **exchange** (string) - Exchange name - **market_id** (string) - Exchange-specific market ID - **slug** (string) - URL-friendly market identifier - **asset_id** (string) - Unique asset/token ID - **bid_price_N** (string) - Price at level N (Flattened schema only) - **bid_size_N** (string) - Size at level N (Flattened schema only) - **bids** (list) - List of objects with price/size (Full schema only) - **asks** (list) - List of objects with price/size (Full schema only) ### Response Example { "timestamp_us": 1730851200000000, "bid_price_0": "0.650", "bid_size_0": "500", "ask_price_0": "0.655", "ask_size_0": "400" } ``` -------------------------------- ### Download Metadata Datasets Source: https://telonex.io/docs/sdk/python Downloads daily-updated parquet files containing market or tag metadata. These functions do not require an API key. ```python from telonex import download_markets, download_tags path_markets = download_markets(exchange="polymarket", download_dir="./datasets") path_tags = download_tags(exchange="polymarket", download_dir="./datasets") ``` -------------------------------- ### GET /downloads/polymarket/trades/{date} - Identify by Market ID + Outcome Source: https://telonex.io/docs/api/identifier-options Retrieves trade data by combining a `market_id` with a specific `outcome` label. This method is useful when integrating with the Polymarket API and knowing the outcome names. ```APIDOC ## GET /downloads/polymarket/trades/{date} ### Description Retrieves trade data by combining a `market_id` with a specific `outcome` label. This method is useful when integrating with the Polymarket API and knowing the outcome names. ### Method GET ### Endpoint `/downloads/polymarket/trades/{date}` ### Parameters #### Query Parameters - **market_id** (string) - Required - The unique identifier for the market. - **outcome** (string) - Required - The specific outcome of the market (e.g., 'Yes', 'No'). ### Request Example ```bash curl -L "https://api.telonex.io/v1/downloads/polymarket/trades/2026-01-20?market_id=0x285908f7d6ef04ca37e4650ebb8ba9b6d323bbe5ab3e33d8162a80906a552e5f&outcome=Yes" \ -o trades.parquet ``` ### Response #### Success Response (200) - **data** (file) - Parquet file containing trade data. #### Response Example (Binary data for parquet file) ```