File size: 4,905 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
"""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)