Spaces:
Running
Running
Download pmct/client.py from sharpflowapp/web: direct link, hf CLI and curl.
- Browser
- Download file 6.47 kB
-
https://huggingface.co/spaces/sharpflowapp/web/resolve/main/pmct/client.py
- Command line
-
hf download hf://spaces/sharpflowapp/web/pmct/client.py
-
curl -L -o client.py https://huggingface.co/spaces/sharpflowapp/web/resolve/main/pmct/client.py
6.47 kB
| """Thin HTTP clients for Polymarket's public read APIs. | |
| Three services are used (all read-only, no auth needed for the endpoints here): | |
| - Data API https://data-api.polymarket.com -> per-wallet activity/positions | |
| - Gamma API https://gamma-api.polymarket.com -> market metadata / resolution | |
| - CLOB API https://clob.polymarket.com -> prices / order book | |
| Verified live 2026-07 against the real API: Gamma /markets, CLOB /price & | |
| /prices-history, Data API /activity /positions /holders, and the leaderboard | |
| at lb-api.polymarket.com/profit|/volume. If Polymarket later changes a path and | |
| a call 404s, open https://docs.polymarket.com and fix it in ONE place here. | |
| """ | |
| from __future__ import annotations | |
| import time | |
| from typing import Any, Iterable | |
| import requests | |
| from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type | |
| class RetryableHTTP(Exception): | |
| """A 429/5xx worth backing off and retrying (unlike a 4xx, which is fatal).""" | |
| # Data API refuses offset-based paging past this point: | |
| # {"error":"max historical activity offset of 3000 exceeded"} | |
| MAX_ACTIVITY_OFFSET = 3000 | |
| DATA_API = "https://data-api.polymarket.com" | |
| GAMMA_API = "https://gamma-api.polymarket.com" | |
| CLOB_API = "https://clob.polymarket.com" | |
| # Leaderboard host has historically differed from the main data-api; verify. | |
| LEADERBOARD_API = "https://lb-api.polymarket.com" | |
| class PolymarketClient: | |
| def __init__(self, sleep_sec: float = 0.25, timeout: int = 20): | |
| self.sleep_sec = sleep_sec | |
| self.timeout = timeout | |
| self.s = requests.Session() | |
| self.s.headers.update({"User-Agent": "pmct-research/0.1"}) | |
| def _get(self, url: str, params: dict | None = None) -> Any: | |
| r = self.s.get(url, params=params, timeout=self.timeout) | |
| if r.status_code == 429 or r.status_code >= 500: | |
| raise RetryableHTTP(f"{r.status_code} on {url}") | |
| r.raise_for_status() # 4xx -> HTTPError, NOT retried (e.g. offset cap) | |
| if self.sleep_sec: | |
| time.sleep(self.sleep_sec) | |
| return r.json() | |
| # ----- Data API: per-wallet history ------------------------------------- | |
| def activity(self, wallet: str, limit: int = 500, offset: int = 0) -> list[dict]: | |
| """Trade/redeem/reward ledger for a wallet, newest first. | |
| Each item is expected to carry at least: type (TRADE/REDEEM/...), | |
| side (BUY/SELL), size, price, usdcSize, timestamp, conditionId, asset, | |
| outcome, title/slug. Field names vary — normalize in ledger.py. | |
| """ | |
| return self._get( | |
| f"{DATA_API}/activity", | |
| {"user": wallet.lower(), "limit": limit, "offset": offset}, | |
| ) | |
| def iter_activity(self, wallet: str, page_limit: int, max_pages: int) -> Iterable[dict]: | |
| """Yield a wallet's most-recent activity, newest first. Offset paging is | |
| capped by the API at MAX_ACTIVITY_OFFSET, so very active wallets return | |
| only their latest ~3500 events — enough for pattern/behavior analysis; | |
| lifetime PnL for ranked wallets comes from the leaderboard instead.""" | |
| offset = 0 | |
| for _ in range(max_pages): | |
| if offset > MAX_ACTIVITY_OFFSET: | |
| return | |
| try: | |
| page = self.activity(wallet, limit=page_limit, offset=offset) | |
| except requests.HTTPError: | |
| return # offset cap or other 4xx -> stop with what we have | |
| if not page: | |
| return | |
| yield from page | |
| if len(page) < page_limit: | |
| return | |
| offset += page_limit | |
| def positions(self, wallet: str) -> list[dict]: | |
| """Open positions with avgPrice, curPrice, size, cashPnl, percentPnl.""" | |
| return self._get(f"{DATA_API}/positions", {"user": wallet.lower()}) | |
| def value(self, wallet: str) -> Any: | |
| """Current portfolio USD value for a wallet.""" | |
| return self._get(f"{DATA_API}/value", {"user": wallet.lower()}) | |
| def holders(self, condition_id: str, limit: int = 40) -> list[dict]: | |
| """Largest holders of a market's outcome tokens -> source of whales.""" | |
| return self._get( | |
| f"{DATA_API}/holders", {"market": condition_id, "limit": limit} | |
| ) | |
| # ----- Leaderboard ------------------------------------------------------ | |
| # Verified live 2026-07: host lb-api.polymarket.com, paths /profit and | |
| # /volume, window in {all, 1d, 7d, 30d}. Each row: {proxyWallet, amount, | |
| # name, pseudonym, ...} where `amount` is profit-USD (/profit) or | |
| # volume-USD (/volume). | |
| def leaderboard(self, window: str = "all", top_n: int = 200, | |
| metric: str = "profit") -> list[dict]: | |
| """Top traders by `metric` in {profit, volume} for a window in | |
| {all, 1d, 7d, 30d}. For copy-trading you want profit.""" | |
| assert metric in ("profit", "volume") | |
| return self._get( | |
| f"{LEADERBOARD_API}/{metric}", | |
| {"window": window, "limit": top_n}, | |
| ) | |
| # ----- Gamma: market metadata / resolution ------------------------------ | |
| def markets(self, **params) -> list[dict]: | |
| """Query markets. Useful params: active, closed, limit, offset, | |
| order, ascending, condition_ids (comma-joined), volume_num_min.""" | |
| return self._get(f"{GAMMA_API}/markets", params) | |
| def market_by_condition(self, condition_ids: list[str]) -> list[dict]: | |
| return self._get( | |
| f"{GAMMA_API}/markets", | |
| {"condition_ids": ",".join(condition_ids), "limit": len(condition_ids)}, | |
| ) | |
| # ----- CLOB: prices ----------------------------------------------------- | |
| def price(self, token_id: str, side: str = "buy") -> Any: | |
| return self._get(f"{CLOB_API}/price", {"token_id": token_id, "side": side}) | |
| def prices_history(self, token_id: str, interval: str = "max", fidelity: int = 60) -> Any: | |
| """Historical price series for a CLOB outcome token; used to mark | |
| positions and to reconstruct fill context in the backtest.""" | |
| return self._get( | |
| f"{CLOB_API}/prices-history", | |
| {"market": token_id, "interval": interval, "fidelity": fidelity}, | |
| ) | |