polymarket-pnl

polymarket-pnl: Accurate P&L calculator for any Polymarket address. Reconstructs realized P&L from Data API cash flows (buy/sell/redeem/merge/split/rebate) and adds unrealized position value. In leaderboard validation, mean absolute percentage error (MAPE) versus the official /profit endpoint is about 0.2%. Requires a local Python environment (uses the httpx library).

Last repository push
GitHub Stars
205
Forks
26
Issues / PRs
1

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "polymarket-pnl" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-736754fee42632cc7bb615270b89d6511ab4e1ccfbc38a1962ab6d4c0e62885a. Verify the upstream source and version against https://github.com/runesleo/polymarket-toolkit before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

polymarket-pnl: Accurate P&L calculator for any Polymarket address. Reconstructs realized P&L from Data API cash flows (buy/sell/redeem/merge/split/rebate) and adds unrealized position value. In leaderboard validation, mean absolute percentage error (MAPE) versus the official /profit endpoint is about 0.2%. Requires a local Python environment (uses the httpx library).

0 Downloads

Introduction source: third_party · runesleo · 0.3.0 Reference

SkillPi interpretation

Tasks
Precise PnL calculator for any Polymarket address — reconstructs profit/loss from Data API cashflow (BUY/SELL/REDEEM/MERGE/SPLIT/REBATE) plus unrealized position value. Matches official /profit within ~0.2% MAPE on leaderboard validation. Bring-your-own Python (httpx).
Inputs and outputs
Each line is one address record: | Field | Type | Meaning | |-------|------|---------| | `address` | str | The lowercase 0x proxy wallet | | `pnl` | float | Trading cashflow PnL (BUY/SELL/REDEEM/MERGE/SPLIT/REBATE + unrealized). **Primary metric.** | | `pnl_inclusive` | float | `pnl` + REWARD + REFERRAL_REWARD + CONVERSION (platform credits) | | `total_buy`, `total_sell`, `total_redeem`, `total_merge`, `total_split`, `total_rebate`, `total_reward`, `total_referral`, `total_conversion` | float | Sum of each activity type | | `unrealized` | float | Current mark-to-market value of open positions | | `open_positions` | int | Number of open positions | | `trade_count` | int | Total BUY + SELL eve
Software, accounts and paid services
`python3` (3.9+) One Python package: `httpx` Install once: ```bash pip install -r ${SKILL_DIR}/requirements.txt
Limits and differences
**Data API offset ceiling (~10k)**: extremely high-frequency accounts may hit it on one activity type. The record is still emitted with `pagination_incomplete=True` and the field list so you can flag or re-fetch via timestamp-chunked backfill. **Same-second full-page boundary**: the timestamp-based pagination uses `end = oldest - 1` with a heuristic backfill pass that only triggers when the boundary timestamp already appears more than once in the current page. If a full page ends with exactly one row at timestamp `T` and additional same-second rows continue onto the next page, those rows may be skipped without `pagination_incomplete` being set. This affects a small subset of very-high-freque
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: polymarket-pnl
description: Precise PnL calculator for any Polymarket address — reconstructs profit/loss from Data API cashflow (BUY/SELL/REDEEM/MERGE/SPLIT/REBATE) plus unrealized position value. Matches official /profit within ~0.2% MAPE on leaderboard validation. Bring-your-own Python (httpx).
allowed-tools: Bash(python3:*) Read Write Edit
metadata: {"version":"0.3.0","openclaw":{"skillKey":"polymarket-pnl","homepage":"https://leolabs.me","requires":{"anyBins":["python3"]}}}

Polymarket Precise PnL

Compute precise, audit-grade PnL for any Polymarket address via the Data API cashflow method. Unlike position-level approximations used by most profilers, this reconstructs every BUY / SELL / REDEEM / MERGE / SPLIT / REBATE event and reconciles against current unrealized position value.

Validated against Polymarket's official /profit endpoint on the public leaderboard: MAPE ~0.2%, all top accounts within 1% error.

Trigger

Invoke this skill when the user wants:

  • Audit-grade PnL for one or more Polymarket addresses
  • Bulk PnL over a leaderboard or an address list
  • Benchmark mode: compare a local PnL dataset vs. the official /profit values

If the user just wants a quick profile (win rate, positions, category breakdown), use the polymarket-profile skill instead — it's lighter and runs on curl alone.

Requirements

  • python3 (3.9+)
  • One Python package: httpx

Install once:

pip install -r ${SKILL_DIR}/requirements.txt
# or
pip install httpx

${SKILL_DIR} is the path where this skill lives (for example, /path/to/your/agent/skills/polymarket-pnl/).

Core CLI

All invocations run from the skill directory (or with python3 <skill_dir>/compute_precise_pnl.py):

# Single address
python3 compute_precise_pnl.py --address 0x63ce342161250d705dc0b16df89036c8e5f9ba9a

# Bulk: top N on the leaderboard (auto-fetched)
python3 compute_precise_pnl.py --leaderboard 50

# Address list from a text file (one 0x per line, `#` for comments)
python3 compute_precise_pnl.py --addresses-file targets.txt

# Benchmark: compare your local PnL JSONL against the recomputed precise PnL
python3 compute_precise_pnl.py --leaderboard 100 \
  --benchmark local_pnl.jsonl \
  -o precise_vs_local.jsonl

Output is JSONL streamed to --output (default: ./precise_pnl.jsonl).

Output schema

Each line is one address record:

Field Type Meaning
address str The lowercase 0x proxy wallet
pnl float Trading cashflow PnL (BUY/SELL/REDEEM/MERGE/SPLIT/REBATE + unrealized). Primary metric.
pnl_inclusive float pnl + REWARD + REFERRAL_REWARD + CONVERSION (platform credits)
total_buy, total_sell, total_redeem, total_merge, total_split, total_rebate, total_reward, total_referral, total_conversion float Sum of each activity type
unrealized float Current mark-to-market value of open positions
open_positions int Number of open positions
trade_count int Total BUY + SELL events
computed_at int Unix seconds when record was produced
complete bool True if every paginated activity call returned fully
pagination_incomplete bool True if the Data API's ~10k offset ceiling was hit for at least one activity type
pagination_incomplete_types list[str] | None Which activity types hit the ceiling ("BUY", "SELL", ...)

Known limitations

  • Data API offset ceiling (~10k): extremely high-frequency accounts may hit it on one activity type. The record is still emitted with pagination_incomplete=True and the field list so you can flag or re-fetch via timestamp-chunked backfill.
  • Same-second full-page boundary: the timestamp-based pagination uses end = oldest - 1 with a heuristic backfill pass that only triggers when the boundary timestamp already appears more than once in the current page. If a full page ends with exactly one row at timestamp T and additional same-second rows continue onto the next page, those rows may be skipped without pagination_incomplete being set. This affects a small subset of very-high-frequency accounts; most addresses stay within 1% of the official /profit. A stricter backfill is on the roadmap.
  • pnl vs pnl_inclusive choice: Polymarket's official /profit endpoint inconsistently includes platform credits across addresses. The primary pnl field deliberately excludes them so the number is reproducible from public trade data alone.
  • Requires httpx: the only third-party dependency, for its robust TLS/HTTP/1.1 handling against the Data API.
  • No authentication: uses only public endpoints (data-api.polymarket.com, gamma-api.polymarket.com), so there are no API keys to manage but also no access to private endpoints.

Comparison with polymarket-profile

Aspect polymarket-profile polymarket-pnl (this skill)
Runtime curl + jq / node Python 3 + httpx
PnL accuracy Position-level cashPnL (approximate) Cashflow reconstruction (~0.2% MAPE)
Bulk mode Single address per call Single / leaderboard / address list
Win rate / categories ✅ ❌ (PnL only)
Benchmarking ❌ ✅ vs local dataset
Best for "Who is this address?" "What is their audit-grade PnL?"

Use them together: polymarket-profile for the qualitative picture, polymarket-pnl when the PnL number has to hold up to scrutiny.

Data sources

All public, no authentication required:

API What it provides
data-api.polymarket.com/activity BUY / SELL / REDEEM / MERGE / SPLIT / REBATE / REWARD / REFERRAL_REWARD / CONVERSION events
data-api.polymarket.com/positions Current open positions, for unrealized value
data-api.polymarket.com/v1/leaderboard Ranked addresses with official /profit values

Setup

# Claude Code
export AGENT_SKILLS_DIR=/path/to/your/agent/skills
cp -R skills/polymarket-pnl "$AGENT_SKILLS_DIR/"
pip install httpx

# OpenClaw
cp -R skills/polymarket-pnl ~/.openclaw/skills/
pip install httpx

New to Polymarket? Create an account here.

License

MIT — see repository root LICENSE.

Version history

  1. v0.7.0 GitHub ↗
    Original release notes

    ## v0.7 — MCP server for AI agents The toolkit's read-only CLI is now available as [Model Context Protocol](https://modelcontextprotocol.io) tools: [`mcp/`](https://github.com/runesleo/polymarket-toolkit/tree/main/mcp) · [docs/mcp.md](https://github.com/runesleo/polymarket-toolkit/blob/main/docs/mcp.md) - **10 read-only tools** for Claude / Codex / Cursor / any MCP client: `pm_profile`, `pm_activity`, `pm_brier`, `pm_pnl_check`, `pm_scan`, `pm_updown`, `pm_leaderboard`, `pm_redeem_watchdog`, `pm_v2_check`, `pm_rate_limits` - **The CLI is the contract**: every tool shells out to `pm` (argv array, no shell) — the server can do exactly what the read-only CLI can do, nothing more - **Hardened**: allowlist input validation (SDK layer + independent handler re-validation), pinned activity paging, 2MB subprocess output cap, spawn concurrency limit, 60s timeout - **No trading over MCP** — order placement stays in the separate opt-in `executor/` package, human-wired only - **npm packaging**: `npx -y polymarket-toolkit-mcp` one-liner (bundled dist, Node >=20) — npm listing goes live once published Setup: ```bash claude mcp add polymarket-toolkit -- npx -y polymarket-toolkit-mcp ``` (or from source: `cd mcp && npm install && npm start`)

  2. v0.6.0 GitHub ↗
    Original release notes

    ## v0.6 — Opt-in executor sub-package The core stays **zero-dependency, read-only, key-free**. Order execution now lives in an isolated, opt-in sub-package: [`executor/`](https://github.com/runesleo/polymarket-toolkit/tree/main/executor) · [docs/executor.md](https://github.com/runesleo/polymarket-toolkit/blob/main/docs/executor.md) ### Executor - CLOB V2 limit orders (GTC/GTD) via `@polymarket/clob-client-v2`, isolated deps — never imported by the core - **Safety ladder**: narrow façade (raw client not exposed) · dry-run by default (`EXECUTOR_LIVE=1` to post) · full canonical-field re-validation + notional cap recomputed at the boundary (`EXECUTOR_MAX_USD`, default $10) · fail-closed credential validation with redacted errors · live-call console redaction (the underlying client logs auth headers on HTTP errors) - Builder attribution end-to-end: default / override / opt-out, resolved once per instance; dry-run preview matches live behavior. Disclosure: [docs/builder-attribution.md](https://github.com/runesleo/polymarket-toolkit/blob/main/docs/builder-attribution.md) ### Core fix - `src/builder.ts`: a malformed `POLY_BUILDER_CODE` override now **disables** attribution instead of silently falling back to the author's default ### Verification - 51 tests green (root 23 + executor 28), both typechecks clean - 3-round adversarial code review before ship

  3. v0.5.0 GitHub ↗
    Original release notes

    ## Polymarket Toolkit v0.5.0 **For builders who run code** — CLI, TypeScript helpers, and AI skills over public Polymarket APIs. No API keys. No signing. ### Highlights - **`pm` CLI** — `profile`, `activity`, `scan`, `updown`, `v2-check`, `lb`, `pnl-check`, `limits`, `brier`, `redeem`, `markets` - **Activity ~4000 row cap warnings** — duplicate-page detection so truncated history is not mistaken for complete data - **V2 CTF FAQ** + read-only `pm v2-check` — split/merge infra alignment diagnostics (not execution) - **Validation templates** — handoff, backtest, paper, live-gate, platform runbook - **Bilingual README** — [README.zh.md](./README.zh.md) - **Builder attribution helper** — `src/builder.ts` for future executor paths (read-only tools unchanged) ### Quick try ```bash git clone https://github.com/runesleo/polymarket-toolkit.git && cd polymarket-toolkit ./bin/pm profile 0x63ce342161250d705dc0b16df89036c8e5f9ba9a ``` Node 22+ recommended. ### Boundaries This release does **not** sign transactions or run merge/split/redeem on your wallet. For audit-grade PnL use `skills/polymarket-pnl`. For normal redemption use the official Polymarket app. Full notes: [README.md](https://github.com/runesleo/polymarket-toolkit/blob/main/README.md)

  4. v0.4.0 GitHub ↗
    Original release notes

    **One-liner:** pUSD-era redeem observability for AI agents. No keys required. After Polymarket's pUSD redemption flow shipped, normal users redeem in-app. Agents still need a status lane: which wallet has redeemable value, which condition still surfaces as `redeemable=true` in the Data API, whether a low-cash strategy account needs attention. v0.4 adds three small helpers to fill that gap — read-only, zero-dep, no signing. ## New helpers (`src/index.ts`) - `fetchRedeemablePositionsPage(user, opts)` — Data API `/positions?redeemable=true` - `summarizeRedeemablePositions(rows)` — group by `conditionId`, sum `currentValue` (losing rows correctly contribute `$0`, not their `size`; negative values clamp to `0`) - `resolveRedeemMode({ mode, lowWatermark })` — returns `"watchdog"` or `"low_watermark"`. Intentionally no `"active"` value: this toolkit never executes a redeem, so an active label belongs in your own wallet system. ## New artifacts - `examples/15-redeem-watchdog.ts` — copy-paste demo - `docs/cookbook.md §11` — bilingual recipe (EN + ZH localized rewrite) - `tests/redeem_watchdog.test.ts` — 9 tests covering pure functions, network URL assembly, and the regression points caught during review ## Safety boundary This release **only reads public APIs**. It does not redeem tokens, sign Safe transactions, call relayers, move funds, or require private keys. The official Polymarket app remains the right place for normal user redemption. ## Review trail This release went through two rounds of independent Codex review: - **Round 1** caught `currentValue || size` falsely inflating losing redeemable rows: a demo wallet with three losing tokens (`size > 0`, `currentValue = 0`) was reporting `$1.84` payable, when the real payable amount is `$0`. Fixed by replacing the `||` fallback with a `currentValue == null` null-check. - **Round 2** caught a missing `>= 0` clamp on negative `currentValue`. Fixed by clamping at the summary level. Tests went from 2 → 9. Full review trail visible in PR #10 and commits `9f89557` + `64f9d15`. ## Tests - `npm test` — 9/9 pass - `tsc --noEmit` — clean - Example 15 smoke against demo wallet `0x63ce342161250d705dc0b16df89036c8e5f9ba9a` returns `estimatedRedeemableValue: 0` (was falsely `$1.84` before the fix) ## Quickstart ```bash npx tsx examples/15-redeem-watchdog.ts <proxy_wallet> [low_watermark] ```

Current listing version

0.3.0

Verify the source revision ↗

Safety and assessment details

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value95/100

Highlights

  • 提供 Polymarket 地址的审计级盈亏计算,误差仅 ~0.2%,具备高实用价值
  • 支持单地址、批量、排行榜、基准测试等多种使用模式,功能完整
Trigger Precision95/100

Highlights

  • Trigger 章节清晰定义三种典型使用场景,边界明确
  • description 准确描述核心功能,与其他技能有明确区分
Structure and Standards85/100

Areas to improve

  • requirements.txt 文件缺失 Reported severity: Minor

    主文件提及 pip install -r ${SKILL_DIR}/requirements.txt,但该文件未传入 ZIP 包

    Recommendation: 请补充 requirements.txt 文件或移除相关引用

Highlights

  • 文档结构清晰,包含 Setup/Core CLI/Output schema/Known limitations 等完整章节
  • 提供多个端到端调用示例,便于用户理解和使用
Execution Reliability80/100

Highlights

  • 明确处理 Data API offset ceiling 异常,提供 pagination_incomplete 标志位
  • 所有数据源均为公开 API,无需认证,降低使用门槛
  • Known limitations 章节诚实披露技术限制,增强可信度
Evidence Verifiability (mean of the first four)89/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

Domains or addresses referenced in the document

These addresses may be documentation links or examples, not an approved network allowlist. Verify actual destinations and outgoing data before use.

  • leolabs.me
  • polymarket.com

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

`python3` (3.9+) One Python package: `httpx` Install once: ```bash pip install -r ${SKILL_DIR}/requirements.txt

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.