File size: 6,466 Bytes
d4c51f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
"""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"})

    @retry(
        reraise=True,
        stop=stop_after_attempt(4),
        wait=wait_exponential(multiplier=0.5, min=0.5, max=8),
        retry=retry_if_exception_type(
            (requests.ConnectionError, requests.Timeout, RetryableHTTP)),
    )
    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},
        )