"""Source a set of candidate wallet addresses to analyze. Three independent sources, unioned and de-duped: 1. leaderboard - top traders by realized profit over several windows 2. market holders - the largest holders of currently active, high-volume markets (catches whales who never top the leaderboard) 3. seed_wallets - addresses you already want to include The goal is recall, not precision: cast a wide net here, then let metrics + screening throw out the noise. """ from __future__ import annotations import re from .client import PolymarketClient _ADDR = re.compile(r"^0x[a-fA-F0-9]{40}$") def _extract_wallet(item: dict) -> str | None: for k in ("proxyWallet", "wallet", "user", "address", "account", "maker"): v = item.get(k) if isinstance(v, str) and _ADDR.match(v): return v.lower() return None def leaderboard_profit_map(client: PolymarketClient, windows, top_n: int) -> dict[str, dict]: """{wallet: {lb_profit_all, lb_volume_all, on_leaderboard}} — the AUTHORITATIVE profit/volume Polymarket reports, used to cross-check (and override) our own reconstructed PnL for wallets that are actually ranked. 'all' window is the long-term figure; we keep the max seen across windows to be safe.""" out: dict[str, dict] = {} for metric, key in (("profit", "lb_profit"), ("volume", "lb_volume")): for w in windows: try: rows = client.leaderboard(window=w, top_n=top_n, metric=metric) except Exception as e: # noqa: BLE001 print(f" [lb {metric} {w}] failed: {e}") continue for r in rows if isinstance(rows, list) else rows.get("data", []): addr = _extract_wallet(r) if not addr: continue amt = float(r.get("amount", 0) or 0) rec = out.setdefault(addr, {"lb_profit": None, "lb_volume": None, "on_leaderboard": True}) if w == "all": # prefer the all-time figure rec[key] = amt elif rec.get(key) is None: rec[key] = amt return out def from_leaderboard(client: PolymarketClient, windows, top_n: int) -> set[str]: out: set[str] = set() for w in windows: try: rows = client.leaderboard(window=w, top_n=top_n) except Exception as e: # noqa: BLE001 - discovery is best-effort print(f" [leaderboard {w}] failed: {e}") continue for r in rows if isinstance(rows, list) else rows.get("data", []): addr = _extract_wallet(r) if addr: out.add(addr) return out def _volume(m: dict) -> float: try: return float(m.get("volume") or m.get("volumeNum") or 0) except (TypeError, ValueError): return 0.0 def from_market_holders(client: PolymarketClient, n_markets: int, holders_per: int) -> set[str]: out: set[str] = set() # Gamma's server-side `order=volume` is unreliable, so over-fetch active # markets and rank by volume client-side, then take the busiest N. try: markets = client.markets(active=True, closed=False, limit=max(n_markets * 6, 300)) except Exception as e: # noqa: BLE001 print(f" [markets] failed: {e}") return out rows = markets if isinstance(markets, list) else markets.get("data", []) rows = sorted(rows, key=_volume, reverse=True)[:n_markets] for m in rows: cid = m.get("conditionId") or m.get("condition_id") if not cid: continue try: holders = client.holders(cid, limit=holders_per) except Exception as e: # noqa: BLE001 print(f" [holders {cid[:10]}] failed: {e}") continue # shape: [{token, holders:[{proxyWallet,...}]}, ...] (one group per outcome) groups = holders if isinstance(holders, list) else [holders] for g in groups: for h in (g.get("holders") if isinstance(g, dict) else g) or []: addr = _extract_wallet(h) if addr: out.add(addr) return out def discover(client: PolymarketClient, cfg: dict) -> list[str]: wallets: set[str] = set(a.lower() for a in cfg.get("seed_wallets", []) if _ADDR.match(a)) if cfg.get("use_leaderboard"): lb = from_leaderboard(client, cfg["leaderboard_windows"], cfg["leaderboard_top_n"]) print(f" leaderboard -> {len(lb)} wallets") wallets |= lb if cfg.get("use_market_holders"): mh = from_market_holders(client, cfg["markets_to_scan"], cfg["holders_per_market"]) print(f" market holders -> {len(mh)} wallets") wallets |= mh print(f" total unique candidates: {len(wallets)}") return sorted(wallets)