{
  "markdown": "# Polymarket Wallet Intelligence\n\n<!-- mcp-name: io.github.aemery13/polymarket-intel -->\n\n**An MCP server and REST API that classifies Polymarket wallets as human or bot, scores their trading edge from 0–10, and streams their current open positions.** Built for AI agents on copy-trading and signal-following stacks.\n\n```bash\n# Use it from any MCP client (Claude Desktop, Cursor, etc.)\npip install polymarket-intel-mcp\npolymarket-intel-mcp\n\n# Or call the hosted REST API directly\ncurl https://polymarket-intel-production.up.railway.app/wallet/0xf1528f12e645462c344799b62b1b421a6a4c64aa\n```\n## How this fits with other Polymarket MCP servers\n## Status\n\n**Latest:** v1.2 (May 2026) — classifier improved to distinguish active human grinders from HFT bots. See [release notes](https://github.com/aemery13/polymarket-intel/commits/main) and [v1.3 backlog issue](https://github.com/aemery13/polymarket-intel/issues) for what's next.\n\nA daily snapshot job runs at 08:00 UTC and re-scores the top 50 leaderboard wallets, building a historical dataset of classification stability over time.\n\n\nThere are several MCP servers covering Polymarket, each at a different layer:\n\n| Server | What it does | When to use it |\n|---|---|---|\n| **polymarket-intel** (this) | Wallet intelligence — classify human vs bot, score trading edge, read open positions | Deciding *whose* signals to follow |\n| graph-polymarket-mcp | Market data via The Graph subgraphs (20 tools, 8 subgraphs) | Reading raw on-chain market data |\n| whitmorelabs/polymarket-mcp | Slippage, liquidity, arbitrage, price feeds | Pricing your own trades |\n| joinQuantish/polymarket | Self-hosted trading agent | Running an autonomous bot |\n\nThese complement each other. A copy-trading agent would use **polymarket-intel** to filter wallets worth following, then **graph-polymarket-mcp** to read the markets those wallets are betting on, then **whitmorelabs/polymarket-mcp** to size its own entries.\n\n## What it answers\n\n- **\"Is this trader a human or a bot?\"** — `score_polymarket_wallet(wallet_address)` → returns `classification ∈ {human, bot, insufficient_data}` plus a confidence score and reason codes.\n- **\"Do they actually have an edge?\"** — `edge_score` from 0–10, gated on net realised PnL so distributed-but-losing wallets don't get false positives.\n- **\"What are they betting on right now?\"** — `get_open_positions(wallet_address)` returns live positions sorted by size, refreshed every 30s.\n- **\"How has their edge changed over time?\"** — `/wallet/{address}/history` returns the score time series from the daily snapshots.\n\n## Why this exists\n\nThe Polymarket leaderboard is misleading. It includes unrealised PnL marked-to-current-price, so the names at the top are dominated by bots running structural arb plus a few wallets sitting on huge open positions that may never resolve in their favour. Agents that copy-trade naively from the leaderboard get burned.\n\nThis service runs every leaderboard wallet through behavioural fingerprinting (focus ratio, holding period, timing regularity, category concentration) plus PnL reconstruction from raw activity, and only surfaces traders that look like genuine humans with a real edge.\n\n**The dataset grows more valuable over time** — every day the snapshot job runs, historical signals accumulate. Wallets that have been consistently above edge 7 for 90 days are a stronger signal than any single point-in-time score.\n\n## Distributed as both a REST API and an MCP server\n\n| Surface     | Use case                                    | Setup                               |\n|-------------|---------------------------------------------|-------------------------------------|\n| MCP server  | Agent that needs tool-style access          | `pip install polymarket-intel-mcp`  |\n| REST API    | Custom HTTP integration, dashboards         | `curl https://polymarket-intel-production.up.railway.app/...` |\n| Hosted MCP  | Agent on any MCP-compatible client          | Add `https://polymarket-intel-production.up.railway.app/mcp` to client config |\n\n## Architecture\n\n```\n┌──────────────────────────────────────────────┐\n│  core/                                       │\n│    client.py    — Polymarket data API client │\n│    signals.py   — pure signal calculators    │\n│    scorer.py    — classifier + edge score    │\n│    models.py    — Pydantic response schemas  │\n├──────────────────────────────────────────────┤\n│  db/                                         │\n│    schema.sql   — Postgres tables + indexes  │\n│    repository.py — Repository protocol +     │\n│                    InMemoryRepository        │\n│    supabase_repo.py — Supabase impl          │\n│    converters.py — ScoreResult ↔ records     │\n├──────────────────────────────────────────────┤\n│  api/main.py    — FastAPI HTTP server        │\n│  mcp_server/    — MCP server (stdio)         │\n│  scripts/                                    │\n│    analyze_wallet.py — CLI                   │\n│    snapshot_job.py   — daily cron entry      │\n│  tests/                                      │\n└──────────────────────────────────────────────┘\n```\n\nCore has no idea persistence exists. The API and snapshot job depend on the `Repository` protocol — Supabase in production, in-memory in tests and when env vars are unset. This is what makes the suite run without a database and what lets you swap Supabase for Neon, RDS, or anything else later by adding one file.\n\n## Quickstart\n\n```bash\ngit clone <repo> && cd polymarket-intel\npython -m venv .venv && source .venv/bin/activate\npip install -r requirements-dev.txt\npytest                             # 19 tests, all green\n```\n\n### CLI\n\n```bash\npython scripts/analyze_wallet.py phonesculptor\npython scripts/analyze_wallet.py 0xf1528f12e645462c344799b62b1b421a6a4c64aa --json\n```\n\n### REST API\n\n```bash\nuvicorn api.main:app --reload --port 8000\nopen http://localhost:8000/docs\n```\n\nThe API is split into a **slow tier** (cached aggressively, cheap, ideal for one-off discovery) and a **fast tier** (short cache, ideal for live copy-trading agents). The split exists because the underlying data has different freshness needs — a wallet's classification doesn't change minute-to-minute, but their open positions do.\n\n| Tier | Method | Path                                     | TTL  | Notes                                    |\n|------|--------|------------------------------------------|------|------------------------------------------|\n| slow | GET    | `/wallet/{address}`                      | 1h   | Score blob — classification, edge_score, signals. No positions. Persisted to history (debounced). |\n| fast | GET    | `/wallet/{address}/positions`            | 30s  | Open positions only. No DB write per call. |\n| —    | GET    | `/wallet/{address}/history`              | DB   | Score time series                        |\n| —    | GET    | `/wallet/{address}/positions/history`    | DB   | Position changes over time               |\n| —    | GET    | `/wallet/by-username/{username}`         | 1h   | Convenience lookup                       |\n| —    | GET    | `/leaderboard?limit=50`                  | 30m  | Raw Polymarket top traders               |\n| —    | GET    | `/leaderboard/verified?min_edge=5`       | 1h   | Filtered to scored humans                |\n| —    | GET    | `/leaderboard/historical?date=…`         | DB   | Leaderboard at any past date             |\n| —    | GET    | `/snapshots/latest`                      | DB   | When did the cron last run?              |\n\n**Why 30s on positions and not faster?** Polygon block time is ~2s and Polymarket's activity index lags a few seconds. Polling below 10s gets you no fresher data, just rate-limit errors. 30s is the sweet spot for cost/freshness/upstream-friendliness.\n\n**Why debounced DB writes?** A trading agent may hit `/wallet/{address}` thousands of times an hour. Writing a row per call would bloat history with near-duplicate snapshots. The score endpoint persists at most once per wallet per hour. The daily snapshot job guarantees coverage of the top 50 regardless of API traffic.\n\n### MCP server (Claude Desktop, Cursor, Continue)\n\n```bash\npython mcp_server/server.py\n```\n\nThen drop `mcp_server/claude_desktop_config.example.json` into your Claude Desktop config and edit the absolute path.\n\nThe server exposes four tools:\n\n- `score_polymarket_wallet(wallet_address)` — full score\n- `score_polymarket_user(username)` — lookup by display name\n- `get_polymarket_leaderboard(limit)` — raw leaderboard\n- `get_open_positions(wallet_address)` — fast snapshot of live bets\n\n## Scoring methodology\n\n### Bot triggers (any one fires → bot)\n\n| Signal              | Threshold     | Source                      |\n|---------------------|---------------|-----------------------------|\n| Focus ratio         | > 12          | Hubble Research, validated empirically |\n| Median hold time    | < 60s         | HFT / MEV pattern           |\n| Timing CV           | < 0.3 (n≥100) | Scheduled trading           |\n\nSoft signals stack: crypto-market-maker pattern, > 200 trades/day, etc.\n\n### Edge score (0–10) for humans\n\n```\nHard gate: net realised PnL ≤ 0  →  capped at 2.0\nHard gate: < 10 winning markets  →  capped at 3.0\n\n35%  PnL magnitude (log-scaled)\n25%  win rate (capped at 70%)\n15%  PnL distribution (penalises top-1 concentration)\n15%  sample size (winning markets, capped at 50)\n10%  win/loss ratio (capped at 3x)\n```\n\nNet PnL is the hard gate so wallets like neutralwave23 — many distributed tiny wins masking $375k of losses — are correctly flagged as poor.\n\n### PnL reconstruction\n\n```\nmoney_in   = sum(BUY usdcSize per conditionId)\nmoney_out  = sum(SELL usdcSize) + sum(REDEEM usdcSize)\npnl        = money_out - money_in\n\nstatus:\n  REDEEM exists                                    → won\n  SELL exists, no REDEEM                           → exited\n  no SELL, no REDEEM, last trade > 7 days old      → lost\n  no SELL, no REDEEM, last trade within 7 days     → open\n```\n\nWhy activity rather than the positions endpoint: positions vanish from the API after redeem, so any naive analysis using `/positions` undercounts wins. Always reconstruct from `/activity?type=TRADE` + `/activity?type=REDEEM` (separate calls — comma-joined types return 400).\n\n## Persistence (Supabase)\n\nThe historical dataset is the moat. Every day the snapshot job pulls the leaderboard, scores the top N wallets, and persists three things: the score itself (`wallet_scores`), the wallet's open positions at that moment (`open_position_snapshots`), and the leaderboard as it stood (`leaderboard_snapshots`). After 90 days you can answer questions no one else can: \"who has been consistently above edge 7 for the last quarter?\", \"which wallets just entered the top 50?\", \"show me everyone who held YES on this market three days before resolution.\"\n\n### Setup\n\n```bash\n# 1. Create a Supabase project, get the URL and service_role key\ncp .env.example .env  # fill in SUPABASE_URL and SUPABASE_KEY\n\n# 2. Apply the schema (Supabase dashboard → SQL editor → paste db/schema.sql → run)\n#    Or via psql:\n#    psql \"$DATABASE_URL\" -f db/schema.sql\n\n# 3. Run the snapshot job once to verify it writes:\npython scripts/snapshot_job.py --top 10\n```\n\nIf `SUPABASE_URL` and `SUPABASE_KEY` are unset, both the API and the snapshot job fall back to an in-memory repository — the suite still passes, the API still serves live scoring, but history endpoints will be empty until you wire up Supabase.\n\n### Daily snapshot job\n\nSchedule `python scripts/snapshot_job.py --top 50` daily (Railway cron, GitHub Actions, or Supabase pg_cron triggering an edge function — your call). The job is idempotent: running twice creates two snapshots, which is fine — history queries pick the closest one.\n\n```bash\npython scripts/snapshot_job.py --top 50              # production\npython scripts/snapshot_job.py --top 5  --dry-run    # local testing, no writes\n```\n\nEach run records an audit row in `snapshot_runs` with start/finish times, wallets scored, and error count.\n\n### Schema overview\n\n| Table                       | Purpose                                          |\n|-----------------------------|--------------------------------------------------|\n| `wallets`                   | One row per wallet ever seen                     |\n| `wallet_scores`             | Append-only score time series                    |\n| `open_position_snapshots`   | What each wallet held at each tick               |\n| `leaderboard_snapshots`     | Full leaderboard, preserved daily                |\n| `snapshot_runs`             | Audit trail for the cron job                     |\n\nTwo views (`latest_wallet_scores`, `latest_leaderboard`) make the common \"what's current\" queries cheap.\n\n### Repository pattern\n\n`db/repository.py` defines a `Repository` protocol. Two implementations:\n\n- `InMemoryRepository` — thread-safe, lossy across restarts. Used in tests and as the dev-mode fallback.\n- `SupabaseRepository` — production. Wraps the supabase-py client.\n\nThe API and snapshot job depend only on the protocol. To swap Supabase for Neon or self-hosted Postgres, write one new class implementing the same six method signatures.\n\n## Pricing dimensions\n\nThe endpoint split was designed so each tier maps cleanly to a billing model. Suggested ranges:\n\n| Tier            | Endpoints                              | Suggested price          | Why                              |\n|-----------------|----------------------------------------|--------------------------|----------------------------------|\n| Discovery       | `/wallet/{address}`, `/leaderboard/*`  | $0.001–$0.01 / call      | Slow cache, mostly DB reads      |\n| Monitoring      | `/wallet/{address}/positions`          | $0.01–$0.05 / call       | Fresh data, hits Polymarket each time |\n| Streaming (v2)  | SSE feed of position changes           | $20–$100 / month flat    | Continuous fetch on our side     |\n| History         | `/wallet/{address}/history` etc.       | $0.005 / call            | Pure DB read, value grows over time |\n\nThe streaming endpoint is the one serious copy-trading bots will actually pay for, but it requires a continuous-fetch worker on our side — leaving it for v2 once we have signal that the per-call business works.\n\n## Deploy\n\n### Railway\n\nPush the repo, point at it. `railway.toml` handles the rest.\n\n### Render / Heroku-style\n\n`Procfile` is in place.\n\n### Caching\n\n`api/cache.py` is a thread-safe in-memory TTL cache with the same interface as a Redis client. For multi-worker production, swap the singleton for `redis.Redis()` in one file. TTLs:\n\n- wallet score: 1h\n- open positions only: 5m\n- leaderboard: 30m\n- verified leaderboard: 1h\n\n## Testing\n\n```bash\npytest -v\n```\n\nSynthetic fixtures in `tests/fixtures.py` mimic the three real wallet patterns from the research phase (phonesculptor MLB human, gabigol HFT bot, neutralwave23 tilt loser) plus a low-data newbie. Tests run against fixtures only — no live API calls — so the suite is deterministic and CI-safe.\n\n## Distribution roadmap\n\n1. **Now** — REST API on Railway, Supabase for daily snapshot persistence\n2. **Next** — Publish to MCP Hub, Replit Agent Market, awesome-mcp-servers\n3. **Later** — x402 micropayments per call (USDC), historical query endpoints (the moat: every day we run, the dataset grows)\n\n## Verified wallet examples\n\nThese are the personas the test fixtures target. Live numbers will differ as activity changes:\n\n| Wallet                                        | Score | Notes                                         |\n|-----------------------------------------------|-------|-----------------------------------------------|\n| `phonesculptor`                               | ~9/10 | MLB-focused human, distributed wins, real edge|\n| `gabigol`                                     | bot   | Crypto 5-min Up/Down arb (edge largely dead post-Feb 2026) |\n| `neutralwave23`                               | ~1/10 | Distributed tiny wins masking large net loss  |\n",
  "bytes": 15943,
  "sha": "e8b3608401803f64c28287b37161e60844e63881a936d172fdfaac9fa56c881d",
  "repo_slug": "aemery13/polymarket-intel",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/mcp_io_github_aemery13_polymarket_intel_c7e0d08f/readme"
}