-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Add Polymarket Gamma API support for instrument loading #3141
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
cjdsellers
merged 79 commits into
nautechsystems:develop
from
DeirhX:gamma-markets-fetch
Nov 6, 2025
Merged
Changes from 78 commits
Commits
Show all changes
79 commits
Select commit
Hold shift + click to select a range
32b0e70
Release 1.176.0
cjdsellers e658ba6
Release 1.177.0
cjdsellers ef75e5f
Release 1.178.0
cjdsellers ef4d72e
Release 1.179.0
cjdsellers 622014e
Release 1.180.0
cjdsellers 63c191b
Release 1.181.0
cjdsellers f1b643d
Release 1.182.0
cjdsellers 178d621
Release 1.183.0
cjdsellers a79c2bb
Release 1.184.0
cjdsellers 9d09e96
Release 1.185.0
cjdsellers 8aae236
Release 1.186.0
cjdsellers 61debf2
Release 1.187.0
cjdsellers 92aee66
Release 1.188.0
cjdsellers 5e12bdf
Release 1.189.0
cjdsellers 5f31d43
Release 1.190.0
cjdsellers 0eb0b56
Release 1.191.0
cjdsellers 3db0827
Release 1.192.0
cjdsellers c059eb8
Release 1.193.0
cjdsellers 86acc83
Release 1.194.0
cjdsellers 1364ac3
Release 1.195.0
cjdsellers e40eb3d
Release 1.196.0
cjdsellers c760fb0
Release 1.197.0
cjdsellers 84442a2
Release 1.198.0
cjdsellers 7a496b4
Release 1.199.0
cjdsellers 5823764
Release 1.200.0
cjdsellers eed7861
Release 1.201.0
cjdsellers 5089347
Release 1.201.0
cjdsellers fad3968
Release 1.202.0
cjdsellers 928f5a7
Release 1.203.0
cjdsellers 3fd212d
Release 1.204.0
cjdsellers 59ca217
Release 1.205.0
cjdsellers 230b42f
Release 1.206.0
cjdsellers 02a9ef1
Release 1.207.0
cjdsellers 845ebea
Release 1.208.0
cjdsellers 290bd8e
Release 1.209.0
cjdsellers fa0f1c0
Release 1.210.0
cjdsellers 014098b
Release 1.211.0
cjdsellers c63653f
Release 1.211.0
cjdsellers 8ca4a13
Release 1.212.0
cjdsellers c68468b
Release 1.212.0
cjdsellers e317039
Release 1.213.0
cjdsellers e4fff98
Release 1.214.0
cjdsellers 4a95295
Release 1.215.0
cjdsellers bdc275e
Release 1.216.0
cjdsellers e8d6677
Fix CI build workflow for release
cjdsellers e479ab4
Release 1.217.0
cjdsellers f8f2122
Release 1.218.0
cjdsellers e9f3471
Add high-precision settings
odobias 62c1f34
Fix the dependencies format
odobias 44ac6ab
Fix the dependencies format
odobias cab4f67
Fix the dependencies format, again
odobias c56b4a0
Remove high-precision feature
DeirhX 1a7d2dd
Try to find a good home for the native cpu flag
DeirhX 3adbdaa
Merge branch 'develop' of https://github.com/nautechsystems/nautilus_…
DeirhX fd0dd74
Merge with nautech develop
DeirhX fc33c90
When venue_id can be obtained from cache, use it for the query instea…
DeirhX e5da382
Merge branch 'develop' of https://github.com/nautechsystems/nautilus_…
DeirhX 66c8f9a
Merge branch 'develop' of https://github.com/DeirhX/nautilus_trader i…
DeirhX 1a68ec4
Merge branch 'develop' of https://github.com/nautechsystems/nautilus_…
DeirhX f92220e
Merge branch 'develop' of https://github.com/nautechsystems/nautilus_…
DeirhX 04dcc19
Merge with develop and remove native CPU
DeirhX 94c7649
Optionally use Gamma API to fetch a large number of markets
DeirhX dc11142
Add more data that was present in clob api
DeirhX 2d6d8b6
Normalize as much Gamma API data to CLOB format
DeirhX 44823df
Don't iterate all, just the condition ids we need
DeirhX 196e35c
Formalize the condition_id limit after measuring it is indeed 100
DeirhX 2db77b6
Merge branch 'develop' of https://github.com/nautechsystems/nautilus_…
DeirhX 13e9c5a
Formatting adjustments
DeirhX a034ef2
Formatting fix
DeirhX 19d8eda
Formatting fix
DeirhX 69e218a
Styling improvements
DeirhX 8b7ff16
Docformatted
DeirhX 5aab08b
Style fixes
DeirhX aa5c3a5
Remove proprietary logger
DeirhX 9eff8dc
Adjust unit tests for gamma markets API
DeirhX a43dc5f
Better documentation
DeirhX b2f7637
Trimmed whitespace
DeirhX b7ecf9b
Merged with develop
DeirhX ea10488
Made _load_ids_using_gamma_markets async
DeirhX File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
293 changes: 293 additions & 0 deletions
293
nautilus_trader/adapters/polymarket/common/gamma_markets.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,293 @@ | ||
| # ------------------------------------------------------------------------------------------------- | ||
| # Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved. | ||
| # https://nautechsystems.io | ||
| # | ||
| # Licensed under the GNU Lesser General Public License Version 3.0 (the "License"); | ||
| # You may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| # ------------------------------------------------------------------------------------------------- | ||
| """ | ||
| Thin Gamma Markets API client utilities for Polymarket. | ||
|
|
||
| Provides functions to fetch markets using server-side filters, returning | ||
| raw market dictionaries ready for further client-side filtering. | ||
|
|
||
| References | ||
| ---------- | ||
| - Gamma Get Markets docs: https://docs.polymarket.com/developers/gamma-markets-api/get-markets | ||
|
|
||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| from collections.abc import Generator | ||
| from typing import Any | ||
|
|
||
| import requests | ||
|
|
||
|
|
||
| DEFAULT_GAMMA_BASE_URL = os.getenv("GAMMA_API_URL", "https://gamma-api.polymarket.com") | ||
|
|
||
|
|
||
| def _normalize_base_url(base_url: str | None) -> str: | ||
| url = base_url or DEFAULT_GAMMA_BASE_URL | ||
| return url[:-1] if url.endswith("/") else url | ||
|
|
||
|
|
||
| def build_markets_query(filters: dict[str, Any] | None = None) -> dict[str, Any]: | ||
| """ | ||
| Build query params for Gamma Get Markets from a generic filter dict. | ||
|
|
||
| Supported keys (passed through if present): | ||
| - active, archived, closed, limit, offset, order, ascending, id, slug, | ||
| clob_token_ids, condition_ids, | ||
| liquidity_num_min, liquidity_num_max, | ||
| volume_num_min, volume_num_max, | ||
| start_date_min, start_date_max, | ||
| end_date_min, end_date_max, | ||
| tag_id, related_tags | ||
|
|
||
| Special handling: | ||
| - is_active=True implies active=true, archived=false, closed=false | ||
| - next_cursor: will be added separately by the fetch function | ||
|
|
||
| """ | ||
| params: dict[str, Any] = {} | ||
| if not filters: | ||
| return params | ||
|
|
||
| if filters.get("is_active") is True: | ||
| params["active"] = "true" | ||
| params["archived"] = "false" | ||
| params["closed"] = "false" | ||
|
|
||
| passthrough_keys = ( | ||
| "active", | ||
| "archived", | ||
| "closed", | ||
| "limit", | ||
| "offset", | ||
| "order", | ||
| "ascending", | ||
| "id", | ||
| "slug", | ||
| "clob_token_ids", | ||
| "condition_ids", | ||
| "liquidity_num_min", | ||
| "liquidity_num_max", | ||
| "volume_num_min", | ||
| "volume_num_max", | ||
| "start_date_min", | ||
| "start_date_max", | ||
| "end_date_min", | ||
| "end_date_max", | ||
| "tag_id", | ||
| "related_tags", | ||
| ) | ||
| for key in passthrough_keys: | ||
| if key in filters and filters[key] is not None: | ||
| params[key] = filters[key] | ||
|
|
||
| return params | ||
|
|
||
|
|
||
| def _request_markets_page( | ||
| session: requests.Session, | ||
| base_url: str, | ||
| params: dict[str, Any], | ||
| offset: int, | ||
| limit: int, | ||
| timeout: float, | ||
| ) -> list[dict[str, Any]]: | ||
| """ | ||
| Fetch a single page of markets using limit/offset pagination. | ||
|
|
||
| Returns a list of market dicts. | ||
|
|
||
| """ | ||
| url = f"{base_url}/markets" | ||
| effective_params = dict(params) | ||
| effective_params["limit"] = limit | ||
| effective_params["offset"] = offset | ||
|
|
||
| resp = session.get(url, params=effective_params, timeout=timeout) | ||
| if resp.status_code != 200: | ||
| raise RuntimeError(f"Gamma Get Markets failed: {resp.status_code} for url {url} with params {effective_params} and body {resp.text}") | ||
|
|
||
| data = resp.json() | ||
| if isinstance(data, list): | ||
| return data | ||
| if isinstance(data, dict) and "data" in data: | ||
| return data.get("data", []) or [] | ||
|
|
||
| raise RuntimeError("Unrecognized response schema from Gamma Get Markets") | ||
|
|
||
|
|
||
| def iter_markets( | ||
| filters: dict[str, Any] | None = None, | ||
| base_url: str | None = None, | ||
| timeout: float = 10.0, | ||
| ) -> Generator[dict[str, Any], None, None]: | ||
| """ | ||
| Iterate markets that pass server-side filters, yielding raw market dicts. | ||
| """ | ||
| base = _normalize_base_url(base_url) | ||
| params = build_markets_query(filters) | ||
| limit = int(filters.get("limit", 500)) if filters else 500 | ||
| offset = int(filters.get("offset", 0)) if filters else 0 | ||
|
|
||
| with requests.Session() as session: | ||
| while True: | ||
| markets = _request_markets_page( | ||
| session=session, | ||
| base_url=base, | ||
| params=params, | ||
| offset=offset, | ||
| limit=limit, | ||
| timeout=timeout, | ||
| ) | ||
| if not markets: | ||
| break | ||
| yield from markets | ||
| if len(markets) < limit: | ||
| break | ||
| offset += limit | ||
|
|
||
|
|
||
| def normalize_gamma_market_to_clob_format(gamma_market: dict[str, Any]) -> dict[str, Any]: | ||
| """ | ||
| Normalize Gamma API market format to CLOB API format. | ||
|
|
||
| Gamma API uses camelCase field names, while the CLOB API and parsing code | ||
| expects snake_case field names. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| gamma_market : dict[str, Any] | ||
| Market data from Gamma API in camelCase format. | ||
|
|
||
| Returns | ||
| ------- | ||
| dict[str, Any] | ||
| Market data normalized to CLOB API format with snake_case fields. | ||
|
|
||
| """ | ||
| import json | ||
|
|
||
| # Handle rewards field | ||
| rewards = gamma_market.get("clobRewards", []) | ||
| rewards_dict = None | ||
| if rewards and len(rewards) > 0: | ||
| reward = rewards[0] | ||
| rewards_dict = { | ||
| "rates": reward.get("rewardsDailyRate"), | ||
| "min_size": gamma_market.get("rewardsMinSize"), | ||
| "max_spread": gamma_market.get("rewardsMaxSpread"), | ||
| } | ||
|
|
||
| # Build tokens array from clobTokenIds and outcomes | ||
| tokens = [] | ||
| clob_token_ids = gamma_market.get("clobTokenIds", []) | ||
| outcomes = gamma_market.get("outcomes", []) | ||
| outcome_prices = gamma_market.get("outcomePrices", []) | ||
|
|
||
| # Parse JSON strings if needed | ||
| if isinstance(clob_token_ids, str): | ||
| clob_token_ids = json.loads(clob_token_ids) | ||
| if isinstance(outcomes, str): | ||
| outcomes = json.loads(outcomes) | ||
| if isinstance(outcome_prices, str): | ||
| outcome_prices = json.loads(outcome_prices) | ||
|
|
||
| # Create tokens array in CLOB format | ||
| for i, (token_id, outcome) in enumerate(zip(clob_token_ids, outcomes)): | ||
| token_entry = { | ||
| "token_id": token_id, | ||
| "outcome": outcome, | ||
| "price": float(outcome_prices[i]) if i < len(outcome_prices) else 0.5, | ||
| "winner": False, # Default value | ||
| } | ||
| tokens.append(token_entry) | ||
|
|
||
| normalized = { | ||
| # Core identifiers | ||
| "condition_id": gamma_market.get("conditionId"), | ||
| "question_id": gamma_market.get("questionID"), | ||
| "question": gamma_market.get("question"), | ||
| "description": gamma_market.get("description"), | ||
| "market_slug": gamma_market.get("slug"), | ||
|
|
||
| # Order book and trading settings | ||
| "enable_order_book": gamma_market.get("enableOrderBook", True), | ||
| "minimum_tick_size": gamma_market.get("orderPriceMinTickSize", 0.001), | ||
| "minimum_order_size": gamma_market.get("orderMinSize", 5), | ||
| "accepting_orders": gamma_market.get("acceptingOrders", True), | ||
| "accepting_order_timestamp": gamma_market.get("acceptingOrdersTimestamp"), | ||
| "seconds_delay": gamma_market.get("secondsDelay", 0), | ||
|
|
||
| # Market status flags | ||
| "active": gamma_market.get("active", False), | ||
| "closed": gamma_market.get("closed", False), | ||
| "archived": gamma_market.get("archived", False), | ||
|
|
||
| # Dates | ||
| "end_date_iso": gamma_market.get("endDateIso"), | ||
| "game_start_time": gamma_market.get("startDateIso"), | ||
|
|
||
| # Fee structure | ||
| "maker_base_fee": 0, # Gamma API doesn't provide fees directly, use known defaults | ||
| "taker_base_fee": 0, # Gamma API doesn't provide fees directly, use known defaults | ||
| "fpmm": gamma_market.get("marketMakerAddress", ""), | ||
|
|
||
| # Negative risk settings | ||
| "neg_risk": gamma_market.get("negRisk", False), | ||
| "neg_risk_market_id": gamma_market.get("negRiskMarketID"), | ||
| "neg_risk_request_id": gamma_market.get("negRiskRequestID"), | ||
|
|
||
| # Media | ||
| "icon": gamma_market.get("icon"), | ||
| "image": gamma_market.get("image"), | ||
|
|
||
| # Rewards and notifications | ||
| "rewards": rewards_dict, | ||
| "notifications_enabled": True, # Default value | ||
|
|
||
| # Outcome pricing flag | ||
| # "is_50_50_outcome": False, # Gamma API doesn't provide this flag | ||
|
|
||
| # Tokens array (CLOB API format) | ||
| "tokens": tokens, | ||
|
|
||
| # Preserve original data for reference | ||
| "_gamma_original": gamma_market, | ||
| } | ||
| return normalized | ||
|
|
||
|
|
||
| def list_markets( | ||
| filters: dict[str, Any] | None = None, | ||
| base_url: str | None = None, | ||
| timeout: float = 10.0, | ||
| max_results: int | None = None, | ||
| ) -> list[dict[str, Any]]: | ||
| """ | ||
| Collect markets into a list. | ||
|
|
||
| Use `max_results` to cap total items fetched. | ||
|
|
||
| """ | ||
| results: list[dict[str, Any]] = [] | ||
| count = 0 | ||
| for market in iter_markets(filters=filters, base_url=base_url, timeout=timeout): | ||
| results.append(market) | ||
| count += 1 | ||
| if max_results is not None and len(results) >= max_results: | ||
| break | ||
| return results |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.